How can I access to the localized strings inside Settings.bundle in Objective-C? - objective-c

I need to access to the Settings.bundle and get the descriptions and titles with the localized string.

Use NSLocalizedStringFromTableInBundle function. Create an instance of NSBundle with URL of your bundle and use it as bundle argument. Use “Root” as the table name for tbl argument.
For example:
NSBundle *bundle = [[NSBundle alloc] initWithURL: ...];
NSString *string = NSLocalizedStringFromTableInBundle("SOME_KEY", "Root", bundle, "Comment");

In the end I did it this way:
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"bundle"];
NSBundle *settingsBundle = [NSBundle bundleWithPath:resourcePath];
NSURL *url = [settingsBundle URLForResource:#"Root" withExtension:#"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfURL:url];
NSArray *preferences = dictionary[#"PreferenceSpecifiers"];
for (NSDictionary *dic in preferences){
NSString *localizedTitle = NSLocalizedStringWithDefaultValue(dic[#"Title"], #"Root", settingsBundle, dic[#"Title"], #"");
}

Related

Unable to convert a string to a NSURL

I am trying to turn off WAL in CoreData using this code:
// Code to disable journaling mode
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *urlString = [applicationDocumentsDirectory stringByAppendingPathComponent: #"saori.sqlite"];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSDictionary *options = #{NSSQLitePragmasOption:#{#"journal_mode":#"DELETE"}};
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] init];
[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:options error:nil];
This is my NSString that I need to convert to a URL:
/Users/rolfmarsh/Library/Application Support/iPhone Simulator/7.1/Applications/7A614C51-AC51-4F5B-9716-6E3D2F160324/Documents/saori.sqlite
When I use that string in this statement, it generates nil.
NSURL *url = [[NSURL alloc] initWithString:urlString];
I don't see anything wrong with the string. What am I doing wrong?
Read the docs for NSURL. You have a file path and you need to create a file URL from the file path.
NSURL *url = [NSURL fileURLWithPath:urlString];

Objective C - NSString working but plist string doesn't work

I have a piece of code that finds a random word in a plist and then assigns it to the NSString 'correctWord'. For some reason the code works fine in one instance but doesn't work in another.
This code works:
- (void) viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:
#"small" ofType:#"plist"];
NSArray *plistArray = [[NSArray alloc] initWithContentsOfFile:path];
NSInteger randV = arc4random_uniform(plistArray.count); // randV is from 0 to number of strings -1 in array
[super viewDidLoad];
self.correctWord = #"Hello"; //<--- Code works fine here..
[self setupHangmanWord:self.correctWord];
}
This code doesn't work. (there are no errors in the compiler though)
- (void) viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:
#"small" ofType:#"plist"];
NSArray *plistArray = [[NSArray alloc] initWithContentsOfFile:path];
NSInteger randV = arc4random_uniform(plistArray.count); // randV is from 0 to number of strings -1 in array
[super viewDidLoad];
self.correctWord = [plistArray objectAtIndex:randV]; //<--- Doesn't work anymore.
[self setupHangmanWord:self.correctWord];
}
use:
NSString *path = [[NSBundle mainBundle] pathForResource:#"small" ofType:#"plist"];
NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:path];

loading AVAudioPlayer file URLs from a Plist

I'm working with about 50 AVAudioPlayers that each load a separate audio file. The files are fixed and within the app bundle. They are triggered by events later on in the app. Currently I'm hardcoding the creation of each player instance, like so:
//No01
NSURL *no01URL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:#"audio1" ofType:#"aiff"]];
self.no01Player = [[AVAudioPlayer alloc] initWithContentsOfURL:no01URL error:nil];
no01Player.numberOfLoops = 0;
no01Player.volume = 0;
no01Player.delegate = self;
//No02
NSURL *no02URL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:#"audio2" ofType:#"aiff"]];
self.no02Player = [[AVAudioPlayer alloc] initWithContentsOfURL:no02URL error:nil];
no02Player.numberOfLoops = 0;
no02Player.volume = 0;
no02Player.delegate = self;
//No03 and so on...
Obviously this is labourious and bad coding practice. I'd like to instead have the list of files in a Plist and load these into variables that populate just one example of the above code. I'd like to learn how to be DRY with this but have limited experience of loading data from Plists, arrays, dictionaries, etc.
Any help is appreciated, even if it is to point me in the direction of a relevant tutorial.
Thank you.
You can simply place the audio file names in text file using 'new line' separator. And read the file and store the names in an array. To create the URL take the file names dynamically from array as given below
// Read description from text file
NSBundle *audioBundle = [NSBundle mainBundle];
NSString *audioPath = [audioBundle pathForResource:audioFileNames ofType:#"txt"];
NSString *audioContent = [NSString stringWithContentsOfFile:audioPath encoding:NSUTF8StringEncoding error:nil];
// ===========Make an array using audioContent=============
NSArray *audioFiles = [audioContent componentsSeparatedByString:#"\n"];
Use the array to get file names :
NSURL *no01URL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#",[audioFiles objectAtIndex:audioCount]] ofType:#"aiff"]];
If your file names are like audio1,audio2.. no need of using all these. Just change in URL like :
NSURL *no01URL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"audio%d",audioCount] ofType:#"aiff"]];
OK for anyone else needing to do this, here's what I ended up with:
//Load location data from Plist file into an Array
NSString *path = [[NSBundle mainBundle] pathForResource:#"Audionodes" ofType:#"plist"];
locationArray = [[NSArray alloc] initWithContentsOfFile:path];
// Create AVAudioPlayers for this view
self.audioPlayerArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [locationArray count]; i++) {
NSString *filename = [[locationArray objectAtIndex:i] valueForKey:#"filename"];
NSString *filetype = [[locationArray objectAtIndex:i] valueForKey:#"filetype"];
int loops = [[[locationArray objectAtIndex:i] valueForKey:#"loops"] intValue];
NSURL *url = [[NSURL alloc]initFileURLWithPath:[[NSBundle mainBundle] pathForResource:filename ofType:filetype]];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.delegate = self;
player.numberOfLoops = loops;
player.volume = 0;
[self.audioPlayerArray addObject:player];
[url release];
[player release];
}
Putting the generated players in audioPlayerArray means I can get at them later.

Read .strings file in Objective-C?

I'm creating a Mac app and I want to localize my Labels. I thought a .strings file would be a better choice. But I have trouble reading .strings file in Objective-C. I'm looking for a simpler method.
This is my .string file content:
"LABEL_001" = "Start MyApp";
"LABEL_002" = "Stop MyApp";
"LABEL_003" = "My AppFolder";
...
I have already looked at http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/LoadingResources/Strings/Strings.html.
This is my code:
NSBundle *bundle = [NSBundle mainBundle];
NSString *strFilePath = [[NSBundle mainBundle] pathForResource:#"Labels" ofType:#"strings"];
NSString *tt =NSLocalizedStringFromTableInBundle(#"LABEL_001",strFilePath,bundle, nil);
NSLog(#"STRING ::: %#",tt);
But the string tt gives "LABEL_001", I want "Start MyApp"
What am I doing wrong?
One. You have to name your file Localizable.strings in the <LANGUAGENAME>.lproj directory in the app bundle.
Two. Use the NSLocalizedString macro:
NSString *loc = NSLocalizedString(#"LABEL_001", nil);
Three. If nothing works, you can initialize an NSDictionary using a strings file, as a strings file is a special type of plist:
NSString *fname = [[NSBundle mainBundle] pathForResource:#"whatever" ofType:#"strings"];
NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile:fname];
NSString *loc = [d objectForKey:#"LABEL_001"];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Labels" ofType:#"strings"];
NSData *plistData = [NSData dataWithContentsOfFile:path];
NSString *error; NSPropertyListFormat format;
NSDictionary *dictionary = [NSPropertyListSerialization propertyListFromData:plistData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&error];
NSString *stringname = [dictionary objectForKey:#"LABEL_001"];
I think it will be helpful to you.
Here the your code
NSBundle *bundle = [NSBundle mainBundle];
NSString *strFilePath = [[NSBundle mainBundle] pathForResource:#"Labels" ofType:#"strings"];
NSString *tt =NSLocalizedStringFromTableInBundle(#"LABEL_001",strFilePath,bundle, nil);
NSLog(#"STRING ::: %#",tt);
The problem here is the 2nd Param "strFilePath", change it to #"Labels" so the above code would become,
NSString *tt =NSLocalizedStringFromTableInBundle(#"LABEL_001",#"Labels",bundle, nil);
For reference, the following line copied from Apple Docs regarding table name,
"When specifying a value for this parameter, include the filename without the .strings extension."
hope this helps.
Simple Code
Just create a method as follows
- (void)localisationStrings
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"localisation" ofType:#"strings"];
NSDictionary *localisationDict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(#"\n %#",[localisationDict objectForKey:#"hello"]);
}

iphone read from file

i create a view based application , in this project i want read data from .plist file.
how it is possible,
Pleas help me ?
NSString *path = [[NSBundle mainBundle] pathForResource:#"plistfilename" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:#"%#", path]];
NSString *body = [dict objectForKey:#"Keyname"];
with the use of this anyone can read data from plist file.
If you are sure the .plist file is a dictionary at root level,
return [NSDictionary dictionaryWithContentsOfFile:#"path/to/your.plist"];
otherwise,
NSData* plist_data = [NSData dataWithContentsOfFile:#"path/to/your.plist"];
return [NSPropertyListSerialization propertyListFromData:plist_data mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL];