if statements and stringWithFormat - ios

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];
}

Related

How should I localise with multiple parameters?

Let's say I have the following string:
[NSString stringWithFormat:#"Booked for %# at %#", colleagueName, time];
And I realise I've forgotten to localise that string, so I replace it:
[NSString stringWithFormat:NSLocalizedString(#"bookings.bookedFor", "Booked for user at time"), colleagueName, time];
Now when doing translations, I find that the language X needs the parameters the other way round; something closer to:
<time> for booking of <colleague> is done.
What is the best way to address the fact that now I need the second parameter of my formatted string to be time and the third to be colleagueName please?
As is often the case, my colleague found the solution almost as soon as I had asked on here! Apparently Objective-C has positional arguments
The positions are 1-indexed so %1$# refers to the first argument.
NSString *firstParam = #"1st";
NSString *secondParam = #"2nd";
NSLog(#"First %1$# Second: %2$#", firstParam, secondParam);
NSLog(#"Second %2$# First: %1$#", firstParam, secondParam);
This prints:
First 1st Second: 2nd
Second 2nd First: 1st
You can try like this:
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
if ([language isEqualToString:#"X"]) {//X is language code like "fr","de"
[NSString stringWithFormat:NSLocalizedString(#"bookings.bookedFor", "Booked for user at time"), time, colleagueName];
} else {
[NSString stringWithFormat:NSLocalizedString(#"bookings.bookedFor", "Booked for user at time"), colleagueName,time];
}

Splitting string into substring in iOS

I have a small doubt on splitting a string into substring.
I want to display State and Country name in one label. i have a string in a service coming from json file "FullAddress": "New Windsor,New York,USA". i want only New York,USA to display in a label.
Use this and get your desire String from Array element 1 and 2
NSArray *strings = [FullAddress componentsSeparatedByString:#","];
Please Use this code it will be help you out
NSString *fullAddress=#"New Windsor,New York,USA";
NSRange range=[fullAddress rangeOfString:#","];
if (range.location!=NSNotFound) {
NSString *string=[fullAddress substringFromIndex:range.location+range.length];//this is address you want
NSLog(#"%#",string);
}

iOS Convert phone number to international format

In my iOS app I have to convert a phone number (taken in the contacts) and convert it in international format (to send SMS automatically with an extern library). I saw libPhoneNumber but the problem is that we have to enter the country code, and the app have to work in all (almost) countries, so I don't know what is the user's country.
Here is how the library works :
let phoneUtil = NBPhoneNumberUtil()
let phoneNumberConverted = try phoneUtil.parse("0665268242", defaultRegion: "FR") // So I don't know the country of the user here
print(try? phoneUtil.format(phoneNumberConverted, numberFormat: NBEPhoneNumberFormat.INTERNATIONAL))
formattedPhoneNumberSubstring takes a partial phone number string and formats it as the beginning of a properly formatted international number, e.g. "16463" turns to "+1 646-3".
NSString *formattedPhoneNumberSubstring(NSString *phoneNumber) {
NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
phoneNumber = [phoneUtil normalizeDigitsOnly:phoneNumber];
NSString *nationalNumber;
NSNumber *countryCode = [phoneUtil extractCountryCode:phoneNumber nationalNumber:&nationalNumber];
if ([countryCode isEqualToNumber:#0])
return phoneNumber;
NSString *regionCode = [[phoneUtil regionCodeFromCountryCode:countryCode] objectAtIndex:0];
NSString *paddedNationalNumber = [nationalNumber stringByPaddingToLength:15 withString:#"0" startingAtIndex:0];
NSString *formatted;
NSString *formattedSubstr;
for (int i=0; i < paddedNationalNumber.length; i++) {
NSError *error = nil;
formattedSubstr = [phoneUtil format:[phoneUtil parse:[paddedNationalNumber substringToIndex:i] defaultRegion:regionCode error:&error]
numberFormat:NBEPhoneNumberFormatINTERNATIONAL error:&error];
if (getExtraCharacters(formattedSubstr) > getExtraCharacters(formatted)) // extra characters means more formatted
formatted = formattedSubstr;
}
// Preparing the buffer for phoneNumber
unichar phoneNumberBuffer[phoneNumber.length+1];
[phoneNumber getCharacters:phoneNumberBuffer range:NSMakeRange(0, phoneNumber.length)];
// Preparing the buffer for formatted
unichar formattedBuffer[formatted.length+1];
[formatted getCharacters:formattedBuffer range:NSMakeRange(0, formatted.length)];
int j=0;
for(int i = 0; i < phoneNumber.length && j < formatted.length; i++) {
while(formattedBuffer[j] != phoneNumberBuffer[i]) j++;
j++;
}
return [formatted substringToIndex:j];
}
You can get the region using either the users locale or the users geo position.
See stackoverflow question get device location country code for more details.
If you don’t know the country code of a phone number, you can’t generate the international format of it.
You could try using the location of the phone or its region settings to guess the country code, but it won’t be reliable. For example, my phone number is Spanish, I’m currently in Italy and my region is set to New Zealand. My contact list contains numbers from all over the world, and if they weren’t entered in international format there would be no way to guess what country code to use for each number.
If you absolutely have to guess, the best approach might be to think about how the phone would interpret the numbers in the contact list itself. This would require you to determine the country code of the phone’s SIM card. See this answer to a related question for a way of doing that, or here’s some Swift code I’ve used:
let networkInfo = CTTelephonyNetworkInfo()
if let carrier = networkInfo.subscriberCellularProvider {
NSLog("Carrier: \(carrier.carrierName)")
NSLog("ISO: \(carrier.isoCountryCode)")
NSLog("MCC: \(carrier.mobileCountryCode)")
NSLog("MNC: \(carrier.mobileNetworkCode)")
}
The ISO country code can be used to look up a country code for dialling; an example table is in the answer linked above.

How do I search an NSString sentence with words separated by commas for a specific word in iOS7?

I came across a question that had an example using rangeOfString. How ever the first thing that came to mind was NSPredicate.
I have different strings that return words separated by sentences. For example I have one that returns "Male, Female".
What is the most efficient way to search either "Male" or "Female". I'd like to perform some actions if the word happens to be part of the sentence and if it doesn't.
NSDictionary with stored words separated by commas. I use different keys to grab specific bunch of words. Below I use the "selectedGenders" key which returns "Male, Female":
if ([combinedRefinementSelection valueForKey:#"selectedGenders"]) {
NSString *selectedGenders = [combinedRefinementSelection valueForKey:#"selectedGenders"];
// Show string in label so customer knows how their clothes items will be filtered
[[_thisController chosenGender] setText:selectedGenders];
}
I simply want to search selectedGenders and find out if Male or Female is part of the string.
As you said, rangeOfString works just fine.
NSString* sentence = #"Male, Female";
if ([sentence rangeOfString:#"Male"].location != NSNotFound)
{
NSLog(#"Male is found");
}
if ([sentence rangeOfString:#"Female"].location != NSNotFound)
{
NSLog(#"Female is found");
}

Integer from .plist

I'm new to plists, and I really need to use one. What I have is a plist where different numbers are stored, under two dictionaries. I need to get that number which is stored, and make it an integer. This process will be run from a method called 'readPlist.
The plist is called 'properties.plist'. The first dictionary is called 'Enemies'. It contains various other dictionaries, which will have the name stored in the NSMutableString called 'SpriteType'. The name of the number will have the format 'L - %d', with the %d being an integer called 'LevelNumber'.
If possible, can someone give me the code on how to get that integer using the information, and the names of dictionaries above.
I have looked around at how to access plists, but the code that people have shown doesn't work.
Thanks in advance.
EDIT: Too make it more understandable, this is my plist. What i want in an integer, called 'SpriteNumber' to be equal to the value of 'L - %d'
If you read the contents of your plist into a dictionary (I won't tell you how to do it, but this is the tutorial I refer to often), then it's a matter of getting the string out of the key for the level with [[myDictionary objectForKey:#"key"]stringValue];. Then, using of NSString's extremely helpful -stringByReplacingOccurencesOfString:withString: to get rid of the "L -" part and only get a numerical value. Finally, get an integer from the string with [myString intValue].
well, the easiest way would be something like :
-(int) getMosquitoCountForLevel:(int) level {
int mosquitoCount=0;
NSString *gsFile = #"whateverFullyQualifiedFileNameYourPlistIs";
NSDictionary* definitions = [NSDictionary dictionaryWithContentsOfFile:gsFile];
NSDictionary* mosquitos = [definitions objectForKey:#"Mosquito"];
if(mosquitos) {
NSString *levelKey = [NSString stringWithFormat:#"L - %d",level];
NSNumber *mosquitoCountAsNumber = [mosquitos objectForKey:levelKey];
if(mosquitoCountAsNumber) {
mosquitoCount=[mosquitoCountAsNumber intValue];
} else {
CCLOGERROR(#"%# - Mosquito definitions in %# does not contain a en entry for level %#.",self.class,gsFile,levelKey);
}
} else {
CCLOGERROR(#"%# - file %# does not contain a Mosquito dictionary.",self.class,gsFile);
}
return mosquitoCount;
}
this compiles but not tested with actual data.

Resources