-2

I can't find out how to declare the following method in 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);
                            }
                       }];
}

I found this method from natashatherobot blog : http://natashatherobot.com/ios-how-to-download-images-asynchronously-make-uitableview-scroll-fast/

I would like to call same method in swift and once the asynchronous request gets the image pass it to the completionBlock.

What would you suggest ?

2

1 Answer 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)
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks dude, you rock ! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.