Search code examples
iosjsonposturlsession

using POST API in ios using URLSession


I'm learning IOS right now and I completely wrote same code with the tutorial. But I got an error like this

"2019-05-29 14:01:25.974883+0900 URLSessionJSONRequests[18165:938499] Task <0EC532CF-8CA6-42C9-9BD8-6D6E74BB9C06>.<10> finished with error - code: -1002"

My Code is this.

@IBAction func onPostTab(_ sender: UIButton) {

    let parameters = ["id":"[email protected]","pw":"1q2w3e4r"]

    guard let url = URL(string:"https//taky.co.kr/login/app_login") else{return}
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])else{
        return}
    request.httpBody = httpBody
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)

        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [] )
                print(json)
            }catch{
                print(error)
            }
        }
    }.resume()


}

what is error code -1002?? I used placeholder API and it is still supported and I think the server is not the problem. Any reference or advice would be grateful!


Solution

  • Kindly check URL first you missed ':' after https.

    Just replace your API End-point

    https//taky.co.kr/login/app_login

    With

    https://taky.co.kr/login/app_login

    After doing the above changes everything works fine.

    API Response:

    <NSHTTPURLResponse: 0x60000327d120> { URL: https://taky.co.kr/login/app_login } { Status Code: 200, Headers {
        "Cache-Control" =     (
            "no-store, no-cache, must-revalidate"
        );
        Connection =     (
            "Keep-Alive"
        );
        "Content-Encoding" =     (
            gzip
        );
        "Content-Length" =     (
            93
        );
        "Content-Type" =     (
            "text/html; charset=UTF-8"
        );
        Date =     (
            "Wed, 29 May 2019 05:32:58 GMT"
        );
        Expires =     (
            "Thu, 19 Nov 1981 08:52:00 GMT"
        );
        "Keep-Alive" =     (
            "timeout=5, max=100"
        );
        Pragma =     (
            "no-cache"
        );
        Server =     (
            "Apache/2.4.18 (Ubuntu)"
        );
        "Set-Cookie" =     (
            "cookie=9f73o1c13mggukb15fq25usfpc6ms6cp; expires=Wed, 29-May-2019 09:32:58 GMT; Max-Age=14400; path=/; HttpOnly"
        );
        Vary =     (
            "Accept-Encoding"
        );
    } }
    {
        code = E01;
        message = "\Uc544\Uc774\Ub514\Ub97c \Uc785\Ub825\Ud574 \Uc8fc\Uc138\Uc694.";
    }