在使用URLSession的iOS中使用POST API

时间:2019-05-29 05:07:55

标签: ios json post urlsession

我现在正在学习IOS,并且与本教程完全编写了相同的代码。但是我遇到了这样的错误

  

“ 2019-05-29 14:01:25.974883 + 0900 URLSessionJSONRequests [18165:938499]   任务<0EC532CF-8CA6-42C9-9BD8-6D6E74BB9C06>。<10>完成并出现错误-   代码:-1002“

我的代码是这个。

@IBAction func onPostTab(_ sender: UIButton) {

    let parameters = ["id":"uuzaza@naver.com","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()


}

什么是错误代码-1002?我使用了占位符API,仍然支持它,我认为服务器不是问题。任何参考或建议将不胜感激!

1 个答案:

答案 0 :(得分:1)

请先检查网址,然后再错过https后的“:”。

只需更换您的API端点

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

使用

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

完成上述更改后,一切正常。

API响应:

<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.";
}