Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new email to CNMutableContact in Swift 3?

Quickly .. I have this code to add new contact , it was working until converting my code to Swift 3 , now it accept all properties except the email I get two errors :

1-Argument type 'String?' does not conform to expected type 'NSCopying'

2-Argument type 'String?' does not conform to expected type 'NSSecureCoding'

this is my code when I try to add email to contact :

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

any help ?

like image 804
Zizoo Avatar asked Sep 22 '16 21:09

Zizoo


3 Answers

In Swift 3, CNLabeledValue is declared as:

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

You need to make Swift able to infer the ValueType, which conforms to NSCopying and NSSecureCoding.

Unfortunately, String or String? does not conform to neither of them.

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

Please try this:

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

Or this:

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

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

And one more, as suggested by Cesare, you'd better use predefined constants like CNLabel... for labels as far as possible:

if let email = emp.getEmail() {
    let workEmail = CNLabeledValue(label: CNLabelWork, value: email as NSString)
    contact.emailAddresses = [workEmail]
}
like image 175
OOPer Avatar answered Nov 16 '22 02:11

OOPer


Swift 3: Email and Phone entry

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

let workPhoneEntry : String = "(408) 555-0126"
let workEmailEntry : String = "[email protected]"
let workEmail = CNLabeledValue(label:CNLabelWork, value:workEmailEntry as NSString)
    contact.emailAddresses = [workEmail]

    contact.phoneNumbers = [CNLabeledValue(
        label:CNLabelPhoneNumberMain,
        value:CNPhoneNumber(stringValue:workPhoneEntry))]
like image 38
9BallOnTheSnap Avatar answered Nov 16 '22 03:11

9BallOnTheSnap


 let workemail = "" //Your Input goes here
 let WorkEmail = CNLabeledValue(label:CNLabelWork, value: workmail as NSString)
 contact.emailAddresses = [WorkEmail]

For Swift 3

like image 3
BHAVIK Avatar answered Nov 16 '22 01:11

BHAVIK