Generate vCard without image - iphone

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.

Related

Unable to fetch mobile numbers from Contact List. iOS6

I am new to iphone App Development(using iOS6) and have been facing problem with fetching the mobile Numbers from the contact List into a UITableViewController. I can get the first name and last name correctly but the phone Numbers are being returned as null. I could not understand the reason behind this.What is it that I am doing wrong? My code is as follows:
NSMutableArray *people = (__bridge_transfer NSMutableArray *) ABAddressBookCopyArrayOfAllPeople (addressBookRef);
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:indexPath.row]), kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:indexPath.row]), kABPersonLastNameProperty);
ABMultiValueRef phoneNumbers = ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:indexPath.row]),kABPersonPhoneProperty);
if (([firstName isEqualToString:#""] || [firstName isEqualToString:#"(null)"] || firstName == nil) &&
([lastName isEqualToString:#""] || [lastName isEqualToString:#"(null)"] || lastName == nil))
{
// do nothing
}
else
{
aName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
if ([firstName isEqualToString:#""] || [firstName isEqualToString:#"(null)"] || firstName == nil)
{
aName = [NSString stringWithFormat:#"%#", lastName];
}
if ([lastName isEqualToString:#""] || [lastName isEqualToString:#"(null)"] || lastName == nil)
{
aName = [NSString stringWithFormat:#"%#", firstName];
}
//[self.tableItems addObject:aName];
NSLog(#"%# added",aName);
}
//fetch multiple phone nos. and use only 0th
id person = people[indexPath.row];
ABMultiValueRef multi = ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonPhoneProperty);
NSString* phone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(multi, 0);
NSLog(#"%#",phone);
[cell.detailTextLabel setText:phone];
[cell.textLabel setText:aName];
return cell;
Here this is a full working code
-(void)GetAddressBook
{
Contacts = [[NSMutableArray alloc]init];
if (ABAddressBookCreateWithOptions) {
#try {
ABAddressBookRef addressBook = ABAddressBookCreate();
// NSArray *people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
if (!addressBook) {
NSLog(#"opening address book");
}
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSLog(#"opening address book ==%ld",nPeople);
for (int i=0;i < nPeople;i++) {
NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
NSString *Contact;
ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));
CFStringRef firstName, lastName;
NSMutableArray *array = [[NSMutableArray alloc]init];
NSString *email;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
ABMultiValueRef multiValueRef = ABRecordCopyValue(ref, kABPersonEmailProperty);
array = [(__bridge NSMutableArray *)ABMultiValueCopyArrayOfAllValues(multiValueRef) mutableCopy];
email = ([array count] > 0) ? array[0] : #"";
if(firstName)
{
Contact = [NSString stringWithFormat:#"%#", firstName];
if(lastName)
Contact = [NSString stringWithFormat:#"%# %#",firstName,lastName];
}
[dOfPerson setObject:Contact forKey:#"name"];
[dOfPerson setObject:[NSString stringWithFormat:#"%d", i] forKey:#"id"];
[dOfPerson setObject:[NSString stringWithFormat:#"%#",#""] forKey:#"found"];
[dOfPerson setObject:email forKey:#"email"];
NSString* mobileLabel;
for(CFIndex j = 0; j< ABMultiValueGetCount(phones); j++)
{
mobileLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(phones, j);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
[dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:#"Phone"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
[dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:#"Phone"];
break ;
}
}
[Contacts addObject:dOfPerson];
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
dispatch_async(dispatch_get_main_queue(), ^{
});
}
The Phone numbers are to be taken like ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));

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

Parse html NSString with REGEX [duplicate]

This question already has answers here:
Convert first number in an NSString into an Integer?
(6 answers)
Objective-C: Find numbers in string
(7 answers)
Closed 10 years ago.
I have NSString with couple strings like this that the 465544664646 is change between them :
data-context-item-title="465544664646"
How i parse the 465544664646 string to a Array ?
Edit
NSRegularExpression* myRegex = [[NSRegularExpression alloc] initWithPattern:#"(?i)(data-context-item-title=\")(.+?)(\")" options:0 error:nil];
[myRegex enumerateMatchesInString:responseString options:0 range:NSMakeRange(0, [responseString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
NSRange range = [match rangeAtIndex:1];
NSString *string =[responseString substringWithRange:range];
NSLog(string);
}];
Try this one:
NSString *yourString=#"data-context-item-title=\"465544664646\" data-context-item-title=\"1212121212\"";
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:yourString];
[scanner scanUpToString:#"\"" intoString:nil];
while(![scanner isAtEnd]) {
NSString *tempString;
[scanner scanString:#"\"" intoString:nil];
if([scanner scanUpToString:#" " intoString:&tempString]) {
[substrings addObject:tempString];
}
[scanner scanUpToString:#"\"" intoString:nil];
}
//NSLog(#"->%#",substrings); //substrings contains all numbers as string.
for (NSString *str in substrings) {
NSLog(#"->%ld",[str integerValue]); //converted each number to integer value, if you want to store as NSNumber now you can store each of them in array
}
Something like this?
-(NSString *)stringFromOriginalString:(NSString *)origin betweenStartString: (NSString*)start andEndString:(NSString*)end {
NSRange startRange = [origin rangeOfString:start];
if (startRange.location != NSNotFound) {
NSRange targetRange;
targetRange.location = startRange.location + startRange.length;
targetRange.length = [origin length] - targetRange.location;
NSRange endRange = [origin rangeOfString:end options:0 range:targetRange];
if (endRange.location != NSNotFound) {
targetRange.length = endRange.location - targetRange.location;
return [origin substringWithRange:targetRange];
}
}
return nil;
}
You can use
- (NSArray *)componentsSeparatedByString:(NSString *)separator
method like
NSArray *components = [#"data-context-item-title="465544664646" componentsSeparatedByString:#"\""];
Now you should got the string at 2. index
[components objectAtIndex:1]
Now you can create array from that string using the method here
NSString to NSArray

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

Extract an NSString using NSScanner

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