如何从推送通知中获取内容?

时间:2017-07-05 06:49:30

标签: ios swift

将Swift3与xcode8.3一起使用

以下是我的功能代码

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    print("==== didReceiveRemoteNotification ====")
    print(userInfo)

    let state = UIApplication.shared.applicationState

    if state == .background {
        // background
        if let pushUrl = userInfo[AnyHashable("url")] as? String {
            viewController?.redirectTo(url: pushUrl)
        }
    }
    else if state == .active {
        // foreground
        print("==== foreground Running ====")
        let pushUrl = userInfo[AnyHashable("url")]
        let pushApns = userInfo[AnyHashable("aps")]
        let pushAlert = pushApns["alert"]
        viewController?.showAlertBox(url: pushUrl as! String, msg: pushAlert)
    }
}

当我收到有关前台的通知时,我需要从中获取内容并将其传递给viewController。

下面的

是我的Xcode的日志

==== didReceiveRemoteNotification ====
[AnyHashable("aps"): {
    alert = "this is alert";
    badge = 0;
}, AnyHashable("url"): https://www.google.com]

但上面的代码不起作用?我怎样才能得到警告"和" url"来自通知的内容?

2 个答案:

答案 0 :(得分:1)

要使用

访问警报
if let aps = userInfo["aps"] as? [String:AnyObject] {
     if let alert = aps["alert"] as? NSString {
      //Use alert
    }
    if let alert = aps["badge"] as? NSNumber {
      //Use badge
    }
}
  if let url = userInfo["url"] as? String {
 // use url
}

答案 1 :(得分:1)

你快到了!请尝试以下方法:

let data = userInfo as! [String: AnyObject]

if let url = data["url"] {
    print(url)
}

if let aps = data["aps"] {
    print(aps["alert"])
}