0

In my app I send push notifications from Parse.com. I created and installed all the certificates and the app functions as it should. However, if the app is in the background, I get a notification in the notification center I doing tap and open my app, I can not see any alert containing the message sent. The code below:

import UIKit
import Parse

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        Parse.setApplicationId("appid",
            clientKey: "clientkey")

        // 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)
            }
        }

        if application.respondsToSelector("registerUserNotificationSettings:") {
            let userNotificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
            let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        } else {
            let types: UIRemoteNotificationType = [UIRemoteNotificationType.Badge, UIRemoteNotificationType.Alert, UIRemoteNotificationType.Sound]
            application.registerForRemoteNotificationTypes(types)
        }

        if let notification = launchOptions as? [String : AnyObject] {
            if let notificationDictionary = notification[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] {
                self.application(application, didReceiveRemoteNotification: notificationDictionary)
            }
        }

        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]) {

        if application.applicationState == UIApplicationState.Inactive {
            PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
        }

        PFPush.handlePush(userInfo)
    }

    func clearBadges() {

        let installation = PFInstallation.currentInstallation()
        installation.badge = 0
        installation.saveInBackgroundWithBlock { (success, error) -> Void in
            if success {
                print("cleared badges")
                UIApplication.sharedApplication().applicationIconBadgeNumber = 0
            }
            else {
                print("failed to clear badges")
            }
        }
    }


    func applicationDidBecomeActive(application: UIApplication) {

        clearBadges()
    }


    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 active state; here you can undo many of the changes made on entering the background.
    }


    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
}
Cœur
  • 32,421
  • 21
  • 173
  • 232
Alessio Chiappe
  • 145
  • 1
  • 9

1 Answers1

1

The payload of the notification is not automatically popped up when you open your application from that notification.

The method:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

Doesn't track when the application is opened from a push notification - this method does:

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

As down by M.Othman in this thread: Detect if the app was launched/opened from a push notification

To check for notification:

UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (notification) {
    NSLog(@"app recieved notification from remote%@",notification);
    [self application:application didReceiveRemoteNotification:(NSDictionary*)notification];
}else{
     NSLog(@"app did not recieve notification");
}

The PFPush HandlePush method should display an alert if it doesn't you can also create your own alert view controller as well.

Community
  • 1
  • 1
JoshR604
  • 155
  • 1
  • 5
  • I'm sorry but i write this swift code: let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary if ((notification) != nil) { print("There was a notification") self.application(application, didReceiveRemoteNotification: notification as! [NSObject : AnyObject]) } But when i open my app by tapping on a push notification i can’t see the alert message (i can see the alert message only if the app is in foreground) – Alessio Chiappe Oct 06 '15 at 21:02
  • Is the 'didReceiveRemoteNotification' method being reached? Maybe try displaying your own UIAlertController instead of using Parse's Push Handler – JoshR604 Oct 06 '15 at 22:42
  • Now i display an UIAlertController: `if application.applicationState == .Inactive || application.applicationState == .Background { let alertController = UIAlertController(title: "Boiade", message: "", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil) }`. Now, how can i write in the message of the AlertController the message of the push notification sent? – Alessio Chiappe Oct 07 '15 at 23:52