Martin Muldoon Martin Muldoon - 1 year ago 44
Swift Question

How to call Main Thread after an asynchronous request

When I make the following network request the print statement appears to fire before the async. request has completed. I'm trying to call the main thread only after the async request is complete.

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

Answer Source

You need to do the main thread inside your Alamofire response completion block and it should work

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()
    }
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download