Localizing with different element count - ios

I'd like to give my users a warm welcome, when they are opening my application. So I want to have different sentences to show them randomly. The count of messages differs in each language.
What is the preferred way to solve this problem?
My ideas:
Save the count also in the strings file -> Don't like this idea, because this must be maintained
"welcomeCount" = "5";
"welcomeN" = "Hi....";
Seperating the messages -> Don't like this idea, because you have to mind this
"welcomeMessages" = "Hey there...|MessageN";
Anyone out there with an idea to solve this issue in a elegant manner?

You can store the welcome messages in localized property lists.
In Xcode, go to File -> New -> File ...
Choose the Resource -> Property List template and for example "Welcome.plist" as file name.
Select Welcome.plist in Xcode and change the type of the root object from Dictionary to Array.
Select Welcome.plist, to go the File Inspector and click on "Make Localized ...". Then select the localizations that you want for the Welcome.plist., for example English and German.
Now you have a Welcome.plist for each language which you can edit separately.
To add strings, click on the "+" symbol in the property list.
In your program, you can load the list easily with
NSString *path = [[NSBundle mainBundle] pathForResource:#"Welcome" ofType:#"plist"];
NSArray *messages = [NSArray arrayWithContentsOfFile:path];
This loads the "right" properly list, depending on the user's language, into the array messages. You can choose a random message with
int idx = arc4random_uniform([messages count]);
NSString *msg = [messages objectAtIndex:idx];

To minimize maintenance, you can use a binary search to find out how many variations are available. Say you have the following in your Localizable.strings:
"Welcome_0" = "Hello";
"Welcome_1" = "Hi";
"Welcome_2" = "What up";
"Welcome_3" = "Howdy";
You can find the count using:
int lower = 0, upper = 10;
while (lower < upper - 1) {
int mid = (lower + upper) / 2;
NSString *key = [NSString stringWithFormat:#"Welcome_%i", mid];
BOOL isAvailable = ![key isEqualToString:NSLocalizedString(key, #"")];
if (isAvailable) lower = mid;
else upper = mid;
}
Finally select you random message using:
NSString *key = [NSString stringWithFormat:#"Welcome_%i", rand() % upper];
NSString *welcome = NSLocalizedString(key, #"");

Related

if statements and stringWithFormat

I need to know if there is a way to use if statements to display certain nsstrings, depending on whether or not that NSString contains any data.
I have an nsstringcalled visitorInfo.
The string uses data from other strings (i.e. which operating system the user is running) and displays that info. Here is an example of what I'm talking about:
NSString *visitorInfo = [NSString stringWithFormat:#"INFO\n\nVisitor Location\n%#\n\nVisitor Blood Type\n\%#", _visitor.location, _visitor.bloodType];
And it would display like this:
INFO
Location
Miami, FL
Blood Type
O positive
However, I have several pieces of data that only load if the user chooses to do so. i.e their email address.
This section of code below would do what I want, but my visitorInfo string contains tons of different strings, and if I use this code below, then it won't load any of them if the user chooses not to submit his blood type.
if ([self.visitor.bloodType length] > 0) {
NSString *visitorInfo = [NSString stringWithFormat:#"INFO\n\nVisitor Location\n%#\n\nVisitor Blood Type\n\%#", _visitor.location, _visitor.bloodType];
}
So basically if their is data stored in bloodType then i went that code to run, but if there isn't any data I only want it to skip over bloodType, and finish displaying the rest of the data.
Let me know if you have any more questions
Additional details. I'm using an NSString for a specific reason, which is why I'm not using a dictionary.
Just build up the string as needed using NSMutableString:
NSMutableString *visitorInfo = [NSMutableString stringWithFormat:#"INFO\n\nVisitor Location\n%#, _visitor.location];
if ([self.visitor.bloodType length] > 0) {
[visitorInfo appendFormat:#"\n\nVisitor Blood Type\n\%#", _visitor.bloodType];
}
You can check if a string has any data in it by using the following
if([_visitor.location length]<1){
//This means there's no data and is a better way of checking, rather than isEqualToString:#"".
}else{
//there is some date here
}
** EDIT - (just re-reading your question, sorry this answer is dependant on _visitor.location being a string in the first place)*
I hope this helps
Try this -
NSString *str = #"INFO";
if (_visitor.location) {
str = [NSString stringWithFormat:#"\n\nVisitor Location\n%#",_visitor.location];
}
if (_visitor.bloodType) {
str = [NSString stringWithFormat:#"\n\nVisitor Blood Type\n\%#",_visitor.bloodType];
}

How to generate random messages from strings

I've google and i can't find the exact closest thing to the function i'm seeking.
So this is the idea of the generating message on the iOS apps.
This just randomly generate random number depend on the length
// Generates alpha-numeric-random string
- (NSString *)genRandStringLength:(int)len {
static NSString *letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
for (int i=0; i<len; i++) {
[randomString appendFormat: #"%C", [letters characterAtIndex: arc4random() % [letters length]]];
}
return randomString;
}
What i'm seeking is for the apps to generate random messages store in the array list depending on the settled time.
This is how i want it to work
static NSString *letters = #"Hello all","You're awesome","This is awkward","Are you sleeping?";
I need help to generate random messages in the string of arrays . Thank you in advance
This is not a way of doing this certain task. you have to make one array with most of word instad of punting single string with all alphabet character And create random sentence. This is logical and programmatic task xcode not generate random word it self. you have to do some logical stuff your self.
Here i found one github example code please check Bellow you got idea how does you can achieve this task. Hope you getting some idea with this example.
https://github.com/dav/Objective-C-Lorem-Ipsum-Generator

Reading in .CSV individual values

I have a .CSV File below that is already put into a nice format rather than a solid list of values.
How would i be able to read individual values from this list … for example 'Time of 5 & 6" and return the number?
I know how would retrieve this from a normal .csv file that is listed, however not from one that has a weird layout like this one. Any ideas?
Thank
If the column titles (such as "Time 4" and "Time of 5 & 6") are consistent, you could separate each line and then by commas, look for the index of the column title, and then grab the same column in the next line.
I haven't tested this, but I think it should work. Assuming your file is read in as a string:
NSArray *componentsByLine = [myFile componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
int firstIndex = 0;
int secondIndex = 0;
BOOL found = NO;
for(firstIndex = 0; firstIndex < componentsByLine.count; firstIndex++)
{
NSArray *componentsByComma = [[componentsByLine objectAtIndex:firstIndex] componentsSeparatedByString:#","];
for(secondIndex = 0; secondIndex < componentsByComma.count; secondIndex++)
{
if([[componentsByComma objectAtIndex:secondIndex] isEqualToString:#"Time of 5 & 6"])
{
found = YES;
break;
}
}
if(found)
break;
}
float requestedTime = [[[[componentsByLine objectAtIndex:firstIndex+1] componentsSeparatedByString:#","] objectAtIndex:secondIndex] floatValue];

NSString find and replace html tags attgibutes

I have pretty simple NSString
f.e
<scirpt attribute_1="x" attribute2="x" attribute3="x" ... attributeX="x"/>
I need to find specific parameter, let's say attribute2 and replace it's value,
I know the exact name of parameter f.e attribute2 but I don't know anything about it's value.
I guess it can be easily done by regexp, but I quite newbie on it.
In conclusion: I want to grab
attribute2="xxxx...xxx"
from incoming string
Note: I don't want to use some 3rd party libs to achieve that (it's temporary hack)
Any help is appreciated
I hacked it together with some string operations:
NSDictionary* valuesToReplace = #{#"attribute_1" : #"newValue1"};
NSString* sourceHtml = #"<scirpt attribute_1=\"x\" attribute2=\"x\" attribute3=\"x\" attributeX=\"x\" />";
NSArray* attributes = [sourceHtml componentsSeparatedByString:#" "];
for (NSString* pair in attributes)
{
NSArray* attributeValue = [pair componentsSeparatedByString:#"="];
if([attributeValue count] > 1) //to skip first "script" element
{
NSString* attr = [attributeValue firstObject]; //get attribute name
if([valuesToReplace objectForKey:attr]) //check if should be replaced
{
NSString* newPair = [NSString stringWithFormat:#"%#=\"%#\"", attr, [valuesToReplace objectForKey:attr]]; //create new string for that attribute
sourceHtml = [sourceHtml stringByReplacingOccurrencesOfString:pair withString:newPair]; //replace it in sourceHtml
}
}
}
It's really only when you want to hack it and you know the format :) Shoot a question if you have any.
you can try this.. https://github.com/mwaterfall/MWFeedParser
import "NSString+HTML.h" along with dependencies
And write like this...
simpletxt.text = [YourHTMLString stringByConvertingHTMLToPlainText];

How to retrieve the pretext before an array in iOS Objective C (parse)

Array object at index 0---:
<Merchandise:AW9JgReRyQ:(null)>
{
ACL = "<PFACL: 0x201b2590>\";
CoverPhotos = "<ItemPhotos:L5ln3ZN5rm>\";
item = ugh;
listingprice = 356;
originalprice = "25)";
user = "<PFUser:KdRfesAJA3>";
},
I have implemented my iOS app using Parse.com
In that I have an array of objects (Array of dictionaries)
in those I have print the 1st object of that array..
I have some pre text Merchandise:AW9JgReRyQ:(null before every object / dictionary which is related to object id
i want to get the preText " Merchandise:AW9JgReRyQ:(null) " or atleast "AW9JgReRyQ"
How to do ..>?
Total entire array of all objects is
array-------
(
"<Merchandise:AW9JgReRyQ:(null)>
{\n ACL = \"<PFACL: 0x201b2590>\";\n CoverPhotos = \"<ItemPhotos:L5ln3ZN5rm>\";\n Photos = \"<PFRelation: 0x201bff80>(<00000000>.(null) -> ItemPhotos)\";\n brand = \"Baby Gap\";\n description = \"\\nFight\";\n item = ugh;\n listingprice = 356;\n originalprice = \"25)\";\n user = \"<PFUser:KdRfesAJA3>\";\n}",
"<Merchandise:bMPFijErWI:(null)>
{\n ACL = \"<PFACL: 0x201a2300>\";\n CoverPhotos = \"<ItemPhotos:4pm7vX7q26>\";\n Photos = \"<PFRelation: 0x2019a490>(<00000000>.(null) -> ItemPhotos)\";\n brand = \"3 Pommes\";\n description = Sett;\n item = udder;\n listingprice = 245;\n originalprice = 245;\n user = \"<PFUser:KdRfesAJA3>\";\n}"
)
It seems like you have two options for this. Either parse each one out into a string (definitely the less elegant/way uglier way). Or also it looks more likely that it could be an array of arrays that contain a string and dictionary.
If it ends up being the second option, you could easily just grab the object at index 0 twice to get the preText your looking for. However, if thats no avail..then you can just go for it like so:
//Convert your object into an NSString
NSString *converted = (NSString*)[yourArray objectAtIndex:i];
//Or..your may need to do NSString *converted = [NSString stringWithFormat:#"%#",[yourArray objectAtIndex:0]];
NSArray *firstSplitterArray = [converted componentsSeparatedByString:#"<"];//split by <
NSString *partialSplit = [splitterArray objectAtIndex:0];
NSArray *secondSplitterArray = [partialSplit componentsSeparatedByString:#">"];//split by >
NSString *yourPreText = [secondSplitterArray objectAtIndex:0];//final step
//now yourPreText should equal Merchandise:AW9JgReRyQ:(null)
I wrote this according to your first code snippet. If there is actually a leading quotation mark or something, you'll need to change your indexes. But this gives you the idea. Just do some print statements to verify your arrays at each step and you will be good to go. Not the cleanest, but if your in a pinch this could work.

Resources