最近我在swift做了一个项目,不得不通过网络从网站上下载图像,我记得在Objective-C中我可以做这样的事情来实现异步下载,然后更新主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);
}];
}];
}
这就是我目前在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)")
}
}
}
我很好奇swift版本是否或多或少地做了我认为的同样的事情。主要应该在globals()和main()上使用.sync()或.async()方法吗?