2017-05-17 33 views
0

這是我的代碼,我的應用程序在打印數據的過程中崩潰,沒有在日誌中顯示錯誤消息。它打印了30人,然後崩潰,對代碼行墜毀此消息:應用程序在打印聯繫人名稱和數字時崩潰

Thread 1: EXC_BREAKPOINT (code=1, subcode =.....) 

我將迎來的代碼行與地方在我的代碼上出現此消息// CRASH:

import UIKit 
import Contacts 
class ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 
    for cont in contacts { 
     print(cont.givenName) 
     let num = ((cont.phoneNumbers.first?.value)! as CNPhoneNumber).stringValue //CRASH 
     print(num) 
    } 
    // Do any additional setup after loading the view, typically from a nib. 
} 

lazy var contacts: [CNContact] = { 
    let contactStore = CNContactStore() 
    let keysToFetch = [ 
     CNContactFormatter.descriptorForRequiredKeys(for: .fullName), 
     CNContactEmailAddressesKey, 
     CNContactPhoneNumbersKey, 
     CNContactImageDataAvailableKey, 
     CNContactThumbnailImageDataKey] as [Any] 

    // Get all the containers 
    var allContainers: [CNContainer] = [] 
    do { 
     allContainers = try contactStore.containers(matching: nil) 
    } catch { 
     print("Error fetching containers") 
    } 

    var results: [CNContact] = [] 

    // Iterate all containers and append their contacts to our results array 
    for container in allContainers { 
     let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier) 

     do { 
      let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as! [CNKeyDescriptor]) 
      results.append(contentsOf: containerResults) 
     } catch { 
      print("Error fetching results for container") 
     } 
    } 

    return results 
}() 

}

我想我可能會展開爲零,但其並非如此,因爲它不是一個可選的(我試圖解開它以安全的方式和編譯器說,這是不是一個可選類型)。

+1

當它崩潰時,在調試器中檢查「cont.phoneNumbers.first?.value」的值(或者只是打印它)。 –

+0

你的意思是打印它沒有鑄造和扭曲它? – Eyzuky

+0

是的,只是爲了看看是否有任何可疑的崩潰與可以。 –

回答

1

從評論:

的問題真可謂是cont.phoneNumbers.first?.value被迫展開,因爲這將是零,如果沒有電話號碼(因此沒有先評估)。

相關問題