2016-01-22 73 views
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); 
}]; 
+1

請閱讀[如何問好問題](// stackoverflow.com/help/how-to-ask)並嘗試編輯您的問題。有了高質量的問題,您將會收到更快的答案。謝謝! – SmokeDispenser

+0

什麼不能確切地工作?哪一行似乎是造成問題? – Larme

+0

@Larme我編輯了我的問題。 –

回答

1

改變這一行:

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

這將提取創建電子名片所需的所有信息。

相關問題