2016-01-22 4 views
5

Ich verwende diesen Code, um den Kontakt aus dem ios-Telefonbuch in die .vcf-Datei zu exportieren. Ich habe diesen Code für die Aufgabe verwendet. Aber vcardString gibt immer nil zurück. Bitte helfen Sie mir, dieses Problem zu lösen.Nicht in der Lage, vCard von Kontakten mit Kontaktrahmen zu erstellen

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

Bitte lesen Sie über [wie Sie gute Fragen stellen] (// stackoverflow.com/help/how-to-ask) und versuchen Sie, Ihre Frage zu bearbeiten. Bei qualitativ hochwertigen Fragen erhalten Sie schneller bessere Antworten. Vielen Dank! – SmokeDispenser

+0

Was funktioniert nicht genau? Welche Zeile scheint Probleme zu verursachen? – Larme

+0

@Larme Ich habe meine Frage bearbeitet. –

Antwort

1

Ändern Sie diese Zeile:

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

Dieser holt alle erforderlichen Informationen für eine vCard zu schaffen.