在Swift中以编程方式添加联系人 [英] Programmatically add contact in Swift

查看:64
本文介绍了在Swift中以编程方式添加联系人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Swift中以编程方式添加联系人(只是姓名和电话号码).我找到了一些Objective-C的示例,但我什至没有在Objective-C中使用它们.我不希望这涉及AddressBookUI,因为我想从自己的UI中获取值.

I want to add a contact (just the name and phone number) programatically in Swift. I've found some Objective-C examples but I didn't get them to work, not even in Objective-C. I don't want this to involve AddressBookUI, because I want to get the values from my own UI.

推荐答案

这是在Swift中添加联系人的快速方法.我在iPhone 5 iOS 7.1上对其进行了验证,因为我发现模拟器并不总是与手机上的AB东西匹配相同的结果.

Here's a quick method to add a contact in Swift. I verified it on my iPhone 5 iOS 7.1 as I've found the simulator doesn't always match the same results as my phone does for AB stuff.

您可以添加一个按钮并指向此方法:

You can add a button and point to this method:

@IBAction func createContact(sender: AnyObject) {
    var newContact:ABRecordRef! = ABPersonCreate().takeRetainedValue()
    var success:Bool = false
    var newFirstName:NSString = "AA"
    var newLastName = "a"

//Updated to work in Xcode 6.1
        var error: Unmanaged<CFErrorRef>? = nil
//Updated to error to &error so the code builds in Xcode 6.1
    success = ABRecordSetValue(newContact, kABPersonFirstNameProperty, newFirstName, &error)
    println("setting first name was successful? \(success)")
    success = ABRecordSetValue(newContact, kABPersonLastNameProperty, newLastName, &error)
    println("setting last name was successful? \(success)")
    success = ABAddressBookAddRecord(adbk, newContact, &error)
    println("Adbk addRecord successful? \(success)")
    success = ABAddressBookSave(adbk, &error)
    println("Adbk Save successful? \(success)")

}//createContact

顺便说一句,它假定您已经分配了一个地址簿变量,您可以通过覆盖viewDidAppear来打开视图.它还会执行安全提示:

btw-it assumes you've already got an addressbook var assigned, which you can on opening the view by overriding viewDidAppear. It does the security prompt as well:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    if !self.authDone {
        self.authDone = true
        let stat = ABAddressBookGetAuthorizationStatus()
        switch stat {
        case .Denied, .Restricted:
            println("no access")
        case .Authorized, .NotDetermined:
            var err : Unmanaged<CFError>? = nil
            var adbk : ABAddressBook? = ABAddressBookCreateWithOptions(nil, &err).takeRetainedValue()
            if adbk == nil {
                println(err)
                return
            }
            ABAddressBookRequestAccessWithCompletion(adbk) {
                (granted:Bool, err:CFError!) in
                if granted {
                    self.adbk = adbk
                } else {
                    println(err)
                }//if
            }//ABAddressBookReqeustAccessWithCompletion
        }//case
    }//if
}//viewDidAppear

这篇关于在Swift中以编程方式添加联系人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