0
votes

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

1
You should use NSURL fileURLWithPath initializer - Leo Dabus
Just on my destinationURL object? Not the one thats passed in from the function right? - NSGangster
Yes I would work only with url but if you are working with paths you need to use fileURLWithPath - Leo Dabus
Btw you should use downloadTask.response?.suggestedFilename - Leo Dabus
I'll take a look. Likely its the same name, but I suppose I'll use what apple gives me. And it looks like chainging my initializer worked. Thank you. If you want to write an answer I'll accept it. Maybe you can explain what the difference between NSURL.init(String:) and NSURL.init(fileURLWithPath:). I thought the String I passed in to init(String:) was supposed to be the string representing the path. - NSGangster

1 Answers

1
votes

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