ios - NSURLSessionDownloadTask 快速完成

标签 ios objective-c swift

有人可以帮我把这个语句翻译成 Swift 吗?

 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; });
                  }
               }
            }];

completionHandler 应该是这样的吗?

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

我一输入它就不喜欢冒号的。

最佳答案

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()

关于ios - NSURLSessionDownloadTask 快速完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24416245/

相关文章:

ios - 如何过滤在 Core Data 中有对象的 TableView ?

ios - iBeacon Bluetooth didEnterRegion 和 didExitRegion 方法永远不会触发

iphone - 停止后台线程的CFRunLoop

objective-c - 有什么方法可以将 NSArray 传递给需要可变数量参数的方法,例如 +stringWithFormat :

iphone - [self.tableView reloadData] 处的 EXC_BAD_ACCESS

ios - UITableViewCell textLabel 在选择时改变位置

ios - iOS 中有哪些用户统计数据?

ios - 如何在 ios 中使用 google Analytics,而无需在所有库中扩展库 GAY Tracked ViewController

iphone - AFNetworking SPARQL查询失败,URL错误

ios - 如何使用存储在 CocoaTouch 框架中的 Localizable.strings?