Search code examples
iosobjective-cnsfilemanagernsbundlensdocumentdirectory

Copy all the bundle resources to a separate folder inside the Documents directory


What is the correct way of copying all the files contained in the Bundle (not the [NSBundle mainBundle]) and putting them to a newly created directory inside the Documents directory?


Solution

  • You need to copy the items one by one, it's fairly straightforward.

    let bundle: Bundle = ... // Whatever bundle you want to copy from
        guard let resourceURL = bundle.resourceURL else { return }
    let fileManager = FileManager.default
    do {
        let documentsDirectory = try fileManager.url(for: .documentDirectory,
                                                     in: .userDomainMask,
                                                     appropriateFor: nil,
                                                     create: false)
        let destination = documentsDirectory.appendingPathComponent("BundleResourcesCopy", isDirectory: true)
    
        var isDirectory: ObjCBool = false
        if fileManager.fileExists(atPath: destination.path, isDirectory: &isDirectory) {
            assert(isDirectory.boolValue)
        } else {
            try fileManager.createDirectory(at: destination, withIntermediateDirectories: false)
        }
    
        let resources = try fileManager.contentsOfDirectory(at: resourceURL, includingPropertiesForKeys: nil)
        for resource in resources {
            print("Copy \(resource) to \(destination.appendingPathComponent(resource.lastPathComponent))")
            try fileManager.copyItem(at: resource,
                                     to: destination.appendingPathComponent(resource.lastPathComponent))
        }
    } catch {
        print(error)
    }
    

    Depending on the size of the bundle this could take some time to perform, so you may want to perform this on a background thread.