Apple - Provisioning profile + Push Notifications - xcode

I followed the guide on Parse.com on how to create a certificate and prepare a provisioning account to accept Push Notifications. When i go to Preferences/Accounts :
It shows on the bottom, but when i try to choose it from the Build Settings Tab, it doesn't show, and i always get this error : "no valid 'aps-environment' entitlement string found for application"
I tried this from scratch several times, using several Xcode & parse Apps, Please help me.
Appdelegate code :
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("MyAppId", clientKey: "MyAppClientKey")
var notificationType: UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
var settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var currentInstallation: PFInstallation = PFInstallation()
currentInstallation.setDeviceTokenFromData(deviceToken)
currentInstallation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println(error.localizedDescription)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
}

Have you added the device onto the Development Provisioning Profile, then download and installed it? I got that same error until the device was added.

Related

iOS 10 UNNotification doesn't show alert

The code is very easy:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { (granted, error) in
if !granted {
print("Not allowed")
}
})
let content = UNMutableNotificationContent()
content.title = "Alert"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 20, repeats: false)
let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
return true
}
It works well on iOS 11, like this:
but on iOS 10, the alert doesn't show.
On both iOS 10 and iOS 11, the sound did appear.
My Xcode version is 9.2(9C40b)
Any help is appreciated.
Try to add the body of notification like this
content.body = "Any text/Blank Space"
Hope this will help you

Remote Push notifications actions

I created a code that receive remote push norification, this code is worked ok. Now I need to add two "buttons" that swip left and do a action. I know that this below code is used to indetify the action
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if identifier == "optin1" {
//do something
}
else identifier == "option2" {
//do something
}
completionHandler()
}
But I dont knew how to create the buttons to swip left. How can I do it
This is my AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
// Override point for customization after application launch.
let types:UIUserNotificationType = [.Alert, .Sound, .Badge]
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: types, categories: nil))
initLocationManager()
return true
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
//print(error)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print(deviceToken)
}
func application(application: UIApplication, didReceiveRemoteNotificationuserInfo userInfo: [NSObject : AnyObject]) {
print(userInfo)
}
Update: new version Swift 4 compatible. This example was adapted from this amazing tutorial https://cocoacasts.com/actionable-notifications-with-the-user-notifications-framework
Configure User Notification Center
import UserNotifications
...
UNUserNotificationCenter.current().delegate = self
Define Actions
let actionReadLater = UNNotificationAction(identifier: Constants.Action.readLater,
title: "Read Later",
options: [])
Define Category
let tutorialCategory = UNNotificationCategory(identifier: Constants.Category.tutorial,
actions: [actionReadLater],
intentIdentifiers: [],
options: [])
Register Category
UNUserNotificationCenter.current().setNotificationCategories([tutorialCategory])
Schedule local notifications by instance from an IBAction
// Request Notification Settings
UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
switch notificationSettings.authorizationStatus {
case .notDetermined:
self.requestAuthorization(completionHandler: { (success) in
guard success else { return }
// Schedule Local Notification
self.scheduleLocalNotification()
})
case .authorized:
// Schedule Local Notification
self.scheduleLocalNotification()
case .denied:
print("Application Not Allowed to Display Notifications")
case .provisional:
print("provisional")
}
}
previous version
You can copy&paste this code in didFinishLaunchingWithOptions method:
Create the action
// NOTFICATION
let incrementAction = UIMutableUserNotificationAction()
incrementAction.identifier = "HI_ACTION"
incrementAction.title = "Hi!"
incrementAction.activationMode = UIUserNotificationActivationMode.Background
incrementAction.authenticationRequired = false
incrementAction.destructive = false
Create the category
let counterCategory = UIMutableUserNotificationCategory()
counterCategory.identifier = "HELLO_CATEGORY"
Associate action and category
counterCategory.setActions([incrementAction],
forContext: UIUserNotificationActionContext.Default)
counterCategory.setActions([incrementAction],
forContext: UIUserNotificationActionContext.Minimal)
Registration
let categories = NSSet(object: counterCategory) as! Set<UIUserNotificationCategory>
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: categories)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
The last step is only for demostration
let notification = UILocalNotification()
notification.alertBody = "Hey!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.fireDate = NSDate(timeIntervalSinceNow: 5)
notification.category = "HELLO_CATEGORY"
UIApplication.sharedApplication().scheduleLocalNotification(notification)
When the app is launched you have to push CMD+L
Here's a link to an example

