如何使用完成块在swift中声明此方法?

时间:2015-11-13 11:45:14

标签: swift completionhandler

我无法找到如何在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/

我想在swift中调用相同的方法,一旦异步请求将图像传递给completionBlock。

你会建议什么?

1 个答案:

答案 0 :(得分: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)
        }
    }
}