Ios 以编程方式在Swift中添加联系人
我想在Swift中以编程方式添加联系人(仅包括姓名和电话号码)。我发现了一些Objective-C示例,但我没有让它们工作,甚至在Objective-C中也没有。我不希望这涉及AddressBookUI,因为我想从自己的UI中获取值。我使用了以下代码行Ios 以编程方式在Swift中添加联系人,ios,iphone,swift,abaddressbook,Ios,Iphone,Swift,Abaddressbook,我想在Swift中以编程方式添加联系人(仅包括姓名和电话号码)。我发现了一些Objective-C示例,但我没有让它们工作,甚至在Objective-C中也没有。我不希望这涉及AddressBookUI,因为我想从自己的UI中获取值。我使用了以下代码行 var addressBook : ABAddressBookRef = ABAddressBookCreate() var contactPerson : ABRecordRef = ABPersonCreate() ABRecordSetV
var addressBook : ABAddressBookRef = ABAddressBookCreate()
var contactPerson : ABRecordRef = ABPersonCreate()
ABRecordSetValue(contactPerson, kABPersonFirstNameProperty, txtFirstName.text, nil);
ABRecordSetValue(contactPerson, kABPersonLastNameProperty, txtLastName.text, nil);
但是当插入的记录包含“nil”时
在从通讯录中读取联系人时,以下代码片段有所帮助
var firstName: NSString! = Unmanaged<CFString>.fromOpaque(ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty).toOpaque()).takeUnretainedValue().__conversion()
var firstName:NSString!=非托管的.fromOpaque(ABRecordCopyValue(contactPerson,KabbersonfirstNameProperty).toOpaque()).TakeUnrepainedValue()。\uu转换()
以下是在Swift中添加联系人的快速方法。我在我的iPhone5iOS7.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
@IBAction func createContact(发件人:AnyObject){
var newContact:ABRecordRef!=ABPersonCreate().takeRetainedValue()
var成功:Bool=false
var newFirstName:NSString=“AA”
var newLastName=“a”
//已更新为在Xcode 6.1中工作
变量错误:非托管?=nil
//更新为error to&error,因此代码构建在Xcode 6.1中
success=ABRecordSetValue(newContact、kabbersonfirstnameproperty、newFirstName和error)
println(“设置名字成功?\(成功)”)
success=ABRecordSetValue(newContact、kABPersonLastNameProperty、newLastName和error)
println(“设置姓氏成功?\(成功)”)
success=ABAddressBookAddRecord(adbk、newContact和error)
println(“Adbk addRecord成功?\(成功)”)
success=ABAddressBookSave(adbk,&error)
println(“Adbk保存成功?\(成功)”)
}//创建联系人
顺便说一句,它假设您已经分配了一个addressbook变量,您可以在打开视图时覆盖ViewDidDisplay。它还执行安全提示:
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
覆盖函数视图显示(动画:Bool){
super.viewdide显示(动画)
如果!self.authDone{
self.authDone=true
let stat=ABAddressBookGetAuthorizationStatus()
开关状态{
案例。拒绝,。限制:
println(“无访问权限”)
案例。已授权,未确定:
变量错误:非托管?=nil
var adbk:ABAddressBook?=ABAddressBookCreateWithOptions(nil,&err)。takeRetainedValue()
如果adbk==nil{
println(err)
返回
}
ABAddressBookRequestAccessWithCompletion(adbk){
(被授予:Bool,err:CFError!)在
如果允许的话{
self.adbk=adbk
}否则{
println(err)
}//如果
}//ABAddressBookRequeustAccesswithCompletion
}//案例
}//如果
}//视图显示
使用swift 3单击按钮添加联系人
在项目plist中添加此行
隐私-联系人使用说明
然后
单击按钮时,添加以下内容
在应用程序委托上添加一些自定义类
你完了;测试项目并检查联系人应用程序。Swift 4和5
import ContactsUI
继承此类CNContactViewControllerDelegate
@IBOutlet var contactNameTxt: UITextField!
@IBOutlet var phoneNumberTxt: UITextField!
@IBAction func saveActionBtn(_ sender: UIButton) {
let store = CNContactStore()
let contact = CNMutableContact()
// Name
contact.givenName = contactNameTxt.text ?? ""
// Phone
contact.phoneNumbers.append(CNLabeledValue(
label: "mobile", value: CNPhoneNumber(stringValue: phoneNumberTxt.text ?? "")))
// Save
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
try? store.execute(saveRequest)
}
1
ABAddressBookCreate()
已弃用。您确实应该使用ABAddressBookCreateWithOptions()
。例如,let addressBook:ABAddressBookRef!=ABAddressBookCreateWithOptions(无,&错误)。takeRetainedValue()
。2.在最新的Beta中,不再需要来自不透明/toOpaque
的舞蹈。例如,let first=ABRecordCopyValue(person,kABPersonFirstNameProperty)。将retainedvalue()作为字符串。
。回答得好。顺便说一句,如果您调用ABAddressBookCreateWithOptions
,您的err
是非托管的,因此除非您调用takeRetainedValue()。同样,在设置ABRecordRef
的属性时,(a)我认为可以消除unasfemeutablepointer
,只需使用var error:Unmanaged?
;(b)如果这些行中的任何一行产生了错误,您也会想要获取保留值
。谢谢-前几天我花了一个小时学习了什么是非托管,所以我终于理解了您在这里写的内容:)找到了如何解决Rob几个月前突出显示的Xcode 6.1错误的方法。更改为他建议的语法,而不是作为参数传入error,而是传入一个指针(&error)。您必须在按钮的视图中添加“let contactStore=CNContactStore()”。这不是问题。。您只是忘了添加我在代码示例中编写的行:)
// MARK: Custom functions
class func getAppDelegate() -> AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
func showMessage(_ message: String) {
let alertController = UIAlertController(title: "Birthdays", message: message, preferredStyle: UIAlertControllerStyle.alert)
let dismissAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action) -> Void in
}
alertController.addAction(dismissAction)
let pushedViewControllers = (self.window?.rootViewController as! UINavigationController).viewControllers
let presentedViewController = pushedViewControllers[pushedViewControllers.count - 1]
presentedViewController.present(alertController, animated: true, completion: nil)
}
func requestForAccess(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
switch authorizationStatus {
case .authorized:
completionHandler(true)
case .denied, .notDetermined:
self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
if access {
completionHandler(access)
}
else {
if authorizationStatus == CNAuthorizationStatus.denied {
DispatchQueue.main.async(execute: { () -> Void in
let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
self.showMessage(message)
})
}
}
})
default:
completionHandler(false)
}
}
import ContactsUI
@IBOutlet var contactNameTxt: UITextField!
@IBOutlet var phoneNumberTxt: UITextField!
@IBAction func saveActionBtn(_ sender: UIButton) {
let store = CNContactStore()
let contact = CNMutableContact()
// Name
contact.givenName = contactNameTxt.text ?? ""
// Phone
contact.phoneNumbers.append(CNLabeledValue(
label: "mobile", value: CNPhoneNumber(stringValue: phoneNumberTxt.text ?? "")))
// Save
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
try? store.execute(saveRequest)
}