5

我正在使用此代码将联系人从 ios 电话簿导出到 .vcf 文件。我已将此代码用于该任务。但vcardString总是回归nil。请帮我解决这个问题。

NSMutableArray *contacts=[NSMutableArray alloc] init];
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (!granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
        return;
    }
    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) {

        [contactsArray addObject:contact];
        // NSString *string = [formatter stringFromContact:contact];

        //NSLog(@"contact = %@", string);
    }

    //NSError *error;
    NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];

    NSLog(@"vcardString = %@",vcardString);
}];
4

1 回答 1

3

更改此行:

CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[[CNContactVCardSerialization descriptorForRequiredKeys]]

这将获取创建 vCard 所需的所有信息。

于 2016-06-29T16:39:48.223 回答