How To Read Images From NSMainBundle in iOS - ios

I have the structure like the following in my Xcode project.
I need to read all the images from project and need to store it in array.
I have used the following code from some other StackOverflow posts, but it's not working.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Images"ofType:#""];
NSDirectoryEnumerator *direnum;
direnum = [fileManager enumeratorAtPath: filePath];
imageFolder = [NSMutableArray new];
for(NSString *filename in direnum){
if([[filename pathExtension] isEqualToString:#"png"]){
[imageFolder addObject:filename];
}
}
NSLog(#"Files in the folder %#",imageFolder);
I would appreciate, if any one help me to complete this.

it's simple to get all the images into a array
NSBundle *imageBundle=[NSBundle bundleWithPath: myBundlePath];
NSArray *allImageURLs=[imageBundle URLsForResourcesWithExtension:#"png" subdirectory:nil];

- (NSArray *)pathsForResourcesOfType:(NSString *)extension inDirectory:(NSString *)subpath will get you the array you want.
NSArray *imagesArray = [[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:#"Images"];

You can try below
NSArray *pathArray = [[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:nil];
[pathArray enumerateObjectsUsingBlock:^(NSString *pathString, NSUInteger idx, BOOL *stop) {
UIImage *yourImage = [[UIImage alloc] initWithContentsOfFile:pathString];
}];

Please use this code, hope it will work.
NSString *dirPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"images"];
NSError * error;
NSArray * images = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:dirPath error:&error];

Related

Objective-c accessing values in plist

I'm modifying someone elses code and struggling to access values within a plist, I can access Info.plist etc.. with code such as:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"Info.plist"];
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:finalPath];
NSLog(#"ret=%#", plistData);
However when trying to access Account.plist, it returns null, I'm assuming it's a path issue?
Any help/pointers appreciated.
Here are examples of how to get either a Dictionary or an Array out of a plist.
//*******************************************
- (NSArray *)loadArrayFromPlist:(NSString *)plistName {
NSString *plistPath = [[NSBundle mainBundle] pathForResource: plistName ofType: #"plist"];
return [NSArray arrayWithContentsOfFile: plistPath];
}
//*******************************************
- (NSDictionary *)loadDictionaryFromPlist:(NSString *)plistName {
NSString *plistPath = [[NSBundle mainBundle] pathForResource: plistName ofType: #"plist"];
return [NSDictionary dictionaryWithContentsOfFile: plistPath];
}

NSBundle path for resource return nil in iOS

I've a bgs.bundle which contains 20 images, I'm trying to load image_file.
NSString *bpath = [[NSBundle mainBundle] pathForResource:#"bgs" ofType:#"bundle"];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bpath error:NULL];
for (NSString *fileName in files) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"nil"];
if (filePath){
NSLog(filePath);
}else{
NSLog(#"file path is null");
}
filePath is always null, I've also printed fileName which is working fine.
What can be the problem with my code or there is some other way to load files from bundle?
You main issue is that you attempt to load fileName from the main bundle instead of the bgs.bundle.
Change your code like this:
NSString *bpath = [[NSBundle mainBundle] pathForResource:#"bgs" ofType:#"bundle"];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bpath error:NULL];
for (NSString *fileName in files) {
NSString *filePath = [bpath stringByAppendingPathComponent:fileName];
NSLog(#"filePath = %#", filePath);
}
Another option would be to get an NSBundle for bgs.bundle.
NSString *bpath = [[NSBundle mainBundle] pathForResource:#"bgs" ofType:#"bundle"];
NSBundle bgsBundle = [NSBundle bundleWithPath:bpath];
Now you can use bgsBundle as needed. Example:
NSString *filePath = [bgsBundle pathForResource:#"someImage" ofType:#"png"];

read from .plist file

Got a little problem. I have a .plist file which contain next data
So i cant understand, how i need read first array, than in array read dictionary. Or maybe need rewrite file and change Root key to type dictionary, and read like this:
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:#"Data.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!temp) {
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
self.personName = [temp objectForKey:#"Name"];
self.phoneNumbers = [NSMutableArray arrayWithArray:[temp objectForKey:#"Phones"]];
You can do it by the following code:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSArray *dataArray = [NSArray arrayWithContentsOfFile:plistPath];
This array will contain all the dictionaries, you can get them like:
NSDictionary *dict = [dataArray objectAtIndex:0];
SString *plistFile = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:plistFile];
for(NSDictionary *dictionary in array) {
NSLog(#"%#", dictionary);
}
NSDictionary *item0 = array[0];
NSString *imageName = item[0][#"name"];

Dictionary with contents of file not working in ios

I am trying to get a dictionary from a plist in ios.The problem is the code is not working.It works in a different function but not this one.
NSDictionary* pdata=[NSDictionary dictionaryWithContentsOfFile:datapath];
The file exists at path but for some reason its not working.I get null when I try to print the dictionary.
EDIT: Here is my path/private/var/mobile/Applications/F4D5EFE8-58FC-4179-9492-4C4F9FD01024/Library/Preferences/abc.def.ghi.plist.This is a jailbroken application and I was able to do this successfully for another pplist in a seperate location.
This Should Work Fine.
NSString *plistFileUrl=[[NSBundle mainBundle] pathForResource:#"someplistFile" ofType:#"plist"];
NSURL *url=[NSURL fileURLWithPath:plistFileUrl];
NSDictionary *aDict=[[NSDictionary alloc] initWithContentsOfURL:url];
This must work for you.
NSString *aStr=[[NSBundle mainBundle] pathForResource:#"Property List" ofType:#"plist"];
NSURL *aUrl=[NSURL fileURLWithPath:aStr];
NSDictionary *aDict=[[NSDictionary alloc] initWithContentsOfURL:aUrl];
Try this .
NSDictionary* dict = [NSDictionary dictionaryWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"example" ofType:#"plist"]isDirectory:NO]];
NSLog(#"data is %#",dict);
Try this
//Local mainbundle
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *filePath = [path stringByAppendingPathComponent:#"Contents.plist"];
NSMutableDictionary *dictContent = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
NSLog(#"%#",dictContent);
///DocumentsDirectory
NSMutableDictionary *dictItem=[[NSMutableDictionary alloc]init];
[dictItem setObject:#"ravi" forKey:#"name"];
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *docFilePath = [documentsDirectoryPath
stringByAppendingPathComponent:#"data.plist"];
[dictItem writeToFile:docFilePath atomically: YES];
NSMutableDictionary *dictContent1 = [NSMutableDictionary dictionaryWithContentsOfFile:docFilePath];
NSLog(#"%#",dictContent1);

iOS - Copy specific images from bundle resource path to Documents Dir

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

Resources