美文网首页Swift编程Swift
Swift & OC 获取手机通讯录

Swift & OC 获取手机通讯录

作者: 贝尔特伦 | 来源:发表于2016-12-14 11:14 被阅读611次

    '
    获取手机通讯录,分为两种方式,一是跳转到系统的UI视图上进行选择,这种方式是不需要添加权限的,二是,自定义视图选择,这个是需要添加权限的。主要框架是

    -系统UI

    #import <Contacts/CNContact.h>
    #import <ContactsUI/ContactsUI.h>
    

    我这里是使用跳转到系统UI选择联系人,分别讲述OC和Swift的实现方法。

    OC的实现方式

    导入头文件,引入代理,定义一个数组,接收数据

    #import <Contacts/CNContact.h>
    #import <ContactsUI/ContactsUI.h>
    @interface ViewController ()<CNContactPickerDelegate,CNContactViewControllerDelegate>
    
    @property (nonatomic, strong) NSMutableArray *dateArray;
    
    @end
    

    创建系统UI视图,签署代理,跳转系统UI

    - (void)viewDidLoad {
    [super viewDidLoad];
    _dateArray = [[NSMutableArray alloc] init];
    CNContactPickerViewController *nav = [[CNContactPickerViewController alloc] init];
    nav.delegate = self;
    [self presentViewController:nav animated:YES completion:nil];
    
    [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    }
    

    取消调用的代理方法 可不写,取消时,自动dismiss

    - (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
    
    }
    

    完成调用的方法 遍历所选中的联系人,定义一个字典,存储需要的数据,然后加到dateArray中

     - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact*> *)contacts{
    for (CNContact *cont in contacts) {
        NSMutableDictionary *userDic = [[NSMutableDictionary alloc] init];
        //名字
        NSString *name = @"";
        if (cont.familyName) {
            name = [NSString stringWithFormat:@"%@",cont.familyName];
        }
        if (cont.givenName) {
            name = [NSString stringWithFormat:@"%@%@",name,cont.givenName];
        }
        [userDic setObject:name forKey:@"name"];
        if (cont.organizationName) {
            
            [userDic setObject:cont.organizationName forKey:@"organizationName"];
        }
        if (cont.imageData) {
            [userDic setObject:[UIImage imageWithData:cont.imageData] forKey:@"image"];
        }
        if (cont.phoneNumbers) {
      
            for (CNLabeledValue *labeValue in cont.phoneNumbers) {
                CNPhoneNumber *phoneNumber = labeValue.value;
                NSString *phone = [[phoneNumber.stringValue componentsSeparatedByString:@"-"] componentsJoinedByString:@""];
                if (phone.length == 11) {
                    [userDic setObject:phone forKey:@"phone"];
                }
            }
            
        }
        [_dateArray addObject:userDic];
        
        
    }
    
    }
    

    Swift的实现方式

    导入头文件,引入代理,定义一个数组,接收数据

    import ContactsUI
    class ViewController: UIViewController ,CNContactPickerDelegate,CNContactViewControllerDelegate{
    
    var dateArray : Array<Dictionary<String,Any>>?;
    

    创建系统UI视图,签署代理,跳转系统UI

    override func viewDidLoad() {
        super.viewDidLoad()
        dateArray = Array.init();
        let contUI = CNContactPickerViewController.init();
        contUI.delegate = self;
        self.present(contUI, animated: true, completion: nil);
        CNContactStore.authorizationStatus(for: CNEntityType.contacts);
        
    }
    

    //取消的代理方法

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        
    }
    

    //完成的代理方法

     func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        for cont in contacts {
            var userDic:Dictionary<String,Any> = Dictionary();
            
           let name = String.init(format: "%@%@", cont.familyName,cont.givenName);
            userDic["name"] = name;
            let organ = cont.organizationName;
            if cont.imageData != nil{
                let img = UIImage.init(data: cont.imageData!);
                userDic["image"] = img;
            }
            userDic["organ"] = organ;
            
            dateArray?.append(userDic);
        }
        
        
    
    }
    

    获取系统通讯录全部信息-Swift

    通讯录权限 Privacy - Contacts Usage Description

    引入import Contacts

    创建通讯录

     //创建通讯录
    func contacts(){
        //创建通讯录
        let store = CNContactStore.init();
        //获取授权状态
        let AuthStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts);
        
        //没有授权
        if AuthStatus == CNAuthorizationStatus.notDetermined{
            
            //用户授权
            store.requestAccess(for: CNEntityType.contacts, completionHandler: { (isLgranted, error) in
                if isLgranted == true{
                    print("授权成功");
                    self.getPhoneList();
                }else{
                    print("授权失败");
                }
                
            });
            
        }else{
            getPhoneList();
        }
    
    }
    

    获取通讯录

    //获取通讯录
    func getPhoneList(){
        //创建通讯录
        let store = CNContactStore.init();
        //获取授权状态
        let AuthStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts);
    
        if AuthStatus == CNAuthorizationStatus.authorized{
            
            //获取所有的联系人
            let keys = [CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey];
            let request = CNContactFetchRequest.init(keysToFetch: keys as [CNKeyDescriptor]);
            try?store.enumerateContacts(with: request, usingBlock: { (contact, iStop) in
             
                //姓
                let firstName = contact.familyName;
                //名
                let lastName = contact.givenName;
               print(firstName,lastName);
                let phoneArr = contact.phoneNumbers;
                var phonetextArr:Array<String> = Array.init();
                for labelValue in phoneArr{
                    let cnlabelV = labelValue as CNLabeledValue;
                    let value = cnlabelV.value;
                    
                    let phoneValue = value.stringValue;
                    let phoneLabel = cnlabelV.label;
                    print(phoneLabel,phoneValue);
                }
          
            });
          
        }
    
    }
    
    }
    

    注意

    在笔者的测试过程中,iStop返回的一直是false,OC里面返回的也一直是NO
    如何判断读取完成呢?

     try?store.enumerateContacts(with: request, usingBlock: { (contact, iStop) in{
    
        });
    

    经过测试发现,上面那个方法,是阻塞当前线程的,所以在那个方法之后,再做自己需要的操作。

    相关文章

      网友评论

        本文标题:Swift & OC 获取手机通讯录

        本文链接:https://www.haomeiwen.com/subject/rbkimttx.html