天天看點

iOS10 擷取系統通訊錄新方法

  • 所需架構
  • 遵循代理
CNContactPickerDelegate
           
  • 調用通訊錄
    • 如果在iOS10的機器上調用以前的ABPeoplePickerNavigationController老方法将直接崩潰.
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //iOS 10
//    AB_DEPRECATED("Use CNContactPickerViewController from ContactsUI.framework instead")
    CNContactPickerViewController * contactVc = [CNContactPickerViewController new];
    contactVc.delegate = self;
    [self presentViewController:contactVc animated:YES completion:^{

    }];
}
           
  • 選擇完成代理回調
#pragma mark - 使用者點選聯系人擷取方法 兩個方法都寫隻調用此方法
-(void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{

//    NSLog(@"contact : %@",contact);

                                // 姓氏               名字
    NSLog(@"name:%@%@",contact.familyName,contact.givenName);

    //公司名
    NSLog(@"公司: %@",contact.organizationName);

    //擷取通訊錄某個人所有電話并存入數組中 需要哪個取哪個
    NSMutableArray * arrMPhoneNums = [NSMutableArray array];
    for (CNLabeledValue * labValue in contact.phoneNumbers) {

        NSString * strPhoneNums = [labValue.value stringValue];
        NSLog(@"所有電話是: %@",strPhoneNums);
        [arrMPhoneNums addObject:strPhoneNums];
    }

    //所有郵件位址數組
    NSMutableArray * arrMEmails = [NSMutableArray array];
    for (CNLabeledValue * labValue in contact.emailAddresses) {

        NSLog(@"email : %@",labValue.value);
        [arrMEmails addObject:labValue.value];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 使用者點進去擷取屬性調用方法 例如從通訊錄選擇聯系人打電話兩個方法都寫隻調用上面方法
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty{

//    NSLog(@"contactProperty : %@",contactProperty);
//    NSLog(@"contact : %@",contactProperty.contact);
//    NSLog(@"key : %@",contactProperty.key);
//    [[UIApplication sharedApplication] openURL:url];
//    NSLog(@"identifier : %@",contactProperty.identifier);
//    NSLog(@"label : %@",contactProperty.label);

    //獲得點選的屬性,在此進行處理...
    NSLog(@"value : %@",[contactProperty.value stringValue]);
    [picker dismissViewControllerAnimated:YES completion:nil];
}
           
  • 取消選擇回調
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{

    [picker dismissViewControllerAnimated:YES completion:nil];
}