【问题标题】:NSURLDownload: Assertion failed ([path isAbsolutePath]) troublesNSURLDownload: Assertion failed ([path isAbsolutePath]) 麻烦
【发布时间】:2015-09-06 23:04:46
【问题描述】:

我正在尝试从 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)

有什么想法吗?

【问题讨论】:

  • 你应该使用 NSURLSessionDownloadTask 代替。
  • 这是一个 OSX 应用程序。 NSURLSessionDownloadTask 不是更适合 IOS 吗?

标签: macos swift cocoa nsurldownload


【解决方案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 上使用。

使用它的原因是 Apple 不断更新此 Api 以符合最新标准。例如,您无需担心 IPv4 或 IPv6 等问题。这可以避免您的应用出现崩溃和奇怪的行为。

这就是你使用它的方式(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()

注意url是下载图片的路径。

【讨论】:

  • 非常感谢。我会试试这个!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多