Reputation: 1935
This is my code, my app crashes in the middle of printing the data, without an error message in the log. it prints almost 30 people and then crashes, with this message on the line of code that crashed:
Thread 1: EXC_BREAKPOINT (code=1, subcode =.....)
I will mark the line of code with //CRASH where this message appears on in my code:
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
}()
}
I thought I may be unwrapping nil but its not the case since it is not an optional (I tried to unwrap it in a safe way and the compiler says it is not an optional type).
Upvotes: 0
Views: 98
Reputation: 31016
From the comments:
The problem turns out to be the forced unwrapping of cont.phoneNumbers.first?.value
since it will be nil if there are no phone numbers (and therefore no first to evaluate).
Upvotes: 1