In this section, we present a
sample application that prompts the user to enter a query for a person.
This query is used to retrieve a person with a photo and display it on
the screen as shown in Figure 1
The source code for this application can be found in the PersonPhotoRetriever project available from the source downloads.
Listing 1 shows a category on UIImage to return the photo of the first person in the address book whose name matches a given query.
Example 1. A category on UIImage to return the photo of the first person in the address book whose name matches a given query.
@interface UIImage (AddressBook)
+(UIImage*)photoForAperson:(NSString*)_name;
@end
@implementation UIImage (AddressBook)
// returns the image of the first person give a query
+(UIImage*)photoForAperson:(NSString*)_name{
UIImage *_image = nil;
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *people = (NSArray*)
ABAddressBookCopyPeopleWithName(addressBook, (CFStringRef)_name);
int index = 0;
while (index < [people count]){
ABRecordRef person = (ABRecordRef)[people objectAtIndex:index++];
NSData *photoData = (NSData*) ABPersonCopyImageData(person);
if (photoData){
_image = [UIImage imageWithData:photoData];
[photoData release];
break;
}
}
[people release];
CFRelease(addressBook);
return _image;
}
@end
|
The photoForAperson:
method takes the query text as an argument and returns the photo. It
starts by creating an address book object. After that, the method ABAddressBookCopyPeopleWithName
is used to perform a prefix search using the given query. The function
returns an array of person records that match this query. The method
then iterates through this array retrieving the image data of each
person record using ABPersonCopyImageData function. If the photo data is not nil, a UIImage instance is created from this data and the image is returned.
Listing 2 shows the method triggered when the user taps the Retrieve Photo
button. It simply retrieves the image view and sets it to the image if
an image with the query exists. Otherwise, it displays an alert view.
Example 2. The method triggered when the user taps the Retrieve Photo button.
-(void)buttonPushed{
NSString *name = [(UITextField*)[self.view viewWithTag:999] text];
UIImageView *imageView = (UIImageView*)[self.view viewWithTag:1234];
UIImage *image = [UIImage photoForAperson:name];
if(image){
imageView.image = image;
[[self.view viewWithTag:999] resignFirstResponder];
}
else{
[[[UIAlertView alloc] initWithTitle:@"No Records!"
message:[NSString stringWithFormat:@"%@ photo not found", name]
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"OK", nil] show];
}
}