CNContact显示名称目标c/swift

Dav*_*dze 2 objective-c ios swift cncontact

我正在开发应用程序,我需要将联系人导入NSMutableDictionary,但有时人们不会填写所有联系人详细信息.所以只留下号码或公司名称.我是否需要浏览所有联系人详细信息以检查哪个字段将成为我的"显示名称".在Android中我知道有displayName变量.但是如何在Swift或Objective C中呢?

我的代码:

 BOOL success = [addressBook
  enumerateContactsWithFetchRequest:request   
                              error:&contactError       
                         usingBlock:^(CNContact *contact, BOOL *stop){

        NSString * contactId = contact.identifier;
        NSString * firstName = contact.givenName;
        NSString * lastName  = contact.familyName;
                 }];
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 7

使用CNContactFormatter建立的显示名称.指定请求的密钥时,请descriptorForRequiredKeysForStyle确保您请求了相应的字段.

在Swift中,它将是:

let store = CNContactStore()
store.requestAccess(for: .contacts) { granted, error in
    guard granted else {
        print(error?.localizedDescription ?? "Unknown error")
        return
    }

    let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as CNKeyDescriptor, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])

    let formatter = CNContactFormatter()
    formatter.style = .fullName

    do {
        try store.enumerateContacts(with: request) { contact, stop in
            if let name = formatter.string(from: contact) {
                print(name)
            }
        }
    } catch let fetchError {
        print(fetchError)
    }
}
Run Code Online (Sandbox Code Playgroud)

您建议您的情况是既没有姓名也没有公司,只有电话号码.那么,你必须亲自手动处理:

let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])

do {
    try store.enumerateContacts(with: request) { contact, stop in
        if let name = formatter.string(from: contact) {
            print(name)
        } else if let firstPhone = contact.phoneNumbers.first?.value {
            print(firstPhone.stringValue)
        } else {
            print("no name; no number")
        }
    }
} catch let fetchError {
    print(fetchError)
}
Run Code Online (Sandbox Code Playgroud)

对于Swift 2,请参阅此答案的先前版本.