NSBundle pathForResource: returns nil - ios

I am attempting to access a .txt file from my supporting files folder in Xcode on iOS using the following piece of code:
NSString* filePath = #"filename.txt";
NSLog(#"File path: %#", filePath);
NSString* fileRoot = [[NSBundle mainBundle] pathForResource:filePath ofType:#"txt"];
NSLog(#"File root: %#", fileRoot);
The first NSLog prints just what I expect it to print, but the last NSLog always simply prints
File root: (null)
Accessing text from the file after (attempting to) reading it into memory also simply gives me a (null) printout.
The solution for this problem is probably right under my nose, I just can't seem to find it. Any help is very appreciated! Thanks in advance.

filePath already contains the suffix ".txt", therefore you must not specify it
again when locating the resource. Either
NSString* filePath = #"filename.txt";
NSString* fileRoot = [[NSBundle mainBundle] pathForResource:filePath ofType:nil];
or
NSString* filePath = #"filename";
NSString* fileRoot = [[NSBundle mainBundle] pathForResource:filePath ofType:#"txt"];

Related

Read info.plist in custom framework

I want to read the files contained within the framework info.plist my own creation. When I try to read, the rferans it've read his file info.plist framework applications.
I need to read both. How can I do it? Could you help?
NSLog(#"*** %#", [[[NSBundle mainBundle] localizedInfoDictionary] valueForKey:#"ASD"]);
NSLog(#"*** %#", [[[NSBundle mainBundle] infoDictionary] valueForKey:#"ASD"]);
NSLog(#"*** %#", [[[[NSBundle allFrameworks] objectAtIndex:0] infoDictionary] valueForKey:#"ASD"]);
First create bundle by using your framework path:
NSString* mainBundlePath = [[NSBundle mainBundle] resourcePath];
NSString* frameworkBundlePath = [mainBundlePath stringByAppendingPathComponent:#"YourFrameworkBundle.bundle"];
frameworkBundle = [NSBundle bundleWithPath:frameworkBundlePath];
Then access Info Dictionary or what you want
Thank you for your answers.
Solution are as shown below:
[[[NSBundle bundleForClass:[self class]] infoDictionary] objectForKey:#"ASD"]

How to read .m file as NSString in iOS

I am trying to display an implementation file(Code inside the .m file) in UITextView. Below is the code snippet i used. But it returns nil.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"TextCheck.m" ofType:#"m"];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"TextCheck.m" ofType:#"m"];
Replace the code as below line :
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"TextCheck" ofType:#"m"];
I really doubt you can do this. The source code is not a 'resource'..When you execute the app they are in binary form.. there is no code in there..
If you need to do display something that you know already - try storing the text/code you intend to display in a plain file and display..

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

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.

File I/O on iPad

Experts.. a newb question
I have developed a GIS like app which runs perfectly within Xcode and iPad simulator environment. Now I want to test on a real iPAD. I have gone through the provisioning certificates process and able to run the app on my device. The problem comes up when the program tries to read a file which is on my development computer (file path is something like /Users/user/Document/data.txt).
Can I copy that "data.txt" file to ipad and if I can, what will be it's path for I/O.
Thanks for your help.
KAS
You will add it to your application. and it will be in the bundle.
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"data" ofType:#"txt"]];
After you load it up, Parse it with a string.
You can use NSScanner to parse your string
NSString *fileName = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"txt"];
NSError *error = nil;
NSString *myData = [NSString stringWithContentsOfFile:fileName encoding:NSASCIIStringEncoding error:&error];
NSScanner *myScanner = [NSScanner scannerWithString:myData];
int myNewInt = 0;
if ([myScanner scanInt:&myNewInt])
{
//Do Something with my New Int
}
You can include the file in your project then access it. To get the full file path:
NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];
NSString *filePath = [appFolderPath stringByAppendingPathComponent:#"data.txt"];

Resources