我想在swift中使用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
}
我做错了什么?
答案 0 :(得分:3)
问题是pathUrl
计算属性。如果您打印网址(而不是url.path
),则会看到您的网址无效。这是因为您使用的是NSURL(string:)
,而对于文件网址,您应该使用NSURL(fileURLWithPath:)
。因此:
var pathUrl: NSURL {
let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let documentsURL = NSURL(fileURLWithPath: documentsFolder)
return documentsURL.URLByAppendingPathComponent("file.pdf")
}
或者,更好的是,完全绕过路径,并使用URLForDirectory
将.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")
}