【发布时间】:2015-02-22 04:03:49
【问题描述】:
我正在尝试使用 NSURL 库和以下函数下载文件。它曾经将其存储在临时文件夹中,因此在文件被删除之前我无法访问它们。
我正在尝试将下载的文件重新定位到 Documents 目录中,但是当我尝试将 NSData 打印为 NSString 时,它返回 nil。我不明白下面的代码有什么问题。
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
//create a NSFileManager Instance
let fileManager = NSFileManager.alloc()
//Get documents directory URL
let documentsUrl:NSArray = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentsDirectory:NSURL = documentsUrl.firstObject as NSURL
//Get the file name and create a destination URL
let sendingFileName = downloadTask.originalRequest.URL
//convert sendingFileName into String
let fileString = sendingFileName.absoluteString
let destinationURL = documentsDirectory.URLByAppendingPathComponent(fileString!)
//Hold this file as an NSData and write it to the new location
let fileData = NSData(contentsOfURL: location)
let fileDataString = NSString(data: fileData!, encoding: NSUTF8StringEncoding)
println(fileDataString)
fileData?.writeToURL(destinationURL, atomically: false)
}
【问题讨论】:
标签: ios swift download nsurl temporary