我正在尝试使用以下代码获取联系人:
var addressBook: ABAddressBook!
let addressBookRef: ABAddressBook = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
var arrContacts = [""]
var personNameContactNo:[String: String] = ["":""]
var arrOfDictContacts = NSMutableArray()
var Name: String!
if let people = ABAddressBookCopyArrayOfAllPeople(addressBook)?.takeRetainedValue() as? NSArray {
for person in people{
if let name = ABRecordCopyValue(person, kABPersonFirstNameProperty).takeRetainedValue() as? String {
Name = name
}
let numbers:ABMultiValue = ABRecordCopyValue(
person, kABPersonPhoneProperty).takeRetainedValue()
var number = ABMultiValueCopyValueAtIndex(numbers,0).takeRetainedValue() as! String
println("number = \(number)")
if(number.isEmpty) {
println("empty")
} else {
personNameContactNo.removeAll(keepCapacity: true)
personNameContactNo.updateValue(number, forKey:Name)
arrOfDictContacts.addObject(personNameContactNo)
}
println(personNameContactNo)
}
println(arrOfDictContacts)
}
what am expecting is: ["Arun":"123455"], ["John":"23456122"], etc...
它在模拟器中运行良好但在设备上运行良好。也许这是由于一些零价值。
该应用程序崩溃时出现以下消息:fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
答案 0 :(得分:2)
尝试;这应该可以解决你的问题。
var addressBookRef: ABAddressBookRef = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
var arrOfDictContacts:NSMutableArray = NSMutableArray()
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 (ABMultiValueGetCount(numbers) > 0) { //This condition is optional because using '?' before calling takeRetainedValue
if let number:String = ABMultiValueCopyValueAtIndex(numbers,0)?.takeRetainedValue() as? String {
println("number = \(number)");
arrOfDictContacts.addObject(["\(name)":"\(number)"]);
}
// }
}
}
//--
println(arrOfDictContacts);