ios - URLSession didFinishDownloadingToURL 后移动文件失败

标签 ios xcode swift

我在模拟器上运行,出现此错误:

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. (Cocoa error 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
    }
}

最佳答案

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

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

关于ios - URLSession didFinishDownloadingToURL 后移动文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30816032/

相关文章:

objective-c - 在应用程序中跨类共享方法的最佳实践是什么?

计算二维数组中的值 - C

swift - 我们可以使用 SwiftUi 构建 iOS Today Extension 吗?

ios - swift UITabbaritem 颜色

ios - 如何检查点击是否发生在特定位置

ios - Swift 使用AlertController在mapView上添加注释

swift - 获取 NSTableView 的第一个可见行

ios - 在 iOS 上使用 Storyboard显示自定义键盘构建

ios - 检测 iPhone 连接的 AirPlay 设备类型

ios - 核心数据: Handling multiple profiles that can customize a prepopulated,静态sql数据库?