首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >CNContact显示名称目标c/ swift

CNContact显示名称目标c/ swift
EN

Stack Overflow用户
提问于 2016-04-26 08:55:49
回答 4查看 5.8K关注 0票数 3

我正在开发应用程序,我需要将联系人导入到NSMutableDictionary中,但有时人们没有填写所有的联系人详细信息。所以只留下号码或公司名称。我是否需要查看所有联系人细节,以检查哪个字段将是我的“显示名称”。在安卓系统中,我知道有displayName变量。但是它在Swift还是目标C中是怎样的呢?

我的代码:

代码语言:javascript
运行
复制
 BOOL success = [addressBook
  enumerateContactsWithFetchRequest:request   
                              error:&contactError       
                         usingBlock:^(CNContact *contact, BOOL *stop){

        NSString * contactId = contact.identifier;
        NSString * firstName = contact.givenName;
        NSString * lastName  = contact.familyName;
                 }];
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-04-26 09:22:38

使用CNContactFormatter生成显示名称。指定请求的键时,请使用descriptorForRequiredKeysForStyle确保您请求了适当的字段。

在Swift中,它将是:

代码语言:javascript
运行
复制
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)
    }
}

你建议你有这样的情况:没有名字也没有公司,只有电话号码。好吧,那么,你必须自己手动处理:

代码语言:javascript
运行
复制
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)
}

有关Swift 2,请参见previous revision of this answer

票数 8
EN

Stack Overflow用户

发布于 2016-04-26 08:59:36

您可以使用以下代码从电话簿中获取联系人名称:-

代码语言:javascript
运行
复制
- (void) fetchContacts
{
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusDenied) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts" preferredStyle:UIAlertControllerStyleAlert];

        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:TRUE completion:nil];
        return;
    }

    CNContactStore *store = [[CNContactStore alloc] init];    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {

        // make sure the user granted us access

        if (!granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                // user didn't grant access;
                // so, again, tell user here why app needs permissions in order  to do it's job;
                // this is dispatched to the main queue because this request could be running on background thread
            });
            return;
        }

        // build array of contacts

        NSMutableArray *contacts = [NSMutableArray array];

        NSError *fetchError;
        CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactIdentifierKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];

        BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
            [contacts addObject:contact];
        }];



        if (!success) {
            NSLog(@"error = %@", fetchError);
        }



        // you can now do something with the list of contacts, for example, to show the names

        CNContactFormatter *formatter = [[CNContactFormatter alloc] init];

        for (CNContact *contact in contacts) {
            if (!_contacts) {
                _contacts = [[NSMutableArray alloc] init];
            }

            NSString *string = [formatter stringFromContact:contact];
            NSLog(@"contact = %@", string);
            [_contacts addObject:string];
        }
        [_contactatableview reloadData];

    }];
}
票数 1
EN

Stack Overflow用户

发布于 2016-04-26 08:57:52

代码语言:javascript
运行
复制
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>


- (IBAction)displayContact:(id)sender {

    id keysToFetch = @[[CNContactViewController descriptorForRequiredKeys]];
     CNContact *contact = [self.store unifiedContactWithIdentifier:self.contactIdentifier keysToFetch:keysToFetch error:nil];

    self.controller = [[CNContactViewController alloc] init];

    [self.controller.view setFrameSize:NSMakeSize(500, 500)];

    [self presentViewController:self.controller asPopoverRelativeToRect:self.view.bounds ofView: self.view preferredEdge: NSMaxXEdge behavior:NSPopoverBehaviorTransient];

    self.controller.contact = contact;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36859991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档