Swift CN联系人

Swift CNContacts

我正在使用一个函数来创建 CNContact。每当我发送一个没有 phone 号码的联系人时,都会产生一个错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

如何将 nil 字符串发送到我的函数?

@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
}

将函数的实现更改为:

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

此外,您应该检查 phone 是否为零,如果是,则不要在联系人中包含 phone 号码。

if phone != nil {
    contact.phoneNumbers = [CNLabeledValue(
        label:CNLabelWork,
        value:CNPhoneNumber(stringValue: phone!))]
}