当前位置: > > > Swift - 添加、修改、删除通讯录联系人

Swift - 添加、修改、删除通讯录联系人

使用AddressBook.framework框架,我们除了可以很方便的获取通信录里的联系人。同时,还能对通讯录进行新增、修改、删除联系人操作。
(注意:这些操作同查询一样,首先需要发起授权请求)

1,添加新联系人
import UIKit
import AddressBook
import AddressBookUI

class ViewController: UIViewController {
    
    //address Book对象,用来获取电话簿句柄
    var addressBook:ABAddressBookRef?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //定义一个错误标记对象,判断是否成功
        var error:Unmanaged<CFErrorRef>?
        addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
        
        //发出授权信息
        let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()
        if (sysAddressBookStatus == ABAuthorizationStatus.NotDetermined) {
            println("requesting access...")
            var errorRef:Unmanaged<CFError>? = nil
            //addressBook = extractABAddressBookRef(ABAddressBookCreateWithOptions(nil, &errorRef))
            ABAddressBookRequestAccessWithCompletion(addressBook, { success, error in
                if success {
                    //添加新联系人
                    self.addRecord();
                }
                else {
                    println("error")
                }
            })
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Denied ||
            sysAddressBookStatus == ABAuthorizationStatus.Restricted) {
                println("access denied")
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Authorized) {
            println("access granted")
            //添加新联系人
            self.addRecord();
        }
    }
    
    //添加新联系人
    func addRecord(){
        //定义一个错误标记对象,判断是否成功
        var error:Unmanaged<CFErrorRef>?
        
        //创建一个联系人对象
        var newContact:ABRecordRef! = ABPersonCreate().takeRetainedValue()
        var success:Bool = false
        
        //设置联系人对象昵称
        success = ABRecordSetValue(newContact, kABPersonNicknameProperty, "小李", &error)
        println("设置昵称结果:\(success)")
        
        //设置联系人姓氏
        success = ABRecordSetValue(newContact, kABPersonLastNameProperty, "李", &error)
        println("设置姓氏结果:\(success)")
        
        //设置联系人名字
        success = ABRecordSetValue(newContact, kABPersonFirstNameProperty, "大木", &error)
        println("设置名字结果:\(success)")
        
        //设置联系人电话
        let phones:ABMutableMultiValueRef = ABMultiValueCreateMutable(
            ABPropertyType(kABStringPropertyType)).takeRetainedValue()
        success = ABMultiValueAddValueAndLabel(phones, "123456", "公司", nil)
        println("设置电话条目:\(success)")
        success = ABRecordSetValue(newContact, kABPersonPhoneProperty, phones, nil)
        println("设置电话结果:\(success)")
        
        //设置联系人邮箱
        let addr:ABMutableMultiValueRef = ABMultiValueCreateMutable(
            ABPropertyType(kABStringPropertyType)).takeRetainedValue()
        success = ABMultiValueAddValueAndLabel(addr, "ABG@hangge.com", "公司", nil)
        println("设置邮箱条目结果:\(success)")
        success = ABRecordSetValue(newContact, kABPersonEmailProperty, addr, nil)
        println("设置邮箱结果:\(success)")
        
        //保存联系人
        success = ABAddressBookAddRecord(addressBook, newContact, &error)
        println("保存记录是否成功:\(success)")
        
        //修改数据库
        success = ABAddressBookSave(addressBook, &error)
        println("修改数据库是否成功:\(success)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

2,编辑修改联系人
先获取所有联系人遍历,根据联系人姓名或者电话来判断是否修改
import UIKit
import AddressBook
import AddressBookUI

class ViewController: UIViewController {
    
    //address Book对象,用来获取电话簿句柄
    var addressBook:ABAddressBookRef?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //定义一个错误标记对象,判断是否成功
        var error:Unmanaged<CFErrorRef>?
        addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
        
        //发出授权信息
        let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()
        if (sysAddressBookStatus == ABAuthorizationStatus.NotDetermined) {
            println("requesting access...")
            var errorRef:Unmanaged<CFError>? = nil
            //addressBook = extractABAddressBookRef(ABAddressBookCreateWithOptions(nil, &errorRef))
            ABAddressBookRequestAccessWithCompletion(addressBook, { success, error in
                if success {
                    //编辑联系人
                    self.editRecord();
                }
                else {
                    println("error")
                }
            })
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Denied ||
            sysAddressBookStatus == ABAuthorizationStatus.Restricted) {
                println("access denied")
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Authorized) {
            println("access granted")
            //编辑联系人
            self.editRecord();
        }
    }
    
    //编辑联系人
    func editRecord(){
        //定义一个错误标记对象,判断是否成功
        var error:Unmanaged<CFErrorRef>?
        var sysContacts:NSArray = ABAddressBookCopyArrayOfAllPeople(addressBook)
            .takeRetainedValue() as NSArray
        
        //遍历通讯录
        for contact in sysContacts {
            //获取姓名
            var lastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?
                .takeRetainedValue() as! String? ?? ""
            println("姓:\(lastName)")
            var firstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?
                .takeRetainedValue() as! String? ?? ""
            println("名:\(firstName)")
            
            var success:Bool = false
            if lastName == "李" && firstName == "大木"{
                //设置联系人新对象昵称
                success = ABRecordSetValue(contact, kABPersonNicknameProperty, "小李子", &error)
                println("设置昵称结果:\(success)")
            }
        }
        
        //保存数据库
        var success = ABAddressBookSave(addressBook, &error)
        println("修改数据库是否成功:\(success)")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

3,删除联系人
先获取所有联系人遍历,根据联系人姓名或者电话来判断是否删除
import UIKit
import AddressBook
import AddressBookUI

class ViewController: UIViewController {
    
    //address Book对象,用来获取电话簿句柄
    var addressBook:ABAddressBookRef?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //定义一个错误标记对象,判断是否成功
        var error:Unmanaged<CFErrorRef>?
        addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
        
        //发出授权信息
        let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()
        if (sysAddressBookStatus == ABAuthorizationStatus.NotDetermined) {
            println("requesting access...")
            var errorRef:Unmanaged<CFError>? = nil
            //addressBook = extractABAddressBookRef(ABAddressBookCreateWithOptions(nil, &errorRef))
            ABAddressBookRequestAccessWithCompletion(addressBook, { success, error in
                if success {
                    //删除联系人
                    self.deleteRecord();
                }
                else {
                    println("error")
                }
            })
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Denied ||
            sysAddressBookStatus == ABAuthorizationStatus.Restricted) {
                println("access denied")
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Authorized) {
            println("access granted")
            //删除联系人
            self.deleteRecord();
        }
    }
    
    //删除联系人
    func deleteRecord(){
        //定义一个错误标记对象,判断是否成功
        var error:Unmanaged<CFErrorRef>?
        var sysContacts:NSArray = ABAddressBookCopyArrayOfAllPeople(addressBook)
            .takeRetainedValue() as NSArray
        
        //遍历通讯录
        for contact in sysContacts {
            //获取姓名
            var lastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?
                .takeRetainedValue() as! String? ?? ""
            var firstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?
                .takeRetainedValue() as! String? ?? ""
            
            var success:Bool = false
            if lastName == "李" && firstName == "大木"{
                success = ABAddressBookRemoveRecord(addressBook, contact, nil)
                println("删除结果:\(success)")
            }
        }
        
        //保存数据库
        var success = ABAddressBookSave(addressBook, &error)
        println("修改数据库是否成功:\(success)")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
评论0