Как обрабатывать параметры запуска в Swift 3 при прослушивании уведомления? Получение синтаксических проблем
Я пытаюсь обработать параметр запуска и открыть определенный контроллер представления, нажав удаленное уведомление, которое я получаю в быстром 3. Я видел аналогичный вопрос, например здесь, но ничего для новой быстрой реализации 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'
У меня были подобные ошибки, когда я ранее использовал аналогичный код, чтобы получить значение из словаря по ключу, и мне пришлось заменить коды и в основном безопасно развернуть словарь сначала. Но, похоже, это не работает. Любая помощь будет оценена по достоинству. Благодарю.
Ответы
Ответ 1
Итак, оказалось, что вся подпись метода изменилась, и когда я реализовал новую подпись, все работает отлично. Ниже приведен код.
new 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.
}
}
Надеюсь, это поможет.
Ответ 2
Apple внесла множество изменений в 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")
}
}
Swift 5:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Launched from push notification
guard let options = launchOptions,
let remoteNotif = options[UIApplication.LaunchOptionsKey.remoteNotification] as? [String: Any]
else {
return
}
let aps = remoteNotif["aps"] as? [String: Any]
NSLog("\n Custom: \(String(describing: aps))")
handleRemoteNotification(remoteNotif)
}
А о LaunchOptionKeys
читайте в документации Apple.
Ответ 3
Swift 4
// 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)")
}
Ответ 4
swift 3:
if let notification = launchOptions?[.localNotification] as? NSDictionary{
#if DEBUG
print("iOS9 didFinishLaunchingWithOptions notification\n \(notification)")
#endif
Ответ 5
if let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: Any] {
if let notification = remoteNotif["aps"] as? [AnyHashable : Any] {
//handle PN
}
}