Swift 3 - Copy the folder with the contents from the main package to the document directory

I have folders with files inside them in my main set, and I want to copy them / them to the document directory when I first run the application to access them from there. I saw examples, but they are all in Obj-C, and I use Swift 3. How can I do this?

+4
source share
1 answer

I managed to do this 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")
            }
    }
+5
source

Source: https://habr.com/ru/post/1678780/


All Articles