Swift读取远程通知的userInfo

Swift read userInfo of remote notification

我实现了一个功能,当我收到这样的远程通知时打开 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 始终为 nil。

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

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

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

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

对我来说,当我从 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

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

Alert should be showing while the app is in active state. So check the state is active or not.

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)
  }

From this if a user need message then he can get alert message.

方法(Swift 4):

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)

我使用 APNs 提供程序和 json 负载如下

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

由于提供者将其作为 JSON-defined 字典创建,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)
}

这是我的 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"];
        }
    }
}

Swift 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)