What does this mean? I tried this... still, it gives me the same message:
DispatchQueue.main.async {
if let imageData = try? Data(contentsOf: url) {
self.image = UIImage(data: imageData)
}
}
What does this mean? I tried this... still, it gives me the same message:
DispatchQueue.main.async {
if let imageData = try? Data(contentsOf: url) {
self.image = UIImage(data: imageData)
}
}
As the message says, this means that the Data(contentsOf:)
call will not return until it got the data, which could be slow if the image is large and the network slow. As you called this function from the main thread, the whole app UI would freeze for several seconds in the worst case.
The compiler/runtime is just helping you to avoid this potential pitfall by returning this error message containing clear indications on how to solve the issue : use URLSession.shared.dataTask(with:completionHandler:)
instead of Data(contentsOf:)
.
func setImageFromStringrURL(stringUrl: String) {
if let url = URL(fromString: stringUrl) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
// Error handling...
guard let imageData = data else { return }
DispatchQueue.main.async {
self.image = UIImage(data: imageData)
}
}.resume()
}
}
This method won't block the main thread. Instead, it will schedule the network call to be performed on a background thread and will execute the callback you provided (responsible of updated the UI) once the data is fetched.
As the callback is also executed on the background thread and UI updates must be made on the main thread you still need to explicitly schedule the UI updates to be executed on the main thread with DispatchQueue.main.async
.