1

我想使用 AFNetworking 快速从 URL 下载文件,并显示下载进度。我有这段代码,但它不起作用:

func downloadPdf()
{
    var request = NSURLRequest(URL: NSURL(string: "http://www.sa.is/media/1039/example.pdf"))
    let session = AFHTTPSessionManager()

    var progress: NSProgress?

    var downloadTask = session.downloadTaskWithRequest(request, progress: &progress, destination: {(file, responce) in self.pathUrl},
        completionHandler:
        {
            response, localfile, error in
            println("response \(response)")
        })

    downloadTask.resume()
}

var pathUrl: NSURL
{
    var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    var url = NSURL(string: path.stringByAppendingPathComponent("file.pdf"))
    println(url.path)
    return url
}

我做错了什么?

4

1 回答 1

3

问题是pathUrl计算属性。如果您打印 URL(而不是url.path),您将看到您的 URL 无效。那是因为您使用的是NSURL(string:),对于文件 URL,您应该使用NSURL(fileURLWithPath:). 因此:

var pathUrl: NSURL {
    let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
    let documentsURL = NSURL(fileURLWithPath: documentsFolder)
    return documentsURL.URLByAppendingPathComponent("file.pdf")
}

或者,更好的是,完全绕过路径,并使用作为 URLURLForDirectory获取:.DocumentDirectory

var pathUrl: NSURL {
    return try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
        .URLByAppendingPathComponent("test.pdf")
}

或者在 Swift 3 中:

var pathUrl: URL {
    return try! FileManager.default.urlForDirectory(.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        .appendingPathComponent("test.pdf")
}
于 2014-07-31T22:51:46.530 回答