Sawyer05
Sawyer05

Reputation: 1604

NSURLSessionDownloadTask in swift

Can someone help translating this statement in to Swift for me?

 NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request
            completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {
            // this handler is not executing on the main queue, so we can't do UI directly here
               if (!error) {
                  if ([request.URL isEqual:self.imageURL]) {
                  // UIImage is an exception to the "can't do UI here"
                  UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:localfile]];
                  // but calling "self.image =" is definitely not an exception to that!
                  // so we must dispatch this back to the main queue
                  dispatch_async(dispatch_get_main_queue(), ^{ self.image = image; });
                  }
               }
            }];

should the completionHandler be something like this?

  completionHandler: { (localfile: NSURL!, response: NSURLResponse!, error: NSError!) in ...}

As soon as I entered that it didn't like the colon's.

Upvotes: 1

Views: 2251

Answers (1)

YarGnawh
YarGnawh

Reputation: 4654

var session = NSURLSession.sharedSession()
var request = NSURLRequest(URL: NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk"))

var task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
        if !error {
            var string = NSString(data: data, encoding: 0)
            NSLog("%@", string)
        }
    })

task.resume()

Upvotes: 2

Related Questions