Recently I was doing a project in swift and had to download images from a website over the network, I remember in Objective-C I could do something like this to achieve async downloads and then update the main UI:
- (void)loadImage:(NSString *)stringUrl completion:(void (^)(UIImage *image))completion {
[[[NSOperationQueue alloc] init] addOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:stringUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
completion(image);
}];
}];
}
And here is what I have so far in Swift:
public func loadImage(completion: @escaping (UIImage) -> Void) {
DispatchQueue.global().async {
do {
if let url = URL(string: self.url) {
let imageData = try Data(contentsOf: url)
if let myImage = UIImage(data: imageData) {
DispatchQueue.main.async {
completion(myImage)
}
}
}
}
catch {
print("error loading image: \(error)")
}
}
}
I am curious as to whether or not the swift version is more or less doing the same thing as I think it is. Mainly should I be using the .sync() or .async() methods on globals() and main()?