Swift CN联系人

标签 swift cncontact

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

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 是否为 nil,如果是,则不要在联系人中包含电话号码。

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

关于Swift CN联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45290167/

相关文章:

ios - 如何在 UITableView 的底部加载第二个 UITableViewCell?

ios - XCode8 Swift3 - 打开联系人列表并通过单击检索数据时出现问题

ios - 线程 1 : EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, 子代码 = 0X0) - 错误

swift - CNContactPickerViewController 中的多重选择

ios - 使用 CNContacts (Swift) 实现搜索 Controller 时出现问题

ios - 在 iOS 9 中自定义 ContactPicker UI

ios - SwiftUI 跨多个 subview 拖动手势

swift - 闭包返回值(以前的 completionBlock)

ios - "if"语句的问题 : "trying to style message. 内容根据 message.sender 有所不同

php - 与网站、Swift + PHP 相比,应用程序中 mysql 查询的结果不同