0

I have a curl post that I'd like to turn into a http url request in swift:

curl post (command line):

curl -X POST --header "Content-Type:application/json" --header "Authorization:key=SERVER_KEY" "https://gcm-http.googleapis.com/gcm/send" --data-ascii '{"to":"DEVICE_TOKEN","data":{"uid":"USER_ID"},"priority":10,"notification":{"body":"Hello","badge":"2"}}'

http request (swift):

var request = URLRequest(url: URL(string: globalClass.getAppDelegate().global.sendUrl)!)
        request.httpMethod = "POST"

var bodyData:String!

bodyData = "title=\(title)&body=\(message)&user_id=\(user_id)"

request.httpBody = bodyData.data(using: .utf8)

let task = URLSession.shared.dataTask(with: request)

how do I put the data part into the bodyData of the http request?

"data":{"uid":"USER_ID"}

I don't know how to form it since it is a nested structure.

1 Answer 1

1

Swift 2

Convert to dictionary:

let title = "somthing"
let body = "body text"
let params = ["title":mail, "body": pass] as Dictionary<String, String>

convert dictionary to JSON:

do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
    } catch {
        print("Error")
    }

Adding headers

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(serverKey, forHTTPHeaderField: "Authorization")

Edit:

convert this JSON to Dictionary:

"notification":{"body":"Hello","badge":"3"}

let notification = ["body": "Hello", "badge":"3"]
let data: [String: AnyObject] = ["notification": notification as AnyObject]
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer. do you know how I would form a nested structure, like this one? "notification":{"body":"Hello","badge":"3"}
@mjpablo23, added to post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.