APAddressBook
APAddressBook copied to clipboard
Some users can't get firstname and lastname
Hi
My problem is I can't get first and last name some of users with apaddressbook. also I'm looking my contacts that rows have lastname and firstname
let addressBook = APAddressBook()
addressBook.sortDescriptors = [NSSortDescriptor(key: "name.firstName", ascending: true)]
addressBook.fieldsMask = [APContactField.PhonesOnly, APContactField.Name]
addressBook.loadContacts { (contacts, error) in
if error == nil {
self.contacts = contacts!
}else {
print(error)
}
}
let person = contacts[indexPath.row]
var firstName = person.name?.firstName
var lastName = person.name?.lastName
if firstName == nil || lastName == nil {
if firstName == nil {
firstName = ""
}
if lastName == nil {
lastName = ""
}
if firstName == nil && lastName == nil {
if person.phones![0].number != nil {
firstName = person.phones![0].number
lastName = ""
}else {
firstName = ""
lastName = ""
}
}
}
let fullName: String = firstName! + " " + lastName!
Hi,
The second part of the code looks very strange. You check is firstName/lastName nil, then assign empty string to them (so they not nil anymore!), and then check is firstName/lastName nil again. So, the following code will never executed:
if firstName == nil && lastName == nil {
if person.phones![0].number != nil {
firstName = person.phones![0].number
lastName = ""
} else {
firstName = ""
lastName = ""
}
}
Try Example.app
in this repo. If everything work fine I believe the problem is in your code. And if not I would ask you to help me to find the bug. But try Example.app
first.