当我发出以下网络请求时,print语句似乎在异步之前触发。请求已完成。我只是在异步请求完成后才尝试调用主线程。
func getRating (articleID: String) {
let endPointURL = "http://www.smarttapp.com/DesktopModules/DnnSharp/DnnApiEndpoint/Api.ashx?method=GetRating"
let encodedarticleIDURL = endPointURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let myURL = URL(string: encodedarticleIDURL)
Alamofire.request(
myURL!,
parameters: ["articleID": articleID]
)
.responseData { response in
guard response.result.isSuccess else {
return
}
if let data = response.data, let myDataString = String(data: data, encoding: .utf8) {
print("MyDataString is: \(myDataString)")
let newRating = Double(myDataString)!
self.post.rating = newRating
print(newRating)
}
}
DispatchQueue.main.async {
print("Final value \(self.post.rating)")
self.networkingState = .finishedSearching
self.tableView.reloadData()
}
}
答案 0 :(得分:1)
您需要在Alamofire响应完成块中执行主线程,它应该可以正常工作
Alamofire.request(
myURL!,
parameters: ["articleID": articleID]
)
.responseData { response in
guard response.result.isSuccess else {
return
}
if let data = response.data, let myDataString = String(data: data, encoding: .utf8) {
print("MyDataString is: \(myDataString)")
let newRating = Double(myDataString)!
self.post.rating = newRating
print(newRating)
}
DispatchQueue.main.async {
print("Final value \(self.post.rating)")
self.networkingState = .finishedSearching
self.tableView.reloadData()
}
}