【问题标题】:Copying file from temp url to documents directory always throws. NSURLSessionDownloadTask将文件从临时 url 复制到文档目录总是抛出。 NSURLSessionDownloadTask
【发布时间】:2016-07-29 17:06:18
【问题描述】:

我正在使用运行良好的 NSURLSessionDownloadTask 下载文件。当我将图像或视频文件放入临时目录时。但我需要将其移动到永久 URL 才能将其放入照片库。我正在使用 NSFileManagercopyItemAtURL: 没有任何成功。有什么理由会抛出吗?也许文件类型与文档目录不兼容?

let directory : String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]


func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {

    if let fileName = self.file.zOrigFileName {
        let destinationPath = self.directory.stringByAppendingString("/\(fileName)")

        if let destinationURL = NSURL(string: destinationPath) {

            let fileManager = NSFileManager.defaultManager()

            //IF file with same name exists delete it before copying new file
            if fileAlreadyExistsAtURL(destinationURL) {
                do {
                    try fileManager.removeItemAtURL(destinationURL)
                } catch {
                    print("Error Removing Item At \(destinationURL.path)")
                }
            }

            do {
                try fileManager.copyItemAtURL(location, toURL: destinationURL)
                self.saveURLToPhotosLibrary(destinationURL)
            } catch {
                //This is line always printing. my try statement always throwing.
                print("Error Copying Item from \(location.path) to \(destinationURL.path)")
            }
        }
    }
}

这是打印语句。为了安全起见,我将文档目录中的应用程序包 ID 替换为 $(AppId)

复制项目时出错 可选(“/private/var/mobile/Containers/Data/Application/E8D9C365-15D2-40BD-B0B5-​​A000BEDA9F00/Library/Caches/com.apple.nsurlsessiond/Downloads/$(AppID)/CFNetworkDownload_CK3G3Z.tmp”) 到 可选(“/var/mobile/Containers/Data/Application/E8D9C365-15D2-40BD-B0B5-​​A000BEDA9F00/Documents/shortMovie.mov”)

【问题讨论】:

  • 你应该使用 NSURL fileURLWithPath 初始化器
  • 就在我的destinationURL 对象上?不是从函数传入的那个吗?
  • 是的,我只使用 url,但如果你使用路径,你需要使用 fileURLWithPath
  • 顺便说一句,你应该使用downloadTask.response?.suggestedFilename
  • 我去看看。可能是同名,但我想我会使用苹果给我的东西。看起来链接我的初始化程序有效。谢谢你。如果你想写一个答案,我会接受它。也许您可以解释一下NSURL.init(String:)NSURL.init(fileURLWithPath:) 之间的区别。我以为我传递给init(String:) 的字符串应该是代表路径的字符串。

标签: swift nsurlsession nsfilemanager phphotolibrary


【解决方案1】:

您使用了错误的 NSURL 初始化程序。使用路径时,您需要使用 fileURLWithPath 初始化程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多