Swift:如何同步下载?

标签 swift

我正在使用以下代码来下载一些文件:

    let url = NSURL(string:"https://www.example.org/")!
    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
        if error != nil {
            NSLog("%@", "Error: \(error)");
            return
        }

        NSLog("Loaded %i bytes", data!.length)
    }
    task.resume()

我想处理一些文件并在下载后退出我的应用程序。因此我需要知道下载过程何时完成。最好的是,如果有一种方法可以同步执行此操作(没问题,如果 UI 被阻止 - 它只是一个带有进度条的闪屏)。但据我经过一番研究后了解这个主题,这在 Swift 中不再可能了......

我确实将此代码包装在一个函数中,因此我不能只在 NSLog 语句后添加一些代码。我需要知道的是:最后一个文件什么时候完成下载?我怎样才能检索这些信息?

编辑:这段代码确实对我有用(但要注意,它已被弃用!):

    // download file synchonously ////////////////////////////////////////////////////
    func downloadSync(fromURL: String, toPath: String) {
        let request = NSURLRequest(URL: NSURL(string: fromURL)!)
        var response: NSURLResponse?
        do {
            let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
            data.writeToFile(toPath, atomically: true)
        } catch {
            print("Error while trying to download following file: " + fromURL)
        }
    }

最佳答案

调用task.resume()后,下载开始。

当下载完成(或收到错误)时,代码 在 { } 内调用以下 dataTaskWithURL。这是一个闭包,并且被异步调用。

let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
    // This code is executed asynchronously after data has been received
}
task.resume()

在闭包内你会收到 3 个参数:

  1. data:您请求的NSData
  2. 响应:整个 NSURLResponse
  3. 错误:一个 NSError 对象

这 3 个值是可选的,因此可能是 nil

E.g. error could be populated and data could be nil.

同步方式[iOS 9中已弃用]

此方法在 iOS 9 中已被弃用,您不应该使用它,但是这里是代码

var response: NSURLResponse?
var error: NSError?
let urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)

关于Swift:如何同步下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37978773/

相关文章:

ios - MLKit文本检测异常-[Not A Type _cfTypeID] : message sent to deallocated instance 0x106623e20

ios - 选择第二个单元格时首先调用 Swift UITableViewController didSelectRow

ios - 快速设置模型类属性的值

swift - 在沙盒 macOS 应用程序的 ApplicationScripts 目录中创建文件

ios - 如何将 stackViews 添加到 UITableViewCell?

ios - 如何在 xcode 中将图像覆盖在图像上?

ios - 如何更改 UISearchBar 取消按钮的文本颜色?

swift - 转换字符串!到字符串

ios - 使用 Storyboard 更改导航栏中的后退按钮标签?

swift - 为什么 iOS SpriteKit 场景/ View 坐标在 iOS 7.1 和 iOS 8 之间不同?