NSBundle files with the same name but different Upper / Lower case at first letter - ios

I have been working on a project where I added a file into the app bundle. I didn't relise that the project already included the same name file but with a small difference. The difference is the first letter in name in upper/lower case. I wanted to know how the foundation framework classes load resources in such a case.

Here is a test:
NSString *pathentities = [[NSBundle mainBundle] pathForResource:#"entities" ofType:#"json"];
NSString *pathEntities = [[NSBundle mainBundle] pathForResource:#"Entities" ofType:#"json"];
NSError *error = nil;
NSString *entities = [NSString stringWithContentsOfFile:pathentities encoding:NSUTF8StringEncoding error:&error];
NSString *Entities = [NSString stringWithContentsOfFile:pathEntities encoding:NSUTF8StringEncoding error:&error];
NSLog(#"entities : %# , Entities : %#", entities, Entities);
Entities.json file content: "Entities"
entities.json file content: "entities"
NSLog output:
entities : Entities, Entities : (null)

Related

Could not able to get filePath using Nsfilemanager in Custom FrameWork

I'm working on Apple Watch application, so I have created one custom framework. Currently I'm trying to fetch data from a static JSON file. The JSON file is in my application bundle, but I couldn't parse data from that .json file.
Note: I'm trying to fetch data in custom framework class, my code is here:
NSString *jsonFile = [[NSBundle mainBundle] pathForResource:#"test_json_PCC" ofType:#"json" inDirectory:nil];
NSData *data;
if([[NSFileManager defaultManager] fileExistsAtPath:jsonFile])
{
data = [[NSFileManager defaultManager] contentsAtPath:jsonFile];
}
else
{
NSLog(#"File not exits");
}
I am always getting "File not exits" errors in the console.
try this ....with that u can access the file from your main bundle without using NSFileManager...
NSString *Path = [[NSBundle mainBundle] pathForResource:#"begArray" ofType:#"json"];
contents = [NSMutableString stringWithContentsOfFile:Path
encoding:NSUTF8StringEncoding
error:NULL];//contents is a NSMutableString to store your file data...

Accessing contents of a folder in iOS application bundle

I'm trying to access the contents of a specific folder in my Application Bundle to copy it somewhere else but whenever I go into a folder it seems to be giving me the contents of the entire bundle. Any idea how I can get the contents only in this folder?
My Code
-(void) moveAssets {
NSString * resourcePath = [[NSBundle mainBundle] resourcePath];
NSLog(#"%#", resourcePath);
NSString *newPath = (#"%#/Test/",resourcePath);
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:newPath error:&error];
for (NSString* currentString in directoryContents){
NSLog(#"%#",currentString);
}
}
Logs
Logs keep giving me all the files and not just the ones in the Test folder
Try:
NSString *newPath = [resourcePath stringByAppendingPathComponent:#"Test"];
(reference).

read/write from a .txt file iOS 7 objc

I have this code:
NSString *studentList = _textIn.text;
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:#"ClassOne.txt"];
[studentList writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#", studentList);
NSLog(#"students 1 saved");
I try to write to a text file on the phone system. When I try to read from that file with:
NSError *error;
NSString *strFileContent = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource: #"classOne" ofType: #"txt"] encoding:NSUTF8StringEncoding error:&error];
_textIn.text = strFileContent;
The textfield comes up blank. The NSLog prints what was in the text field but when I try to load it up later the textfield is empty. how do I get the textfield to display what is in the file.
The writing part is alright. You are trying to read the file from your application main bundle instead of your original file path.

writing string to txt file in objective c

Pulling my hair out trying to work this out. i want to read and write a list of numbers to a txt file within my project. however [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error] doesnt appear to write anything to the file. I can see there is the path string returns a file path so it seems to have found it, but just doesnt appear to write anything to the file.
+(void)WriteProductIdToWishList:(NSNumber*)productId {
for (NSString* s in [self GetProductsFromWishList]) {
if([s isEqualToString:[productId stringValue]]) {
//exists already
return;
}
}
NSString *string = [NSString stringWithFormat:#"%#:",productId]; // your string
NSString *path = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
NSError *error = nil;
[string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", error.localizedFailureReason);
// path to your .txt file
// Open output file in append mode:
}
EDIT: path shows as /var/mobile/Applications/CFC1ECEC-2A3D-457D-8BDF-639B79B13429/newAR.app/WishList.txt so does exist. But reading it back with:
NSString *path = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
returns nothing but an empty string.
You're trying to write to a location that is inside your application bundle, which cannot be modified as the bundle is read-only. You need to find a location (in your application's sandbox) that is writeable, and then you'll get the behavior you expect when you call string:WriteToFile:.
Often an application will read a resource from the bundle the first time it's run, copy said file to a suitable location (try the documents folder or temporary folder), and then proceed to modify the file.
So, for example, something along these lines:
// Path for original file in bundle..
NSString *originalPath = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
NSURL *originalURL = [NSURL URLWithString:originalPath];
// Destination for file that is writeable
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *documentsURL = [NSURL URLWithString:documentsDirectory];
NSString *fileNameComponent = [[originalPath pathComponents] lastObject];
NSURL *destinationURL = [documentsURL URLByAppendingPathComponent:fileNameComponent];
// Copy file to new location
NSError *anError;
[[NSFileManager defaultManager] copyItemAtURL:originalURL
toURL:destinationURL
error:&anError];
// Now you can write to the file....
NSString *string = [NSString stringWithFormat:#"%#:", yourString];
NSError *writeError = nil;
[string writeToFile:destinationURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", writeError.localizedFailureReason);
Moving forward (assuming you want to continue to modify the file over time), you'll need to evaluate if the file already exists in the user's document folder, making sure to only copy the file from the bundle when required (otherwise you'll overwrite your modified file with the original bundle copy every time).
To escape from all the hassle with writing to a file in a specific directory, use the NSUserDefaults class to store/retrieve a key-value pair. That way you'd still have hair when you're 64.

how to store an image path in a plist?

I know this is probably a silly question but I'm storing most of my game data in a plist - with that I'd like to include references to images used within my game - same hierarchal level as 'supporting files'. I have different types of images stored in 3 separate folders. One folder for example is called imageclue. How could I store the path in my plist, I'm stuck because I can't just store the path in my plist as string - filename.jpg. I've tried getting the path of the file but when I log it out it .
Sorry if I'm not explaining well and thank you in advance for any help :)
EDIT**
I have a plist file added to my program I don't want to programatically add to it as the images are constants - the screenshots below show a tutorial instead of the filename.jpg (because that won't work seen as my images are stored in a file) I wondered what path name do I use as a string.
The image is from a tutorial off of appcoda.com - where it says thumbnails are the image path files. If you look at where the images are stored on the left - they are stored with the program files. My images are in a folder in there so I'm confused as to what to enter in my plist for the image file.
Hope this clears up what I meant, sorry :)
Store three variables in .h file
#interface YourViewController : UIViewController
{
NSString *folder1;
NSString *folder2;
NSString *folder3;
}
in viewdidload:
-(void) viewdidLoad
{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//getting the folder name:
folder1 = [NSString stringWithFormat:#"%#/imageclue",
documentsDirectory];
folder2 = [NSString stringWithFormat:#"%#/folder2",
documentsDirectory];
folder3 = [NSString stringWithFormat:#"%#/folder3",
documentsDirectory];
}
-(NSArray*) getPlistFromFolder:(NSString*)folder imageName:(NSString*)image
{
NSString *imageTitle = [NSString stringWithFormat:#"%#/image",
folder];
NSArray *data = [[NSArray alloc] initWithContentsOfFile:plistName];
return data;
}
So in the plist file, just store the image name.
Hope this helps...
Do it like this,
NSDictionary *imagePaths = #{#"image 1": [NSHomeDirectory() stringByAppendingPathComponent:#"image 1"]};
[self writeToPlist:imagePaths];
- (void)writeToPlist:imagePaths:(id)plist{
NSError *error;
NSData *data = [NSPropertyListSerialization dataWithPropertyList:plist format:kCFPropertyListXMLFormat_v1_0 options:0 error:&error];
if(error){
NSLog(#"Could not write to file");
return;
}
[data writeToFile:[self plistPath] atomically:YES];
}
Like wise loading is simple as this;
[self loadImagePathForImageNamed:#"image 1"];
- (NSString*)loadImagePathForImageNamed:(NSString*)imageName{
}
- (NSString*)loadImagePathForImageNamed:(NSString*)imageName{
NSData *data = [NSData dataWithContentsOfFile:[self plistPath]];
NSString *error;
NSPropertyListFormat format;
NSDictionary *dictionary = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
if(error){
NSLog(#"Could not open plist %#", error);
return nil;
}
return dictionary[imageName];
}
You may have to handle the error when the file is not there by creating a new one, otherwise this should work.
You are storing path right way, just need to store filename of image with extension in plist when your images are in your Application Bundle, for more reference you can define key name Instead "item1", "item2" in your plist.
Now coming to actual Question, how to access image from plist
Step 1 : Read your recipes.plist from Application Bundle
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"recipes" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:bundlePath];
Step 2 : Now Get Image/Thumbnails name out of it, which you want to load
Step 3 : Define following Function in your Controller, which returns image from name
- (UIImage *)getImageWithName:(NSString *)imageFileName
{
NSString *ext = [imageFileName pathExtension];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:[imageFileName stringByDeletingPathExtension] ofType:ext];
return [UIImage imageWithContentsOfFile:imagePath];
}
HOW TO USE
Suppose you want to load Image with key "Item2" then write following code
NSString *imageFileName = [[dict objectForKey:#"Thumbnail"] valueForKey:#"Item2"];
UIImage *item2Image = [self getImageWithName:imageFileName];
For "Item6"
NSString *imageFileName1 = [[dict objectForKey:#"Thumbnail"] valueForKey:#"Item6"];
UIImage *item6Image = [self getImageWithName:imageFileName1];

Resources