Bawpotter Bawpotter - 4 months ago 28
HTTP Question

HTTP Post in Swift

I've been trying to send an HTTP post request to the Firebase Cloud Messaging Server. This is the code I've been working with, but it doesn't seem to be working. What am I doing wrong?/Is there better code I should be using to accomplish this?

EDIT: Well, now I'm getting this response. According to Firebase docs the message should have sent, except that it's not showing up when I send it to my devices, not in the background, nor in

didReceiveRemoteNotification
.

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

Error: nil
Success: Optional(1)


Code Below:

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()

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