I can get the contents of a .txt file in this way:
NSString *articlePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#".txt"];
return [NSString stringWithContentsOfFile:articlePath encoding:NSUTF8StringEncoding error:nil];
However,it is no use when the file is a markdown file:
NSString *articlePath = [[NSBundle mainBundle] pathForResource:#"test2" ofType:#".md"];
return [NSString stringWithContentsOfFile:articlePath encoding:NSUTF8StringEncoding error:nil];
The articlePath is "nil",but the file is exist actually.
I wonder if there any method I can use to get the contents of a .md file.
Thanks in advance.
Go to : Target -> "Build Phases" -> "copy bundle Resources" Then add that particular file here.
Make sure that test2 file is there
Related
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..
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 have created a custom plist named as test.plist in Supporting Files folder. In that i stored App product name and App version number.
Now, how could i get product name from test.plist for PRODUCT NAME in Build Settings in Target.
I can get values from user defined build settings. But i don't want that.
Note: I need to store product name in test.plist only. And others can access the value from this file.
Thanks in Advance..
you can read the values from the plist in main bundle, put below code in viewDidLoad , method, Please note that all files in main bundle are read only if you want to write any data to plist then you have to copy it to app's document directory
NSString *bundle = [[NSBundle mainBundle] pathForResource:#”test” ofType:#”plist”];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:bundle];
NSString *productName = [dict objectForKey:#"ProductName"];
NSString * appVersion = [dict objectForKey:#"AppVersion"];
Another way is to read app properties
NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleDisplayName"];
NSString appVersion = [NSString stringWithFormat:#"Version %# (%#)", [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"], kRevisionNumber];
Hope it helps!
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.
Can't understand, why does this line of the code return (null)?
// Get path of data.plist file to be created
plistPath = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"];
I need to create new plist but can't understand, does the empty file should be created before to get the path to it.. Any ideas?
PS I had only h,m and no plist files in my project now.
You don't create new files in your bundle after deployment. The bundle contains all the resources and files that ship with your app.
Instead, you create new files in your app's Documents folder. To get the documents folder path, you can use a method like this (as included in some of the app template projects):
- (NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
Then you simply append the file name you want to use.
NSString *path = [self applicationDocumentsDirectory];
path = [path stringByAppendingPathComponent:#"data.plist"];
You might also want to have some additional folders in your Documents folder for organizational purposes. You can use NSFileManager to do that.
Yes, your guess was right - you would need to create a file first. Here is what the class reference documentation had to say about the method's return value
"Return Value
The full pathname for the resource file or nil if the file could not be located."
You could do something like:
if ( [ [NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"] )
plistPath = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"];
else
// Create new file here
Also, you could leave out the type extenxion in the method call above if you are searching for a unique file name.
Source: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/Reference/Reference.html