在使用AlamoFire发出请求并访问完成块上的UI元素时,我没有得到任何警告,但是,如果我在没有AlamoFire的情况下尝试做同样的事情,我会得到“UILabel.text必须仅在主线程中使用“,我想知道这里发生了什么?
AlamoFire示例
makeRequest(parameters:parameters,URL:.request){
validatedResponse in
label.text = "anything"
}
private func makeRequest(parameters:[String:Any]?,URL:URLs,requestType:requestType,method:HTTPMethod , completion: @escaping (_ response:APIResponse) -> ())
{
APIinterface.afManager.request(
baseUrl + URL.rawValue,
method: method,
parameters: parameters
)
.validate()
.validate(contentType: ["application/json"])
.responseJSON
{
response in
debugPrint(response)
guard let validatedResponse = self.validateResponseForAPI(response: response) else { return }
//let validatedResponse = (requestType == .api) ?
// : self.validateExternalResponse(response: response)
completion(validatedResponse)
}
}
原生示例
makeRequest(parameters:parameters,URL:.request){
validatedResponse in
label.text = "anything"
}
private func makeRequest(parameters:[String:Any]?,url:URLs,requestType:requestType,method:HTTPMethod , completion: @escaping (_ response:ResponseObject?) -> ())
{
guard let url = URL(string:baseUrl + url.rawValue) else
{
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest, completionHandler:
{
(data, response, error) in
// do stuff with response, data & error here
print(response)
print(error)
completion(self.validateResponseForAPISwift4(response: data))
})
task.resume()
}
答案 0 :(得分:1)
除非另有说明,否则Alamofire回调总是在主线程上执行。这就是为什么你在使用Alamofire时没有收到警告的原因。