How to create a NSMutableDictionary using dictionaryWithContentsOfFile: method - iphone

I want create and return a dictionary using the keys and values found in a file specified by a given path. I have my file on my Desktop:ciudades.txt (a human readable file!!! no a xml, just for practice). What method of my NSString i need to use and how? Please can somebody help me filling on my code the XXXXXXX. Thanks in advance
- (NSMutableDictionary)ciudades
{
if (!ciudades) {
NSString *path = [NSString XXXXXXXXX];
ciudades = [NSMutableDictionary dictionaryWithContentsOfFile:path];
}

Define a function.
-(NSMutableDictionary*) ReadFileAsDictionaryForPath:(NSString* ) path
{
return [NSMutableDictionary dictionaryWithContentsOfFile:path];
}
Use it as below
NSString *path = [[NSBundle mainBundle] pathForResource:#"MyFile" ofType:#"txt"];
NSMutableDictionary* myDictionary = [self ReadFileAsDictionaryForPath:path];
if(!myDictionary)
{
NSLog(#"Error while reading data from file at path:%#",path);
}

First add that file to your application bundle By adding a existing file from xcode to your project. Then use this method to get the file path for example I'm getting a image's path.
NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:#"png"];
then try the dictionaryWithContentsOfFile method and see if it works or not.

Related

Data persistance tableView issue iPhone(reading and writing to plist)

In my application I want to implement a simple Alarm function. I know how to use UILocalNotifications, but I came across this source code with a like UI of the iPhone's native Clock app alarm area as well as it having a believe a type of data persistence. Two things I am not good at interface design and data persistence this source code has. But I downloaded it and started playing around with it to find the alarms are not persistent.
Download
Does anyone know how the source code can be adjusted so that it is persistent and the plist can be saved and read to and from? I am open to learning too, this area is somewhat unknown to me too. Thanks
I review your code and find issue that you not moved your "Alarms.plist" file form resource to document directory. we are not able to edit file which is in resource folder. so write following code in app delegate file.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *theFileName = #"Alarms.plist"; //Change this appropriately
NSString *oldPath = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];//[NSString stringWithFormat:#"%#/Inbox/%#", documentsDirectory, theFileName];
NSString *newPath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, theFileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:newPath])
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];
Perform save operation on file which is in Document directory folder.
try this code... to save plist from bundle to Document Directory
Notice that you will have "Unable to read... " just at the first app launch
- (NSMutableArray *)displayedObjects
{
if (_displayedObjects == nil)
{
NSString *path = [[self class] pathForDocumentWithName:#"Alarms.plist"];
NSArray *alarmDicts = [NSMutableArray arrayWithContentsOfFile:path];
if (alarmDicts == nil)
{
NSLog(#"Unable to read plist file: %#", path);
NSLog(#"copy Alarms.plist to: %#", path);
NSString *pathToSetingbundle = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];
[[NSFileManager defaultManager]copyItemAtPath:pathToSetingbundle toPath:path error:nil];
}
_displayedObjects = [[NSMutableArray alloc]
initWithCapacity:[alarmDicts count]];
for (NSDictionary *currDict in alarmDicts)
{
Alarm *alarm = [[Alarm alloc] initWithDictionary:currDict];
[_displayedObjects addObject:alarm];
NSLog(#"#disply obj %#", alarm);
}
}
return _displayedObjects;
}

iOS - how to read entire content of an html resource file into an NSString *?

I want to put the content of my html resource file into an NSString object. Is it possible and advisable to do that? How could it be done?
Possible? - yes
Advisable? - unless it is an extremely large file, why not?
How? - There is already a method to do it for you in NSString - stringWithContentsOfFile:encoding:error:.
See the snippet below:
NSError* error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource: #"foo" ofType: #"html"];
NSString *res = [NSString stringWithContentsOfFile: path encoding:NSUTF8StringEncoding error: &error];

Multiple SQLite Databases for Multiple Languages?

I would like to implement a multi language support for my app. So I created the Localizing.strings file and all that stuff and translated my interface. So far so good …
Now I want to duplicate my database in order to have a *.db-file for every single language. So I did and then I clicked via XCode on the "+" under the Localization tab. I now have a *.db-file in my en.lproj and de.lproj folder.
My problem: If I want to copy the db-files to the app's documents directory the *.db file is not available of course because it is in the *.lproj-folder. Is there any command to get the right lproj-folder?
To clarify my needs:
This doesn't work
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"mydatabase.db"]
… this does:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"de.lproj/mydatabase.db"]
… but I don't want to add the "de.lproj" and "en.lproj" etc. manually. Is there any way to fix it dynamically?
just do the following:
NSString *dbpathResource =
[[NSBundle mainBundle] pathForResource:#"databaseName" ofType:#"db"];
and if you have your localized .db file in xx.lproj so the correct database will be taken.
What you want is the current language locale, the following code should return the code:
NSArray *languagesArray = [[NSUserDefaults standardUserDefaults] objectForKey:#"AppleLanguages"];
NSString *currentLanguage = [languagesArray objectAtIndex:0];
You can then do the following
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.lproj/mydatabase.db", currentLanguage]];
You may want to check if the path exists and is a valid file, if not maybe use some default path like the one for English (en.lproj)
Edit: There is another way you can do this using NSLocale's preferred languages because then you get a list of the preferred languages, so some updated code for the first bit would be:
NSArray *languagesArray = [NSLocale preferredLanguages];
NSString *currentLanguage = [languagesArray objectAtIndex:0];
In the end, you'd end up with something like so:
NSString *pathComponent = [NSString stringWithFormat:#"%#.lproj/mydatabase.db", currentLanguage];
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:pathComponent];
NSString *activePath = nil; // This will store the active language file
// Check if the file exists...
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
activePath = path;
} else {
activePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"en.lproj/mydatabase.db"]; // Fallback
}
Please note, the above code is untested but should suffice. You may need to modify it a little...
Something like this:
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString * rootPath = [[NSBundle mainBundle] resourcePath];
NSString * resourcePath = [[NSBundle mainBundle] pathForResource: #"mydatabase" ofType: #"db" inDirectory: rootPath forLocalization: language];

can't read plist from resources

in my resources directory i have a file called lsf.plist
i want to load this file (dictionary) but i always get null as content of the file. i am using the following code. i've verified that the file is in the app after the build.
self.path = [[NSBundle mainBundle] pathForResource:#"lsf" ofType:#"plist"];
NSLog(self.path);
self.lsf = [NSMutableArray arrayWithContentsOfFile:path];
NSLog(#"%#",lsf);
The first log-output shows the path and the second one gives me null....
it would be great if you can help me to solve this issue!
Br,
martin
Is root of your plist array or dictionary?
Also you dont need to use self.
Heres an example from a project of mine:
NSString* path = [[NSBundle mainBundle] pathForResource:#"property" ofType:#"plist"];
NSDictionary *newDict = [NSDictionary dictionaryWithContentsOfFile:path];

pathForResource? without using extension (Iphone)

Here is what I'm doing, when I create an image with the path in the bundle:
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"image" ofType:#"jpg"]];
What I want to do is trying to find the path for my image but without using the extension, without using 'ofType' (because the name of my image and her extension is store in my database) something like that:
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"image.jpg"]];
But I don't know how to do it.
Best regards,
Why don't you split the string that you get from the DB?
NSString* fullFileName = #"image.jpg";
NSString* fileName = [[fullFileName lastPathComponent] stringByDeletingPathExtension];
NSString* extension = [fullFileName pathExtension];
Now you can simply use:
[[NSBundle mainBundle] pathForResource:fileName ofType:extension]];
You can easily use the NSBundle method without passing the extension, just pass nil for extension.
[[NSBundle mainBundle] pathForResource:#"image.jpg" ofType:nil];
- (NSData *)applicationDataFromFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease];
return myData;
}
taken from http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/FilesandNetworking/FilesandNetworking.html#//apple_ref/doc/uid/TP40007072-CH21-SW21
Could be easily adapted if you wanted it to return a UIImage instead of an NSData.
Also, you don't say if you are saving the images to the documents directory, or adding them to your app bundle before compiling. because if it's the latter, you can use [UIImage imageNamed:(NSString *)filename] to get the image. It expects an extension as part of the file-name.
The easiest way is to store the name and file type in your database separately, and retrieve them using the first method.I'm not sure that you can be successful in implementing the latter one.
I found that with an extension of ".jpg" it was necessary to use ofType for the extension for the app to work on an iPod Touch, whereas with an extension of ".png" I could just put "image.png" in pathForResource and say ofType:nil. But all versions worked on the simulator.
The app bundle contains the image file, and I am using:
[[NSBundle mainBundle] pathForResource:#"Auto" ofType:#"jpg"]
to get a path.