要将应用程序中的联系人添加到iOS通讯录中,您需要使用苹果提供的Contacts框架。以下是一个简单的步骤说明:
CNContactStore
类的requestAccess(for:completionHandler:)
方法来请求授权。CNMutableContact
对象,用于表示要添加到通讯录中的联系人。您可以设置联系人的各种属性,例如名字、电话号码、电子邮件地址等。CNContactStore
类的save(_:)
方法将新联系人添加到通讯录中。以下是一个简单的示例代码:
import Contacts
func addContactToAddressBook(name: String, phoneNumber: String) {
// 创建一个联系人对象
let contact = CNMutableContact()
contact.givenName = name
contact.phoneNumbers = [CNLabeledValue(label: CNLabelPhoneNumberMain, value: CNPhoneNumber(stringValue: phoneNumber))]
// 请求授权
let store = CNContactStore()
store.requestAccess(for: .contacts) { (granted, error) in
if granted {
// 添加联系人
do {
try store.add(contact, to: nil)
print("联系人已添加到通讯录")
} catch {
print("添加联系人失败:", error)
}
} else {
print("没有授权访问通讯录")
}
}
}
请注意,这个示例代码仅适用于iOS 9及更高版本。如果您需要支持更低版本的iOS,您需要使用AddressBook框架。
领取专属 10元无门槛券
手把手带您无忧上云