Extract an NSString using NSScanner - iphone

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

Related

Not getting "-" "." " " while picking up a contact from phonebook from ABPerson

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
}

in IOS,how to remove +-#*() ,which get from address book

In IOS,how to remove +-#*() ,which get from address book.
for example:
NSString *txt = #"+1(510)1234567"
txt = [NSString stringWithFormat:#"tel://%#", txt];
[[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:txt]];
it's a invalid number to call.
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlToCall]]; is useless for this type number.
could I have some better options except use
[txt stringByReplacingOccurrencesOfString:#"-" withString:#""]....
I just wanna make a call.
Thanks for your help.
In fact:we can make a call by openURL: the format of call is not "tel://",It is "tel:".
So,what I should do is that:
NSString *cleanedString = [[phoneNumber componentsSeparatedByCharactersInSet:
[[NSCharacterSet characterSetWithCharactersInString:#"0123456789-+()"]
invertedSet]] componentsJoinedByString:#""];
NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:#"tel:%#", cleanedString]];
That's OK.
————————————————————————————————
#"tel://“ isn't the right url to make a call!
we must use #"tel:"
if not some number ,as +1 (510) 3436 which
BOOL bCanCall = [[UIApplication sharedApplication]canOpenURL:urlToCall]; will return False. you can't make a call.
Try this, it may work
-(NSString *) formatIdentificationNumber:(NSString *)string
{
NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:#"\n_!##$%^&*()[]{}'\".,<>:;|\\/?+=\t~` "];
NSString * result = #"";
NSScanner * scanner = [NSScanner scannerWithString:string];
NSString * scannerResult;
[scanner setCharactersToBeSkipped:nil];
while (![scanner isAtEnd])
{
if([scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult])
{
result = [result stringByAppendingString:scannerResult];
}
else
{
if(![scanner isAtEnd])
{
[scanner setScanLocation:[scanner scanLocation]+1];
}
}
}
return result;
}
or see the link
You can remove like this..
NSString *s = #"+1(510)1234567";
NSCharacterSet *unwantedStr = [NSCharacterSet characterSetWithCharactersInString:#"+()"];
s = [[s componentsSeparatedByCharactersInSet: unwantedStr] componentsJoinedByString: #""];
NSLog(#"%#", s);
Alternativ, some hints here, but you can optimize the code.
- (void)testExample
{
NSMutableCharacterSet *mvalidCharSet = [[NSMutableCharacterSet alloc] init];
[mvalidCharSet formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet] ];
[mvalidCharSet addCharactersInString: #"+"];
NSCharacterSet *validCharSet = [mvalidCharSet copy]; // not mutable -> more efficient
NSCharacterSet *invalidCharSet = [validCharSet invertedSet];
NSString *txt = #"+1(510)1234567";
NSArray * components = [txt componentsSeparatedByCharactersInSet:invalidCharSet];
NSString * rejoin = [components componentsJoinedByString:#""];
NSLog(#"%#", rejoin);
}

Generate vCard without image

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.

Remove Html Format from String

I have been trying to format a string in my text view but I cant work it out. Im very new to xcode.
Am i missing something in this file? I have been looking through stack and this is how you do it..but its not working.
- (NSString *)stripTags:(NSString *)str
{
NSMutableString *html = [NSMutableString stringWithCapacity:[str length]];
NSScanner *scanner = [NSScanner scannerWithString:str];
scanner.charactersToBeSkipped = NULL;
NSString *tempText = nil;
while (![scanner isAtEnd])
{
[scanner scanUpToString:#"<" intoString:&tempText];
if (tempText != nil)
[html appendString:tempText];
[scanner scanUpToString:#">" intoString:NULL];
if (![scanner isAtEnd])
[scanner setScanLocation:[scanner scanLocation] + 1];
tempText = nil;
}
return html;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *str = newsArticle;
descTextView.text = [NSString stringWithString:str];
// Do any additional setup after loading the view from its nib.
}
This code is a modified version of what was posted as an answer to a similar question here https://stackoverflow.com/a/4886998/283412. This will take your HTML string and strip out the formatting.
-(void)myMethod
{
NSString* htmlStr = #"<some>html</string>";
NSString* strWithoutFormatting = [self stringByStrippingHTML:htmlStr];
}
-(NSString *)stringByStrippingHTML:(NSString*)str
{
NSRange r;
while ((r = [str rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
{
str = [str stringByReplacingCharactersInRange:r withString:#""];
}
return str;
}
You are trying to put HTML into a label. You want to use a UIWebView.
#try this one
-(NSString *) stringByStrippingHTML:(NSString *)HTMLString {
NSRange r;
while ((r = [HTMLString rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
HTMLString = [HTMLString stringByReplacingCharactersInRange:r withString:#""];
return HTMLString;
}

iphone sdk - Remove all numbers except for characters a-z from a string

In my app I want to remove numbers except characters a-z from string. How can I get only characters?
This is the short answer which doesnt need any lengthy coding
NSString *newString = [[tempstr componentsSeparatedByCharactersInSet:
[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:#""];`
swift 3:
(tempstr.components(separatedBy:NSCharacterSet.letters.inverted)).joined(separator: "")
eg:
("abc123".components(separatedBy:NSCharacterSet.letters.inverted)).joined(separator: "")
NSString *stringToFilter = #"filter-me";
NSMutableString *targetString = [NSMutableString string];
//set of characters which are required in the string......
NSCharacterSet *okCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyz"];
for(int i = 0; i < [stringToFilter length]; i++)
{
unichar currentChar = [stringToFilter characterAtIndex:i];
if([okCharacterSet characterIsMember:currentChar])
{
[targetString appendFormat:#"%C", currentChar];
}
}
NSLog(targetString);
[super viewDidLoad];
}
this was an answer given to me and works fine
I found an answer:
from remove-all-but-numbers-from-nsstring
NSString *originalString = #"(123) 123123 abc";
NSLog(#"%#", originalString);
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyz"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog(#"%#", strippedString);