Swift NSURLSession didFinishDownloadingURL从Temp文件移动

时间:2015-02-22 04:03:50

标签: ios swift download nsurl temporary

我正在尝试使用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)


}

3 个答案:

答案 0 :(得分:1)

//Get documents directory URL
let documentsDirectoryUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL

let sourceUrl = NSURL(string:"https://dl.dropboxusercontent.com/u/87285547/timerApp.zip")!

//Get the file name and create a destination URL
let fileName = sourceUrl.lastPathComponent!
let destinationURL = documentsDirectoryUrl.URLByAppendingPathComponent(fileName)

//Hold this file as an NSData and write it to the new location
if let fileData = NSData(contentsOfURL: sourceUrl) {
    fileData.writeToURL(destinationURL, atomically: false)   // true
    println(destinationURL.path!)
}

答案 1 :(得分:1)

这也应该有用。

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)

答案 2 :(得分:0)

您应该使用NSFileManager.defaultManager()。如果您打印出目标网址,它会说什么?