2016-01-22 18 views
5

Tôi đang sử dụng mã này để xuất liên hệ từ danh bạ ios sang tệp .vcf. Tôi đã sử dụng mã này cho công việc. Nhưng vcardString luôn quay trở lại nil. Làm ơn giúp tôi giải quyết vấn đề này.Không thể tạo vcard liên hệ bằng khung liên hệ

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

Vui lòng đọc về [cách đặt câu hỏi hay] (// stackoverflow.com/help/how-to-ask) và thử chỉnh sửa câu hỏi của bạn. Với câu hỏi chất lượng cao, bạn sẽ nhận được câu trả lời tốt hơn nhanh hơn. Cảm ơn! – SmokeDispenser

+0

Điều gì không hoạt động chính xác? Dòng nào dường như đang gây ra sự cố? – Larme

+0

@Làm tôi đã chỉnh sửa câu hỏi của mình. –

Trả lời

1

Thay đổi dòng này:

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

này fetches tất cả thông tin cần thiết cho việc tạo ra một vCard.

Các vấn đề liên quan