我想在
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