I am trying to get selected files from bundle resourcePath on application launch. I am able to get all the files at resource path but when i try to get files with name stored in BGImage.plist i get error "cocoa 260" (item not found at specified path).
But images are present at the path and I can get all the images by doing [fileManager copyItemAtPath:bundlePath toPath:BGImagePath error:nil];
code below doesnt work.. (reference : iPhone (iOS): copying files from main bundle to documents folder error )
NSString* BGImagePath =[[[AppDelegate applicationDocumentsDirectory]
URLByAppendingPathComponent:#"BGImages" isDirectory:YES]
path];
NSFileManager* fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:BGImagePath error:&error];
NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
NSString *BundleImagePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"BGImages.plist"]; //has file names
bgImagesArray = [[NSArray arrayWithContentsOfFile:BundleImagePath] retain];
if (folderContents.count == 0) {
for (id obj in bgImagesArray) {
NSError* error;
if ([fileManager
copyItemAtPath:[bundlePath :obj]
toPath:[BGImagePath stringByAppendingPathComponent:obj]
error:&error])
NSLog(#" *-> %#", [bundlePath stringByAppendingPathComponent:obj]);
}
}
}
Is there any other elegant way to get specific files without storing names in plist?
This following code fixed the issue:
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* bgImagePath =[[[AppDelegate applicationDocumentsDirectory]
URLByAppendingPathComponent:#"BGImages" isDirectory:YES]
path];
[fileManager createDirectoryAtPath:bgImagePath withIntermediateDirectories:NO attributes:nil error:nil];
NSArray * folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bgImagePath error:nil];
NSString * bundlePath = [[NSBundle mainBundle] resourcePath];
NSString * bundleImagePath = [[NSBundle mainBundle] pathForResource:#"BGImages" ofType:#"plist"];
NSArray* bgImagesArray = [NSArray arrayWithContentsOfFile:bundleImagePath];
if (folderContents.count == 0) {
[bgImagesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString * sourcePath = [bundlePath stringByAppendingPathComponent:obj];
NSString * destinationPath = [bgImagePath stringByAppendingPathComponent:obj];
[fileManager copyItemAtPath:sourcePath toPath:destinationPath error:nil];
}];
}
Related
I have unzipped a file and sent to my documents directory:
[SSZipArchive unzipFileAtPath:path toDestination:destinationPath];
In the unzipped file there will be 5 different types of files. I only want to know the path and file name for the file with an extension type of '.shp'.
I've tried the following:
NSString *filePath = [[NSBundle mainBundle] pathForResource:destinationPath ofType:#"shp"];
Afterwards, I would like to delete all the contents of the files in that folder.
Any ideas? Thanks in advance.
First, get all directory files.
NSString *bundle = [[NSBundle mainBundle] bundlePath];
NSFileManager * aMan = [NSFileManager defaultManager];
NSArray * allFiles = [aMan contentsOfDirectoryAtPath: bundle];
Then it is possible to filter needed extension with one of following methods:
NSPredicate *filter = [NSPredicate predicateWithFormat:#"self ENDSWITH '.shp'"];
NSArray *filtered = [allFiles filteredArrayUsingPredicate:filter];
Next - delete files, looping filtered. But it looks not good for me.
So, I prefer this one:
NSError *error;
for (NSString * elem in allFiles) {
if ([[elem pathExtension] isEqualToString:#"shp"])
[aMan removeItemAtPath:[bundle stringByAppendingPathComponent:elem] error:&error];
Hope, it helps
You can use NSFileManager to remove the files:
NSFileManager * fileManager = [[NSFileManager alloc]init];
[fileManager removeItemAtPath:#"your path" error:nil];
You can do it in the following way:
NSURL *baseURL = [NSURL URLWithString:destinationPath];
NSDirectoryEnumerator* filesEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:baseURL includingPropertiesForKeys:#[] options:0 errorHandler:nil];
NSURL* fileURL;
while (fileURL = [filesEnumerator nextObject]) {
NSString* file = [fileURL lastPathComponent];
BOOL match = [file containsString:#".shp"];
if (match) {
[[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
}
}
Please let me know if it resolves the problem..
I have a framework that expects a .string file from the Project that it is imported to. How do I save a .string file from my app's [NSBundle mainBundle] to NSLibraryDirectory, and then have the framework read it from NSLibraryDirectory?
Thank you
Thanks #iOS_Developer for the writing part.
NSString *resourcepath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"filename.strings"];
NSString *filePath = [kSXBFileManLibraryDirectoryPath stringByAppendingPathComponent:#"filename.strings"];
Write:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
if ([fileManager copyItemAtPath: resourcepath toPath:destination error:&error]){
NSLog(#"Copy Success");
}
else{
NSLog(#"Copy error: %#", error);
}
Read:
NSString *newPath = [kLibraryDirectoryPath stringByAppendingPathComponent:#"filename.strings"];
NSDictionary *contents = [NSDictionary dictionaryWithContentsOfFile:newPath];
NSLog(#"contents:%#", [contents objectForKey:#"login.background"]);
where;
#define kLibraryDirectoryPath [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject]
filename.strings
"login.background" = "FE8100";
"login.textField" = "FE8100";
"login.button" = "1B0D62";
You can get path to bundle Directory and Library directory and Move file from bundle to Library directory with CopyItemAtPath
NSArray *libraryPath=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *directoryPath = [libraryPath objectAtIndex:0];
NSString *imagePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Templete.string"];
// Copy the image Folder from the package to the users filesystem
[fileManager copyItemAtPath:imagePathFromApp toPath:directoryPath error:nil];
I have PDFs in my project. I want to give feature to download that file to mobile directory and load it with other apps.
You can directly used your image if it is in app bunldle like,
UIImage *img = [UIImage imageNamed:#"Amy.png"];
If you want to load pdf in webview from app bundle then you can do something like,
NSString *path = [[NSBundle mainBundle] pathForResource:#"yourPdfName" ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
In short if you have files available in app bundle then you not need to copy it to documentDirectory because it will use double memory, you can direct used it from bundle.
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
//NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/RTOFiles"];;
if (![[NSFileManager defaultManager] fileExistsAtPath:documentsDir])
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDir withIntermediateDirectories:NO attributes:nil error:&error];
NSString *pdfName = #"form_1.pdf";
NSString *docPdfFilePath = [documentsDir stringByAppendingPathComponent: pdfName];
//Using NSFileManager we can perform many file system operations.
BOOL success = [fileManager fileExistsAtPath: docPdfFilePath];
if (!success) {
NSString *samplePdfFile = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: pdfName];
success = [fileManager copyItemAtPath: samplePdfFile toPath: docPdfFilePath error: &error];
if (!success)
// NSAssert1(0, #"Failed to copy file ‘%#’.", [error localizedDescription]);
NSLog(#"Failed to copy %# file, error %#", pdfName, [error localizedDescription]);
else {
NSLog(#"%# File copied to %#", pdfName,documentsDir);
}
}
else{
NSLog(#"File already Exists !");
}
I am having an app in which I have a folder named "Images" in my main bundle.
In This folder there is another folder called "Images1" containing some images.
When my app Launch I want the folder "Images" on the documents directory.
I want to fetch images from the folder "Images1".
But I can't get my images in the folder "Images" at documents directory with the following code.
Edited
BOOL success1;
NSFileManager *fileManager1 = [NSFileManager defaultManager];
NSError *error1;
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *writableDBPath1 = [documentsDirectory1 stringByAppendingPathComponent:#"Images/Images1"];
success1 = [fileManager fileExistsAtPath:writableDBPath1];
if (success1) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Images/Images1"];
NSLog(#"Default : %#",defaultDBPath1);
success1 = [fileManager1 copyItemAtPath:defaultDBPath1 toPath:writableDBPath1 error:&error1];
if (!success1) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error1 localizedDescription]);
}
Please help me.
Are you sure that you have the files in your folder tree?
NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"/Images/Images1"];
usually when xcode make a package it flatten the directory contents. So first check you have all the things in your source folder. Even if you see that the folder is shown in your package explorer, when copied in the app, you will see the images are in the root folder. To avoid this, when you add the Image folder, in your xcode project, you can check the option to 'create folder reference'.
However, your write may fail because of an overwrite. In that case you have to implement a delegate method for NSFileManager given below.
- (void) copyFolder {
BOOL success1;
NSFileManager *fileManager1 = [NSFileManager defaultManager];
fileManager1.delegate = self;
NSError *error1;
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *writableDBPath1 = [documentsDirectory1 stringByAppendingPathComponent:#"/Images"];
success1 = [fileManager1 fileExistsAtPath:writableDBPath1];
if (success1 )
{
NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Images"];
NSLog(#"default path %#",defaultDBPath1);
success1 = [fileManager1 copyItemAtPath:defaultDBPath1 toPath:writableDBPath1 error:&error1];
} else {
if (![[NSFileManager defaultManager] fileExistsAtPath:writableDBPath1])
[[NSFileManager defaultManager] createDirectoryAtPath:writableDBPath1 withIntermediateDirectories:NO attributes:nil error:&error1];
}
}
- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath{
if ([error code] == 516) //error code for: The operation couldn’t be completed. File exists
return YES;
else
return NO;
}
I want to retrieve in an array of the name of the files in Resources folder that have the .html extension. I have done this:
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Resources"];
NSError *error = nil;
NSArray *documentArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
for (int i=0; i < [documentArray count] - 1; i++) {
NSLog(#"value %#", [documentArray objectAtIndex:i]);
}
But the for loop displays continously null. Anyone knows how can I get this task right? thank you
Don't use NSHomeDirectory. Use [[NSBundle mainBundle] resourcePath] to get path to app's resources.
Edited: here's your example code.
NSString *resPath = [[NSBundle mainBundle] resourcePath];
NSError *error = nil;
NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:resPath error:&error];
if (!error)
{
for (NSString * filename in filenames)
{
NSString *extension = [filename pathExtension];
if ([extension isEqualToString:#"html"])
{
NSLog(#"%#", filename);
}
}
}