2017-07-24 53 views
0

我正在使用函數來創建CNContact。每當我發送沒有電話號碼的聯繫人,它創建了一個錯誤:Swift CNContacts

fatal error: unexpectedly found nil while unwrapping an Optional value

如何發送一個零字符串我的功能?

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

回答

1

更改函數的實現,這樣的:

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

此外,你應該檢查是否phone是零,如果是,不包括與該聯繫人的電話號碼。

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

當我這樣說s比較類型'字符串'的非可選值爲零總是返回true –

+0

檢查我更新的答案。 – the4kman

+0

那工作謝謝! –