首页 > 解决方案 > 来自后台的远程通知

问题描述

我正在快速创建一个将使用UNNotificationAction按钮的应用程序。

我已经userNotificationCenter正确设置,我可以在应用程序打开时正确调用didReceive...从这里我显示一个模式窗口。

问题是,当应用程序未在前台或后台运行时(用户尚未打开应用程序)didFinishLaunchingWithOptions,当我检查时我无法解析我的代码launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification]

当用户使用UNNotificationAction.

标签: iosswiftapple-push-notificationsapn

解决方案


请检查下面的代码,希望这会有所帮助。

     @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        application.registerForRemoteNotifications()
    }



   @available(iOS 10, *)

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
     Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // print(userInfo)
      completionHandler([.alert, .badge, .sound])
    // Change this to your preferred presentation option
   // completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }
    switch response.actionIdentifier {
    case "action1":
        print("Action First Tapped")
    case "action2":
        print("Action Second Tapped")
    default:
        break
    }

    // Print full message.
    print(userInfo)
    Messaging.messaging().appDidReceiveMessage(userInfo)
    completionHandler()
}

推荐阅读