Show an Alert in iOS 10-Swift 3.0 After Making a RestFul API Call

54 sec read

Recently we were developing a simple iOS 10 app to send/receive data to a RESTFul API.
All we wanted to do was, simple make a POST request to an API and display its result.
When we tried it to display the result in an Alert box, the app got crashed with the error “Terminating app due to uncaught exception ‘NSInternalInconsistencyException'”. How I fixed it?

App image screenshot
What I initially tried and that was crashing:
[source lang=java]
let responseString = String(data: data, encoding: .utf8)
// Print to console
print(“API 1 – responseString = \(responseString)”)
// Show it as iOS10 Alert
self.result_label.text = self.result_label.text + “\n\n\n” + “\(responseString)”
[/source]
What I tried was:
[source lang=java]
let responseString = String(data: data, encoding: .utf8)
// Print to console
print(“API 1 – responseString = \(responseString)”)
DispatchQueue.main.async {
// Show it as iOS10 Alert
self.result_label.text = self.result_label.text + “\n\n\n” + “\(responseString)”
}
[/source]
What exactly made it work ?
As you can see we added a new code line with DispatchQueue.main.async which helps us to make this alert from an blocking call.
DispatchQueue manages the execution of work items. Each work item submitted to a queue is processed on a pool of threads managed by the system.
UI updates can be only performed on the main thread. On performing UI updates on a background thread,we would face “Terminating app due to uncaught exception “NSInternalInconsistencyException” or “Assertion failure”, this could be avoided by using DispatchQueue method that would make the background thread now the main thread.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *