【问题标题】:I can't correctly check the response status from URLSession in func. Swift我无法正确检查 func 中 URLSession 的响应状态。迅速
【发布时间】:2021-05-24 21:13:08
【问题描述】:

函数返回结果为零。我知道它异步工作。我尝试使用completionHandler,但我做得不够好,而且我只有很多错误。在这种情况下如何使用completionHandler?有没有更简单的方法来检查令牌?

func isAuthenticated() -> Bool {
        guard let url = URL(string: self.url + "/api/authenticate") else {
            return false
        }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.addValue("*/*", forHTTPHeaderField: "accept")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue(JWT.getToken(), forHTTPHeaderField: "Authorization")
        
        var result: Bool?
        URLSession.shared.dataTask(with: request){ (data, response, error) in
            guard error == nil else { print(error!.localizedDescription); return }
            let httpResponse = response as! HTTPURLResponse
            if httpResponse.statusCode == 200 {
                result = true
            } else {
                result = false
            }
        }.resume()
        return result!
    }

函数调用:

    if isAuthenticated() {
        self.performSegue(withIdentifier: "loginOK", sender: self)
    }

【问题讨论】:

  • dataTask(with:completion:) 是异步的。您不能这样返回它,因为尚未完成。当您执行if httpResponse.statusCode == 200 时,在print("Did get httpResponse: \(httpResponse.statusCode)") 之前添加,在return result! 之前添加``print("before return")`。哪个会先打印?依你的意见?在现实中?

标签: ios swift session url completionhandler


【解决方案1】:
func isAuthenticated(completion: @escaping (_ success: Bool) -> Void) {
    guard let url = URL(string: self.url + "/api/authenticate") else {
        completion(false)
        return
    }
    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    request.addValue("*/*", forHTTPHeaderField: "accept")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue(JWT.getToken(), forHTTPHeaderField: "Authorization")
    
    URLSession.shared.dataTask(with: request){ (data, response, error) in
        guard error == nil else { print(error!.localizedDescription); return }
        let httpResponse = response as! HTTPURLResponse
        if httpResponse.statusCode == 200 {
            completion(true)
        } else {
            completion(false)
        }
    }.resume()
}

函数调用:

isAuthenticated() { success in
    if success {
        self.performSegue(withIdentifier: "loginOK", sender: self)
    }
}

【讨论】:

  • 我对你的代码进行了一些更改,它可以工作:) apiManager 是类对象,如果成功 { DispatchQueue.main.async { self.performSegue( withIdentifier: "loginOK", 发件人: self) } } }
猜你喜欢
  • 2021-09-26
  • 2021-03-23
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
相关资源
最近更新 更多