Ios 如何在Swift 3中向CNMutableContact添加新电子邮件?
快点。。我使用此代码添加新联系人,在将我的代码转换为Swift 3之前一直有效,现在它接受除电子邮件之外的所有属性。我收到两个错误: 1参数类型“字符串”与预期类型不符 “复制” 2参数类型“字符串”与预期类型不符 “NSSecureCodeding” 这是我尝试向联系人添加电子邮件时的代码:Ios 如何在Swift 3中向CNMutableContact添加新电子邮件?,ios,swift,cncontact,Ios,Swift,Cncontact,快点。。我使用此代码添加新联系人,在将我的代码转换为Swift 3之前一直有效,现在它接受除电子邮件之外的所有属性。我收到两个错误: 1参数类型“字符串”与预期类型不符 “复制” 2参数类型“字符串”与预期类型不符 “NSSecureCodeding” 这是我尝试向联系人添加电子邮件时的代码: let workEmail = CNLabeledValue(label:"Work Email", value:emp.getEmail()) contact.emailAddresse
let workEmail = CNLabeledValue(label:"Work Email", value:emp.getEmail())
contact.emailAddresses = [workEmail]
有任何帮助吗?在Swift 3中,
CNLabeledValue
声明为:
public class CNLabeledValue<ValueType : NSCopying, NSSecureCoding> : NSObject, NSCopying, NSSecureCoding {
//...
}
或者这个:
if let email = emp.getEmail() {
let workEmail = CNLabeledValue(label:"Work Email", value:email as NSString)
contact.emailAddresses = [workEmail]
}
(也许后者更好,你不应该做一个空条目。)
还有一点,正如Cesare所建议的,您最好尽可能为标签使用预定义常量,如CNLabel…
:
if let email = emp.getEmail() {
let workEmail = CNLabeledValue(label: CNLabelWork, value: email as NSString)
contact.emailAddresses = [workEmail]
}
对于Swift 3和ios>=9.0
您可以使用方法CNContact mutableCopy
func saveVCardContacts (vCard : Data) {
if #available(iOS 9.0, *) {
let contactStore = CNContactStore()
do {
let saveRequest = CNSaveRequest()
let contacts = try CNContactVCardSerialization.contacts(with: vCard)
var mutablePerson: CNMutableContact
for person in contacts{
mutablePerson = person.mutableCopy() as! CNMutableContact
saveRequest.add(mutablePerson, toContainerWithIdentifier: nil)
}
try contactStore.execute(saveRequest)
} catch {
print("Unable to show the new contact")
}
}else{
print("CNContact not supported.")
}
}
对于Swift 3Swift 3:电子邮件和电话输入 文档:
这并不能回答问题。OP的代码创建了一个
CNLabeledValue
,他在那里遇到了问题。您的示例没有以任何方式解决此问题。在workemail中,添加输入值并将workemail添加到contact中。EmailAddresses最好使用CNLabelWork
而不是“Work email”,因为前者在每个language@Cesare谢谢好建议。我会在回答中接受它。
func saveVCardContacts (vCard : Data) {
if #available(iOS 9.0, *) {
let contactStore = CNContactStore()
do {
let saveRequest = CNSaveRequest()
let contacts = try CNContactVCardSerialization.contacts(with: vCard)
var mutablePerson: CNMutableContact
for person in contacts{
mutablePerson = person.mutableCopy() as! CNMutableContact
saveRequest.add(mutablePerson, toContainerWithIdentifier: nil)
}
try contactStore.execute(saveRequest)
} catch {
print("Unable to show the new contact")
}
}else{
print("CNContact not supported.")
}
}
let workemail = "" //Your Input goes here
let WorkEmail = CNLabeledValue(label:CNLabelWork, value: workmail as NSString)
contact.emailAddresses = [WorkEmail]
let workPhoneEntry : String = "(408) 555-0126"
let workEmailEntry : String = "test@apple.com"
let workEmail = CNLabeledValue(label:CNLabelWork, value:workEmailEntry as NSString)
contact.emailAddresses = [workEmail]
contact.phoneNumbers = [CNLabeledValue(
label:CNLabelPhoneNumberMain,
value:CNPhoneNumber(stringValue:workPhoneEntry))]