How to get user's email id of google account? - iphone

I am working on an iPhone app in which I am giving user option to login with his/her google account. Now, I want that user's google email id through JSON or XML. I have searched a lot, but did not satisfactory result.
Thanx in advance.

did you check the oauth autorization with google api at their developers site?
https://developers.google.com/accounts/docs/OAuth2

i think you can find something from this link.....
hope this link help you.....
http://code.google.com/p/gdata-objectivec-client/wiki/GDataObjCIntroduction
and
also https://code.google.com/p/gdata-objectivec-client/
:)
write bellow code when you want to get contact....
GDataServiceGoogleContact *service = [self contactService];
GDataServiceTicket *ticket;
BOOL shouldShowDeleted = TRUE;
const int kBuncha = 2000;
NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
GDataQueryContact *query = [GDataQueryContact contactQueryWithFeedURL:feedURL];
[query setShouldShowDeleted:shouldShowDeleted];
[query setMaxResults:kBuncha];
ticket = [service fetchFeedWithQuery:query
delegate:self
didFinishSelector:#selector(contactsFetchTicket:finishedWithFeed:error:)];
[self setContactFetchTicket:ticket];
bellow method is GmailAPI delegate method...
- (GDataServiceGoogleContact *)contactService
{
static GDataServiceGoogleContact* service = nil;
if (!service) {
service = [[GDataServiceGoogleContact alloc] init];
[service setShouldCacheResponseData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
[service setUserCredentialsWithUsername:txtEmail.text
password:txtPass.text];
return service;
}
after that you can get contact with bellow code...
for (int i = 0; i < [contacts count]; i++) {
GDataEntryContact *contact = [contacts objectAtIndex:i];
// NSLog(#">>>>>>>>>>>>>>>> elementname contact :%#", [[[contact name] fullName] contentStringValue]);
NSString *ContactName = [[[contact name] fullName] contentStringValue];
GDataEmail *email = [[contact emailAddresses] objectAtIndex:0];
// NSLog(#">>>>>>>>>>>>>>>> Contact's email id :%# contact name :%#", [email address], ContactName);
NSString *ContactEmail = [email address];
}
hope this help you....
:)

Related

GData Objective-C Client Contact Service

I downloaded the last GData client via SVN https://code.google.com/p/gdata-objectivec-client/
I succesfully compiled it and I integrated successfully the static library inside my project.
I need to retrieve all gmail contacts about a google username:
- (GDataServiceGoogleContact *)contactService {
static GDataServiceGoogleContact* service = nil;
if (!service) {
service = [[GDataServiceGoogleContact alloc] init];
[service setShouldCacheResponseData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
// update the username/password each time the service is requested
NSString *username = usr.text;
NSString *password = psw.text;
[service setUserCredentialsWithUsername:username
password:password];
return service;
}
- (IBAction)getContacts:(id)sender; {
GDataServiceGoogleContact *gc =[self contactService];
NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:usr.text];
GDataServiceTicket *ticket;
ticket = [gc fetchFeedWithURL:feedURL
delegate:self
didFinishSelector:#selector(ticket:finishedWithFeed:error:)];
[self startLoading];
}
The callback selector looks like this:
- (void)ticket:(GDataServiceTicket *)ticket finishedWithFeed:(GDataFeedContact *)feed
error:(NSError *)error {
[self stopLoading];
if (error == nil) {
NSArray *entries = [NSArray arrayWithArray:[feed entries]];
if ([entries count] > 0) {
for (GDataEntryContact *firstContact in entries) {
NSString *name = [((GDataNameElement*)[[firstContact name] fullName]) stringValue];
NSString *email = ([firstContact emailAddresses] != nil && [[firstContact emailAddresses] count]!=0) ? [[[firstContact emailAddresses] objectAtIndex:0] stringValueForAttribute:#"address"]: NSLocalizedString(#"not found",#"");
if (name == nil) {
name = email;
}
BBGmailContact *tmpContact = [[BBGmailContact alloc] initWithName:name email:email];
[contacts addObject:tmpContact];
[self.navigationController popViewControllerAnimated:YES];
}
[gmailDelegate contactsDidDownload:contacts];
} else {
[self createAlertView:NSLocalizedString(#"Warning", #"") message:NSLocalizedString(#"No contact found", #"")];
}
} else {
[self createAlertView:NSLocalizedString(#"Error", #"Error") message:NSLocalizedString(#"Please, check your user and password", #"")];
}
}
Why is every entry of entries a kind of class: GDataEntryBase instead GDataEntryContact?
Where is my error? Can someone help me?
Entries are created as GDataEntryBase if the application does not have the service-specific classes for Contacts compiled and linked into the app.
Be sure too that the appropriate build flags for the Contacts service are specified as described in the docs.

How to get user details using twitter api v1.1 (Twitter error 215)

I have used the twitter api provided by twitter,to get the details but
not able to execute it, even tried to pass the authentication data
like consumer secret key, consumer key, token but the result is same.
I am able to login and receiving twitter authentication token but not able to get user details.
Below code is used by me (I am using MGtwitter engine) :
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1.1/users/show.json?screen_name=%#",username]]];
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *err = nil;
twitterLogin = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
Error is shown as below:
errors = (
{
code = 215;
message = "Bad Authentication data";
} );
First, you need to Authenticate your request (Get permission).
second, see follow these steps:
1.Download FHSTwitterEngine Twitter Library.
2.Add the folder FHSTwitterEngine" to your project and #import "FHSTwitterEngine.h".
3.add SystemConfiguration.framework to your project.
Usage : 1.in the [ViewDidLoad] add the following code.
UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
logIn.frame = CGRectMake(100, 100, 100, 100);
[logIn setTitle:#"Login" forState:UIControlStateNormal];
[logIn addTarget:self action:#selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:logIn];
[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:#"<consumer_key>" andSecret:#"<consumer_secret>"];
[[FHSTwitterEngine sharedEngine]setDelegate:self];
and don't forget to import the delegate FHSTwitterEngineAccessTokenDelegate.
you need to get the permission for your request, with the following method which will present Login window:
- (void)showLoginWindow:(id)sender {
[[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) {
NSLog(success?#"L0L success":#"O noes!!! Loggen faylur!!!");
}];
}
when the Login window is presented, enter your Twitter Username and Password to authenticate your request.
add the following methods to your code:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[FHSTwitterEngine sharedEngine]loadAccessToken];
NSString *username = [[FHSTwitterEngine sharedEngine]loggedInUsername];// self.engine.loggedInUsername;
if (username.length > 0) {
lbl.text = [NSString stringWithFormat:#"Logged in as %#",username];
[self listResults];
} else {
lbl.text = #"You are not logged in.";
}
}
- (void)storeAccessToken:(NSString *)accessToken {
[[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:#"SavedAccessHTTPBody"];
}
- (NSString *)loadAccessToken {
return [[NSUserDefaults standardUserDefaults]objectForKey:#"SavedAccessHTTPBody"];
}
4.Now you are ready to get your request, with the following method(in this method I created a Twitter search for some Hashtag, to get the screen_name for example):
- (void)listResults {
dispatch_async(GCDBackgroundThread, ^{
#autoreleasepool {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// the following line contains a FHSTwitterEngine method wich do the search.
dict = [[FHSTwitterEngine sharedEngine]searchTweetsWithQuery:#"#iOS" count:100 resultType:FHSTwitterEngineResultTypeRecent unil:nil sinceID:nil maxID:nil];
// NSLog(#"%#",dict);
NSArray *results = [dict objectForKey:#"statuses"];
// NSLog(#"array text = %#",results);
for (NSDictionary *item in results) {
NSLog(#"text == %#",[item objectForKey:#"text"]);
NSLog(#"name == %#",[[item objectForKey:#"user"]objectForKey:#"name"]);
NSLog(#"screen name == %#",[[item objectForKey:#"user"]objectForKey:#"screen_name"]);
NSLog(#"pic == %#",[[item objectForKey:#"user"]objectForKey:#"profile_image_url_https"]);
}
dispatch_sync(GCDMainThread, ^{
#autoreleasepool {
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Complete!" message:#"Your list of followers has been fetched" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
});
}
});
}
That's all.
I just got the screen_name from a search Query, you can get a timeline for a user using the following methods:
// statuses/user_timeline
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count;
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count sinceID:(NSString *)sinceID maxID:(NSString *)maxID;
instead of the search method above.
Note: see the FHSTwitterEngine.h to know what method you need to use.
Note: to get the <consumer_key> and the <consumer_secret> you need to to visit this link
to register your app in Twitter.
Got the solution after MKAlatrash revert, to get the user profile follow certain steps in the code as under :
[[FHSTwitterEngine sharedEngine]getProfileImageForUsername:username andSize:FHSTwitterEngineImageSizeNormal];
jump to definition of this function and replace the if ... else if part
if ([userShowReturn isKindOfClass:[NSError class]]) {
return [NSError errorWithDomain:[(NSError *)userShowReturn domain] code:[(NSError *)userShowReturn code] userInfo:[NSDictionary dictionaryWithObject:request forKey:#"request"]];
NSLog(#"user show return %#",userShowReturn);
} else if ([userShowReturn isKindOfClass:[NSDictionary class]]) {
return userShowReturn;
NSString *url = [userShowReturn objectForKey:#"profile_image_url"]; // normal
if (size == 0) { // mini
url = [url stringByReplacingOccurrencesOfString:#"_normal" withString:#"_mini"];
} else if (size == 2) { // bigger
url = [url stringByReplacingOccurrencesOfString:#"_normal" withString:#"_bigger"];
} else if (size == 3) { // original
url = [url stringByReplacingOccurrencesOfString:#"_normal" withString:#""];
}
id ret = [self sendRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
if ([ret isKindOfClass:[NSData class]]) {
return [UIImage imageWithData:(NSData *)ret];
}
return ret;
}
That really was helpful thanks

iphone to send email using smtp server?

in my application i am able to send email using smtp server,for that i have enter my correct email id and password.
but when i enter my gmail or yahoo account details i am not able to send the mail.
as i have set my relayHost = #"smtp.gmail.com"; then also i am not able to send the mail.
please help me out this.
following is my code :
-(void)sendEMAIL{
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = str_uname;
NSLog(#"str_Uname=%#",testMsg.fromEmail);
testMsg.toEmail = str_info;
NSLog(#"autoemail=%#",testMsg.toEmail);
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = str_uname;
NSLog(#"autoelogin=%#",testMsg.login);
testMsg.pass = str_password;
NSLog(#"autopass=%#",testMsg.pass);
testMsg.subject = #"Schedule Sms And Email";
testMsg.wantsSecure = YES;
NSString *sendmsg=[[NSString alloc]initWithFormat:#"%#",str_info2];
NSLog(#"automsg=%#",sendmsg);
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
sendmsg, kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
}
-(void)messageSent:(SKPSMTPMessage *)message{
[message release];
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
[message release];
}
you can also source code from hear https://github.com/kailoa/iphone-smtp Its a awesome code using smtp server.
http://iphonesdksnippets.com/send-email-with-attachments-on-iphone.html
use this link is also good....Just download framework from there and use that code.Its nice too.
you can manage relay host for yahoo, gmail, hotmail etc. in this way-
NSArray *arr1 = [fromEmail componentsSeparatedByString:#"#"];
NSArray *arr2 = [[arr1 objectAtIndex:1] componentsSeparatedByString:#"."];
if ([arr2 containsObject:#"gmail"]) {
smtp_message.relayHost = #"smtp.gmail.com";
}
else if ([arr2 containsObject:#"yahoo"]) {
smtp_message.relayHost = #"smtp.mail.yahoo.com";
}
else if ([arr2 containsObject:#"hotmail"] || [arr2 containsObject:#"live"]) {
smtp_message.relayHost = #"smtp.live.com";
}
else
{
NSString *smtpRelay = [[NSString alloc]init];
smtpRelay = [NSString stringWithFormat:#"smtp.%#.com",[arr2 objectAtIndex:0]];
smtp_message.relayHost = smtpRelay;
}

Reduce time to perform big operation on iphone app

When I launch an app, I need to retrieve all contacts from Address Book & store it in array to display it in table view. I wrote this code in viewDidAppear method. While contacts are retrieving from Address Book , I am showing activity indicator. I have around 1100 contacts in my address book. For this it took 14 seconds to retrieve data & store it in array. Its not acceptable time. So I need to optimize this & reduce time to max 2 to 3 seconds.
I need all contacts because when my app launches , I need to search for contacts so I need all the data available in my array.
How can I reduce this timing ? If you need more information just let me know.
Any kind of help is highly appreciated. Thanks.
UPDATE 1 : My code
- (NSMutableArray*)getAddressBookData {
self.tempArray = [[NSMutableArray alloc]init];
addressBook = ABAddressBookCreate();
APP_DELGATE.people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
peopleCount = [APP_DELGATE.people count];
for (int i=0; i<peopleCount; i++) {
ABRecordRef record = [APP_DELGATE.people objectAtIndex:i];
NSNumber *recordId = [NSNumber numberWithInteger:ABRecordGetRecordID(record)];
NSLog(#"record id is %#",recordId);
// 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* phoneNumbers = [self getPhoneNoWithoutSymbols:(NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty)];
NSString *strPhoneNos = [self getStringRepresentaionFromArray:phoneNumbers];
NSLog(#"strPhoneNos => %#",strPhoneNos);
// Get emails
ABMultiValueRef emailProperty = ABRecordCopyValue(record, kABPersonEmailProperty);
NSArray* emails = (NSArray*)ABMultiValueCopyArrayOfAllValues(emailProperty);
NSString *strEmails = [self getStringRepresentaionFromArray:emails];
NSLog(#"strEmails => %#",strEmails);
// Get URL
ABMultiValueRef urlProperty = ABRecordCopyValue(record, kABPersonURLProperty);
NSArray* urls = (NSArray*)ABMultiValueCopyArrayOfAllValues(urlProperty);
NSString *strURLs = [self getStringRepresentaionFromArray:urls];
NSLog(#"strURLs => %#",strURLs);
// 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];
}
}
NSString *strAddress = [self getStringRepresentaionFromArray:addressArray];
NSLog(#"strAddress => %#",strAddress);
// 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];
}
// Create User object & add it to array
User *user = [[User alloc]initUserWithUniqID:recordId.intValue FirstName:fnm lastName:lnm company:comp phoneNumbers:strPhoneNos emails:strEmails urls:strURLs address:strAddress notes:noteString dob:birthdateString userImage:image];
[self.tempArray addObject:user];
[user release];
}
self.tempArray = [NSMutableArray arrayWithArray:[self.tempArray sortedArrayUsingSelector:#selector(compare:)]];
APP_DELGATE.allUsersArray = self.tempArray;
return tempArray;
}
-(NSMutableArray*)getPhoneNoWithoutSymbols:(NSArray*)array {
self.phNoArray = [[NSMutableArray alloc]init];
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];
}
Firstly, try some general approaches to reduce time by using more optimized code and less repetition of code and also through less use of loops or may be only iterate loops only till the data is obtained. Also you can check whether your code is properly distributed as far as the Time Profiling is concerned.
Secondly, we feel that time required is more because user is shown an Activity Indicator till 14 seconds. If you don't show it and don't block the User Interface till data is getting copied into your array, then user may feel that it is more smooth So here is how you can do that:
You can use NSThread to allow the application to launch while you retrieve all your data from the AddressBook and Store it in your array.
You can use
[NSThread detachNewThreadSelector:#selector(fetchAddressContacts:) withObject:nil];
For more information you can refer to detachNewThreadSelector: from NSThread
So basically in AppDelegate you need to code as following in AppDelegate.m
-(void)applicationDidFinishLaunching:(UIApplication *)application {
[NSThread detachNewThreadSelector:#selector(fetchAddressContacts) withObject:nil];
}
-(void)fetchAddressContacts {
//Do your stuff to copy your contacts from address book to array
// Once you finish this task you can trigger an NSNotification which could be caught on some other viewController or implement a delegate to transfer data to a viewController and proper actions can be executed once the data is loaded.
}
Let me know if you need more help.
Hope this helps you.
Perform your contacts retrieval method diagnostics and identify what calls are causing the bottleneck here.
Share your code and describe the bottlenecks
Any operation taking serious amount of time should be performed in a thread. In this case, I'd gather the data on first startup only and store them internally. You can refresh the primary data anytime later on demand (refresh button?) otherwise work with the internally stored "clone" of the contacts rather than calling any time-consuming operation on every app's start.
BTW: Be careful about the address book contacts these days :-)
When your app first install fetch all the contacts and save in coredate/plist file when next time app opens then show the contacts from the storage which is very fast as compare to fetching contacts from iPhone database. Now the problem how to update contacts which newly added, so for every contact there is property called "kABPersonModificationDateProperty" and "kABPersonCreationDateProperty" ,use this to find only updated contacts and add in the storage. Hope this helps.

Problem when retrieving address, photo from iphone address book

I have a task to develop the application with phone gap. And retrieve in my application.using javascript.
I want first name,last name,address,photo,home page,email,phone no in my application using phone gap. i have done the following code to retrive them. but i am not getting photo and address in my field.
I have done all code to retrieve the contact in native code. and i am sending it to the javascript file by creating the jsstring object of javascript function.
This is my native implement to read address book data.
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)picker
shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
/** Fetch Contact name */
name = (NSString *)ABRecordCopyCompositeName(person);
NSLog(#"name:%#",name);
/** Fetch Mobile number */
ABMultiValueRef *phones = (ABMultiValueRef *) ABRecordCopyValue(person, kABPersonPhoneProperty);
mobile=[[NSString alloc] initWithString:#""];
NSString *mobileLabel = [[NSString alloc] initWithString:#""];
for (CFIndex i=0; i < ABMultiValueGetCount(phones); i++) {
mobileLabel = (NSString *) ABMultiValueCopyLabelAtIndex(phones, i);
if ([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel]) {
mobile = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
}
else if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneIPhoneLabel]) {
mobile = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
}
}
/** Fetch Email addres */
emailID = [NSString stringWithFormat:#""];
ABMultiValueRef emails = (ABMultiValueRef) ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex i=0; i < ABMultiValueGetCount(emails); i++) {
[emailID release];
emailID = (NSString *)ABMultiValueCopyValueAtIndex(emails, 0);
NSLog(#"emailid:%#",emailID);
}
/** Fetch Homepage */
ABMultiValueRef homepage = (ABMultiValueRef *) ABRecordCopyValue(person, kABPersonURLProperty);
NSString *homepageLabel = [NSString stringWithFormat:#""];
homepageID = [NSString stringWithFormat:#""];
for(CFIndex i=0; i < ABMultiValueGetCount(homepage);i++)
{
homepageLabel = (NSString *) ABMultiValueCopyLabelAtIndex(homepage, i);
if([homepageLabel isEqualToString:(NSString *)kABPersonHomePageLabel]){
homepageID = (NSString *)ABMultiValueCopyValueAtIndex(homepage, i);
NSLog(#"homepage:%#",homepageID);
}
}
/** Fatch Image */
NSData *imgData = (NSData *)ABPersonCopyImageData(person);
// call the js to fill the all contact infromation
{
NSString* jsString = [[NSString alloc] initWithFormat:#"fillContactInfo('%#','%#','%#','%#','%#');",name ,mobile ,emailID, homepageID, imgData];
NSLog(#"jstring:%#",jsString);
[webView stringByEvaluatingJavaScriptFromString:jsString];
[jsString release];
}
[emailID release];
[mobile release];
[mobileLabel release];
[homepageID release];
[homepageLabel release];
return YES;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)picker shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)identifier{
/*
* Set up an ABMultiValue to hold the address values; copy from address
* book record.
*/
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonAddressProperty);
// Set up an NSArray and copy the values in.
NSArray *theArray = [(id)ABMultiValueCopyArrayOfAllValues(multi) autorelease];
// Figure out which values we want and store the index.
const NSUInteger theIndex = ABMultiValueGetIndexForIdentifier(multi, identifier);
// Set up an NSDictionary to hold the contents of the array.
NSDictionary *theDict = [theArray objectAtIndex:theIndex];
// Set up NSStrings to hold keys and values. First, how many are there?
const NSUInteger theCount = [theDict count];
NSString *keys[theCount];
NSString *values[theCount];
// Get the keys and values from the CFDictionary. Note that because
// we're using the "GetKeysAndValues" function, you don't need to
// release keys or values. It's the "Get Rule" and only applies to
// CoreFoundation objects.
[theDict getObjects:values andKeys:keys];
// Set the address label's text.
addressid = [NSString stringWithFormat:#"%#, %#",
[theDict objectForKey:(NSString *)kABPersonAddressStreetKey],
[theDict objectForKey:(NSString *)kABPersonAddressCityKey]];
// call the js to fill the all contact infromation
{
NSString* jsString = [[NSString alloc] initWithFormat:#"fillContactAddress('%#');",addressid];
NSLog(#"jscript:%#",jsString);
[webView stringByEvaluatingJavaScriptFromString:jsString];
[jsString release];
}
[[self appViewController] dismissModalViewControllerAnimated:YES];
// If they didn't pick an address, return YES here to keep going.
return NO;
}
At this point i am getting the name,address,phone number,email address,home page,photo in NSLog console when i run the application. Following is my javascript function to retrive them:
function fillContactInfo(name,mobile,email,homepage,imgData){
mobile = mobile.replace(" ", "").replace("(", "").replace(")", "").replace("-", "").replace("+", "").replace("-", "").replace("-", "");
user.contactname = name;
user.contactemail = email;
user.contactphone = mobile;
user.contactimage = imgData;
user.contacturl = homepage;
document.getElementById("contactname").value = user.contactname;
document.getElementById("contactemail").value = user.contactemail;
document.getElementById("contactphone").value = user.contactphone;
document.getElementById("contactimage").src = "data:image/png;base64,user.contactimage";
document.getElementById("contacturl").value = user.contacturl;
}
function fillContactAddress(address){
user.address = address;
document.getElementById("contactaddress").value = user.contactaddress;
}
In the above code I have develop to retrive the contact in my application. But when i run the application at that time i only get name, email, phone number, and home page in my view. but i cant get address, and photo in my view.
I also have try to put the name, phone number, email, and home page in the
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)picker shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)identifier
class method but it is not giving me result.
And I have html image tag to display image of the contact list.
The content of address inside the ABMultiValue is a NSDictionary structure. You can use the following keys to retrieve desired values. The detail is in this official document.
const CFStringRef kABPersonAddressStreetKey;
const CFStringRef kABPersonAddressCityKey;
const CFStringRef kABPersonAddressStateKey;
const CFStringRef kABPersonAddressZIPKey;
const CFStringRef kABPersonAddressCountryKey;
const CFStringRef kABPersonAddressCountryCodeKey;
About image data, I cannot get a clear picture about how it will be processed in javascript. Maybe you need to transfer those binary data with base64 manner.
Edit:
An address example:
ABMultiValueRef aMulti = ABRecordCopyValue(srcRecord, kABPersonAddressProperty);
if (aMulti != nil) {
int aMultiCount = ABMultiValueGetCount(aMulti);
for (int i = 0; i < aMultiCount; ++i) {
NSDictionary *abDict = (NSDictionary *)ABMultiValueCopyValueAtIndex(aMulti, i);
NSString *street = [abDict objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [abDict objectForKey:(NSString *)kABPersonAddressCityKey];
// obtains other properties ....
[abDict release];
}
CFRelease(aMulti);
}