2015-09-06 97 views
1

我試圖讓使用下面的代碼觸點崩潰:應用程序同時從iPhone獲取聯繫人號碼在SWIFT

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)

Crashing Image

+0

你能指定你的代碼在哪一行崩潰嗎? – Shoaib

+0

我不知道在哪一行,它沒有在崩潰時指向 – AAA

+0

嘗試在我的答案中發佈的代碼。 – Shoaib

回答

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); 
+0

@Shoib仍然崩潰,同樣的錯誤。在問題中添加屏幕截圖 – AAA

+0

@AAA我已更新我的帖子。如果它仍然崩潰,則使用斷點來查找實際代碼崩潰的行。 – Shoaib

+0

好的,該應用程序既不崩潰也不提取​​任何聯繫人。 'arrOfDictContacts'爲空 – AAA

相關問題