繁体   English   中英

如何使用swift从launchOptions获取自定义推送通知值?

[英]How to get custom Push Notification value from launchOptions with swift?

我正在使用Swift构建一个接收推送通知的应用程序。 我在JSON中发送自定义值。

我通过通知打开应用程序,所以我知道我必须在“didFinishLaunchingWithOptions”中执行此操作并从“launchOptions”中读取值。

如何阅读这些值并在我的应用程序中使用它们。

非常感谢。

当您的应用未启动时,这是适用于SWIFT 2的功能。 由于可选的绑定,代码不是很优雅。 但它的确有效。

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

    // if launched from a tap on a notification
    if let launchOptions = launchOptions {
        if let userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] {
            if let action = userInfo["action"], id = userInfo["id"] {
                let rootViewController = self.window!.rootViewController as! ViewController
                let _ = setTimeout(5.0, block: { () -> Void in
                    rootViewController.openNotification(action as! String, id: id as! String)
                })

            }
        }
    }
    return true
}

在应用程序中:didReceiveRemoteNotification:fetchCompletionHandler,自定义数据传递给didReceiveRemoteNotification,这是一个NSDictionary。 您要检索的详细信息可能位于userInfo的“aps”键上。

func application(application: UIApplication, didReceiveRemoteNotification userInfo: NSDictionary!)
{
    var notificationDetails: NSDictionary = userInfo.objectForKey("aps") as NSDictionary
}

当应用程序未启动时,您需要从应用程序中获取它:didFinishedLaunchWithOptions,

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

    if let launchOpts = launchOptions {
      var notificationDetails: NSDictionary = launchOpts.objectForKey(UIApplicationLaunchOptionsRemoteNotificationKey) as NSDictionary
    }

    return true
}

编辑:远程通知修复语法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM