Skip to content

Instantly share code, notes, and snippets.

@anoop4real
Last active November 16, 2022 08:34
Show Gist options
  • Save anoop4real/b50bfe47d8e78bc26de8f0bd324e8fc3 to your computer and use it in GitHub Desktop.
Save anoop4real/b50bfe47d8e78bc26de8f0bd324e8fc3 to your computer and use it in GitHub Desktop.
Swift3: Utility functions to copy a folder and its contents from resources to documents
func copyFolder(){
// Get the resource folder
if let resourceMainPath = Bundle.main.resourcePath{
var isDirectory = ObjCBool(true)
// Get the path of the folder to copy
let originPath = (resourceMainPath as NSString).appendingPathComponent("NameOfFolder")
// Get the destination path, here copying to Caches
let destinationPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
// Append the folder name to dest path so that system creates the directory if it doesnt exist
let destPath = (destinationPath as NSString).appendingPathComponent("/NameOfFolder")
let fileManager = FileManager.default
if fileManager.fileExists(atPath: destPath, isDirectory:&isDirectory ){
// If an overwrite behavior is needed, remove and copy again here
print("Exists")
}else{
// Do the copy
do {
try fileManager.copyItem(atPath: originPath, toPath: destPath)
}catch let error{
print(error.localizedDescription)
}
}
}else{
}
}
func copyTheFolder(){
// Get the resource folder
if let resourceMainURL = Bundle.main.resourceURL{
var isDirectory = ObjCBool(true)
// Get the path of the folder to copy
let originPath = resourceMainURL.appendingPathComponent("NameOfFolder")
// Get the destination path, here copying to Caches
let destinationPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
// Append the folder name to dest path so that system creates the directory if it doesnt exist
let destURL = URL(fileURLWithPath: destinationPath).appendingPathComponent("/NameOfFolder")
let fileManager = FileManager.default
if fileManager.fileExists(atPath: destURL.path, isDirectory:&isDirectory ){
// If an overwrite behavior is needed, remove and copy again here
print("Exists")
}else{
// Do the copy
do {
try fileManager.copyItem(at: originPath, to: destURL)
}catch let error{
print(error.localizedDescription)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment