2016-01-22 18 views
5

このコードを使用して、ios電話帳から.vcfファイルに連絡先をエクスポートしています。私はこのコードをタスクに使用しました。ただし、vcardStringは常にnilを返します。この問題を解決するために私を助けてください。連絡先フレームワークを使用して連絡先のvcardを作成できません

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]]

これはvCardの作成に必要なすべての情報を取得します。

関連する問題