Can`t copy file from bundle to documents directory in iOS
The problem is this line:
let fullDestPathString = String(fullDestPath)
It should be:
let fullDestPathString = fullDestPath.path
Look at the error. The problem is the destination. Notice the file:///
. Your code is not properly converting the URL to a file path. You need to use the path
property of NSURL
to get the path as a string.
In all of your debugging and checking, you never verified the value of fullDestPathString
.
Error trying to copy from bundle to documents directory
Your code is almost correct. It has two flaws with this line:
NSString *destination = [[[Utils applicationDocumentsDirectory] absoluteString] stringByAppendingString:@"myapp.sqlite"];
The use of absoluteString
is incorrect. This gives a file URL in the form file://path/to/Documents/
. You need to use the path
method to get a file path (not file URL) form the NSURL
.
Then you need to properly append the filename to the path. You need to use stringByAppendingPathComponent:
instead of stringByAppendingString:
.
That line should be:
NSString *destination = [[[Utils applicationDocumentsDirectory] path] stringByAppendingPathComponent:@"myapp.sqlite"];
Swift: How to copy files from app bundle to Documents folder when app runs for first time
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")
how to copy file from main bundle to Document Folder
I don't think your documents folder is updating because an older version of that db exists. You can purge your documents directory with the following method, and add it to the top of your viewDidLoad:
- (void)viewDidLoad
{
[self purgeDocumentsDirectory];
[self CopyDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)purgeDocumentsDirectory
{
NSLog(@"Purging Documents Directory...");
NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error = nil;
for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
[[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
}
}
Can't copy files from main bundle to documents directory on iPad
You cannot add files or folder to the NSBundle after it has been built. For the device, Xcode is going to sign the NSBundle. Whatever files and folders you want in the NSBundle on the device will have to be added to your Xcode project.
The other way to add files/folders to your NSBundle is during the build phase before the bundle is signed.
Copy all the bundle resources to a separate folder inside the Documents directory
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.
How can i copy Folder from Project to Document Directory ios swift
Please below code..
I update your code in two functions to copy all files from folder to document directory.
Hope it will work.
func copyFolders() {
let fileManager = FileManager.default
let documentsUrl = fileManager.urls(for: .documentDirectory,
in: .userDomainMask)
guard documentsUrl.count != 0 else {
return // Could not find documents URL
}
let finalDatabaseURL = documentsUrl.first!.appendingPathComponent("Stickers")
if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
print("DB does not exist in documents folder")
let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("Stickers")
do {
if !FileManager.default.fileExists(atPath:(finalDatabaseURL?.path)!)
{
try FileManager.default.createDirectory(atPath: (finalDatabaseURL.path), withIntermediateDirectories: false, attributes: nil)
}
copyFiles(pathFromBundle: (documentsURL?.path)!, pathDestDocs: finalDatabaseURL.path)
} catch let error as NSError {
print("Couldn't copy file to final location! Error:\(error.description)")
}
} else {
print("Database file found at path: \(finalDatabaseURL.path)")
}
}
func copyFiles(pathFromBundle : String, pathDestDocs: String) {
let fileManagerIs = FileManager.default
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")
}
}
How to copy files from a directory to iphone document directory
Use this code:
let fileManager = NSFileManager.defaultManager()
var error : NSError?
var doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
let destinationPath = doumentDirectoryPath.stringByAppendingPathComponent("LocalDatabase1.sqlite")
let sourcePath = NSBundle.mainBundle().pathForResource("LocalDatabase", ofType: "sqlite")
fileManager.copyItemAtPath(sourcePath!, toPath: destinationPath, error: &error)
Related Topics
How to Instantiate and Load a View Controller Before Segueing to It Using Swift
Avcapturevideopreviewlayer Add Overlays and Capture Photo in iOS
Programmatically Auto-Connect to Wifi iOS
iOS Swift Avplayer Inside Uiview How to Make It Work
Format String with Variadic Arguments
Why Does It Take Such a Long Time for UI to Be Updated from Background Thread
Advise Where to Store Data for iOS App
Swift/How to Call Delegate with Popviewcontroller
Uitableview with Different Optional Sections
Uicollectionview Cells with Images Inside Uitableview Prototype
Find Delegate in a Swift Array of Delegates
Convert Nsdate to String with a Specific Timezone in Swift
Changing Constraint When Keyboard Appears - Swift
Uitest Color of a Label (Not UI Label)
Vnfaceobservation Boundingbox Not Scaling in Portrait Mode
Swift:How to Find the Position(X,Y) of a Letter in a Uilabel