iOS調用系統通訊錄(適配iOS9、iOS10)(轉載)

來源:互聯網
上載者:User

標籤:etc   fst   ini   ctc   gpo   nav   family   設定   ace   

由於系統的通訊錄在iOS9的時候提供了新的api,所以我們2種架構都使用。首先我們要匯入架構:

/// iOS 9前的架構  #import <AddressBook/AddressBook.h>  #import <AddressBookUI/AddressBookUI.h>  /// iOS 9的新架構  #import <ContactsUI/ContactsUI.h>  #define Is_up_Ios_9    ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0 @interface ViewController : UIViewController<ABPeoplePickerNavigationControllerDelegate,CNContactPickerDelegate>

 

接著在需要調用通訊錄的vc裡面添加一下代碼

#pragma mark ---- 調用系統通訊錄  - (void)JudgeAddressBookPower {      ///擷取通訊錄許可權,調用系統通訊錄      [self CheckAddressBookAuthorization:^(bool isAuthorized , bool isUp_ios_9) {          if (isAuthorized) {              [self callAddressBook:isUp_ios_9];          }else {              NSLog(@"請到設定>隱私>通訊錄開啟本應用的使用權限設定");          }      }];  }            - (void)CheckAddressBookAuthorization:(void (^)(bool isAuthorized , bool isUp_ios_9))block {      if (Is_up_Ios_9) {          CNContactStore * contactStore = [[CNContactStore alloc]init];          if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {              [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * __nullable error) {                  if (error) {                      NSLog(@"Error: %@", error);                  } else if (!granted) {                      block(NO,YES);                  } else {                      block(YES,YES);                  }              }];          } else if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized){              block(YES,YES);          } else {              NSLog(@"請到設定>隱私>通訊錄開啟本應用的使用權限設定");          }      }else {          ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);          ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();                        if (authStatus == kABAuthorizationStatusNotDetermined) {              ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {                  dispatch_async(dispatch_get_main_queue(), ^{                      if (error) {                          NSLog(@"Error: %@", (__bridge NSError *)error);                      } else if (!granted) {                          block(NO,NO);                      } else {                          block(YES,NO);                      }                  });              });          }else if (authStatus == kABAuthorizationStatusAuthorized) {              block(YES,NO);          }else {              NSLog(@"請到設定>隱私>通訊錄開啟本應用的使用權限設定");          }      }  }            - (void)callAddressBook:(BOOL)isUp_ios_9 {      if (isUp_ios_9) {          CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];          contactPicker.delegate = self;          contactPicker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];          [self presentViewController:contactPicker animated:YES completion:nil];      } else {          ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];          peoplePicker.peoplePickerDelegate = self;          [self presentViewController:peoplePicker animated:YES completion:nil];      }  }        #pragma mark -- CNContactPickerDelegate  進入系統通訊錄頁面 --- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {      CNPhoneNumber *phoneNumber = (CNPhoneNumber *)contactProperty.value;      [self dismissViewControllerAnimated:YES completion:^{          /// 連絡人          NSString *text1 = [NSString stringWithFormat:@"%@%@",contactProperty.contact.familyName,contactProperty.contact.givenName];          /// 電話          NSString *text2 = phoneNumber.stringValue;          //text2 = [text2 stringByReplacingOccurrencesOfString:@"-" withString:@""];          NSLog(@"連絡人:%@, 電話:%@",text1,text2);      }];  }        #pragma mark -- ABPeoplePickerNavigationControllerDelegate   進入系統通訊錄頁面 --- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {       ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);      CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);      CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef,index);      CFStringRef anFullName = ABRecordCopyCompositeName(person);                [self dismissViewControllerAnimated:YES completion:^{          /// 連絡人          NSString *text1 = [NSString stringWithFormat:@"%@",anFullName];          /// 電話          NSString *text2 = (__bridge NSString*)value;          //text2 = [text2 stringByReplacingOccurrencesOfString:@"-" withString:@""];          NSLog(@"連絡人:%@, 電話:%@",text1,text2);      }];  
}

 

最後我們可以調用 [self JudgeAddressBookPower]; 就能簡單的調用系統通訊錄。

 

如果我們輸入一個號碼也可以直接判斷,這個號碼是否在通訊錄內,如果在則調取該使用者資訊,

#pragma mark --#pragma mark -- 根據手機號查詢手機通訊錄 --- (NSString *)getNameBytel:(NSString *)telstr {    telstr = [telstr stringByReplacingOccurrencesOfString:@" " withString:@""];        NSMutableArray* personArray = [[NSMutableArray alloc] init];    //開啟電話本資料庫    ABAddressBookRef addressRef=ABAddressBookCreate();        NSString *firstName, *lastName, *fullName;        //返回所有連絡人到一個數組中    personArray = (__bridge NSMutableArray *)ABAddressBookCopyArrayOfAllPeople(addressRef);        //返回連絡人數量    //    CFIndex personCount = ABAddressBookGetPersonCount(addressRef);    for (id person in personArray) {        firstName = (__bridge NSString *)ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonFirstNameProperty);        firstName = [firstName stringByAppendingFormat:@" "];        lastName = (__bridge NSString *)ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonLastNameProperty);                if (lastName !=nil) {            fullName = [firstName stringByAppendingFormat:@"%@",lastName];        } else {            fullName = firstName;        }                NSLog(@"連絡人===%@",fullName);                ABMultiValueRef phones = (ABMultiValueRef) ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonPhoneProperty);                for(int i = 0 ;i < ABMultiValueGetCount(phones); i++) {            NSString *phone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phones, i);                        phone = [phone stringByReplacingOccurrencesOfString:@"(" withString:@""];                        phone = [phone stringByReplacingOccurrencesOfString:@")" withString:@""];                        phone = [phone stringByReplacingOccurrencesOfString:@"-" withString:@""];                        phone = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];                        NSLog(@"===%@",phone);                        if ([phone isEqualToString:telstr]) {                _isNo = NO;                                NSArray *array = [fullName componentsSeparatedByString:@" "];                fullName = [NSString stringWithFormat:@"%@%@",array[1],array[0]];                                _moren = fullName;                return fullName;            } else {                _isNo = YES;            }        }    }        if (_isNo == YES) {        _moren = @"非通訊錄好友";        return @"非通訊錄好友";    }    return nil;}

 

tips:如果要適配iOS 10,就必須在plist檔案的Source code模式下添加

<key>NSContactsUsageDescription</key>  <string>App需要您的同意,才能訪問通訊錄</string>  

 

iOS調用系統通訊錄(適配iOS9、iOS10)(轉載)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.