M
M
Mimuss2017-01-06 00:33:43
iOS
Mimuss, 2017-01-06 00:33:43

How to make post request swift?

There is this code:

import Foundation

var request = URLRequest(url: URL(string: "https://translate.yandex.net/api/v1.5/tr.json/translate")!)
request.httpMethod = "POST"
let key = "trnsl.1.1.20170105T183003Z.a061e235d7abde36.51b76f0ff88678b7d1cdd254edd2951b4fb00dbf"
let postString = "key=" + key + "&text=Hello&lang=en-ru"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {                                                 // check for fundamental networking error
        print("error=\(error)")
        return
    }
    
    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
        print("statusCode should be 200, but is \(httpStatus.statusCode)")
        print("response = \(response)")
    }
    
    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(responseString)")
}
task.resume()

which should execute a request for api yandex translator
and return in JSON or XLM format
In general, the problem is that I do not understand how to correctly send a POST request in swift (I have never done this in any language)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
flyup2high, 2017-01-12
@Mimuss

Actually catch:
Pod Alamofire
https://cocoapods.org/?q=alamofire
Pod SwiftyJSON
https://cocoapods.org/?q=json
Pod SwiftyXMLParser
https://cocoapods.org/?q=lang%3Aswift%20XML
Well and in addition put RealmSwifty to store data
https://cocoapods.org/?q=Realm
I think you will figure out how to throw them into the project.
And yes, when you drive on the simulator in the plist, allow connections to the network.

I
illuzor, 2017-01-06
@iLLuzor

There is a library called alamofire. With her, everything is elementary.

T
tegrato, 2020-09-19
@tegrato

Here is a simple working example: https://www.youtube.com/watch?v=0bV9r1rY2cw (watch the second half of the video, the first one talks about GET)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question