如何在异步请求后调用主线程

时间:2017-08-16 14:20:55

标签: ios swift alamofire

当我发出以下网络请求时,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()
    }
}

1 个答案:

答案 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()
    }
    }