IOS: cannot get user email address

I want to get the email address of the user, as shown in this section: Getting the default email address of the user in Cocoa

But when I tried:

NSString *theEmailAddressWeWantToObtain = @""; ABPerson *aPerson = [[ABAddressBook sharedAddressBook] me]; ABMultiValue *emails = [aPerson valueForProperty:kABEmailProperty]; if([emails count] > 0) theEmailAddressWeWantToObtain = [emails valueAtIndex:0]; 

I have these errors:

  • Using undeclared identifier 'aPerson'
  • Use undeclared id "ABAddressBook"
  • Unknown type 'ABMultiValue'

I linked AddressBook and AddressBookUI and imported AddressBook / AddressBook.h

What's wrong?

+6
source share
1 answer

These are the fixes for your code.

 NSString *theEmailAddressWeWantToObtain = @""; ABPerson *aPerson = [[ABAddressBook sharedAddressBook] me]; ABMultiValueRef *emails = [aPerson valueForProperty:kABEmailProperty]; //No such thing as ABMultiValue; it ABMultiValueRef if(ABMultiValueGetCount(emails) > 0) //"emails" is not an array, so you can't use the "count" method theEmailAddressWeWantToObtain = [emails valueAtIndex:0]; 

I am not very familiar with the encoding of key values, so I'm not sure about your methods related to this.

So I would do it

The ABMultiValueRef contains three email addresses: home, work, and other emails. Try this code to get your home email address:

 NSString *email; ABRecordRef currentPerson = (__bridge ABRecordRef)[[PSAddressBook arrayOfContacts] objectAtIndex:identifier]; ABMultiValueRef emailsMultiValueRef = ABRecordCopyValue(currentPerson, kABPersonEmailProperty); NSUInteger emailsCount; //Goes through the emails to check which one is the home email for(emailsCount = 0; emailsCount <= ABMultiValueGetCount(emailsMultiValueRef);emailsCount++){ NSString *emailLabel = (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex (emailsMultiValueRef, emailsCount); if([emailLabel isEqualToString:@"Home"]){ if ((__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emailsMultiValueRef, emailsCount) != NULL){ email = (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonEmailProperty); } //If the last name property does not exist else{ email = @"NULL"; } } } CFRelease(emailsMultiValueRef); 

If you have any questions about the code, just ask in the comments. Hope this helps!

EDIT:

The PSAddressBook class mentioned in the code can be found here: https://github.com/pasawaya/PSAddressBook

+7
source

Source: https://habr.com/ru/post/919151/


All Articles