【问题标题】:using POST API in ios using URLSession在 ios 中使用 POST API 使用 URLSession
【发布时间】:2019-05-29 05:07:55
【问题描述】:

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

"2019-05-29 14:01:25.974883+0900 URLSessionJSONRequests[18165:938499] 任务 . 以错误结束 - 代码:-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,它仍然受支持,我认为服务器不是问题。任何参考或建议将不胜感激!

【问题讨论】:

  • 能否请您在DispatchQueue 中添加会话以将其放入主线程并让我知道。
  • DispatchQueue.main.sync : appCrash, global() : 同样的问题。也许这是因为我遵循了 swift3 教程??
  • 能否请您更新代码以便我可以看到并使用async 而不是sync
  • 请先检查 URL,您在 https 之后错过了 ':'。您的 API URL 应该是 taky.co.kr/login/app_login 而不是 https//taky.co.kr/login/app_login

标签: ios json post urlsession


【解决方案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.";
}

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    相关资源
    最近更新 更多