0

我正在尝试从 Internet 下载文件并将其放在应用程序支持目录下的应用程序名称目录中,但我不断收到

Assertion failed: ([path isAbsolutePath]), function -[NSURLDownload     setDestination:allowOverwrite:], file /SourceCache/CFNetwork/CFNetwork-720.5.7/Foundation/NSURLDownload.mm, line 370.

这是我写的代码:

    var imageRequest = NSURLRequest(URL: self.source)
    var imageDownload = NSURLDownload(request: imageRequest, delegate:self)
    var error: NSError? = NSError()

    /* does path exist */
    let directoryPath = self.destination.stringByDeletingLastPathComponent
    let fileMgr = NSFileManager();
    fileMgr.createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil, error: &error)
    imageDownload.setDestination(self.destination, allowOverwrite: true);

当我单步执行代码时,一切看起来都是正确的。self.source 是 (https://remoteDomain.com/img/downloadimage.jpg) 一个 NSURL

self.destination 是我系统中的完整路径(文件:/Users/ryan/Library/Application%20Support/AppName/downloadimage.jpg)

有任何想法吗?

4

1 回答 1

1

要回答您的特定主题的问题:错误消息说您的路径无效。为图像创建路径的正确方法如下:

let fileManager = NSFileManager.defaultManager()

var folder = "~/Library/Application Support/[APPNAME]/someFolder" as NSString
folder = folder.stringByExpandingTildeInPath

if fileManager.fileExistsAtPath(folder as String) == false {
    do {
        try fileManager.createDirectoryAtPath(folder as String, withIntermediateDirectories: true, attributes: nil)
    }

    catch {
       //Deal with the error
    }
}

但是 @jtbandes 是对的。您应该使用NSURLSessionDownloadTask来下载您的文件。它是 的一部分,Foundation.framework可在 OS X、iOS 和 watchOS 上使用。

The reason to use it is that Apple keeps updating this Api to meet the latest standards. For example, you don't need to worry about IPv4 or IPv6 etc. This avoids crashes and weird behavior in your app.

This is how you use it (Swift):

var imageRequest = NSURLRequest(URL: self.source)
let session = NSURLSession.sharedSession()
let downloadTask = session.downloadTaskWithRequest(imageRequest) { (url: NSURL?, response: NSURLResponse?, error: NSError?) -> Void in
    //Work with data
}

downloadTask.resume()

Note that url is the path to the downloaded image.

于 2015-09-07T04:09:54.363 回答