53

当我收到这样的远程通知时,我实现了一个打开 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 开发。我现在搜索了几个小时,但没有找到任何有用的信息。通知工作得很好..如果我点击它,警报视图就会打开。我的问题是,我无法从 userInfo 中获取数据。

4

7 回答 7

117

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

请参阅推送通知文档

于 2015-02-19T00:18:28.940 回答
10

斯威夫特 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)
于 2020-06-10T13:21:27.237 回答
9

方法(斯威夫特 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)
于 2018-08-10T02:19:45.897 回答
4

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

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
于 2016-09-21T10:40:12.337 回答
1

这是我的 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"];
        }
    }
}
于 2020-02-04T11:36:25.850 回答
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)
  }

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

于 2018-01-05T11:39:46.887 回答
0

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

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

由于提供者将其作为一个 JSON 定义的字典,iOS 将其转换为一个NSDictionary对象,没有下标 like Dictionary,但可以使用value(forKey:)

这里参考

这是我的 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)
}
于 2019-05-19T09:16:40.197 回答