macos - NSURLDownload:断言失败([path isAbsolutePath])麻烦

标签 macos swift cocoa nsurldownload

我试图从互联网上下载一个文件并将其放在应用程序支持目录下的应用程序名称目录中,但我不断收到

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)

有什么想法吗?

最佳答案

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

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 是下载图像的路径。

关于macos - NSURLDownload:断言失败([path isAbsolutePath])麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32429123/

相关文章:

swift - 无法使用类型为 'encode' 的参数列表调用 'NSAttributedString'

macos - 使用 AppleScript 在 Safari 中选择文件

macos - Raspberry PI 和 Mac OSx 之间的屏幕共享

SwiftUI : text gets cut off with "..." in my view

ios - swift : Crashes due to no superview 中的 VFL 约束

swift - 在 swift cocoa 中将 m3u8 视频保存到磁盘

cocoa - NSWorkspace setIcon :forFile:options: crashes

objective-c - 接收者类型 'WebFrame' 例如消息是前向声明

css - 如果 outline-style 设置为 "solid"(而不是 "auto"),则 Chrome 上的轮廓绘制不正确

macos - PDF文档删除PageAtIndex : is not working when updated to Mac OS X 10. 11