使用 Parse 推送通知:当应用程序处于后台时显示警报

Posted

技术标签:

【中文标题】使用 Parse 推送通知:当应用程序处于后台时显示警报【英文标题】:Push notification with Parse: show an alert when the app is in background 【发布时间】:2015-10-06 17:34:01 【问题描述】:

在我的应用程序中,我从 Parse.com 发送推送通知。我按照应有的方式创建并安装了所有证书和应用程序功能。但是,如果应用程序在后台,我会在通知中心收到通知,我点击并打开我的应用程序,我看不到任何包含已发送消息的警报。下面的代码:

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:.
    

【问题讨论】:

【参考方案1】:

当您从该通知打开应用程序时,通知的有效负载不会自动弹出。

方法:

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

不跟踪从推送通知打开应用程序的时间 - 此方法可以:

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

正如 M.Othman 在此线程中所说:Detect if the app was launched/opened from a push 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");

PFPush HandlePush 方法应该显示警报,如果没有,您也可以创建自己的警报视图控制器。

【讨论】:

对不起,我写了这个快速代码:let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary if ((notification) != nil) print("There was a notification") self.application(application, didReceiveRemoteNotification: notification as! [NSObject : AnyObject]) 但是当我通过点击推送通知打开我的应用程序时我看不到警报消息(只有当应用程序在前台时我才能看到警报消息) 是否达到了 'didReceiveRemoteNotification' 方法?也许尝试显示您自己的 UIAlertController 而不是使用 Parse 的推送处理程序 现在我显示一个 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) 。现在,如何在 AlertController 的消息中写入发送的推送通知消息?

以上是关于使用 Parse 推送通知:当应用程序处于后台时显示警报的主要内容,如果未能解决你的问题,请参考以下文章

后台问题中的 Apple 推送通知

当应用程序处于后台状态时,FCM 多个推送通知无法正常工作

当应用程序处于后台状态时,FCM多次推送通知无法正常工作

当应用程序处于后台时,从推送通知中插入 coredata 记录

关闭应用程序后解析推送通知崩溃

当应用程序处于后台时接收 Apple 推送通知