Ios: Copy a File in Documents Folder

IOS: copy a file in documents folder

Copies txtFile from resource to document if not already present.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:@"txtFile.txt"];

if ([fileManager fileExistsAtPath:txtPath] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"txtFile" ofType:@"txt"];
[fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
}

If you want to overwrite every time then try this:

if ([fileManager fileExistsAtPath:txtPath] == YES) {
[fileManager removeItemAtPath:txtPath error:&error];
}

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"txtFile" ofType:@"txt"];
[fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];

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];
}
}

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 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)

iPhone: How to copy a file from resources to documents?

I just ran into this myself a few days ago. Don't force things down the Path path, embrace the NSURL path. It won't take but a short time to get how to use them.

As to the method, it's simply asking the system to hand you a URL to the standardized documents directory for the application. Use this and most everything regarding where you put new files will be correct.

iOS , Copying files from Inbox folder to Document path

If your app needs to open a file coming from another App you need to implement delegate method

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

and move the url to the folder of your choice inside your App.

let url = url.standardizedFileURL  // this will strip out the private from your url
// if you need to know which app is sending the file or decide if you will open in place or not you need to check the options
let openInPlace = options[.openInPlace] as? Bool == true
let sourceApplication = options[.sourceApplication] as? String
let annotation = options[.annotation] as? [String: Any]
// checking the options info
print("openInPlace:", openInPlace)
print("sourceApplication:", sourceApplication ?? "")
print("annotation:", annotation ?? "")

Moving the file out of the inbox to your destination URL in your case the documents directory appending the url.lastPathComponent:

do {
try FileManager.default.moveItem(at: url, to: destinationURL)
print(url.path)
print("file moved from:", url, "to:", destinationURL)

} catch {
print(error)
return false
}

return true

How to copy a bundle html file to a document directory in iOS Swift?

I have just done this code in a test project which works.

You should ensure that you are performing checks along the way and ensure that your HTML file is in your Copy resources build phase

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

moveHtmlFile()
}

private func moveHtmlFile() {
let fileManager = FileManager.default
let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
guard let sourcePath = Bundle.main.path(forResource: "index", ofType: "html") else {
return
}

if fileManager.fileExists(atPath: sourcePath) {
let sourceUrl = URL(fileURLWithPath: sourcePath)
try? fileManager.createDirectory(atPath: documentsDirectory.appendingPathComponent("www").path,
withIntermediateDirectories: false,
attributes: nil)
let destination = documentsDirectory.appendingPathComponent("www/index.html", isDirectory: false)
try? fileManager.copyItem(at: sourceUrl, to: destination)

if fileManager.fileExists(atPath: destination.path) {
print("file copied")
} else {
print("file copy failed")
}
}
}

}

Result:

Sample Image

How to copy a file from URL to document folder?

NSFileManager can only handle local paths. It won't do anything useful if you give it a URL.

copyItemAtPath:toPath:error: takes an error parameter. Use it, like this:

NSError *error;
if (![fileManager copyItemAtPath:urlText toPath:filePath error:&error]) {
NSLog(@"Error %@", error);
}

You would then get this error:

Error Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be
completed. (Cocoa error 260.)" UserInfo=0x9a83c00 {NSFilePath=http://www.abc.com/text.txt,
NSUnderlyingError=0x9a83b80 "The operation couldn’t be completed.
No such file or directory"}

It can't read the file at http://www.abc.com/text.txt, because it is not a valid path.


as Sunny Shah stated without explanation you have to fetch the object at the URL first:

NSString *urlText = @"http://www.abc.com/text.txt";

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSURL *url = [NSURL URLWithString:urlText];
NSError *error;
NSData *data = [[NSData alloc] initWithContentsOfURL:url options:0 error:&error];
if (!data) { // check if download has failed
NSLog(@"Error fetching file %@", error);
}
else {
// successful download
if (![data writeToFile:filePath options:NSDataWritingAtomic error:&error]) { // check if writing failed
NSLog(@"Error writing file %@", error);
}
else {
NSLog(@"File saved.");
}
}
}

Always check for errors!

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")
}
}


Related Topics



Leave a reply



Submit