在URLSession didFinishDownloadingToURL之后移动文件失败

时间:2015-06-13 07:07:10

标签: ios xcode swift

我在模拟器上运行,我收到此错误:

  

文件:///用户/ hunterp /库/开发商/ CoreSimulator /设备/ asd3243423-A1A4-4CFB-8A8F-234asdasd /数据/容器/数据/应用/ 4564561we-5FC5-4718-843B-sdasdwq4134 / TMP / CFNetworkDownload_o0xtzV.tmp   移动失败并显示错误:无法完成操作。 (可可   错误4。)

我做了:

    var test = DownloadClass(url: s, completionBlock: { (location) -> () in
        println (location)
        var toPath = self.getDocPath().stringByAppendingPathComponent("s.jpg")
        self.moveFile(location.absoluteString!, toThePath: toPath )
        println ("DONE")
    })
    test.start()

其中:

   func moveFile(fromPath: String, toThePath: String) {

        var error: NSError?
        let filemgr = NSFileManager.defaultManager()

        if filemgr.moveItemAtPath(fromPath, toPath: toThePath, error: &error) {
            println("Move successful")
        } else {
            println("Moved failed with error: \(error!.localizedDescription)")
        }
    }

    func getDocPath() -> String {
        return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
    }

class DownloadClass: NSObject,NSURLSessionDelegate,NSURLSessionDownloadDelegate {
    var session:NSURLSession?
    var downloadUrl:String
    var completion:(NSURL)->()
    init(url:String,completionBlock:(location:NSURL)->()){
        completion = completionBlock
        downloadUrl = url
        super.init()
        session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil)
    }
    func start(){
        let request = NSURLRequest(URL: NSURL(string: downloadUrl)!);
        let downloadTask = session!.downloadTaskWithRequest(request)
        downloadTask.resume()
    }
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        completion(location)
    }
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        //here get progress
    }
}

1 个答案:

答案 0 :(得分:0)

将移动路径代码更改为此,它将起作用

self.moveFile(location.path!, toThePath: toPath )