Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to copy files from app bundle to Documents folder when app runs for first time

Tags:

ios

swift

There are all sorts of sample code & questions on SO dealing with how to programmatically copy files in Obj-C from the app bundle to the application's sandboxed Documents folder (e.g. here, here, and here) when the application runs for the first time.

How do you do this in Swift?

like image 862
MMac Avatar asked Jan 02 '19 21:01

MMac


Video Answer


2 Answers

You could use FileManager API:

Here's example with a function that copies all files with specified extension:

func copyFilesFromBundleToDocumentsFolderWith(fileExtension: String) {
    if let resPath = Bundle.main.resourcePath {
        do {
            let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
            let filteredFiles = dirContents.filter{ $0.contains(fileExtension)}
            for fileName in filteredFiles {
                if let documentsURL = documentsURL {
                    let sourceURL = Bundle.main.bundleURL.appendingPathComponent(fileName)
                    let destURL = documentsURL.appendingPathComponent(fileName)
                    do { try FileManager.default.copyItem(at: sourceURL, to: destURL) } catch { }
                }
            }
        } catch { }
    }
}

Usage:

copyFilesFromBundleToDocumentsFolderWith(fileExtension: ".txt")
like image 118
Brooketa Avatar answered Nov 15 '22 22:11

Brooketa


For Swift 4.2:

Assuming the file in your App Bundle is called Some File.txt

In ViewDidLoad, add:

let docName = "Some File"
let docExt = "txt"
copyFileToDocumentsFolder(nameForFile: docName, extForFile: docExt)

and then create a function as follows:

func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {

    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let destURL = documentsURL!.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
    guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
        else {
            print("Source File not found.")
            return
    }
        let fileManager = FileManager.default
        do {
            try fileManager.copyItem(at: sourceURL, to: destURL)
        } catch {
            print("Unable to copy file")
        }
}
like image 41
MMac Avatar answered Nov 15 '22 23:11

MMac