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...
Related
I have the following structure inside my Xcode project in resource navigator which I want to reflect inside my app.
Namely, I want to "scan" inside the "Books" folder and get an NSArray of all the folders in it. The next step is I want to get an NSArray of all the files in each folder.
So far, I've tried using anything, that's connected to NSBundle to get the list of folders, but this gives me wrong results:
NSLog(#"bundle path is %#", [[NSBundle mainBundle] bundlePath]);
NSLog(#"resource path is %#", [[NSBundle mainBundle] resourcePath]);
Both of these methods don't reflect the actual folder structure programmatically.
Is there any way we can do this?
As #rmaddy noted, you should actually have blue folders in your Xcode project and then use the NSDirectoryEnumerator to get a complete list of all the folders.
Here is how I've solved this:
NSURL *bundleURL = [[[NSBundle mainBundle] bundleURL] URLByAppendingPathComponent:#"Books" isDirectory:YES];
NSDirectoryEnumerator *dirEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:bundleURL includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey,nil] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants errorHandler:nil];
for (NSURL *theURL in dirEnumerator){
// Retrieve the file name. From NSURLNameKey, cached during the enumeration.
NSString *folderName;
[theURL getResourceValue:&folderName forKey:NSURLNameKey error:NULL];
// Retrieve whether a directory. From NSURLIsDirectoryKey cached during the enumeration.
NSNumber *isDirectory;
[theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
if([isDirectory boolValue] == YES){
NSLog(#"Name of dir is %#", folderName);
}
}
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).
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"];
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.
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"];