首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用NSURLSessionDownloadTask下载文件

用NSURLSessionDownloadTask下载文件
EN

Stack Overflow用户
提问于 2017-11-02 08:57:46
回答 1查看 470关注 0票数 0

我需要下载一个文件与我的桌面应用程序。首先,我创建了一个简单的iOS项目,用于下载视频文件,引用这个网站。它起作用了。我也想为macOS做同样的事情。

代码语言:javascript
复制
class ViewController: NSViewController, URLSessionDownloadDelegate {
    var downloadTask: URLSessionDownloadTask!
    var backgroundSession: URLSession!
    var assetFile = String() // file in application's sandboxed folder

    override func viewDidLoad() {
        super.viewDidLoad()

        let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")
        backgroundSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)
    }

    override func viewDidAppear() {
        super.viewDidAppear()
        let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!
        downloadTask = backgroundSession.downloadTask(with: url)
        downloadTask.resume()
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        let fileManager = FileManager()
        do {
            let assetURL = URL(fileURLWithPath: assetFile)
            try fileManager.moveItem(at: location, to: assetURL)
        } catch {
            print("An error occurred while moving file to destination url")
        }
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        downloadTask = nil
        if (error != nil) {
            print(error!.localizedDescription) // <<< error here?
        } else {
            print("The task finished transferring data successfully")
        }
    }
}

如果我运行它,我会收到一条日志消息,上面写着“未知错误”。我想知道我做错了什么?我确实将App Transport Security Setting > Allow Allow Arbitrary Loads设置为YES。谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-02 10:07:23

当您的应用程序处于沙箱状态时,请确保沙箱功能中启用了传出连接。

ATS设置对HTTPS连接没有影响。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47071142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档