Bawpotter Bawpotter - 1 year ago 169
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



Error: nil
Success: Optional(1)

Code Below:

let url = NSURL(string: "")!
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)")

Answer Source
    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 {}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download