Swift 中的 HTTP Post

HTTP Post in Swift

我一直在尝试向 Firebase 云消息服务器发送 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()
    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 {}