美文网首页
Swift(十四):通讯录 AddressBook 封装

Swift(十四):通讯录 AddressBook 封装

作者: IMSong | 来源:发表于2016-08-19 18:25 被阅读164次
    示例截图
    //
    //  AddressBookManager.swift
    //  AddressBook
    //
    //  Created by HMC on 16/8/19.
    //  Copyright © 2016年 SKing. All rights reserved.
    //
    
    import UIKit
    import ContactsUI
    
    //定义生日的结构体
    struct birth {
        var year = 1900
        var month = 1
        var day = 1
            
    }
    
    //定义地址的结构体
    struct  personalAddress {
        
        var street = "朝阳三里屯"
        var city = "北京"
        var country = "中国"
        var postalCode = "100000"
        
    }
    
    class AddressBookManager: NSObject {
        
        var delegate:CNContactPickerDelegate!
      
    }
    
    extension AddressBookManager {
        
        /**
         添加新的通信录到 addressbook
         
         - parameter familyName:    姓
         - parameter givenName:     名(必填)
         - parameter imageName:     头像
         - parameter homeMail:      个人邮箱
         - parameter workMail:      工作邮箱
         - parameter phoneNumber:   手机号(必填)
         - parameter bir:           生日(结构体)
         - parameter postalAddress: 地址
         */
        func addContact(familyName : String? ,givenName : String ,imageName : String? ,homeMail : String? ,workMail : String? ,phoneNumber : String ,bir : birth? ,postalAddress : personalAddress? ) {
            
            let contactStore = CNContactStore()
            contactStore.requestAccessForEntityType(.Contacts) { (granted : Bool, error : NSError?) in
                
                if granted {
                    
                    print("授权成功")
                    //创建联系人对象
                    let aPeople = CNMutableContact()
                    
                    if (familyName != nil) {
                        //姓
                        aPeople.familyName = familyName!
                    }
                    
                    //名
                    aPeople.givenName = givenName
                    
                    if (imageName != nil) {
                        //头像
                        aPeople.imageData = UIImagePNGRepresentation( UIImage(named: imageName!)!)
                    }
                    /*
                     
                     CONTACTS_EXTERN NSString * const CNLabelHome                   家庭
                     CONTACTS_EXTERN NSString * const CNLabelWork                   工作
                     CONTACTS_EXTERN NSString * const CNLabelOther                  其他
                     CONTACTS_EXTERN NSString * const CNLabelEmailiCloud            邮箱地址
                     CONTACTS_EXTERN NSString * const CNLabelURLAddressHomePage     url地址
                     CONTACTS_EXTERN NSString * const CNLabelDateAnniversary        日期
                     
                     */
                    var addressArray : [CNLabeledValue] = []
                    if (homeMail != nil) {
                        //私人邮箱
                        let homeMail = CNLabeledValue.init(label: CNLabelHome, value: homeMail!)
                        addressArray.append(homeMail)
                    }
                    if (workMail != nil) {
                        //工作邮箱
                        let workMail = CNLabeledValue.init(label: CNLabelWork, value: workMail!)
                        addressArray.append(workMail)
                    }
                    //设置邮箱
                    aPeople.emailAddresses = addressArray
                    
                    /*
                     CONTACTS_EXTERN NSString * const CNLabelPhoneNumberiPhone
                     CONTACTS_EXTERN NSString * const CNLabelPhoneNumberMobile
                     CONTACTS_EXTERN NSString * const CNLabelPhoneNumberMain
                     CONTACTS_EXTERN NSString * const CNLabelPhoneNumberHomeFax
                     CONTACTS_EXTERN NSString * const CNLabelPhoneNumberWorkFax
                     CONTACTS_EXTERN NSString * const CNLabelPhoneNumberOtherFax
                     CONTACTS_EXTERN NSString * const CNLabelPhoneNumberPager
                     */
                    //电话
                    
                    let phoneNumber = CNLabeledValue.init(label: CNLabelPhoneNumberiPhone, value: CNPhoneNumber(stringValue: phoneNumber))
                    aPeople.phoneNumbers = [phoneNumber]
                    
                    if (bir != nil) {
                        
                        //生日
                        let birthday = NSDateComponents()
                        birthday.day = bir!.day
                        birthday.month = bir!.month
                        birthday.year = bir!.year
                        aPeople.birthday = birthday
                    }
                    if (postalAddress != nil) {
                        
                        //地址
                        let pAddress = CNMutablePostalAddress()
                        pAddress.street = postalAddress!.street
                        pAddress.city = postalAddress!.city
                        pAddress.country = postalAddress!.country
                        //邮编
                        pAddress.postalCode = postalAddress!.postalCode
                        aPeople.postalAddresses = [CNLabeledValue.init(label: CNLabelHome, value: pAddress)]
                    }
                    
                    //请求添加联系人
                    let saveRequest = CNSaveRequest()
                    saveRequest.addContact(aPeople, toContainerWithIdentifier: nil)
                    
                    /*
                     
                     //更新一个联系人  - (void)updateContact:(CNMutableContact *)contact;
                     //删除一个联系人  - (void)deleteContact:(CNMutableContact *)contact;
                     //添加一组联系人  - (void)addGroup:(CNMutableGroup *)group toContainerWithIdentifier:(nullable NSString *)identifier;
                     //更新一组联系人  - (void)updateGroup:(CNMutableGroup *)group;
                     //删除一组联系人  - (void)deleteGroup:(CNMutableGroup *)group;
                     //向组中添加子组  - (void)addSubgroup:(CNGroup *)subgroup toGroup:(CNGroup *)group NS_AVAILABLE(10_11, NA);
                     //在组中删除子组  - (void)removeSubgroup:(CNGroup *)subgroup fromGroup:(CNGroup *)group NS_AVAILABLE(10_11, NA);
                     //向组中添加成员  - (void)addMember:(CNContact *)contact toGroup:(CNGroup *)group;
                     //向组中移除成员  - (void)removeMember:(CNContact *)contact fromGroup:(CNGroup *)group;
                     
                     */
                    
                    
                    //写入通信录
                    guard ((try? contactStore.executeSaveRequest(saveRequest)) != nil) else {
                        
                        print("添加失败")
                        return
                        
                    }
                    
                    
                }else{
                    
                    print("授权失败")
                    
                }
                
            }
        }
        /**
         查找通信录的指定字段
         
         - parameter strArray: 参数字段
         
         CNContactNamePrefixKey
         CNContactGivenNameKey
         CNContactMiddleNameKey
         CNContactFamilyNameKey
         CNContactPreviousFamilyNameKey
         CNContactNameSuffixKey
         CNContactNicknameKey
         CNContactPhoneticGivenNameKey
         CNContactPhoneticMiddleNameKey
         CNContactPhoneticFamilyNameKey
         CNContactOrganizationNameKey
         CNContactDepartmentNameKey
         CNContactJobTitleKey
         CNContactBirthdayKey
         CNContactNonGregorianBirthdayKey
         CNContactNoteKey
         CNContactImageDataKey
         CNContactThumbnailImageDataKey
         CNContactImageDataAvailableKey
         CNContactTypeKey
         CNContactPhoneNumbersKey
         CNContactEmailAddressesKey
         CNContactPostalAddressesKey
         CNContactDatesKey
         CNContactUrlAddressesKey
         CNContactRelationsKey
         CNContactSocialProfilesKey
         CNContactInstantMessageAddressesKey
         
         */
        func searchContact(strArray:[CNKeyDescriptor],completionHandler: (result: [[String : String]]) -> Void) -> Void{
            
            var result = [[String : String]]()
            
            let contactStore = CNContactStore()
            contactStore.requestAccessForEntityType(.Contacts) {(granted : Bool, error : NSError?) in
                
                if granted {
                    
                    let request = CNContactFetchRequest(keysToFetch: strArray)
                    
                    guard ((try? contactStore.enumerateContactsWithFetchRequest(request, usingBlock: { (contact:CNContact,stop) in
                        
                        let numbers = contact.phoneNumbers
                        for number in numbers{
                            
                            let phoneNum = number.value as! CNPhoneNumber
                            //print(contact.familyName,phoneNum.stringValue)
                            
                            let tmpDict = ["name":contact.familyName,"phoneNum":phoneNum.stringValue]
                            result.append(tmpDict)
                        }
                        
                        
                    })) != nil) else {
                        
                        return
                    }
                    
                     completionHandler(result: result)
                    
                    
                }else{
                    
                    print("授权失败")
                    return
                }
                
            }
        }
    }
    
    // MARK: - CNContactPickerDelegate
    extension AddressBookManager : CNContactPickerDelegate {
        
        func contactPickerDidCancel(picker: CNContactPickerViewController) {
            print("Cancel")
        }
        
        func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact) {
            let formatterName = CNContactFormatter.stringFromContact(contact, style: .FullName)
            
            print(formatterName)
        }
        
    }
    
    

    调用

    //
    //  ViewController.swift
    //  AddressBook
    //
    //  Created by HMC on 16/8/19.
    //  Copyright © 2016年 SKing. All rights reserved.
    //
    
    import UIKit
    import ContactsUI
    
    class ViewController: UIViewController {
        
        lazy var addressBook = CNContactPickerViewController()
        lazy var ad = AddressBookManager()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            addressBook.delegate = ad
            ad.addContact("songjinwei", givenName: "jw", imageName: nil, homeMail: nil, workMail: nil, phoneNumber: "15225124020", bir: nil, postalAddress: nil)
    
            ad.searchContact([CNContactFamilyNameKey,CNContactGivenNameKey,CNContactPhoneNumbersKey]) { (result) in
                
                print(result)
            }
            presentViewController(addressBook, animated: true, completion: nil)
            
        }
        
    }
    
    
    
    

    相关文章

      网友评论

          本文标题:Swift(十四):通讯录 AddressBook 封装

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