当应用程序处于后台时如何在 didReceiveRemoteNotification 上打开特定的视图控制器

How to Open a Specific View Controller On didReceiveRemoteNotification when application is in back ground

我正在实施一个警报,我正在从服务器获取 pushNotification,我正在接收完美的推送通知并且它在前台模式下工作正常但是当应用程序进入后台时它只收到推送通知但没有加载视图我想加载

请检查下面的代码

func registerForPushNotifications(application: UIApplication) {
    let notificationSettings = UIUserNotificationSettings(
        forTypes: [.Badge, .Sound, .Alert], categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
}

此方法调用自 didFinishLaunchingWithOptions

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""
    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }
    NSUserDefaults.standardUserDefaults().setObject(tokenString, forKey: "deviceToken")
}

这是最后的方法

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        print(userInfo)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let navigationController = storyboard.instantiateViewControllerWithIdentifier("AlarmDetailsController") as! AlarmDetailsController
        //let dVC:AlarmDetailsController = navigationController.topViewController as! AlarmDetailsController
        navigationController.isPushNotification = true
        self.window?.rootViewController?.presentViewController(navigationController, animated: true, completion: {})        
}

请帮我解决这个问题记住我的应用程序在前台模式下工作正常

1.Firstly 你应该在应用程序中打开后台获取 "Capabilities" 2. 然后在app delegate

中使用下面的代码

在 AppDelegate class 中添加以下代码:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
       // print(userInfo)
let vc = mainStoryBoard.instantiateViewController(withIdentifier: "destinationVC") as! destinationVC
                            self.visibleNavController.pushViewController(vc, animated: true)
    }

对于 iOS 10 使用以下代码: 1.Import

 import UserNotifications

用于前台获取

     @available(iOS 10.0, *)
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
            var userInfo = NSDictionary()
            userInfo = notification.request.content.userInfo as NSDictionary
            let pay = userInfo as NSDictionary
   let driverLocationVC = mainStoryBoard.instantiateViewController(withIdentifier: "destinationVC") as! destinationVC
                                self.visibleNavController.pushViewController(driverLocationVC, animated: true)


    }

背景

 @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Userinfo \(response.notification.request.content.userInfo)")


        var userInfo = NSDictionary()
        userInfo = response.notification.request.content.userInfo as NSDictionary
        print(userInfo)
    let driverLocationVC = mainStoryBoard.instantiateViewController(withIdentifier: "DriverLocationVC") as! DriverLocationVC
                            self.visibleNavController.pushViewController(driverLocationVC, animated: true)
}

用于获取设备令牌

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenString = deviceToken.reduce("", {[=14=] + String(format: "%02X", )})
        print("Got token data! \(tokenString)")

        UserDefaults.standard.set(tokenString, forKey: "device_token")
        UserDefaults.standard.synchronize()
    }

如果您的应用被挂起,请检查来自 application:didFinishLaunchingWithOptions

的字典中的 UIApplicationLaunchOptionsRemoteNotificationKey
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    ...

    // Check if launched from notification
    if let userInfo = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {

        // handle your notification like in application:didReceiveRemoteNotificatioUserInfo:
    }
    ...
}

首先你需要在你的Xcode

中这样设置

共有三种状态:前台、后台、已终止,您需要了解有关通知的详细信息。

1. Foreground : 当您的应用程序处于前台时,一旦您收到通知,它就会转到特定屏幕当您在正常模式下根据您的配置点击横幅或警报时。但是,在后台模式下,它甚至可以在您的通知到达后立即进行静默导航,而无需点击它。

2. Background : 如果你的应用程序不在前台,使用后台模式可以帮助你打开特定的屏幕,如果你处理它在 didReceiveRemoteNotification 内,当您点击它时应用程序打开后,它会立即转到它的特定屏幕。

3. Killed:如果您的应用程序不在内存中,则只有点击推送通知才能导航特定屏幕,因为它不存在t 在设备内存中,因此如果用户忽略通知,didReceiveRemoteNotification 将不会触发。

那么,我们如何处理具体的屏幕导航呢?那是基于你如何开发你的应用程序设计,在我看到你的代码之前我无法提供正确的答案。

但是,是的,当您打开应用程序时,您可以在应用程序处于后台时导航到特定的位置,方法是点击出现在横幅或锁上的通知 screen.Everything 可以在您的 didReceiveRemoteNotification 中完成在一种情况下,当您想在后台执行此操作时。

看看这个:

https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

在您的推送通知 json 中,您必须包含以下内容

content-available : 1 

如果包含它,即使应用程序处于后台,它也可以根据您从服务器发送的附加数据进行后台执行。

在您的附加数据中:

{apns : [],
data : [
   "Navigate" : "Home"
   ]}

然后在您的 didReceiveRemoteNotification,

if let aps = userInfo["data"] as? NSDictionary{
      // get the "Home" data and do navigation here
      // You might need to instantiate storyboard of the specific view controller which you want to go as RootViewController
}

因此,当您收到通知时,如果您点击横幅上的推送通知或 alert.The 应用程序将打开,它将在后台进入特定屏幕,它将进入特定屏幕。