ios – 以编程方式在Swift中添加联系人

前端之家收集整理的这篇文章主要介绍了ios – 以编程方式在Swift中添加联系人前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在 Swift中以编程方式添加联系人(只是名称和电话号码).我发现了一些Objective-C示例,但我没有让它们工作,甚至在Objective-C中也没有.我不希望这涉及到AddressBookUI,因为我想从我自己的UI中获取值.

解决方法

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

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

@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

顺便说一下 – 它假设你已经分配了一个地址簿var,你可以通过覆盖viewDidAppear来打开视图.它也会执行安全提示

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

猜你在找的iOS相关文章