Search code examples
swiftnsurlsessionnsfilemanagerphphotolibrary

Copying file from temp url to documents directory always throws. NSURLSessionDownloadTask


I'm downloading a file using NSURLSessionDownloadTask which is working great. As I get my image or video file into a temp directory. But I need to move it to a permanent URL in order to put it into photos library. I'm using NSFileManager 's copyItemAtURL: without any success. Any reason it would throw? Perhaps file type is not compatible with documents directory?

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

Here is the print statement. For security I'm replacing app bundle id from documents directory with $(AppId)

Error Copying Item from Optional("/private/var/mobile/Containers/Data/Application/E8D9C365-15D2-40BD-B0B5-A000BEDA9F00/Library/Caches/com.apple.nsurlsessiond/Downloads/$(AppID)/CFNetworkDownload_CK3G3Z.tmp") to Optional("/var/mobile/Containers/Data/Application/E8D9C365-15D2-40BD-B0B5-A000BEDA9F00/Documents/shortMovie.mov")


Solution

  • You are using the wrong NSURL initializer. When working wit paths you need to use the fileURLWithPath initializer.