Ryan Hubbard Ryan Hubbard - 3 years ago 117
Swift Question

Swift CNContacts

I am using a function to create a CNContact whenever I send a contact that does not have a phone number it creates an error fatal error: unexpectedly found nil while unwrapping an Optional value How do I send a nil string to my function?

@IBAction func addToContacts(_ sender: Any) {

// Send Data to create a contact card
let contact: CNContact = supportMethods.createContact(lastName: lastNameString, firstName: firstNameString, email: emailString, phone: agentContactPhone!, city: agentCity, title: "Agent", image: imageString, bio: bioScrollView)

do {
try shareContacts(contacts: [contact])
} catch {
}

}

class func createContact(lastName: String, firstName: String, email: String, phone: String, city: String, title: String, image: String, bio: String) -> CNContact {
// Creating a mutable object to add to the contact
let contact = CNMutableContact()

contact.familyName = lastName
contact.givenName = firstName
contact.jobTitle = title
contact.organizationName = "IDX Broker"
contact.note = bio

let imgURL = URL(string: image)
if imgURL != nil {
let data = NSData(contentsOf: (imgURL)!)
// If the Agent has a phot
if data != nil {
contact.imageData = data! as Data
}
}

contact.phoneNumbers = [CNLabeledValue(
label:CNLabelWork,
value:CNPhoneNumber(stringValue: phone))]

let email = CNLabeledValue(label: CNLabelWork, value: email as NSString)
contact.emailAddresses = [email]


let homeAddress = CNMutablePostalAddress()
homeAddress.city = city
contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)]


return contact
}

Answer Source

Change your function's implementation to this:

class func createContact(lastName: String, firstName: String, email: String, phone: String?, city: String, title: String, image: String, bio: String) -> CNContact

Also, you should check if phone is nil and if it is, do not include a phone number with the contact.

if phone != nil {
    contact.phoneNumbers = [CNLabeledValue(
        label:CNLabelWork,
        value:CNPhoneNumber(stringValue: phone!))]
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download