So there are many questions and answers out there but none of them are working for me. When I go to the parse dashboard I have 2 devices in everyone, but when I send a push it says pushes sent 0. They are both iOS devices and I'm using the push portal with a development certificate.p12.
What am I missing?
If you do not receive notification on your device, you may have forgotten to call the method initializeNotificationServices in didFinishLaunchingWithOptions
func initializeNotificationServices() -> Void {
let settings = UIUserNotificationSettings(forTypes: [ .Sound, .Alert, .Badge], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
print("initialize")
// This is an asynchronous method to retrieve a Device Token
// Callbacks are in AppDelegate.swift
// Success = didRegisterForRemoteNotificationsWithDeviceToken
// Fail = didFailToRegisterForRemoteNotificationsWithError
UIApplication.sharedApplication().registerForRemoteNotifications()
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
print("didRegisterForRemoteNotificationsWithDeviceToken")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
print("didReceiveRemoteNotification")
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
And method :
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("MyID",
clientKey: "MyKey")
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var pushPayload = false
if let options = launchOptions {
pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
}
if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let userNotificationTypes = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let settings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
print("register")
} else {
let types = [UIRemoteNotificationType.Badge, UIRemoteNotificationType.Alert, UIRemoteNotificationType.Sound]
application.registerForRemoteNotificationTypes([UIRemoteNotificationType.Badge, UIRemoteNotificationType.Alert, UIRemoteNotificationType.Sound])
}
initializeNotificationServices()
return true
}
Related
How to work around this bug, as I looked all I remember and I find no answer.
Any help would be appreciated.
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import UIKit
import Parse
// If you want to use any of the UI components, uncomment this line
// import ParseUI
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Enable storing and querying data from Local Datastore.
// Remove this line if you don't want to use Local Datastore features or want to use cachePolicy.
Parse.enableLocalDatastore()
// ****************************************************************************
// Uncomment and fill in with your Parse credentials:
// Parse.setApplicationId("your_application_id", clientKey: "your_client_key")
Parse.setApplicationId("xxxxxxxxxx",
clientKey: "xxxxxxxxxxxxx")
// iniciar com facebook
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
// If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as
// described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
// Uncomment the line inside ParseStartProject-Bridging-Header and the following line here:
// PFFacebookUtils.initializeFacebook()
// ****************************************************************************
PFUser.enableAutomaticUser()
let defaultACL = PFACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.setPublicReadAccess(true)
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser: true)
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var noPushPayload = false;
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil;
}
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
//
// Swift 1.2
//
// if application.respondsToSelector("registerUserNotificationSettings:") {
// let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
// let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
// application.registerUserNotificationSettings(settings)
// application.registerForRemoteNotifications()
// } else {
// let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound
// application.registerForRemoteNotificationTypes(types)
// }
//
// Swift 2.0
//
// if #available(iOS 8.0, *) {
// let types: UIUserNotificationType = [.Alert, .Badge, .Sound]
// let settings = UIUserNotificationSettings(forTypes: types, categories: nil)
// application.registerUserNotificationSettings(settings)
// application.registerForRemoteNotifications()
// } else {
// let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
// application.registerForRemoteNotificationTypes(types)
// }
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
//--------------------------------------
// MARK: Push Notifications
//--------------------------------------
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannelInBackground("") { (succeeded: Bool, error: NSError?) in
if succeeded {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n");
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %#.\n", error)
}
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.\n")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#\n", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
///////////////////////////////////////////////////////////
// Uncomment this method if you want to use Push Notifications with Background App Refresh
///////////////////////////////////////////////////////////
// func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// if application.applicationState == UIApplicationState.Inactive {
// PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
// }
// }
//--------------------------------------
// MARK: Facebook SDK Integration
//--------------------------------------
///////////////////////////////////////////////////////////
// Uncomment this method if you are using Facebook
///////////////////////////////////////////////////////////
// func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
// return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication, session:PFFacebookUtils.session())
// }
// resposta do facebook quando ele faz login
func application(application: UIApplication, openUrl url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication,
annotation: annotation)
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
}
The exception is clear :
Edit info plist and a new line with key FacebookAppID, and value your facebook id
or Use FBSDKSettings.setAppID("your app facebook id")
Where can I find my Facebook application id and secret key?
Is Parse's documentation code currently not up to date for iOS 9 Swift 2 xcode 7.1? The last 2 functions both have errors saying 'Definition conflicts with previous value'
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId("key",
clientKey: "key")
// Register for Push Notitications
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var pushPayload = false
if let options = launchOptions {
pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
}
if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// Store the deviceToken in the current Installation and save it to Parse
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
The last 3 functions should be outside of the didFinishLaunchingWithOptions function.
I'm trying to redirect the user to a ViewController when he touches the Push Notification. This is working fine when the user has the App open in background, but it's not working when it has to open the App.
After some research, I have learned when the App opens due tu a push notification, it only reads the "didFinishLaunchingWithOptions".
So, I assume now I need to make some "if" statement to make the segue when the push notification is set, but I don't know how to detect the push notification because it's my first time using notifications in my app.
Here is my code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId(MY_APP_ID, clientKey: MY_CLIENT_KEY)
// Registramos la Push Notification
if application.applicationState != UIApplicationState.Background {
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var pushPayload = false
if let options = launchOptions {
pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
}
if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
else {
//let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound
//application.registerForRemoteNotificationTypes(types)
// Access the storyboard and fetch an instance of the view controller
}
// Change navigation bar appearance
UINavigationBar.appearance().barTintColor = UIColor(hex: 0x00B7BB)
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
if let barFont = UIFont(name: "Avenir Next", size: 20.0) {
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor(), NSFontAttributeName:barFont]
}
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
// Access the storyboard and fetch an instance of the view controller
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("UltimaMarca")
// Then push that view controller onto the navigation stack
let rootViewController = self.window!.rootViewController as! UINavigationController
rootViewController.pushViewController(viewController, animated: true)
}
Do you know some tutorial, guideline or code to show me? Because I have found some lines of code in Objective-C but they are very old and I cannot use it.
Thanks,
I'm trying to add parse to my appDelegate with Swift. I get an error saying
Cannot invoke 'registerForRemoteNotifications' with an argument list of type '(UIUserNotificationType)'
Here's my code. What's wrong?
if application.respondsToSelector("registerUserNotificationSettings:") {
let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
let types = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound
application.registerForRemoteNotifications(types)
}
return true
After you've followed the Parse tutorial for setting up Push Notifications and Certificates with the Apple Developer Console, make sure your AppDelegate.swift looks like this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
Parse.setApplicationId("ID", clientKey:"KEY")
let userNotificationTypes = (UIUserNotificationType.Alert |
UIUserNotificationType.Badge |
UIUserNotificationType.Sound);
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// Store the deviceToken in the current Installation and save it to Parse
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.addUniqueObject("Chat", forKey: "channels")
installation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
This last function resets the badge counter when the user opens the app:
func applicationDidBecomeActive(application: UIApplication) {
//Reset badge counter to zero
var currentInstallation = PFInstallation.currentInstallation()
if(currentInstallation.badge != 0){
currentInstallation.badge = 0
}
}
let settings = UIUserNotificationSettings(forTypes: [.Alert,.Badge,.Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
This could be useful if you're using Swift 2.0, due to some error saying
binary operator cannot apply to two UIUserNotificationType
I am registering for push notifications through Parse this way:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId("RfSGbVes0FGIX1sfxTEb3iybVsKgKPrfDuxco3vC", clientKey: "3pFBMar6vO6iUJouqTMt4VJVKZaXUc6p9RgHzTep")
if application.applicationState != UIApplicationState.Background {
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var pushPayload = false
if let options = launchOptions {
pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
}
if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptionsInBackground(launchOptions, block: nil)
}
}
let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.badge = 0
println(installation.deviceToken) //deviceToken is nil
let standardUserDefaults = NSUserDefaults.standardUserDefaults()
standardUserDefaults.setObject(installation.deviceToken, forKey: "parseDeviceToken")
standardUserDefaults.synchronize()
delegate?.didFinishSettingToken()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackgroundWithBlock(nil)
}
When I run application I have a nil value from println(installation.deviceToken)
Maybe there is other way to handle deviceToken?
EDIT: If I stop application and run it again, it gives deviceToken. I don't receive deviceToken only when I run application first time.
As per the apple documentation:
The first time you register your app’s preferred notification types, the system asks the user whether your app should be allowed to deliver
notifications and stores the user’s response. The system does not
prompt the user during subsequent registration attempts. The user can
always change the notification preferences using the Settings app.
optional func application(_ application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
{
application.registerForRemoteNotifications()
}
Also you have to add
UIApplication.sharedApplication().registerForRemoteNotificationSettings(settings)
For iOS 7 and 8 version issues check this tutorial.
Hope it helps.