使用AddressBook.framework框架,我们除了可以很方便的获取通信录里的联系人。同时,还能对通讯录进行新增、修改、删除联系人操作。

(注意:这些操作同查询一样,首先需要发起授权请求)
1,添加新联系人
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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,编辑修改联系人

先获取所有联系人遍历,根据联系人姓名或者电话来判断是否修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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,删除联系人

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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()
    }
}

Swift - 添加、修改、删除通讯录联系人的更多相关文章

  1. Android 查询 添加 修改 删除通讯录联系人示例

    1.AndroidManifest.xml中添加权限 <uses-permission android:name="android.permission.READ_CONTACTS&q ...

  2. JavaWeb_day03_员工信息添加修改删除

    day03员工的添加,修改,删除 修改功能 思路 : 点击修改员工数据之后,跳转到单行文本,查询要修改的员工id的全部信息,主键id设置为readonly,其余的都可以修改, 修改之后,提交按钮,提交 ...

  3. Web 1三级联动 下拉框 2添加修改删除 弹框

    Web  三级联动 下拉框 using System; using System.Collections.Generic; using System.Linq; using System.Web; u ...

  4. 打通前后端全栈开发node+vue进阶【课程学习系统项目实战详细讲解】(3):用户添加/修改/删除 vue表格组件 vue分页组件

    第三章 建议学习时间8小时      总项目预计10章 学习方式:详细阅读,并手动实现相关代码(如果没有node和vue基础,请学习前面的vue和node基础博客[共10章] 演示地址:后台:demo ...

  5. SpringBoot定时任务升级篇(动态添加修改删除定时任务)

    需求缘起:在发布了<Spring Boot定时任务升级篇>之后得到不少反馈,其中有一个反馈就是如何动态添加修改删除定时任务?那么我们一起看看具体怎么实现,先看下本节大纲: (1)思路说明: ...

  6. 【转】C#添加修改删除文件文件夹大全

    [转]C#添加修改删除文件文件夹大全 C#添加修改删除文件文件夹大全 StreamWriter sw = File.AppendText(Server.MapPath(".")+& ...

  7. oracle 表字段添加 修改 删除语法

    修改列名 alter table 表明 rename column rename 老列名 to 新列名添加 字段alter table 表名 add(字段名 类型):删除字段alter table 表 ...

  8. EF简单的添加修改删除基本语法

    using ( androidhiveEntities db = new androidhiveEntities() )                {                    #re ...

  9. thinkphp 添加 修改删除

    在 MainController.class.php 添加 public function zhuCe() { //时间两个逻辑 // 1 显示页面 2向数据库添加 if(empty($_POST)) ...

随机推荐

  1. c++ 复制构造函数和赋值函数

    c++ 自动提供了下面这些成员函数 1默认构造函数 2.复制构造函数 3.赋值操作符 4.默认析构函数 5.地址操作符 赋值构造函数copy construtor 用于将一个对象复制到新创建的对象中, ...

  2. boost库学习随记六:使用同步定时器、异步定时器、bind、成员函数回调处理、多线程的同步处理示例等

    一.使用同步定时器 这个示例程序通过展示如何在一个定时器执行一个阻塞等待. //makefile #-------------------------------------------------- ...

  3. 【GIVENCHY商务休闲风格/白色/100%精梳棉/撞色拼接领/长袖衬衣】玛萨玛索男装网购商城

    [GIVENCHY商务休闲风格/白色/100%精梳棉/撞色拼接领/长袖衬衣]玛萨玛索男装网购商城 GIVENCHY商务休闲风格/白色/100%精梳棉/撞色拼接领/长袖衬衣

  4. 基于物品的协同过滤推荐算法——读“Item-Based Collaborative Filtering Recommendation Algorithms” .

    ligh@local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.0.3 基于物品的协同过滤推荐算法--读"Item-Based ...

  5. Gstreamer中加入�x265编解码器

    官方的当前gstreamer版本号还不支持x265编解码,因此要加入�x265,须要自己编译.本文基于gstreamer1.3.3版进行编译安装.须要首先自己编译gstreamer1.3.3,以及对应 ...

  6. Cocos2d-x 精灵碰撞检測(方法二)

    将"Cocos2d-x 精灵碰撞检測(方法一)" update函数改动一下. 使用精灵boundingBox函数获取直接精灵边界框, 不用自己计算精灵矩形大小了,还比較精确,然后调 ...

  7. MVC action返回partialView前台html 拼接

    //后台 [HttpPost] public ActionResult GetNextLazyLoadProduct(int[] productIdList)         {           ...

  8. Xcode6中怎么添加空工程模板

    亲们!是不是还在为Xcode中不能创建空工程模板苦恼,轩哥为大家准备了一个脚本,可以在Xcode6中直接创建空工程,跟以前一样一样的! 按照以下要求就可以了!下载地址:里面有一个文档有详细的步骤htt ...

  9. [Swust OJ 249]--凸包面积

        题目链接:    http://acm.swust.edu.cn/problem/0249/   麦兜是个淘气的孩子.一天,他在玩钢笔的时候把墨水洒在了白色的墙上.再过一会,麦兜妈就要回来了, ...

  10. eclipse the user operation is waiting for building workspace" to complete

    "the user operation is waiting for building workspace" to complete", 解决办法: 1.选择菜单栏的“P ...