Swift读取远程通知的userInfo

时间:2015-02-18 23:56:53

标签: ios json swift push-notification userinfo

当我收到这样的远程通知时,我实现了一个打开AlertView的函数:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
        var notifiAlert = UIAlertView()
        var NotificationMessage : AnyObject? =  userInfo["alert"]
        notifiAlert.title = "TITLE"
        notifiAlert.message = NotificationMessage as? String
        notifiAlert.addButtonWithTitle("OK")
        notifiAlert.show()
}

但NotificationMessage总是零。

我的json有效载荷如下所示:

{"aps":{"alert":"Testmessage","badge":"1"}}

我正在使用Xcode 6,Swift和我正在为iOS8开发。 我现在搜索了几个小时,但没有找到任何有用的信息。 通知工作完美..如果我点击它,将打开alertview。 我的问题是,我无法从userInfo中获取数据。

7 个答案:

答案 0 :(得分:95)

userInfo字典的根级项目为"aps",而不是"alert"

尝试以下方法:

if let aps = userInfo["aps"] as? NSDictionary {
    if let alert = aps["alert"] as? NSDictionary {
        if let message = alert["message"] as? NSString {
           //Do stuff
        }
    } else if let alert = aps["alert"] as? NSString {
        //Do stuff
    }
}

请参阅Push Notification Documentation

答案 1 :(得分:4)

对我来说,当我从Accengage发送消息时,以下代码有效 -

private func extractMessage(fromPushNotificationUserInfo userInfo:[NSObject: AnyObject]) -> String? {
    var message: String?
    if let aps = userInfo["aps"] as? NSDictionary {
        if let alert = aps["alert"] as? NSDictionary {
            if let alertMessage = alert["body"] as? String {
                message = alertMessage              
            }
        }
    }
    return message
}

与Craing Stanford的答案唯一不同的是key我用来从alert实例提取的消息body是不同的。请参阅下文以获得更多清晰度 -

if let alertMessage = alert["message"] as? NSString

VS

if let alertMessage = alert["body"] as? String

答案 2 :(得分:2)

方法(swift4):

func extractUserInfo(userInfo: [AnyHashable : Any]) -> (title: String, body: String) {
    var info = (title: "", body: "")
    guard let aps = userInfo["aps"] as? [String: Any] else { return info }
    guard let alert = aps["alert"] as? [String: Any] else { return info }
    let title = alert["title"] as? String ?? ""
    let body = alert["body"] as? String ?? ""
    info = (title: title, body: body)
    return info
}

用法:

let info = self.extractUserInfo(userInfo: userInfo)
print(info.title)
print(info.body)

答案 3 :(得分:0)

  

应用处于活动状态时应显示警报。所以检查状态是否有效。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if application.applicationState == .active {
      if let aps = userInfo["aps"] as? NSDictionary {
        if let alertMessage = aps["alert"] as? String {
          let alert = UIAlertController(title: "Notification", message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
          let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
          alert.addAction(action)
          self.window?.rootViewController?.present(alert, animated: true, completion: nil)
        }
      }
    }
    completionHandler(.newData)
  }
  

如果用户需要消息,那么他可以获得警报消息。

答案 4 :(得分:0)

我使用APNs Provider和json负载,如下所示

{
  "aps" : {
    "alert" : {
      "title" : "I am title",
      "body" : "message body."
    },
  "sound" : "default",
  "badge" : 1
  }
}

由于提供程序的缘故,它是作为JSON定义的字典而产生的,iOS将其转换为NSDictionary对象,没有像Dictionary这样的下标,但是可以使用value(forKey:)

来自here的引用

这是我使用Swift 4的方式

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    guard application.applicationState == .active else { return }
    guard let alertDict = ((userInfo["aps"] as? NSDictionary)?.value(forKey: "alert")) as? NSDictionary,
        let title = alertDict["title"] as? String,
        let body = alertDict["body"] as? String
        else { return }
    let alertController = UIAlertController(title: title, message: body, preferredStyle: .alert)
    let okAct = UIAlertAction(title: "Ok", style: .default, handler: nil)
    alertController.addAction(okAct)
    self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
    completionHandler(UIBackgroundFetchResult.noData)
}

答案 5 :(得分:0)

这是我的objC版本

if (userInfo[@"aps"]){
    NSDictionary *aps = userInfo[@"aps"];
    if (aps[@"alert"]){
        NSObject *alert = aps[@"alert"];
        if ([alert isKindOfClass:[NSDictionary class]]){
            NSDictionary *alertDict = aps[@"alert"];
            if (alertDict[@"message"]){
                NSString *message = alertDict[@"message"];
            }
        }
        else if (aps[@"alert"]){
            NSString *alert = aps[@"alert"];
        }
    }
}

答案 6 :(得分:0)

雨燕5

struct Push: Decodable {
    let aps: APS
    
    struct APS: Decodable {
        let alert: Alert
        
        struct Alert: Decodable {
            let title: String
            let body: String
        }
    }
    
    init(decoding userInfo: [AnyHashable : Any]) throws {
        let data = try JSONSerialization.data(withJSONObject: userInfo, options: .prettyPrinted)
        self = try JSONDecoder().decode(Push.self, from: data)
    }
}

用法:

guard let push = try? Push(decoding: userInfo) else { return }
let alert = UIAlertController(title: push.aps.alert.title, message: push.aps.alert.body, preferredStyle: .alert)