-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 ?

nhgrif
  • 61,578
  • 25
  • 134
  • 173
Sam
  • 1,101
  • 2
  • 13
  • 26
  • 1
    so you are asking how to define a block in swift? – luk2302 Nov 13 '15 at 11:47
  • 3
    Possible duplicate of [How to use NSURLConnection completionHandler with swift](http://stackoverflow.com/questions/24016714/how-to-use-nsurlconnection-completionhandler-with-swift) – NSNoob Nov 13 '15 at 11:49

1 Answers1

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)
        }
    }
}
Drizztneko
  • 161
  • 7