How to retrieve 10-10 contacts from address book - iphone

I want to implement for getting or loading 10 contacts at a time from address book.Any possibility to retrieve all contacts from address book but display them 10-10 contacts at a time.I am retrieving image,first name,last name of all iphone contacts.I want to implement this to email retrive email contacts also like 10-10 email contacts.
Here is my sample code:
SData *imageData = (NSData *)CFBridgingRelease(ABPersonCopyImageDataWithFormat(ref, kABPersonImageFormatThumbnail)) ;
CFStringRef firstName1, lastName1;
firstName1 = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName1 = ABRecordCopyValue(ref, kABPersonLastNameProperty);
NSString *name=[[NSString alloc]init];
if ([[NSString stringWithFormat:#"%#",firstName1] isEqualToString:#"(null)"] && [[NSString stringWithFormat:#"%#",lastName1] isEqualToString:#"(null)"])
{
name = #"No Name";
}
else if([[NSString stringWithFormat:#"%#",firstName1] isEqualToString:#"(null)"] && ![[NSString stringWithFormat:#"%#",lastName1] isEqualToString:#"(null)"])
{
name = [NSString stringWithFormat:#"%#",lastName1];
}
else
{
name = [NSString stringWithFormat:#"%#",firstName1];
}
name= [ name capitalizedString];
EmailandCotactsModel *emailmodel=[[EmailandCotactsModel alloc]init];
emailmodel.emailemailstring=(__bridge NSString *)(contno);
emailmodel.emailusernamestring=name;
if(!imageData)
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"NoImage" ofType:#"png"];
NSData *photoData = [NSData dataWithContentsOfFile:path];
emailmodel.emailimagesData=photoData;
}
else
{
emailmodel.emailimagesData=imageData;
}
[emailarray addObject:emailmodel];
callsmsDataBool=NO;
NSLog(#"table email count %d and i %d",emailarray.count,tablecountint);
if(emailarray.count==tablecountint)
{
NSLog(#"table email reload");
tablecountint=tablecountint+10;
dispatch_async( dispatch_get_global_queue(0,0),^{
[self reloadtable];
});
NSLog(#"perform selection in bg");
}
}
}
[self.tableview reloadData];
if(!emailarray.count && [socialstring isEqualToString:#"Email"])
{
selectedlabel.text=#"Emails not found";
}
else if(emailarray.count && [socialstring isEqualToString:#"Email"])
{
// selectedlabel.text=#"Email";
selectedlabel.text=[NSString stringWithFormat:#"%ld",nPeople];
}
else if(!emailarray.count && [socialstring isEqualToString:#"SMS"])
{
selectedlabel.text=#"Phone no's not found";
}
else if(emailarray.count && [socialstring isEqualToString:#"SMS"])
{
selectedlabel.text=#"SMS";
}
else
{
selectedlabel.text=#"";
}
[tableview reloadData];
Any valuable suggestions will be appreciated....
Thanks in advance.

After getting all contacts in one array copy ten contacts to another array and cal table reload method with that new array by calling this method initially lowerlimit = 0 and upperlimit=10;
-(void)tabledataloadingmethod
{
for (lowerlimit=0+lowerlimit; lowerlimit<upperlimit; lowerlimit++)
{
if (lowerlimit<[self.array1 count])
{
OBJECT *obj=[self.array1 objectAtIndex:lowerlimit];
[self.array2 addObject:obj];
}
}
[self.tbleview reloadData];
}
in table delagete method cellforrowatindex use this
if ([self.array2 count]==indexPath.row)
{
UITableViewCell *cell1=[self.tbleview dequeueReusableCellWithIdentifier:#"cells"];
if(cell1==nil)
{
cell1=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"Cells"];
}
cell1.textLabel.textColor = [UIColor whiteColor];
cell1.textLabel.text=#"Loading more...";
[self performSelector:#selector(loadmorecells) withObject:nil afterDelay:0.2];
return cell1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self.array2 count]>0 && ([self.array2 count]<[self.array1 count]))
{
return [self.array2 count]+1;
}
else
{
return [self.array2 count];
}
}
here we increment lowerlimit and upperlimit in loadmorecells method
-(void)loadmorecells
{
lowerlimit = upperlimit;
upperlimit = upperlimit +10;
[self tabledataloadingmethod];
}

Related

Detect what was changed from ABAddressBookRegisterExternalChangeCallback

I am using ABAddressBookRegisterExternalChangeCallback to get the external changes in AddressbookBook of the user. I am using the following code to register the callback:
ABAddressBookRef ntificationaddressbook = ABAddressBookCreate();
ABAddressBookRegisterExternalChangeCallback(ntificationaddressbook, MyAddressBookExternalChangeCallback, self);
and when this callback is called then MyAddressBookExternalChangeCallback is called successfully
void MyAddressBookExternalChangeCallback (ABAddressBookRef ntificationaddressbook,CFDictionaryRef info,void *context)
{
NSLog(#"Changed Detected......");
}
I have the following questions:
How can i detect which contacts was changed, and which action (ADD,Update,Delete) was performed on that Contact. I need to get the recordID of that contact. Is it Possible ?
Unfortunately if thats not possible then how the apps like viber, tango, watsapp gets the change information ?
I gets the callback method called only when the app is in background if the app is terminated is there any way to get the changes notification.
Please help. Thanks in advance.
I found the solution to find what was changed in the addressbook. I am not sure if its a precise one, But some how that works.
Create a Callback Notification for Addressbook:-
ABAddressBookRef ntificationaddressbook = ABAddressBookCreate();
ABAddressBookRegisterExternalChangeCallback(ntificationaddressbook, MyAddressBookExternalChangeCallback, self);
Than Add the following code when notification Occurs:-
void MyAddressBookExternalChangeCallback (ABAddressBookRef ntificationaddressbook,CFDictionaryRef info,void *context)
{
NSTimeInterval timeStampone = [[NSDate date] timeIntervalSince1970];
NSNumber *timeStamponeobj= [NSNumber numberWithDouble: timeStampone];
NSLog(#"Start Process");
NSUserDefaults *userdefs = [[NSUserDefaults alloc]init];
NSMutableArray *arraytemp = [[NSMutableArray alloc]init];
CFArrayRef peopleRefs = ABAddressBookCopyArrayOfAllPeopleInSource(ntificationaddressbook, kABSourceTypeLocal);
NSMutableArray *changedrecords = [[NSMutableArray alloc]init];
ABAddressBookRevert(ntificationaddressbook);
CFIndex count = CFArrayGetCount(peopleRefs);
for (CFIndex i=0; i < count; i++) {
ABRecordRef ref = CFArrayGetValueAtIndex(peopleRefs, i);
NSDate* datemod = ( NSDate *)(ABRecordCopyValue(ref, kABPersonModificationDateProperty));
NSDate *lastopened = [userdefs valueForKey:#"LastOpenedDate"];
NSTimeInterval datemodifiedtime =[datemod timeIntervalSince1970];
NSNumber *modifieddatenumber= [NSNumber numberWithDouble: datemodifiedtime];
NSTimeInterval lastopeddate = [lastopened timeIntervalSince1970];
NSNumber *lastopenednumber= [NSNumber numberWithDouble: lastopeddate];
if ([modifieddatenumber intValue]>[lastopenednumber intValue]) {
ABRecordRef aSource = CFArrayGetValueAtIndex(peopleRefs,i);
int recordid = ABRecordGetRecordID(aSource);
[changedrecords addObject:[NSString stringWithFormat:#"%d",recordid]];
}
}
NSString *arraystring= [changedrecords componentsJoinedByString:#","];
[userdefs setValue:arraystring forKey:#"ArrayOfChangedPeopleString"];
[userdefs setValue:changedrecords forKey:#"ArrayOfChangedPeople"];
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if ([arraystring isEqualToString:#"(null)"]) {
arraystring = [arraystring stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
}
NSLog(#"arraychangedstring= %# and length = %d",arraystring,arraystring.length);
NSLog(#"Must send data to the server here for this changed people array= %#",changedrecords);
if (arraystring.length>2) {
NSLog(#"inside if");
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allSources = ABAddressBookCopyArrayOfAllPeople( addressBook );
[userdefs setValue:#"" forKey:#"ArrayOfChangedPeopleString"];
[userdefs setValue:#"" forKey:#"ArrayOfChangedPeople"];
for (int i = 0; i<[changedrecords count]; i++) {
NSString *recordid= [changedrecords objectAtIndex:i];
int nPeople = [recordid intValue];
[IntoochUtil current_function_name:#"Inside getcontactdetails - Start"];
if(nPeople != 0){
// for (CFIndex i = nPeople_start; i < (nPeople_end); i++)
// {
// NSString *reocrdid = [NSString stringWithFormat: #"Record %ld",i];
// NSLog(#"Recordid= %#",reocrdid);
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
//common field
NSString *first_name =nil;
NSString *mid_name = nil ;
NSString *last_name =nil ;
NSString *basic_email =nil ;
NSString *basic_mobile =nil ;
NSString *other_phone=nil;
NSString *pager_phone= nil;
//personal filed
NSString *Home_email =nil ;
NSString*home_mobile =nil ;
NSString*home_address =nil;
//business filed
NSString *work_email =nil ;
NSString *company_name =nil ;
NSString *job_title =nil ;
NSString*work_mobile =nil ;
NSString *iphone = nil;
NSString *main = nil;
NSString *work_address =nil ;
NSString *home_fax, *work_fax, *other_fax =nil;
NSString *birthday = nil;
// NSString *blogs = nil;
NSString *record_id;
ABRecordRef aSource = ABAddressBookGetPersonWithRecordID(addressBook, nPeople);
// Fetch all groups included in the current source
// Getting Record id from address book
int recordid = ABRecordGetRecordID(aSource);
record_id = [NSString stringWithFormat:#"%d",recordid];
// Getting Names from address book
// CFStringRef firstName = ABRecordCopyValue(aSource, kABPersonFirstNameProperty);
first_name= ABRecordCopyValue(aSource, kABPersonFirstNameProperty);
// first_name=[NSString stringWithFormat:#"%#",firstName];
// CFRelease(firstName);
// NSLog(#"First name= %#",first_name);
NSMutableDictionary *dict_name = [[NSMutableDictionary alloc]init];
if (!([first_name isEqualToString:#"(null)"]|| first_name == nil || first_name.length ==0))
{
[dict_name setValue:first_name forKey:#"FirstName"];
}
[first_name release];
mid_name= ABRecordCopyValue(aSource, kABPersonMiddleNameProperty);
// NSLog(#"mid name = %#",mid_name);
// CFRelease(midname);
if (!([mid_name isEqualToString:#"(null)"]|| mid_name == nil || mid_name.length ==0))
{
[dict_name setValue:mid_name forKey:#"MiddleName"];
}
[mid_name release];
last_name = ABRecordCopyValue(aSource, kABPersonLastNameProperty);
// NSLog(#"Last Name= %#",last_name);
// CFRelease(lastName);
if (!([last_name isEqualToString:#"(null)"]|| last_name == nil || last_name.length ==0))
{
[dict_name setValue:last_name forKey:#"LastName"];
}
[last_name release];
NSString *dictNamestring = [NSString stringWithFormat:#"%#",dict_name];
if (!([dictNamestring isEqualToString:#"(null)"]|| dictNamestring == nil || dictNamestring.length <4))
{
[dict setValue:dict_name forKey:#"Names"];
}
// [dict_name release];
// Getting Phone numbers from address book
NSMutableDictionary *dict_phone = [[NSMutableDictionary alloc]init];
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(aSource, kABPersonPhoneProperty);
NSString* mobileLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
home_mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i) ;
[dict_phone setValue:home_mobile forKey:#"Mobile"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABHomeLabel])
{
basic_mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
[dict_phone setValue:basic_mobile forKey:#"Home"];
}
else if([mobileLabel isEqualToString:(NSString *)kABWorkLabel])
{
work_mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
[dict_phone setValue:work_mobile forKey:#"Work"];
}
else if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneIPhoneLabel])
{
iphone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
[dict_phone setValue:iphone forKey:#"iPhone"];
}
else if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMainLabel])
{
main = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
[dict_phone setValue:main forKey:#"Main"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABOtherLabel])
{
other_phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
[dict_phone setValue:other_phone forKey:#"OtherPhone"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhonePagerLabel])
{
pager_phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
[dict_phone setValue:pager_phone forKey:#"Pager"];
}
else
{
NSLog(#"%# label is not processed",mobileLabel);
}
}
CFRelease(phones);
NSString *dictphonestring = [NSString stringWithFormat:#"%#",dict_phone];
if (!([dictphonestring isEqualToString:#"(null)"]|| dictphonestring == nil || dictphonestring.length <4))
{
[dict setValue:dict_phone forKey:#"PhoneNos"];
}
// [dict_phone release];
// Getting Fax numbers from address book
NSMutableDictionary *dict_fax = [[NSMutableDictionary alloc]init];
ABMultiValueRef faxes =(NSString*)ABRecordCopyValue(aSource, kABPersonPhoneProperty);
NSString* FaxLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(faxes); i++) {
FaxLabel = (NSString*)ABMultiValueCopyLabelAtIndex(faxes, i);
if([FaxLabel isEqualToString:(NSString *)kABPersonPhoneHomeFAXLabel])
{
home_fax = (NSString*)ABMultiValueCopyValueAtIndex(faxes, i) ;
[dict_fax setValue:home_fax forKey:#"Home"];
}
if ([FaxLabel isEqualToString:(NSString*)kABPersonPhoneWorkFAXLabel])
{
work_fax = (NSString*)ABMultiValueCopyValueAtIndex(faxes, i);
[dict_fax setValue:work_fax forKey:#"Work"];
}
if([FaxLabel isEqualToString:(NSString *)kABPersonPhoneOtherFAXLabel])
{
other_fax = (NSString*)ABMultiValueCopyValueAtIndex(faxes, i);
[dict_fax setValue:other_fax forKey:#"Other"];
}
}
CFRelease(faxes);
NSString *dictfaxstring = [NSString stringWithFormat:#"%#",dict_fax];
if (!([dictfaxstring isEqualToString:#"(null)"]|| dictfaxstring == nil || dictfaxstring.length <4))
{
[dict setValue:dict_fax forKey:#"FaxNos"];
}
[dict_fax release];
// Getting emails from address book
ABMultiValueRef email = ABRecordCopyValue(aSource, kABPersonEmailProperty);
NSMutableDictionary *dict_email = [[NSMutableDictionary alloc]init];
NSString* email_lbl;
for(CFIndex i = 0; i < ABMultiValueGetCount(email); i++) {
email_lbl = (NSString*)ABMultiValueCopyLabelAtIndex(email, i);
if([email_lbl isEqualToString:(NSString *)kABHomeLabel])
{
Home_email = [(NSString*)ABMultiValueCopyValueAtIndex(email, i)retain];
[dict_email setValue:Home_email forKey:#"Home"];
}
else if([email_lbl isEqualToString:(NSString *)kABWorkLabel])
{
work_email = [(NSString*)ABMultiValueCopyValueAtIndex(email, i)retain];
[dict_email setValue:work_email forKey:#"Work"];
}
else if([email_lbl isEqualToString:(NSString *)kABOtherLabel])
{
basic_email = [(NSString*)ABMultiValueCopyValueAtIndex(email, i)retain];
[dict_email setValue:basic_email forKey:#"Other"];
}
else
{
NSLog(#"%# label is processed as other",email_lbl);
basic_email = [(NSString*)ABMultiValueCopyValueAtIndex(email, i)retain];
[dict_email setValue:basic_email forKey:#"Other"];
}
}
CFRelease(email);
NSString *dictemailstring = [NSString stringWithFormat:#"%#",dict_email];
if (!([dictemailstring isEqualToString:#"(null)"]|| dictemailstring == nil || dictemailstring.length <4))
{
[dict setValue:dict_email forKey:#"Emails"];
}
// [dict_email release];
company_name = ABRecordCopyValue(aSource, kABPersonOrganizationProperty);
// NSLog(#"Company name= %#",company_name);
job_title = ABRecordCopyValue(aSource, kABPersonJobTitleProperty);
// NSLog(#"Job title= %#",job_title);
NSDate *birthdate = ABRecordCopyValue(aSource, kABPersonBirthdayProperty);
NSString *birthdate_string = [NSString stringWithFormat:#"%#",birthdate];
if (!([birthdate_string isEqualToString:#"(null)"]|| birthdate_string == nil || birthdate_string.length ==0)) {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:birthdate];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
birthday = [NSString stringWithFormat:#"%d-%d-%d",day,month,year];
NSLog(#"birthday= %#",birthday);
}
[birthdate release];
// Getting addressess from address book
ABMultiValueRef address =(NSString*)ABRecordCopyValue(aSource, kABPersonAddressProperty);
NSDictionary *dict_address = [[NSMutableDictionary alloc]init];
NSString* addLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(address); i++) {
addLabel=(NSString*)ABMultiValueCopyLabelAtIndex(address, i);
if ([addLabel isEqualToString:(NSString*)kABWorkLabel]) {
NSMutableDictionary *dict_work_add = [(NSMutableDictionary *)ABMultiValueCopyValueAtIndex(address, i)retain];
work_address=[NSString stringWithFormat:#"%# %# %# %# %#",[dict_work_add objectForKey:#"Street"],[dict_work_add objectForKey:#"City"],[dict_work_add objectForKey:#"State"],[dict_work_add objectForKey:#"Country"],[dict_work_add objectForKey:#"ZIP"]] ;
work_address = [work_address stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
work_address = [work_address stringByReplacingOccurrencesOfString:#"\n" withString:#""];
// NSLog(#"work address = [%#] and length= %d",work_address,work_address.length);
if (!([work_address isEqualToString:#"(null)"]|| work_address == nil || work_address.length ==0))
{
[dict_address setValue:work_address forKey:#"Work"];
}
}
if ([addLabel isEqualToString:(NSString*)kABHomeLabel])
{
NSMutableDictionary *dict_home_add = [(NSMutableDictionary *)ABMultiValueCopyValueAtIndex(address, i)retain];
home_address = [NSString stringWithFormat:#"%# %# %# %# %#",[dict_home_add objectForKey:#"Street"],[dict_home_add objectForKey:#"City"],[dict_home_add objectForKey:#"State"],[dict_home_add objectForKey:#"Country"],[dict_home_add objectForKey:#"ZIP"]];
home_address = [home_address stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
home_address = [home_address stringByReplacingOccurrencesOfString:#"\n" withString:#""];
// NSLog(#"home address = [%#] and length= %d",home_address,home_address.length);
if (!([home_address isEqualToString:#"(null)"]|| home_address == nil || home_address.length ==0))
{
[dict_address setValue:home_address forKey:#"Home"];
}
}
}
CFRelease(address);
NSString *dictaddrssstring = [NSString stringWithFormat:#"%#",dict_address];
if (!([dictaddrssstring isEqualToString:#"(null)"]|| dictaddrssstring == nil || dictaddrssstring.length <4))
{
[dict setValue:dict_address forKey:#"Addresses"];
}
[dict_address release];
// Getting Social Networks from address book
ABMultiValueRef social =(NSString*)ABRecordCopyValue(aSource, kABPersonSocialProfileProperty);
NSMutableDictionary *dict_social = [[NSMutableDictionary alloc]init];
if (social) {
for (int i = 0 ; i < ABMultiValueGetCount(social); i++) {
NSDictionary *socialDict = (NSDictionary *)ABMultiValueCopyValueAtIndex(social, i);
NSString *twitterid;
if ([socialDict[#"service"] isEqualToString:(NSString*)kABPersonSocialProfileServiceTwitter]) {
twitterid = (NSString*)socialDict[#"username"];
[dict_social setValue:twitterid forKey:#"Twitter"];
}
NSString *facebookid;
if ([socialDict[#"service"] isEqualToString:(NSString*)kABPersonSocialProfileServiceFacebook]) {
facebookid = (NSString*)socialDict[#"username"];
[dict_social setValue:facebookid forKey:#"Facebook"];
}
NSString *linkedinid;
if ([socialDict[#"service"] isEqualToString:(NSString*)kABPersonSocialProfileServiceLinkedIn]) {
linkedinid = (NSString*)socialDict[#"username"];
[dict_social setValue:linkedinid forKey:#"LinkedIn"];
}
NSString *gamecenterid;
if ([socialDict[#"service"] isEqualToString:(NSString*)kABPersonSocialProfileServiceGameCenter]) {
gamecenterid = (NSString*)socialDict[#"username"];
[dict_social setValue:gamecenterid forKey:#"GameCenter"];
}
NSString *myspaceid;
if ([socialDict[#"service"] isEqualToString:(NSString*)kABPersonSocialProfileServiceMyspace]) {
myspaceid = (NSString*)socialDict[#"username"];
[dict_social setValue:myspaceid forKey:#"MySpace"];
}
NSString *flickerid;
if ([socialDict[#"service"] isEqualToString:(NSString*)kABPersonSocialProfileServiceFlickr]) {
flickerid = (NSString*)socialDict[#"username"];
[dict_social setValue:flickerid forKey:#"Flicker"];
}
[socialDict release];
}
CFRelease(social);
}
NSString *dictsocialstring = [NSString stringWithFormat:#"%#",dict_social];
if (!([dictsocialstring isEqualToString:#"(null)"]|| dictsocialstring == nil || dictsocialstring.length <4))
{
[dict setValue:dict_social forKey:#"SocialNetworks"];
}
[dict_social release];
// Getting Other Fields from address book
NSMutableDictionary *dict_others = [[NSMutableDictionary alloc]init];
if (!([company_name isEqualToString:#"(null)"]||company_name == nil || company_name.length ==0)) {
[dict_others setValue:company_name forKey:#"CompanyName"];
}
if (!([job_title isEqualToString:#"(null)"]||job_title == nil || job_title.length ==0)) {
[dict_others setValue:job_title forKey:#"JobTitle"];
}
if (!([birthday isEqualToString:#"1-1-2001"]||[birthday isEqualToString:#"(null)"]||birthday == nil || birthday.length ==0)) {
[dict_others setValue:birthday forKey:#"BirthDay"];
}
NSString *dictothersstring = [NSString stringWithFormat:#"%#",dict_others];
if (!([dictothersstring isEqualToString:#"(null)"]|| dictothersstring == nil || dictothersstring.length <4))
{
[dict setValue:dict_others forKey:#"OtherInfo"];
}
[dict_others release];
[dict setValue:record_id forKey:#"RecordID"];
//This NSLog(#"Value for Dict is========= %# =========",dict);
NSString *namedictionstring = [NSString stringWithFormat:#"%#",dict_name];
NSString *emaildictstring = [NSString stringWithFormat:#"%#",dict_email];
NSString *phonedictstring = [NSString stringWithFormat:#"%#",dict_phone];
// NSLog(#"name dict length= %d email dict length= %d phone dict length = %d",namedictionstring.length,emaildictstring.length,phonedictstring.length);
// [array_addressbook addObject:dict];
if (phonedictstring.length >3) {
[arraytemp addObject:dict];
}
else
{
if (emaildictstring.length>3 && namedictionstring.length) {
[arraytemp addObject:dict] ;
}
else
{
NSLog(#"Contact is not valid= %#",dict_name);
}
}
[dict_name release];
[dict_phone release];
[dict_email release];
[dict release];
[company_name release];
[job_title release];
/* CFRelease(firstName);
CFRelease(midname);
CFRelease(lastName);
CFRelease(jobtitle);
CFRelease(birthday_c);
CFRelease(companyname);*/
// }
}
}
NSString *json_array_string = [arraytemp JSONRepresentation];
[IntoochUtil current_function_name:#"Inside getcontactdetails - End"];
NSLog(#"Json String To send= %#",json_array_string);
if (allSources) {
CFRelease(allSources);
}
if (addressBook) {
CFRelease(addressBook);
}
}
else
{
NSLog(#"This is empty.... nothing to perform");
NSMutableArray *arrayofdeletedpeoples= [[NSMutableArray alloc]init];
ABAddressBookRef addressbook = ABAddressBookCreate();
CFArrayRef allPeoples= ABAddressBookCopyArrayOfAllPeople(addressbook);
NSMutableArray *arrayofrecordIDCallback = [[NSMutableArray alloc]init];
int count = CFArrayGetCount(allPeoples);
for (int i =0; i<count; i++) {
ABRecordRef aSource = CFArrayGetValueAtIndex(allPeoples,i);
NSString * recordid = [NSString stringWithFormat:#"%d",ABRecordGetRecordID(aSource)];
[arrayofrecordIDCallback addObject:recordid];
}
NSLog(#"arrayofrecordIDCallback = %# and count= %d",arrayofrecordIDCallback,[arrayofrecordIDCallback count]);
NSMutableArray *arrayofallrecordids = [userdefs valueForKey:#"AllRecordIDSBackGround"];
NSLog(#"arrayofallrecordids= %# and count= %d",arrayofallrecordids,[arrayofallrecordids count]);
for (int i=0 ; i< [arrayofallrecordids count]; i++) {
if ([arrayofrecordIDCallback containsObject:[arrayofallrecordids objectAtIndex:i]]) {
}
else
{
[arrayofdeletedpeoples addObject:[arrayofallrecordids objectAtIndex:i]];
}
}
NSLog(#"Array of deleted peoples= %#",arrayofdeletedpeoples);
[arrayofdeletedpeoples release];
[arrayofallrecordids release];
[arrayofrecordIDCallback release];
if (allPeoples) {
CFRelease(allPeoples);
}
if (addressbook) {
CFRelease(addressbook);
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
[changedrecords release];
[userdefs release];
[arraytemp release];
NSLog(#"Ends Process");
NSTimeInterval timeStamptwo = [[NSDate date] timeIntervalSince1970];
NSNumber *timeStamptwoObj = [NSNumber numberWithDouble: timeStamptwo];
NSLog(#"Time Difference= %d",[timeStamptwoObj intValue]-[timeStamponeobj intValue]);
}
Yes thats true that you can not get specific notification on Phonebook changes. You will need to synch your data when callback notification fire.
void MyAddressBookExternalChangeCallback (ABAddressBookRef ntificationaddressbook,CFDictionaryRef info,void *context)
{
NSLog(#"Changed Detected......");
// synch data
}
The apps like viber, tango, watsapp also does the same thing but in Background thread.
If the app is terminated, then you will need to synch data when app gets started like in didFinishLaunchingWithOptions.
As far I know, you can't tell what are the difference - I bumped to this problem myself.
My solution was:
I had a local Core Data based address book, and every time I got this notification, I ran a background thread that synchronised the data, and notify in the end all the changes.
During the first time, I am dumping all the data in local database using sqlite, then on external change I am dumping new data from contacts database in dummy db in sqlite, then firing big long compare query based on what has changed. In our case, main focus was on phone numbers and name. Once you get change update that in your contacts db in sqlite.
I think even whatsapp is doing something similar. I checked the time taken to reflect the changes by whatsapp and our app almost are similar. Actually, my app is 2 secs faster than whatsapp in terms of reflecting changes.
Hope this will help.

How do I get a list of the user's contacts in iOS 6?

I have been using the following code for a few years now and it has always worked, but it looks like with iOS 6 it doesn't anymore. How do I get a list of all contacts on an iOS 6 device?
ABAddressBookRef myAddressBook = ABAddressBookCreate();
NSMutableArray *people = (__bridge_transfer NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(myAddressBook);
CFRelease(myAddressBook);
// repeat through all contacts in the inital array we loaded
for(int i=0; i<[people count]; i++)
{
NSString *aName;
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:i]), kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue((__bridge ABRecordRef)([people objectAtIndex:i]), kABPersonLastNameProperty);
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];
}
}
[self.tableItems sortUsingSelector:#selector(compare:)];
In ios6 you need to ask for permission to read the AddressBook, otherwise you'll get nil. Use something like this:
- (BOOL)askContactsPermission {
__block BOOL ret = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS6
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRef addressBook = ABAddressBookCreate();
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
ret = granted;
dispatch_semaphore_signal(sema);
});
if (addressBook) {
CFRelease(addressBook);
}
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);
}
else { // we're on iOS5 or older
ret = YES;
}
return ret;
}
If this method returns NO, bad luck, you won't be able to access the AB. I'm locking with a semaphore here because I don't want to continue with my app if the user does not allow the AB. There other methods, just check the API.
You do need to ask the user for permission which will trigger a prompt to the user when you do so. Here's another way to do this using execution blocks to handle the result, also makes the usage of it version agnostic if you need to query your current access status from common code.
I implement an access manager like so
AppContactsAccessManager.h
#import <AddressBook/AddressBook.h>
typedef enum
{
kABAuthStatusNotDetermined = 0,
kABAuthStatusRestricted,
kABAuthStatusDenied,
kABAuthStatusAuthorized,
kABAuthStatusPending,
}AddressBookAuthStatus;
typedef void (^AddressbookRequestHandler)(ABAddressBookRef addressBookRef, BOOL available);
#interface AppContactsAccessManager : NSObject
{
AddressBookAuthStatus status;
}
- (void) requestAddressBookWithCompletionHandler:(AddressbookRequestHandler)handler;
- (AddressBookAuthStatus) addressBookAuthLevel;
#end
AppContactsAccessManager.m
#implementation AppContactsAccessManager
- (BOOL) isStatusAvailable:(AddressBookAuthStatus)theStatus
{
return (theStatus == kABAuthStatusAuthorized || theStatus == kABAuthStatusRestricted);
}
- (void) requestAddressBookWithCompletionHandler:(AddressbookRequestHandler)handler
{
ABAddressBookRef addressBookRef = NULL;
if([self isiOS6]){
addressBookRef = ABAddressBookCreateWithOptions(nil, nil);
ABAuthorizationStatus curStatus = ABAddressBookGetAuthorizationStatus();
if(curStatus == kABAuthorizationStatusNotDetermined)
{
status = kABAuthStatusPending;
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
status = ABAddressBookGetAuthorizationStatus();
if(handler != NULL){
handler(addressBookRef, [self isStatusAvailable:status]);
}
});
}else
{
status = curStatus;
dispatch_async(dispatch_get_current_queue(), ^{
if(handler != NULL){
handler(addressBookRef, [self isStatusAvailable:status]);
}
});
}
}else
{
addressBookRef = ABAddressBookCreate();
status = kABAuthStatusAuthorized;
dispatch_async(dispatch_get_current_queue(), ^{
if(handler != NULL){
handler(addressBookRef, [self isStatusAvailable:status]);
}
});
}
}
- (AddressBookAuthStatus) addressBookAuthLevel
{
return status;
}
#end
usage would look something like:
AppContactsAccessManager* accessMgr = [AppContactsAccessManager new];
[accessMgr requestAddressBookWithCompletionHandler:^(ABAddressBookRef theAddressBookRef, BOOL available) {
// do your addressbook stuff in here
}];

how to Sort/Group JSON items

***Updated Question ******
The JSON data is the Gym Classes for all week .
At the moment I am downloading and saved the JSON data to An NSObject SearchResult then display on my UItableviewController one row per gym Class.
But I want to Group items (Gym Classes) By Day and display each day on is own table.
So my question is do I need to group items by date "DAY_OF_WEEK" and store each day in to is own array (MonArray ... SunArray)?
or collect all the data Like I am doing now and sort the array in to groups for each day?
I hope this make sense.
thanks for your help .
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: JsonURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES]; }); }
-(SearchResult *)parseTrack:(NSDictionary *)dictionary {
SearchResult *searchResult1 = [[SearchResult alloc] init];
searchResult1.day = [[dictionary objectForKey:#"post"] objectForKey:#"DAY_OF_WEEK"];
searchResult1.classType= [[dictionary objectForKey:#"post"] objectForKey:#"CLASS_TYPE"];
return searchResult1;
}
- (void)fetchedData:(NSData *)responseData { //parse out the json data
searchResults2 = [NSMutableArray arrayWithCapacity:10];
NSError* error;
NSDictionary* dictionary = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions error:&error];
NSArray *array = [dictionary objectForKey:#"posts"];
NSLog(#"array : %#",array);
if (array == nil) {
NSLog(#"Expected 'posts' array");
return;
}
for (NSDictionary *resultDict in array) {
SearchResult *searchResult3;
searchResult3 = [self parseTrack:resultDict];
if (searchResult3 != nil) {
[searchResults2 addObject:searchResult3];
}
NSLog(#"day: %#, class: %#", [[resultDict objectForKey:#"post"] objectForKey:#"DAY_OF_WEEK"], [[resultDict objectForKey:#"post"] objectForKey:#"CLASS_TYPE"]);
}
[self.tableView reloadData];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return searchResults2.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SRCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SRCell1"];
// Configure the cell...
SearchResult *searchResult1 = [searchResults2 objectAtIndex:indexPath.row];
cell.daynameLabel.text = searchResult1.day;
return cell;
}
JSON output NSlog
2012-04-26 06:12:51.256 passingdata[91699:fb03] array : (
{
post = {
"CLASS_LEVEL" = "Intro/General";
"CLASS_TYPE" = "Muay Thai";
"DAY_OF_WEEK" = Friday;
ID = 19;
"ORDER_BY" = 5;
TIME = "1:00pm - 2:30pm";
};
}
{
post = {
"CLASS_LEVEL" = "General/Intermediate/Advanced";
"CLASS_TYPE" = "Muay Thai Spar - Competitive";
"DAY_OF_WEEK" = Friday;
ID = 27;
"ORDER_BY" = 5;
TIME = "6:00pm - 9:00pm";
};
},
{
post = {
"CLASS_LEVEL" = "Fighters/Advanced/Intermediate";
"CLASS_TYPE" = "Fighters Training";
"DAY_OF_WEEK" = Monday;
ID = 1;
"ORDER_BY" = 1;
TIME = "9:30am - 11:00pm";
};
},
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"DAY_OF_WEEK" ascending:TRUE];
[sourceArr sortUsingDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
May this will help you.

How to check value is coming from json is null or not?

I want to check result of json is null or not ..I used this code
- (NSString *)likesCount {
if ([facebook valueForKey:#"likes"] == [NSNull null]) {
return #"";
}
else {
return [facebook valueForKey:#"likes"];
}
}
likes = 1; if it exists and if it is null "like" is not visible in output.. But if it is not present then it is returning (null) .. I used above code but it is not working.
I am printing this value of likes in UItableviewcell
UILabel *commentLike = [[UILabel alloc] initWithFrame:CGRectMake(200, 70, 100, 20)];
commentLike.font = [UIFont fontWithName:#"Arial" size:10.0];
NSString *commentLikeString = [NSString stringWithFormat:#"%# ",[(Facebook *)[tableArray objectAtIndex:indexPath.row]likesCount]];
commentLike.text = [NSString stringWithFormat:#"%# Person"];
[cell.contentView addSubview:commentLike];
Thanks
Use this category on NSDictionary, code will be much cleaner:
TouchJSON, dealing with NSNull
Try this code
- (NSString *)likesCount {
if ([[facebook valueForKey:#"likes"] isEqualToString:#"(null)"] || [facebook valueForKey:#"likes"] == nil) {
return #"";
}
else {
return [facebook valueForKey:#"likes"];
}
}

how to search contact from address book using uitextview in iphone?

i'm using uitextview for searching the contact details from address book. i.e., like uisearchbar search the contact details while text edit change in uitextview.
i'm using uitextview if i tap 'a', the list of the contacts from address book will be display in table view
please give me the solution
Finally I got the solution simple coding here it is
//viewDidLoad
NSMutableArray *personArray = [[NSMutableArray alloc] init];
ABRecordRef personRef;
for (int i = 0; i < CFArrayGetCount(allPeople); i++)
{
personRef = (ABRecordID*)CFArrayGetValueAtIndex(allPeople, i);
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, ABRecordGetRecordID(personRef));
#try
{
if (ABRecordCopyValue(person, kABPersonBirthdayProperty))
[personArray addObject: (id)personRef];
}
#catch (NSException * e)
{
}
#finally
{
}
NSString *FirstName = [[[NSString stringWithString:(NSString *)ABRecordCopyValue(personRef, kABPersonFirstNameProperty)]stringByAppendingString:#" "]stringByAppendingString:(NSString *)ABRecordCopyValue(personRef, kABPersonLastNameProperty)];
[arr addObject:FirstName];
}
[arr3 addObjectsFromArray:arr];
}
//textviewdidchange
[arr3 removeAllObjects];
NSInteger counter = 0;
for(NSString *name in arr)
{
NSRange r = [name rangeOfString:txtView.text options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound)
{
[arr3 addObject:name];
}
counter++;
}
[table reloadData];
Thanks for your help