您好我是iOS开发的新手。我想从默认联系人应用中选择一个联系人。为此,我创建了一个应用程序,允许用户从iPhone默认联系人应用程序中选择一个联系人。对于iOS 9+版本,我使用以下剪辑。
- (IBAction)btnAction:(id)sender {
CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
contactPicker.delegate = self;
contactPicker.displayedPropertyKeys = (NSArray *)CNContactGivenNameKey;
[self presentViewController:picker animated:YES completion:nil];
}
-(void) contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
NSLog(@"Contact : %@",contact);
}
-(void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
NSLog(@"Cancelled");
}
我还在我的uiviewcontroller中添加了CNContactPickerDelegate委托。当我执行上面的代码时,它会打开联系人应用程序,但是当点击一个联系人时,该应用程序将变为空白。
提前致谢,任何人都可以分享您的知识,在Objective-C中使用CNContactPickerViewController。
答案 0 :(得分:7)
问题是由此代码引起的:
contactPicker.displayedPropertyKeys = (NSArray *)CNContactGivenNameKey;
displayedPropertyKeys期望NSArray
包含NSString
个值。在您的代码中,您尝试将NSString类型转换为NSArray并将其设置为此属性的值。
您需要将代码更改为:
contactPicker.displayedPropertyKeys = @[CNContactGivenNameKey];
答案 1 :(得分:2)
#pragma mark - CNContactPickerViewController Delegate method implementation
(void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact
{
NSMutableArray *contactNumberArray = [[NSMutableArray alloc]init];
selectedName=[NSString stringWithFormat:@"%@",contact.givenName];
NSLog(@"%@",selectedName);
NSString *tempString = [NSString stringWithFormat:@"name : %@ %@ %@\n",contact.givenName, contact.familyName, contact.organizationName];
// // 1. (Phone Numbers)
tempString = [NSString stringWithFormat:@"%@phoneNumbers : ",tempString];
// NSArray*phoneNumber = contact.phoneNumbers;
for (CNLabeledValue *phoneNumber in contact.phoneNumbers)
{
CNPhoneNumber *phone = phoneNumber.value;
tempString = [NSString stringWithFormat:@"%@<%@>",tempString,phone.stringValue];
[contactNumberArray addObject:phone];
selectedPhNumber=[[NSString stringWithFormat:@"%@",phone.stringValue] stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"%@",selectedPhNumber);
}
//2. (Emails)
tempString = [NSString stringWithFormat:@"%@\n Email : ",tempString];
for (CNLabeledValue *email in contact.emailAddresses)
{
selectedEmail=[NSString stringWithFormat:@"%@", email.value];
tempString = [NSString stringWithFormat:@"%@<%@>",tempString,email.value];
[contactNumberArray addObject:email];
NSLog(@"%@",selectedEmail);
}
[self sendRefferelDetailsToServer];
}
答案 2 :(得分:0)
-(void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts{
NSLog(@" %@",contacts);
CNContact *contact=[contacts objectAtIndex:0];
NSLog(@"name = %@",contact.givenName);
}
[1]:https://i.stack.imgur.com/9Sp1G.png使用上面的代码从多个选项中获取给定名称,
答案 3 :(得分:-1)
评论以下一行,然后重试。
{{1}}