Cannot convert value of type 'NSData' to expected argument type 'String'

I'm writing codes on swift in XCode. This is the code:
import UIKit
import Foundation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let notificationTypes : UIUserNotificationType = [.Alert, .Badge, .Sound]
let notificationSettings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
return true
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
{
UIApplication.sharedApplication().registerForRemoteNotifications()
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("TOKEN:", deviceToken);
let token = String(data: deviceToken, encoding: NSUTF8StringEncoding);
let myUrl = NSURL(fileURLWithPath: "http://......php?id=" + token);
print("URL:",fileURLWithPath: "http://......php?id=" + token);
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print(error.localizedDescription)
}
/* func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}*/
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
Compiler gives me an error on the func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {" and it says me "Cannot convert value of type 'NSData' to expected argument type 'String'"... but I can't understand the way to solve the problem. So, can somebody help me to correct the error?
var charSet: NSCharacterSet = NSCharacterSet(charactersInString: "<>")
var tokenStr: String = (deviceToken.description as NSString)
.stringByTrimmingCharactersInSet(characterSet)
.stringByReplacingOccurrencesOfString( " ", withString: "") as String
print(deviceTokenString)
Try that
USe this, for sending token to the server. Worked well for me
var token: String = "\(deviceToken)"
let rawtoken = token.stringByReplacingOccurrencesOfString(">", withString: "")
let cleantoken = rawtoken.stringByReplacingOccurrencesOfString("<", withString: "")
var finaltoken = cleantoken.stringByReplacingOccurrencesOfString(" ", withString: "")
Final token is the one that you are supposed to use.
Source was Udemy online courses.
Note that the token is BINARY, so you cannot easily convert it to a string (no UTF8!).
It is a good practice to convert it to hex:
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for var i = 0; i < deviceToken.length; i++ {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("Push token: \(tokenString)")

Getting this error when trying to implement Chartboost on Swift xcode?

I have this code to add my AppID and App Signature to my AppDelegate.swift file but I get an error on the last line of code. It says: "Cannot invoke startWithAppId with an argument list of type (String, String, Delegate: AppDelegate). What am I doing wrong? Thanks!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let kChartboostAppID = "5236547547457856858568"
let kChartboostAppSignature = "523525225"
Chartboost.startWithAppId(kChartboostAppID, appSignature: kChartboostAppSignature, delegate: self)
}
I forgot to add the ChartboostDelegate initializer. It works now!

Xcode , Parse.com - Push notifications don't show on my phone.

followed the guide on Parse.com on how to create a certificate and prepare a provisioning account to accept Push Notifications. When i go to Preferences/Accounts : It shows on the bottom, but when i try to choose it from the Build Settings Tab, it doesn't show, and i always get this error : "no valid 'aps-environment' entitlement string found for application"
My phone is recognised by the Parse app, and it sends notifications successfully, but my phone never receives them. I tried this from scratch several times, using several Xcode & Parse Apps.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("MyAppId", clientKey: "MyAppClientKey")
var notificationType: UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
var settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var currentInstallation: PFInstallation = PFInstallation()
currentInstallation.setDeviceTokenFromData(deviceToken)
currentInstallation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println(error.localizedDescription)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
}
1) Did you allow push notifications from your app project?
2) Do you have the correct build identifiers set in parse and in your app?
I have another delegate method that I don't see in your post.
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings!)
{
UIApplication.sharedApplication().registerForRemoteNotifications()
}

Resources