【问题标题】:Swift NSURLSession didFinishDownloadingURL moving from Temp fileSwift NSURLSession didFinishDownloadingURL 从临时文件移动
【发布时间】: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


    【解决方案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】:

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

      【讨论】:

        猜你喜欢
        • 2018-01-02
        • 1970-01-01
        • 2019-01-07
        • 1970-01-01
        • 1970-01-01
        • 2013-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多