show contact images along with contact name in tableview - iphone

I want to show phone contacts along with the pic in table view in alphabetic order.
I have managed to show contact name in correct order but unable to show images in correct order.
I have been trying these for few days but couldn't succeed .
I know how to sort array but don't know how to sort the image data.
please help me guys.
here is my demo code:
NSArray *sortedFirstNames;
- (void)getPersonDetails
{
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil)
{
NSLog(#"Succesful.");
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger i = 0;
NSMutableArray *firstNames = [[NSMutableArray alloc] init];
NSMutableArray *firstimages = [[NSMutableArray alloc] init];
for (i = 0; i < [allContacts count]; i++)
{
Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName;
if (lastName == nil)
{
fullName = [NSString stringWithFormat:#"%#", firstName];
[firstNames addObject: fullName];
}
else if(firstName ==nil)
{
fullName = [NSString stringWithFormat:#"%#", lastName];
[firstNames addObject: fullName];
}
else
{
fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
[firstNames addObject: fullName];
}
person.firstName = firstName;
person.lastName = lastName;
person.fullName = fullName;
//email
imgdata=(__bridge NSData*)ABPersonCopyImageDataWithFormat(contactPerson, kABPersonImageFormatThumbnail);
NSLog(#"newstris%#",imageStr);
if(imgdata==nil)
{
}
else
{
[firstimages addObject:imgdata];
}
[self.tableData addObject:person];
}
sortedFirstNames = [firstNames sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
}
CFRelease(addressBook);
}
code for showing images in cell:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image1;
// cell.imageView.frame = CGRectMake(0, 0, 50, 50);
if (person.imgdata==nil) {
image1=[UIImage imageNamed:#"default_profile_pic.jpg"];
}
else
{
image1 = [UIImage imageWithData:person.imgdata];
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image1];
imageView.frame = CGRectMake(6.5, 6.5, 45., 45.);
dispatch_sync(dispatch_get_main_queue(), ^{
[cell addSubview:imageView];
});
});
Thanks..

Answer is pretty simple.
Add a field in your Person class which stores a NSData.
Like:
#property (nonatomic, strong) NSData *imageData;
And use:
person.imageData = imgdata;

I too faced same issue. I have fixed this issue by associate object like this.
while loading source array:
objc_setAssociatedObject(hDetails, #"imageUrl", record, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
in cell for row at indexpath :
Record *record = objc_getAssociatedObject(hDetails,#"imageUrl");
for more reference see this :
How do I use objc_setAssociatedObject/objc_getAssociatedObject inside an object?

Related

Access contact image from address book based on name

Err,I have been pulling my hair thinking about a way from quite a few days.I have retrieved all contacts names and placed in an array using dictionary.
What I have is a model class holding a list of names,now I want to search the location of name in contacts list,depending on which I can retrieve the required contact image.
Initially googled and found out an unanswered question not pretty much similar to my requirement,the same can be glanced here
I tried several ways,the below is one way I have implemented:
EDIT
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[self loadReminders];
ReminderClass *reminderToDisplay = [self.remindersArray objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
// Now create the cell to display the reminder data
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
}
tableView.backgroundColor = [UIColor clearColor];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init]autorelease];
[dateFormat setDateFormat:kDateFormat];
NSDate *reminderDate = [dateFormat dateFromString:reminderToDisplay.Date];
[dateFormat setDateFormat:kMinDateFormat];
NSString *dateString = [dateFormat stringFromDate:reminderDate];
NSString *valueString = [NSString stringWithFormat:#"%#'s %#",reminderToDisplay.Name,reminderToDisplay.Event];
NSString *onString = [NSString stringWithFormat:#" on %#",dateString];
NSString *reminderDetailsString = [valueString stringByAppendingString:onString];
//Get the contact image based on name index from contact list
ABAddressBookRef addressBook = ABAddressBookCreate( );
CFStringRef reminderName = (CFStringRef)reminderToDisplay.Name;
CFArrayRef allPeople = ABAddressBookCopyPeopleWithName(addressBook, reminderName);
self.contactsList =[[[NSMutableArray alloc]init]autorelease];
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
for ( int i = 0; i < nPeople; i++ )
{
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
NSString *contactFirstNamePart = (NSString *)ABRecordCopyValue(ref,kABPersonFirstNameProperty);
NSString *contactFirstName = [[[NSString alloc] initWithString:contactFirstNamePart]autorelease];
NSString *contactLastNamePart = (NSString *)ABRecordCopyValue(ref, kABPersonLastNameProperty);
if (contactLastNamePart == nil)
{
self.contactName = contactFirstName;
}
else
{
NSString *contactLastName = [[[NSString alloc] initWithString:contactLastNamePart]autorelease];
NSString *contactLastNameString = [NSString stringWithFormat:#" %#",contactLastName];
self.contactName = [contactFirstName stringByAppendingString:contactLastNameString];
CFRelease(contactLastNamePart);
}
NSDictionary *contactsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:self.contactName, kContactName, [NSNumber numberWithInt:i], kContactIndex, nil];
[self.contactsList addObject:contactsDictionary];
CFRelease(contactFirstNamePart);
}
NSDictionary *contactsDictionary = [self.contactsList objectAtIndex:indexPath.row];
self.contactName = [contactsDictionary objectForKey:kContactName];
int addressIndex = [[contactsDictionary objectForKey:kContactIndex]integerValue];
ABRecordRef recordReference = CFArrayGetValueAtIndex(allPeople, addressIndex);
if (ABPersonHasImageData(recordReference))
{
NSData *imageData = (NSData *)ABPersonCopyImageData(recordReference);
self.reminderImage = [UIImage imageWithData:imageData];
CFRelease(imageData);
}
CFRelease(allPeople);
CFRelease(addressBook);
UIImage *notificationImage = reminderImage;
if (notificationImage != nil)
{
UIImageView *imageView=[[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)]autorelease];
imageView.backgroundColor=[UIColor clearColor];
[imageView setImage:notificationImage];
cell.accessoryView = imageView;
}
else
{
UIImageView *imageView=[[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)]autorelease];
imageView.backgroundColor=[UIColor clearColor];
UIImage *defaultImage = [UIImage imageNamed:kDefaultImage];
[imageView setImage:defaultImage];
cell.accessoryView = imageView;
}
cell.textLabel.text = reminderDetailsString;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
Bad Access Error Screen shot
But I was unable to accomplish the required task.Can any one please guide me.
Thanks all in advance :)
I am sharing the sample code snippet I used in one of my recent app. I have modified to fit it ur requirements and also please note that I have edited this in notepad and may have some typo errors.(Currently I dnt have mac to test it..:P)
Basic idea is to fill the datasource in viewDidLoad method and use that dataSource to update the tableView. Hope this will be an input to solve your problem.
viewDidLoad
contactsToBeAdded=[[NSMutableArray alloc] init];
ABAddressBookRef addressbook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
bool hasPhoneNumber = false;
for (int i=0; i < numPeople; i++) {
hasPhoneNumber = false;
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
ABMutableMultiValueRef phonelist = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex numPhones = ABMultiValueGetCount(phonelist);
if(numPhones > 0){
hasPhoneNumber = true;
}
if(hasPhoneNumber){
NSString *firstName=(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName=(NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
CFTypeRef ABphone = ABMultiValueCopyValueAtIndex(phonelist, 0);
NSString *personPhone = (NSString *)ABphone;
NSMutableDictionary *dictToAdd = [[[NSMutableDictionary alloc]init]autorelease];
if(firstName != nil && firstName != NULL){
[dictToAdd setObject:firstName forKey:#"firstName"];
CFRelease(firstName);
}
else{
[dictToAdd setObject:#"" forKey:#"firstName"];
}
if(lastName != nil && lastName != NULL){
[dictToAdd setObject:lastName forKey:#"lastName"];
CFRelease(lastName);
}
else{
[dictToAdd setObject:#"" forKey:#"lastName"];
}
if(personPhone != nil && personPhone != NULL){
[dictToAdd setObject:personPhone forKey:#"mobile"];
CFRelease(ABphone);
}
else{
[dictToAdd setObject:#"" forKey:#"mobile"];
}
//Get the first name and last name added to dict and combine it to full name
NSString *firstName = [dictToAdd objectForKey:#"firstName"];
NSString *lastName = [dictToAdd objectForKey:#"lastName"];
NSString *fullName = [firstName stringByAppendingString:lastName];
//Now check whether the full name is same as your reminderToDisplay.Name
if(reminderToDisplay.Name isEqualToString:fullName )
{
CFDataRef imageData = ABPersonCopyImageData(person);
UIImage *image = [UIImage imageWithData:(NSData *)imageData];
if(image != nil && image != NULL){
[dictToAdd setObject:image forKey:#"image"];
CFRelease(imageData);
}
else{
[dictToAdd setObject:[UIImage imageNamed:TEMP_IMG] forKey:#"image"];
}
}
[contactsToBeAdded addObject:dictToAdd];
}
CFRelease(phonelist);
}
CFRelease(allPeople);
CFRelease(addressbook);
[self.tableView reloadData];
numberOfRowsInSection
return contactsToBeAdded.count;
cellForRowAtIndexPath
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
}
NSDictionary *contactToAdd;
//This way you can get the data added in viewDidLoad method
contactToAdd = [contactsToBeAdded objectAtIndex:indexPath.row];
NSString *fName = (NSString *)[contactToAdd objectForKey:#"firstName"];
NSString *lName = (NSString *)[contactToAdd objectForKey:#"lastName"];
UIImage *contactImg = (UIImage*)[contactToAdd objectForKey:#"image"];
when you use 'ABAddressBookCopyArrayOfAllPeople' you get an array of persons in the addressbook. I believe they are type of ABPerson.
You can now loop over them list like you are. For each one record call 'ABPersonCopyImageData' and that will give you the image data as a CFDataRef.
And remember CFDataRef is a tool free bridge to NSData.
Just try changing your code like this. You are adding dictionary items to ur contactsList, so get each dictionary and check whether it contains a key matching your reminderToDisplay.Name, if yes then do ur stuff..
for (NSDictionary* dict in contactsList)
{
if(nil != [dict objectForKey:reminderToDisplay.Name])
{
//take image here
}
}
UPDATE:
//This is the reminder's name you want to get contact image
ReminderClass *reminderToDisplay = [self.remindersArray objectAtIndex:indexPath.row];
//Here you are adding your contacts with full name as object and kName as key, but check ur kName here
NSDictionary *contactsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:self.contactName, kName, [NSNumber numberWithInt:i], kIndex, nil];
[self.contactsList addObject:contactsDictionary];
//I dont think this part is needed in ur code
NSDictionary *contactsDictionary = [self.contactsList objectAtIndex:indexPath.row];
self.contactName = [contactsDictionary objectForKey:kName];
int addressIndex = [[contactsDictionary objectForKey:kIndex]intValue];
Now you have your contact names as a dictionary in contactsList array, iterate the array and check whether the dictionary contains your reminderToDisplay.Name as key.
for (NSDictionary* dict in contactsList)
{
//Please note that your dict contains key as kName and object as contact name.
if(nil != [dict objectForKey:reminderToDisplay.Name])
{
}
}
Also, I feel like you can do this in one single loop, like when you are iterating the addressbook itself, you can check whether the contact name is in your reminderlist and if available then extract image.
Hope this helps..all the best...

My app crashes with "Program received EXC_BAD_ACCESS" error iphone

When my app launches from BACKGROUND , I am running a new thread to get AddresssBook data using notification center. Here is my code which shows how I call the method
-(void)appLaunchedFromBackground:(NSNotification *) notification {
// NSThread *backgroundThread; is my ivar
backgroundThread = [[NSThread alloc]initWithTarget:self selector:#selector(getUpdatedAddressBookData) object:nil];
[backgroundThread start];
}
-(void)getUpdatedAddressBookData {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AddressBook *addBook = [[AddressBook alloc]init];
[addBook fetchAddressBookDataInBackground];
[addBook release];
[pool drain];
}
Here is my code for fetchAddressBookDataInBackground method
-(void)fetchAddressBookDataInBackground {
if (self.tempArray == nil) {
NSMutableArray *temp = [[NSMutableArray alloc]init];
self.tempArray = temp;
[temp release];
}
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *tempPeople = [[NSArray alloc]init];
tempPeople = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
APP_DELGATE.people = [NSArray arrayWithArray:tempPeople];
int peoCount = [APP_DELGATE.people count];
for (int i=0; i<peoCount; i++) {
ABRecordRef record = [APP_DELGATE.people objectAtIndex:i];
NSNumber *recordId = [NSNumber numberWithInteger:ABRecordGetRecordID(record)];
// Get fname, lname, company
NSString *fnm = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty) ;
NSString *lnm = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty) ;
NSString *comp = (NSString*)ABRecordCopyValue(record,kABPersonOrganizationProperty);
// Get Ph no
ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(record, kABPersonPhoneProperty);
NSArray *tempPhNos = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
NSArray* phoneNumbers = [self getPhoneNoWithoutSymbols:tempPhNos];
NSString *strPhoneNos = [self getStringRepresentaionFromArray:phoneNumbers];
// Get emails
ABMultiValueRef emailProperty = ABRecordCopyValue(record, kABPersonEmailProperty);
NSArray* emails = (NSArray*)ABMultiValueCopyArrayOfAllValues(emailProperty);
NSString *strEmails = [self getStringRepresentaionFromArray:emails];
// Get URL
ABMultiValueRef urlProperty = ABRecordCopyValue(record, kABPersonURLProperty);
NSArray* urls = (NSArray*)ABMultiValueCopyArrayOfAllValues(urlProperty);
NSString *strURLs = [self getStringRepresentaionFromArray:urls];
// Get Address
ABMultiValueRef address=ABRecordCopyValue(record, kABPersonAddressProperty);
CFDictionaryRef dic=nil;
NSMutableArray *addressArray = [[NSMutableArray alloc]init];
for (int index=0; index<ABMultiValueGetCount(address); index++) {
dic=ABMultiValueCopyValueAtIndex(address, index);
NSString* labelName=(NSString*)ABMultiValueCopyLabelAtIndex(address, index);
if (labelName) {
NSString *street =(NSString*) CFDictionaryGetValue(dic, kABPersonAddressStreetKey);
NSString *city= (NSString*)CFDictionaryGetValue(dic, kABPersonAddressCityKey) ;
NSString *state= CFDictionaryGetValue(dic, kABPersonAddressStateKey);
NSString *country=CFDictionaryGetValue(dic, kABPersonAddressCountryKey);
NSString *zipcode=CFDictionaryGetValue(dic, kABPersonAddressZIPKey);
NSString *addressDetails=#"";
if (street) {
addressDetails=[NSString stringWithFormat:#"%# ",street];
}
if (city) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,city];
}
if (state) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,state];
}
if (country) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,country];
}
if (zipcode) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,zipcode];
}
[addressArray addObject:addressDetails];
}
[labelName release];
CFRelease(dic);
}
NSString *strAddress = [self getStringRepresentaionFromArray:addressArray];
// Get Notes
NSString *noteString=(NSString *)ABRecordCopyValue(record, kABPersonNoteProperty);
// Get Birthdate
NSDate *birthDate=(NSDate*)ABRecordCopyValue(record, kABPersonBirthdayProperty) ;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM dd yyyy"];
NSString *birthdateString = [formatter stringFromDate:birthDate];
[formatter release];
// Get user image
UIImage *image = nil;
if( ABPersonHasImageData( record ) ) {
NSData *imageData = (NSData*)ABPersonCopyImageData(record);
image = [UIImage imageWithData:imageData];
[imageData release];
}
NSString *fullName = [NSString stringWithFormat:#"%# %#",fnm,lnm];
// Create User object & add it to array
User *user = [[User alloc]initUserWithUniqID:recordId.intValue FirstName:fnm lastName:lnm compositeName:fullName company:comp phoneNumbers:strPhoneNos emails:strEmails urls:strURLs address:strAddress notes:noteString dob:birthdateString userImage:image];
[self.tempArray addObject:user];
CFRelease(phoneNumberProperty);
[tempPhNos release];
CFRelease(emailProperty);
[emails release];
CFRelease(urlProperty);
[urls release];
CFRelease(address);
[addressArray release];
[birthDate release];
[comp release];
[noteString release];
[lnm release];
[fnm release];
[user release];
}
[tempPeople release];
CFRelease(addressBook);
addressBook = nil;
self.tempArray = [NSMutableArray arrayWithArray:[self.tempArray sortedArrayUsingSelector:#selector(compare:)]];
APP_DELGATE.allUsersArray = self.tempArray;
NSDictionary *dic = [NSDictionary dictionaryWithObject:self.tempArray forKey:BATCH_DONE_KEY];
[[NSNotificationCenter defaultCenter] postNotificationName:BACKGROUND_WORK_DONE_NOTIFICATION object:self userInfo:dic];
}
-(NSMutableArray*)getPhoneNoWithoutSymbols:(NSArray*)array {
if (self.phNoArray == nil) {
NSMutableArray *temp = [[NSMutableArray alloc]init];
self.phNoArray = temp;
[temp release];
}
[self.phNoArray removeAllObjects];
for (NSString *str in array) {
[self.phNoArray addObject:[self getPhNo:str]];
}
return self.phNoArray;
}
-(NSString*)getPhNo:(NSString*)str {
NSString *str0 = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *str1 = [str0 stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *str3 = [str2 stringByReplacingOccurrencesOfString:#"-" withString:#""];
return str3;
}
-(NSString*)getStringRepresentaionFromArray:(NSArray*)array {
return [array componentsJoinedByString:DELIMITER_SYMBOL];
}
But my app crashes with "Program received EXC_BAD_ACCESS" error at any line where I am using "ABRecordCopyValue" function . What I am missing? I am not getting whats wrong in my code?
I tried setting NSZombieEnabled = YES , but its not showing any message. Just saying "Program received EXC_BAD_ACCESS" at any line using ABRecordCopyValue function & in console I see (gdb) thats it.
Any knid of help is highly appreciated. Thanks.

Potential leak of an object allocated in iphone

when i am analyze my project following code gives me leakage warning. is there any way to solve my memory leakage problem ?
warning :
Potential leak of an object allocated on line 38 and stored into 'addressBook'
Bellow is my code.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
m_tableDataArray = [[[NSMutableArray alloc] init]autorelease];
NSMutableArray *listDate = [[[NSMutableArray alloc] init]autorelease];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *addresses = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSInteger addressesCount = [addresses count];
for (int i = 0; i < addressesCount; i++) {
ABRecordRef record = [addresses objectAtIndex:i];
NSString *firstName = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
if(firstName != nil && lastName != nil){
NSString *contactFirstLast = [NSString stringWithFormat: #"%# %#", firstName, lastName];
[listDate addObject:contactFirstLast];
}
[firstName release];
[lastName release];
}
m_tableDataArray = [[NSArray arrayWithArray:listDate] retain];
[addresses release];
addresses = nil;
[m_mainTable reloadData];
}
Thanks in adv...
Once you have finished using addressBook you need to release it using:
CFRelease(addressBook);
This should probably be placed at the end of your viewWillAppear: method.
Updated: There are a few unnecessary arrays and steps in your version of viewWillAppear:. I have cleaned it up a bit and fixed a potential memory leak.
Note: I haven't actually run this so double-check that it works correctly.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// I assume m_tableDataArray is an instance variable. If so, if the
// view appears multiple times it will result in a leak unless we
// release pre-existing instances first.
[m_tableDataArray release], m_tableDataArray = nil;
m_tableDataArray = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *addresses = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
for (ABRecordRef record in addresses) {
NSString *firstName = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
if(firstName != nil && lastName != nil){
NSString *contactFirstLast = [NSString stringWithFormat: #"%# %#", firstName, lastName];
[m_tableDataArray addObject:contactFirstLast];
}
[firstName release];
[lastName release];
}
[addresses release], addresses = nil;
CFRelease(addressBook);
[m_mainTable reloadData];
}

iphone+UIscrollview or to use uitableview to display image in matrix format

I want to display the image(which comes from webservice) the format such that the output in the screen appears like below image:-
Now the logic i had implemented is,i had added the image in uiscrollview.
with the below logic:-
for (int j=0;j<9;j++) {
for (int i=0; i<[mainRestaurantArray count];i++) {
if ([[[mainRestaurantArray objectAtIndex:i] valueForKey:#"Image"] isKindOfClass:[UIImage class]]) {
[CombineArray addObject:[mainRestaurantArray objectAtIndex:i]];
//NSLog(#"cnt=>%d array==>%#",cnt,[CombineArray objectAtIndex:cnt]);
UIButton* btn = [[UIButton alloc]init];
btn.tag = cnt;
btn.frame = CGRectMake(15+(cnt%5)*60, 15+(cnt/5)*60,Width,Height);
btn.backgroundColor = [UIColor greenColor];
[btn setBackgroundImage:[[CombineArray objectAtIndex:cnt] valueForKey:#"Image"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(Buttonclick:) forControlEvents:UIControlEventTouchUpInside];
[ScrlPhotos addSubview:btn];
[btn release];
cnt++;
}
}
[mainRestaurantArray release];
counter++;
[self urlcalled];//The function which calls the webservice
}
//}
ScrlPhotos.contentSize = CGSizeMake(320, ([CombineArray count]/5.0)*60+25);
The function which does the webservice is below:-
-(void)urlcalled{
#try
{
if (rangeDistance == nil) {
rangeDistance =#"100";
}
urlstring[0]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Gym&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[1]=[NSString stringWithFormat:#"http://www.google.com/maps?q=resort&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[2]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Tourist place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[3]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Hotels&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[4]=[NSString stringWithFormat:#"http://www.google.com/maps?q=shopping Mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[5]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Industries&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[6]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Shopping_mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[7]=[NSString stringWithFormat:#"http://www.google.com/maps?q=garden&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[8]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Religious Place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[9]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Restaurants&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
NSLog(#"conte==>%d urlstring[counter]==>%#",counter,urlstring[counter]);
NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlstring[counter]]];
str1 = [str substringFromIndex:9];
//NSLog(#"===>%#",str1);
NSArray *array = [str1 componentsSeparatedByString:#"overlays:"];
NSString *str2 = [array objectAtIndex:1];
NSString *finalUpperStr = [str2 substringFromIndex:21];
array1 = [finalUpperStr componentsSeparatedByString:#"},panel:"];
NSString *strF = [array1 objectAtIndex:0];
NSArray *arrayF = [strF componentsSeparatedByString:#"{id:"];
///////....................this object will change as require in for loop .............................//
mainRestaurantArray = [[NSMutableArray alloc] init];
for (int i=1; i<[arrayF count]-5; i++) {
NSString *strF12 = [arrayF objectAtIndex:i];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *aryF23 = [strF12 componentsSeparatedByString:#"latlng:{"];
//NSLog(#"%#",[aryF23 objectAtIndex:1]);
NSString *strF23 = [aryF23 objectAtIndex:1];
NSArray *ar = [strF23 componentsSeparatedByString:#"},image:"];
//NSLog(#"%#",[ar objectAtIndex:0]);
NSString *strLat = [ar objectAtIndex:0];
NSArray *arrayLat = [strLat componentsSeparatedByString:#","];
NSString *strFLat = [[arrayLat objectAtIndex:0] substringFromIndex:4];
NSString *strLong = [[arrayLat objectAtIndex:1] substringFromIndex:4];
//NSLog(#"Lati = %# Longi = %#" , strFLat , strLong);
[dic setValue:strFLat forKey:#"Latitude"];
[dic setValue:strLong forKey:#"Longitude"];
NSString *strLAdd = [ar objectAtIndex:1];
NSArray *arrayLAdd = [strLAdd componentsSeparatedByString:#"laddr:"];
//NSLog(#"%#",[arrayLAdd objectAtIndex:1]);
NSString *strLAdd1 = [arrayLAdd objectAtIndex:1];
NSArray *arrayLAdd1 = [strLAdd1 componentsSeparatedByString:#"geocode:"];
// NSLog(#"%#",[arrayLAdd1 objectAtIndex:0]);
NSString *strAddres = [[arrayLAdd1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
//NSLog(#"%#",strAddres);
[dic setValue:strAddres forKey:#"Address"];
NSString *strName = [arrayLAdd1 objectAtIndex:1];
NSArray *arrayName = [strName componentsSeparatedByString:#"name:"];
NSString *strName1 = [[arrayName objectAtIndex:1]stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *arrayName1 = [strName1 componentsSeparatedByString:#"infoWindow:"];
[dic setValue:[arrayName1 objectAtIndex:0] forKey:#"Name"];
// for image load .. 07Dec..
NSString *strImage= [arrayF objectAtIndex:i];
NSRange range = [strImage rangeOfString:#"photoUrl"];
if(range.location == NSNotFound){
NSLog(#"Not found");
[dic setValue:#"" forKey:#"Image"];
}else{
NSArray *arrayImage = [strImage componentsSeparatedByString:#"photoUrl:"];
NSString *strImage1 = [arrayImage objectAtIndex:1];
NSArray *arrayImage1 = [strImage1 componentsSeparatedByString:#",photoType:"];
NSString *strfindImage = [[arrayImage1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strfindImage]]];
[dic setValue:myImage forKey:#"Image"];
}
[mainRestaurantArray addObject:dic];
if (i==20) {
break;
}
}
}
#catch (NSException * e)
{
NSLog(#"NSException==>%#",e);
}
}
But the problem i am facing is the image is displayed after completing the loop at 10 times.
I want to display the image parallely as it comes from webservice,so that time taken should be less..
Is there any way out..
Please help me.
Use UIImageView+cacheWeb.. it makes lazy loading a lot easier
http://hackemist.com/SDWebImage/doc/Categories/UIImageView+WebCache.html

How to put my address book data into UITextField

ABAddressBookRef _addressBookRef = ABAddressBookCreate ();
NSArray* allPeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(_addressBookRef);
NSMutableArray* _allItems = [[NSMutableArray alloc] initWithCapacity:[allPeople count]]; // capacity is only a rough guess, but better than nothing
for (id record in allPeople) {
CFTypeRef phoneProperty = ABRecordCopyValue((ABRecordRef)record, kABPersonPhoneProperty);
NSArray *phones = (NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty);
CFRelease(phoneProperty);
for (NSString *phone in phones) {
NSString* compositeName = (NSString *)ABRecordCopyCompositeName((ABRecordRef)record);
NSString* field = [NSString stringWithFormat#"%#:%#",compositeName,phone];
[compositeName release];
[_allItems addObject:field];
}
[phoness release];
}
CFRelease(_addressBookRef);
[allPeople release];
allPeople = nil;
Thats my code now i need assistance with what to import && how would i set my UITextView as that
Thanks for any help
This code puts name and phone number in the _allItems array, which you can subsequently use to fill a textview with:
for ( NSString *txt in _allItems )
{
mytextview.text = [mytextview.text stringByAppendingFormat:#"%#\n",txt];
}
assuming you have a UITextView hooked up named mytextview.