我正在使用Swift构建一个接收推送通知的应用。我在JSON中发送自定义值。
我通过通知打开应用程序,所以我知道我必须在“didFinishLaunchingWithOptions”中执行此操作并从“launchOptions”中读取值。
如何阅读这些值并在我的应用中使用它们。
非常感谢。
答案 0 :(得分:4)
当您的应用未启动时,这对我在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
}
答案 1 :(得分:2)
在应用程序中: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
}
编辑:远程通知修复语法
答案 2 :(得分:0)
这是针对 Swift 5 更新的 Oliver Zhang 回复。
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[UIApplication.LaunchOptionsKey.remoteNotification] {
}
}
return true
}