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 は常に nil です。

私の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 に答える
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からメッセージを抽出するために使用した違いです。詳細については、以下を参照してください -alertbody

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 に答える