iOS:无法获取用户的电子邮件地址

Rob*_*Rob 6 email addressbook ios abperson

我想获取用户邮件地址,如此主题所示:在Cocoa中获取用户的默认电子邮件地址

但当我尝试时:

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

我有这些错误:

  • 使用未声明的标识符'aPerson'
  • 使用未声明的标识符'ABAddressBook'
  • 未知类型'ABMultiValue'

我已经链接了AddressBook和AddressBookUI,并导入了AddressBook/AddressBook.h

怎么了 ?

pas*_*aya 7

这些是对代码的更正

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

我对Key Value Coding不太熟悉,所以我不确定你的方法与此相关.

这就是我这样做的方式

电子邮件中存储了三个电子邮件地址ABMultiValueRef:家庭,工作和其他电子邮件.尝试使用此代码获取主页电子邮件:

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);
Run Code Online (Sandbox Code Playgroud)

如果您对代码有任何疑问,请在评论中提问.希望这可以帮助!

编辑:

PSAddressBook代码中提到的类可以在这里找到:https://github.com/pasawaya/PSAddressBook