I want to get number as it is with "-" " " "." while picking up a contact from phone book here's my code .
My main motive is to extract the country code from the number if + is present.
Also please suggest me if there is any other way to access country code.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
if (property == kABPersonPhoneProperty) {
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i = 0; i < ABMultiValueGetCount(multiPhones); i++) {
if(identifier == ABMultiValueGetIdentifierAtIndex (multiPhones, i)) {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
CFRelease(multiPhones);
NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
CFRelease(phoneNumberRef);
if ([phoneNumber rangeOfString:#"+"].location == NSNotFound) {
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"." withString:#""];
self.lblMobileNumber.text = [NSString stringWithFormat:#"%#", phoneNumber];
} else {
NSArray *PhoneNumberComponents = [phoneNumber componentsSeparatedByString:#" "];
NSString * strCountryCode = PhoneNumberComponents[0] ;
[self.btnCountryCode setTitle:strCountryCode forState:UIControlStateNormal];
phoneNumber= [phoneNumber stringByReplacingOccurrencesOfString:PhoneNumberComponents[0] withString:#""];
NSLog(#"countryCodeSepratedStr%#",phoneNumber);
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"." withString:#""];
self.lblMobileNumber.text = [NSString stringWithFormat:#"%#", phoneNumber];
}
}
}
}
return NO;
}
I wouldn't be inclined do any of that string manipulation stuff, but just use regular expression to look for + followed by number at start of the string, using capturing parentheses to grab just the country code:
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^\\s*\\+\\s*(\\d+)[^\\d]*(.*)$" options:0 error:&error];
NSTextCheckingResult *result = [regex firstMatchInString:phoneNumber options:0 range:NSMakeRange(0, [phoneNumber length])];
if (result) {
NSString *countryCode = [phoneNumber substringWithRange:[result rangeAtIndex:1]];
NSString *phoneNumberWithoutCountryCode = [phoneNumber substringWithRange:[result rangeAtIndex:2]];
} else {
// no country code found
}
Related
My problem is that I have some text field with number and I must to convert this number to some phone format like this one (xxx) xxx-xxxx. I have tried an regular expression with this code:
wholeText = [wholeText stringByReplacingOccurrencesOfString:#"(\\d{1,3})(\\d{0,3})(\\d{0,4})"
withString:#"($1) $2-$3"
options:NSRegularExpressionSearch
range:NSMakeRange(0, wholeText.length)];
NSLog(#"wholeText = %#", wholeText);
If I gradually enter a text in text field, NSLog output this:
wholeText = (1) -
wholeText = (12) -
wholeText = (123) -
wholeText = (123) 4-
wholeText = (123) 45-
wholeText = (123) 456-
wholeText = (123) 456-7
So my problem that I do not need brackets and hyphens if there is no number before it, i.e. closing bracket should appear after I enter 4th number and hyphen should appear after I enter 7th number.
Use this Utility
UITextField subclass that allows number input in a predefined format.
http://www.cocoacontrols.com/controls/reformattednumberfield
If you have access to lazy operators, this will do what you want (I guess, you didn't give that much details.):
/^(\d{1,3}?)(\d{1,3}?)(\d{1,4})$/
How? Lazy operators.
use below code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
int length = [self getLength:textField.text];
//NSLog(#"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSCharacterSet *charactersToRemove = [[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];
newString = [[newString componentsSeparatedByCharactersInSet:charactersToRemove]componentsJoinedByString:#""];
NSString *expression = #"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
NSLog(#"newString::%#",newString);
if (numberOfMatches == 0)
return NO;
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:#"(%#)",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"%#",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(#"%#",[num substringToIndex:3]);
//NSLog(#"%#",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:#"(%#) %#-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"(%#) %#",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}
#pragma mark - Mobile Validation
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
NSLog(#"%#", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(#"%#", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
int length = [mobileNumber length];
return length;
}
try this you will be succeed
I am currently generating vCards from my Address Book via this function:
ABAddressBookRef ab = ABAddressBookCreateWithOptions(NULL, nil);
NSString *firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
if (!lastName) lastName = #"";
if (!firstName) firstName = #"";
NSString *name = [NSString stringWithFormat:#"%# %#",firstName, lastName];
CFArrayRef contact = ABAddressBookCopyPeopleWithName(ab, (__bridge CFStringRef)(name));
CFDataRef vcard = (CFDataRef)ABPersonCreateVCardRepresentationWithPeople(contact);
This works just fine but I don't want any images in my vCard. Is there any way to generate a vCard without getting the image?
I created a workaround for this by simply removing the the photo part from the string as so:
- (NSString *)removeImageFromVCF:(NSString *)yourString {
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:yourString];
if ([yourString rangeOfString:#"X-SOCIALPROFILE"].location == NSNotFound) {
while ([theScanner isAtEnd] == NO) {
[theScanner scanUpToString:#"PHOTO" intoString:NULL] ;
[theScanner scanUpToString:#"END:VCARD" intoString:&text] ;
yourString = [yourString stringByReplacingOccurrencesOfString:
[NSString stringWithFormat:#"%#", text] withString:#""];
}
}else{
while ([theScanner isAtEnd] == NO) {
[theScanner scanUpToString:#"PHOTO" intoString:NULL] ;
[theScanner scanUpToString:#"X-SOCIALPROFILE" intoString:&text] ;
[theScanner scanUpToString:#"END:VCARD" intoString:NULL];
yourString = [yourString stringByReplacingOccurrencesOfString:
[NSString stringWithFormat:#"%#", text] withString:#""];
}
}
return yourString;
}
Hopefully this will help somebody else.
I have a string with certain pattern. I need to search for the pattern and replace the string inside that pattern. For eg :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSString *result = nil;
// Determine "{" location
NSRange startRange = [string rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [string length] - endRange.location;
endRange = [string rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
result = [string substringWithRange:startRange];
}
}
Here I am able to extract the first substring that is between "{ }" ie - "Hello" but I also need to continue the check and want to extract other strings.
Try this one:
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
//NSString *result = nil;
// Determine "{" location
NSArray *array=[string componentsSeparatedByString:#"{"];
for(NSString *str in array){
NSString *newString=[[str componentsSeparatedByString:#"}"] objectAtIndex:0];
NSLog(#"%#",newString);
}
try this :
NSString *string = #"{Hello} ({World}) ({How}) ({Are}) ({You})";
NSMutableString *result = [[NSMutableString alloc] init];
NSArray *tempArray = [[string componentsSeparatedByString:#" "] mutableCopy];
for (int i=0; i < [tempArray count]; i++)
{
NSString *tempStr = [tempArray objectAtIndex:i];
NSRange startRange = [tempStr rangeOfString:#"{" options:NSCaseInsensitiveSearch];
if (startRange.location != NSNotFound)
{
// Determine "}" location according to "{" location
NSRange endRange;
endRange.location = startRange.length + startRange.location;
endRange.length = [tempStr length] - endRange.location;
endRange = [tempStr rangeOfString:#"}" options:NSCaseInsensitiveSearch range:endRange];
if (endRange.location != NSNotFound)
{
// bracets found: retrieve string between them
startRange.location += startRange.length;
startRange.length = endRange.location - startRange.location;
//result = [tempStr substringWithRange:startRange];
[result appendString:[NSString stringWithFormat:#"%# ",[tempStr substringWithRange:startRange]]];
NSLog(#"%# ",result);
}
}
}
Take care for release for tempArray and result
I happen to have this code lying around. I think it does exactly what you want. I implemented it as a category on NSString. You use it like this:
NSString *template = #"{Hello} ({World}) ({How}) etc etc";
NSDictionary *vars = [NSDictionary dictionaryWithObjectsAndKeys:
#"Bonjour", #"Hello",
#"Planet Earth", #"World",
#"Como", #"How",
// etc.
nil];
NSString *expandedString = [template stringByExpandingTemplateWithVariables:vars];
// expandedString is #"Bonjour (Planet Earth) (Como) etc etc"
Here's the code.
File NSString+TemplateExpansion.h
#import <Foundation/Foundation.h>
#interface NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary;
#end
File NSString+TemplateExpansion.m
#import "NSString+TemplateExpansion.h"
#implementation NSString (TemplateExpansion)
- (NSString *)stringByExpandingTemplateWithVariables:(NSDictionary *)dictionary
{
NSUInteger myLength = self.length;
NSMutableString *result = [NSMutableString stringWithCapacity:myLength];
NSRange remainingRange = NSMakeRange(0, myLength);
while (remainingRange.length > 0) {
NSRange leftBraceRange = [self rangeOfString:#"{" options:0 range:remainingRange];
if (leftBraceRange.location == NSNotFound)
break;
NSRange afterLeftBraceRange = NSMakeRange(NSMaxRange(leftBraceRange), myLength - NSMaxRange(leftBraceRange));
NSRange rightBraceRange = [self rangeOfString:#"}" options:0 range:afterLeftBraceRange];
if (rightBraceRange.location == NSNotFound)
break;
NSRange beforeLeftBraceRange = NSMakeRange(remainingRange.location, leftBraceRange.location - remainingRange.location);
[result appendString:[self substringWithRange:beforeLeftBraceRange]];
remainingRange = NSMakeRange(NSMaxRange(rightBraceRange), myLength - NSMaxRange(rightBraceRange));
NSRange keyRange = NSMakeRange(NSMaxRange(leftBraceRange), rightBraceRange.location - NSMaxRange(leftBraceRange));
NSString *key = [self substringWithRange:keyRange];
NSString *value = [dictionary objectForKey:key];
if (value)
[result appendString:value];
}
[result appendString:[self substringWithRange:remainingRange]];
return result;
}
#end
Hello I m getting firstname, lastname and mobile number from below code
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
NSString* name = (NSString *)ABRecordCopyValue(person,
kABPersonFirstNameProperty);
firstNameLabel.text = name;
[name release];
NSString *lastName =(NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
lastNameLabel.text = lastName;
[lastName release];
if (property == kABPersonPhoneProperty) {
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i = 0; i < ABMultiValueGetCount(multiPhones); i++) {
if(identifier == ABMultiValueGetIdentifierAtIndex (multiPhones, i)) {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
CFRelease(multiPhones);
NSString *phoneNumber = (NSString *) phoneNumberRef;
numberLabel.text = [NSString stringWithFormat:#"%#", phoneNumber];
// [phoneNumber release];
// CFRelease(phoneNumberRef);
}
//CFRelease(multiPhones);
}
}
[self dismissModalViewControllerAnimated:YES];
return NO;
}
And I am getting leaks.. Here is screen shot. Please help me to resolve leaks
Please check the code
if (property == kABPersonPhoneProperty) {
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i = 0; i < ABMultiValueGetCount(multiPhones); i++) {
if(identifier == ABMultiValueGetIdentifierAtIndex (multiPhones, i)) {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = (NSString *) phoneNumberRef;
numberLabel.text = [NSString stringWithFormat:#"%#", phoneNumber];
// [phoneNumber release];
CFRelease(phoneNumberRef);
}
}
CFRelease(multiPhones);
}
I'm fetching data from AllContacts; in that data I'm getting contact details such as (998) 989-8989. Using this number, I'm not able to make a call. Can any one help out with this? Thanks in advance.
HI All
At last i have used this following code to resolve this issue
NSString *originalString = #"(998) 989-8989";
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog(#"%#", strippedString);
Thanks All
Sounds like you can just remove spaces, brackets and hypens.
NSString *phoneNumber = #"(998) 989-8989";
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
phoneNumber = [#"tel://" stringByAppendingString:phoneNumber];
[[UIApplication sharedApplication] openURL:phoneNumber];