標(biāo)題:
IOS9開(kāi)發(fā)中使用CNContact讀取通訊錄
[打印本頁(yè)]
作者:
51黑ele
時(shí)間:
2016-5-12 04:27
標(biāo)題:
IOS9開(kāi)發(fā)中使用CNContact讀取通訊錄
IOS9中最大的變化就是對(duì)通訊錄的操作變得簡(jiǎn)單了,接下來(lái)將演示CNContact的使用。
首先是導(dǎo)入Contacts模型
接下來(lái)是具體的編寫(xiě)代碼的步驟:
1、創(chuàng)建一個(gè)通訊錄對(duì)象
2、定義所有打算獲取的屬性對(duì)應(yīng)的key值,此處獲取姓名,手機(jī)號(hào),頭像
3、創(chuàng)建CNContactFetchRequest對(duì)象
4、初始化一個(gè)數(shù)組,用來(lái)存放遍歷到的所有聯(lián)系人
5、遍歷所有的聯(lián)系人并把遍歷到的聯(lián)系人添加到contactarray
6、打印獲取的聯(lián)系人數(shù)組contactarray
以上就完成了通訊錄的讀取,并保存在數(shù)組中,打印結(jié)果如下:
具體代碼如下:
#import "MainViewController.h"
//導(dǎo)入IOS9新特性之聯(lián)系人模型
@import Contacts;
@interface MainViewController ()
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 創(chuàng)建通信錄對(duì)象
CNContactStore *contactStore = [[CNContactStore alloc] init];
// 定義所有打算獲取的屬性對(duì)應(yīng)的key值,此處獲取姓名,手機(jī)號(hào),頭像
NSArray *keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey,CNContactImageDataKey];
// 創(chuàng)建CNContactFetchRequest對(duì)象
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
// 初始化一個(gè)數(shù)組,用來(lái)存放遍歷到的所有聯(lián)系人
NSMutableArray *contactarray = [NSMutableArray array];
// 5.遍歷所有的聯(lián)系人并把遍歷到的聯(lián)系人添加到contactarray
[contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
[contactarray addObject:contact];
}
];
NSLog(@"%@",contactarray);
}
@end
歡迎光臨 (http://www.torrancerestoration.com/bbs/)
Powered by Discuz! X3.1