简体   繁体   English

URLSession didFinishDownloadingToURL后移动文件失败

[英]Move file failed after URLSession didFinishDownloadingToURL

I am running on the simulator, and I get this error: 我正在模拟器上运行,但出现此错误:

file:///Users/hunterp/Library/Developer/CoreSimulator/Devices/asd3243423-A1A4-4CFB-8A8F-234asdasd/data/Containers/Data/Application/4564561we-5FC5-4718-843B-sdasdwq4134/tmp/CFNetworkDownload_o0xtzV.tmp Moved failed with error: The operation couldn't be completed. 文件:///Users/hunterp/Library/Developer/CoreSimulator/Devices/asd3243423-A1A4-4CFB-8A8F-234asdasd/data/Containers/Data/Application/4564561we-5FC5-4718-843B-sdasdwq4134/tmp/CFNetworkDownload_o0xtzV.tmp移动失败并出现错误:该操作无法完成。 (Cocoa error 4.) (可可错误4。)

and I do: 而我这样做:

    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()

WHERE: 哪里:

   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
    }
}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM