SergeH
SergeH

Reputation: 618

Swift 3 - Copy Folder w/ contents from Main Bundle to Documents Directory

I have folders with files inside them in my main bundle, and I want to copy/cut them to the Documents Directory at first launch of the application to access them from there. I've seen examples but they're all in Obj-C and I'm using Swift 3. How can I do this?

Upvotes: 12

Views: 4215

Answers (2)

Tomm P
Tomm P

Reputation: 826

There is a built in FileManager function to do this.

"If the item at srcURL is a directory, this method copies the directory and all of its contents, including any hidden files."

do {
   let docsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
   let sourceURL = Bundle.main.resourceURL!.appendingPathComponent("sourceDir").absoluteURL
   let destinationURL = docsURL.appendingPathComponent("destDir").absoluteURL
               
   try FileManager.default.copyItem(at: sourceURL, to: destinationURL)     
} catch {
   print("\nError\n")
}

Upvotes: 2

SergeH
SergeH

Reputation: 618

I managed to do it using 2 functions:

func copyFolders() {
    let filemgr = FileManager.default
    filemgr.delegate = self
    let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
    let docsURL = dirPaths[0]

    let folderPath = Bundle.main.resourceURL!.appendingPathComponent("Test").path
    let docsFolder = docsURL.appendingPathComponent("Test").path
    copyFiles(pathFromBundle: folderPath, pathDestDocs: docsFolder)
}

func copyFiles(pathFromBundle : String, pathDestDocs: String) {
    let fileManagerIs = FileManager.default
    fileManagerIs.delegate = self

    do {
        let filelist = try fileManagerIs.contentsOfDirectory(atPath: pathFromBundle)
        try? fileManagerIs.copyItem(atPath: pathFromBundle, toPath: pathDestDocs)

        for filename in filelist {
            try? fileManagerIs.copyItem(atPath: "\(pathFromBundle)/\(filename)", toPath: "\(pathDestDocs)/\(filename)")
        }
    } catch {
        print("\nError\n")
    }
}

Upvotes: 13

Related Questions