我正在尝试使用 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)
}
最佳答案
这也应该有效。
let fileManager = NSFileManager.defaultManager()
//Get documents directory URL
let documentsDirectory = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL
// Check if file exist
if (fileManager.fileExistsAtPath(documentsDirectory)){
fileManager.removeItemAtURL(NSURL(documentsDirectory), error: nil)
}
// Copy File From Temp Folder To Documents Directory
fileManager.copyItemAtURL(location, toURL: NSURL(fileURLWithPath: documentsDirectory), error: &error)
关于ios - Swift NSURLSession didFinishDownloadingURL 从临时文件移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654405/