Swift读取远程通知的userInfo

3k1*_*3k1 49 json push-notification userinfo ios swift

当我收到这样的远程通知时,我实现了一个打开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()
}
Run Code Online (Sandbox Code Playgroud)

但NotificationMessage总是零.

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

{"aps":{"alert":"Testmessage","badge":"1"}}
Run Code Online (Sandbox Code Playgroud)

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

Cra*_*ord 104

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
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅推送通知文档


小智 9

方法(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
}
Run Code Online (Sandbox Code Playgroud)

用法:

let info = self.extractUserInfo(userInfo: userInfo)
print(info.title)
print(info.body)
Run Code Online (Sandbox Code Playgroud)


小智 7

斯威夫特 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

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