Swift中的HTTP Post

时间:2016-08-03 20:52:35

标签: ios swift http firebase firebase-cloud-messaging

我一直在尝试向Firebase Cloud Messaging Server发送HTTP post请求。这是我一直在使用的代码,我收到了以下响应。根据Firebase文档,该消息应该已发送,但是当我将其发送到我的设备时,而不是在后台,也不在didReceiveRemoteNotification中时,它不会显示。为什么信息不会出现?

Body:Optional({"multicast_id":9176652856657890066,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1470318910131254%0753194407531944"}]})

Error: nil
Success: Optional(1)

以下代码:

let url = NSURL(string: "https://fcm.googleapis.com/fcm/send")!
        let session = NSURLSession.sharedSession()

        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
        let dictionary = ["notification":["title":"BBM","text": message,"project_id": "marketplace-management","registration_id":token!]] as AnyObject
        do {
            try request.HTTPBody = NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted)
        } catch {}
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("key=myKey", forHTTPHeaderField: "Authorization")

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            print("Response: \(response)")
            let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Body: \(strData)")
            print("Error: \(error)")
            var json = NSDictionary()
            do { json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! NSDictionary } catch {}
            let parseJSON = json
            let success = parseJSON["success"] as? Int
            print("Success: \(success)")
        })
        task.resume()

1 个答案:

答案 0 :(得分:2)

    let dictionary = ["notification":["title":"","text": message,"project_id": "myProjectID","to":token]]
    print(dictionary)//["notification": ["title": "", "project_id": "myProjectID", "to": "12", "text": "message"]]
    do {
        try request.HTTPBody = NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted)
    } catch {}