我正在尝试处理启动选项并在点击我在swift 3中收到的远程通知时打开一个特定的视图控制器。我已经看到类似的问题,例如here,但没有新的swift 3实现。我看到了一个类似的问题(和)在AppDelegate.swift中我在didFinishLaunchingWithOptions中有以下内容:
var localNotif = (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as! String)
if localNotif {
var itemName = (localNotif.userInfo!["aps"] as! String)
print("Custom: \(itemName)")
}
else {
print("//////////////////////////")
}
但是Xcode给了我这个错误:
Type '[NSObject: AnyObject]?' has no subscript members
我也试过这个:
if let launchOptions = launchOptions {
var notificationPayload: NSDictionary = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as NSDictionary!
}
我收到此错误:
error: ambiguous reference to member 'subscript'
我有类似的错误,无论我以前使用类似的代码通过键从字典中获取值,我不得不替换代码,基本上安全地首先解开字典。但这似乎不适用于此。任何帮助,将不胜感激。谢谢。
苹果在Swift 3
和其中一个上做了很多改变。
编辑:这也适用于Swift 4。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Launched from push notification
let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: Any]
if remoteNotif != nil {
let aps = remoteNotif!["aps"] as? [String:AnyObject]
NSLog("\n Custom: \(String(describing: aps))")
}
else {
NSLog("//////////////////////////Normal launch")
}
}
有关LaunchOptionKeys
的更多信息,请阅读Apple的documentation。
所以事实证明整个方法签名已经改变,当我实现新的签名时,工作得很好。下面是代码。
新的didFinishLaunchingWithOptions方法:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
//and then
if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil {
// Do what you want to happen when a remote notification is tapped.
}
}
希望这可以帮助。
// Check if launched from the remote notification and application is close
if let remoteNotification = launchOptions?[.remoteNotification] as? [AnyHashable : Any] {
// Do what you want to happen when a remote notification is tapped.
let aps = remoteNotification["aps" as String] as? [String:AnyObject]
let apsString = String(describing: aps)
debugPrint("\n last incoming aps: \(apsString)")
}
迅捷3:
if let notification = launchOptions?[.localNotification] as? NSDictionary{
#if DEBUG
print("iOS9 didFinishLaunchingWithOptions notification\n \(notification)")
#endif
if let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: Any] {
if let notification = remoteNotif["aps"] as? [AnyHashable : Any] {
//handle PN
}
}