How to add a new letter to CNMutableContact in Swift 3?

Quickly .. I have this code to add a new contact, it worked before converting my code to Swift 3, now it accepts all properties except email, I get two errors:

1-Argument of type 'String?' does not match expected type 'NSCopying'

2-argument of type 'String?' does not match expected type 'NSSecureCoding'

this is my code when i try to add email address:

let workEmail = CNLabeledValue(label:"Work Email", value:emp.getEmail()) contact.emailAddresses = [workEmail] 

any help?

+8
ios swift cncontact
source share
4 answers

In Swift 3, CNLabeledValue declared as:

 public class CNLabeledValue<ValueType : NSCopying, NSSecureCoding> : NSObject, NSCopying, NSSecureCoding { //... } 

You need to force Swift to draw a ValueType output that matches NSCopying and NSSecureCoding .

Sorry, String or String? does not match any of them.

And, Swift 3 removed some implicit type conversions, such as String to NSString , you need to explicitly specify it.

Please try the following:

 let workEmail = CNLabeledValue(label:"Work Email", value:(emp.getEmail() ?? "") as NSString) contact.emailAddresses = [workEmail] 

Or that:

 if let email = emp.getEmail() { let workEmail = CNLabeledValue(label:"Work Email", value:email as NSString) contact.emailAddresses = [workEmail] } 

(Maybe the latter is better; you should not make an empty entry.)

And one more, as Cesare suggested, you better use predefined constants like CNLabel... for shortcuts as much as possible:

 if let email = emp.getEmail() { let workEmail = CNLabeledValue(label: CNLabelWork, value: email as NSString) contact.emailAddresses = [workEmail] } 
+21
source share

Swift 3 : Email and Phone Recording

Documentation : https://developer.apple.com/reference/contacts

 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))] 
+4
source share
  let workemail = "" //Your Input goes here let WorkEmail = CNLabeledValue(label:CNLabelWork, value: workmail as NSString) contact.emailAddresses = [WorkEmail] 

For Swift 3

0
source share

for Swift 3 and ios> = 9.0

You can use the CNContact mutableCopy method

 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.") } } 
-one
source share

All Articles