swift2xcode7documentsinbox

Move Document/Inbox file to another location - Xcode 7, Swift 2


I have a file that is in my Documents/Inbox and is shown in my Print log:

File: file:///private/var/mobile/Containers/Data/Application/5388031B-48B5-48D6-8299-B3FEDC1D7F45/Documents/Inbox/Pizza-6.pdf

I looked here and saw a way to delete files, but I want to move them out of the Inbox folder to another folder I want to create. How would I do this? I can't find anything for iOS and Swift 2. Thank you.


Solution

  • Here is what I ended up doing:

        // MOVING AND SAVING INCOMING PDF TO FILE MANAGER FROM INBOX
    
        let filemgr = NSFileManager.defaultManager()
        let docsDirURL = try! filemgr.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
    
        // Create a new folder in the directory named "Recipes"
        print("Creating new folder...")
        let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
        let newPath = documentsPath.URLByAppendingPathComponent("Recipes")
        do {
            try NSFileManager.defaultManager().createDirectoryAtPath(newPath.path!, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("Unable to create directory \(error.debugDescription)")
        }
    
        // Then check if the Recipes directory exists. If not, create it
        let recipesURL = docsDirURL.URLByAppendingPathComponent("Recipes")
        if !filemgr.fileExistsAtPath(docsDirURL.path!) {
            do {
                try filemgr.createDirectoryAtURL(recipesURL, withIntermediateDirectories: true, attributes: nil)
                print("Directory created at: \(recipesURL)")
            } catch let error as NSError {
                NSLog("Unable to create directory \(error.debugDescription)")
                return
            }
        }
    
        // Move file from Inbox to Recipes Folder
        let incomingFileName = incomingFileTransfer.lastPathComponent!
        let startingURL = incomingFileTransfer
        let savePDFURL = recipesURL.URLByAppendingPathComponent(incomingFileName)
    
        if !filemgr.fileExistsAtPath(savePDFURL.path!) {
            do {
                try filemgr.moveItemAtURL(startingURL, toURL: savePDFURL)
            } catch let error as NSError {
                NSLog("Unable to move file \(error.debugDescription)")
            }
        }