-2

我不知道如何在 swift 中声明以下方法:

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock {

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if ( !error )
                           {
                                UIImage *image = [[UIImage alloc] initWithData:data];
                                completionBlock(YES,image);
                            } else{
                                completionBlock(NO,nil);
                            }
                       }];
}

我从 natashatherobot 博客中找到了这种方法:http: //natashatherobot.com/ios-how-to-download-images-asynchronously-make-uitableview-scroll-fast/

我想快速调用相同的方法,一旦异步请求获取图像,将其传递给完成块。

你有什么建议?

4

1 回答 1

1
func downloadImageWithURL(url: NSURL, completionBlock: (succeeded: Bool, image: UIImage?) -> ()) {
    let request = NSMutableURLRequest(URL: url)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
        if error == nil {
            let image = UIImage(data: data!)
            completionBlock(succeeded: true, image: image!)
        } else {
            completionBlock(succeeded: false, image: nil)
        }
    }
}
于 2015-11-13T12:13:08.580 回答