2015-10-06 57 views
1

在我的swift应用程序中,我从AddressBook框架中检索AddressBook联系人。除以下情况外,联系人已成功检索。从AddressBook框架中返回空值

案例1:

如果我救孤联系人号码没有联系人姓名,地址簿,联系人添加成功。

但是,如果我尝试检索那个没有名字的联系人,那么应用程序崩溃,并说收到致命错误

编码:

var contactName: String = ABRecordCopyCompositeName(addressBookRecord).takeRetainedValue() as NSString as String 

我不知道如何处理这种空值异常。请引导我,如何解决这个问题。

+0

你为什么不检查是否CONTACTNAME返回null,并为其分配一个空字符串,如果这是案子?像这样http://paste.ubuntu.com/12695416/ – NSNoob

+0

你应该看看新的联系框架https://developer.apple.com/library/prerelease/mac/documentation/Contacts/Reference/Contacts_Framework/ index.html –

+0

应用程序在该行@NSNoob上崩溃。那我该怎么做? –

回答

2

,如果你得到了一个没有名称的任何接触这些代码不会崩溃:

func processAddressbookRecord(addressBookRecord: ABRecordRef) { 

    let addressBookRef: ABAddressBookRef = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue() 

    let people:NSArray = ABAddressBookCopyArrayOfAllPeople(addressBookRef).takeRetainedValue(); 

    for person in people{ 
     if let name:String = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String { 
      let numbers:ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue() 

      if let number:String = ABMultiValueCopyValueAtIndex(numbers,0)?.takeRetainedValue() as? String { 
       print("number = \(number)"); 
       arrayOfContacts.addObject(["\(name)":"\(number)"]); 
      } 
     } 
    } 
} 

原帖:App crashing while fetching contact numbers from iPhone in SWIFT