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

9
我正在使用Swift构建一个接收推送通知的应用程序。我在JSON中发送自定义值。
我通过通知打开应用程序,所以我知道我必须在“didFinishLaunchingWithOptions”中执行此操作,并从“launchOptions”读取该值。
如何读取这些值并在我的应用程序中使用它们。
非常感谢。
3个回答

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
}

3
在application: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
}

编辑:修复远程通知语法


好的。那么我接下来该怎么做?如何从“notification”中获取值? - Aerofan
您可以访问UILocalNotification的userInfo属性,它是一个NSDictionary。 - Raymond Brion
我认为你在这段代码中混淆了Objective-C和Swift。 - Aerofan
是的。对不起,我修复了语法。 - Raymond Brion
这个语法根本不起作用,请更新它。 - Ali Pishvaee

1
这是已更新至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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接