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

问题描述 投票:4回答:3

我正在实现一个警报,我从服务器获取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: {})        
}

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

ios swift xcode7
3个回答
5
投票

1.首先,您应该在应用程序“功能”中启用后台提取2.然后在应用程序委托中使用以下代码

在AppDelegate类中添加以下代码:

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("", {$0 + String(format: "%02X", $1)})
        print("Got token data! \(tokenString)")

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

2
投票

如果您的应用程序被暂停,请查看UIApplicationLaunchOptionsRemoteNotificationKey字典中的application:didFinishLaunchingWithOptions

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

0
投票

首先,你需要在你的Xcode中设置这样的东西

enter image description here

有三种状态:前景,背景,已杀死您需要了解有关通知的明确详细信息。

1.前景:当您的应用程序处于前台时,当您的通知进入时,当您在正常模式下点击横幅或警报时,它将指向特定屏幕。但是,在后台模式下,它甚至可以在您的通知到达时立即进行静音导航,而无需点击它。

2.背景:如果你的应用程序不在前台,使用后台模式可以帮助你打开特定的屏幕,如果你在didReceiveRemoteNotification内处理它,当你点击它时应用程序打开,它将导致它的特定屏幕。

3.已杀:如果您的应用程序不在内存中,则仅点击推送通知工作以导航特定屏幕,因为它不在设备内存中,因此如果用户忽略通知,didReceiveRemoteNotification将不会触发。

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

但是,是的,只要您通过点击横幅或锁定屏幕上显示的通知打开应用程序,您就可以导航到应用程序处于后台的特定情况。当您想要在后台执行此操作时,您可以在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
}

因此,当您的通知到来时,如果您在点击横幅或警报时点击推送通知,则会在后台显示特定屏幕。应用程序将打开,它将导致特定屏幕。

© www.soinside.com 2019 - 2024. All rights reserved.