以编程方式备份完整的iPhone AddressBook [英] Backup complete iPhone AddressBook programmatically
问题描述
我需要以编程方式备份包含所有记录(数字,名称,图像......)的所有联系人。我读到了关于AddressBook.framework的内容,但是有一种简单的方法来备份所有联系人吗?
I need to backup all contacts with all records (numbers, names, image, ...) programmatically. I read about the AddressBook.framework, but is there an easy way to make a backup all contacts?
推荐答案
1.一路这样做是为了创建一个包含所有联系人的vCard字符串。像这样:
1.One way of doing this is to create a vCard string with all your contacts. Like this:
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef peopleForBackup = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFDataRef vcards = (CFDataRef)ABPersonCreateVCardRepresentationWithPeople(peopleForBackup);
vcardString = [[NSString alloc] initWithData:(NSData *)vcards encoding:NSUTF8StringEncoding];
并将此字符串写入文件进行备份。
And write this string to a file for backup.
2.从地址簿中删除当前联系人:
2.Delete current contacts from address book:
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
int arrayCount = CFArrayGetCount(people);
ABRecordRef abrecord;
for (int i = 0; i < arrayCount; i++) {
abrecord = CFArrayGetValueAtIndex(people, i);
ABAddressBookRemoveRecord(addressBook,abrecord, NULL);
}
CFRelease(people);
3.要从备份恢复,您只需将vcard文件读入字符串并通过此人进行修改-records in vcard并将它们作为记录添加到地址簿中,然后保存。
3.To restore from the backup you just read the vcard file into a string and itterate through the person-records in the vcard and add them as records to an addressbook, then save it.
ABAddressBookRef addressBook = ABAddressBookCreate();
NSData *stringData = [NSData dataWithContentsOfFile:contactFilePath];
NSString *vcardFromFile = [[NSString alloc] initWithData:stringData encoding:NSUTF8StringEncoding];
CFDataRef vCardData = (CFDataRef)[vcardFromFile dataUsingEncoding:NSUTF8StringEncoding];
ABRecordRef defaultSource = ABAddressBookCopyDefaultSource(addressBook);
CFArrayRef vCardPeople = ABPersonCreatePeopleInSourceWithVCardRepresentation(defaultSource, vCardData);
for (CFIndex index = 0; index < CFArrayGetCount(vCardPeople); index++) {
ABRecordRef person = CFArrayGetValueAtIndex(vCardPeople, index);
ABAddressBookAddRecord(addressBook, person, NULL);
CFRelease(person);
}
CFRelease(vCardPeople);
CFRelease(defaultSource);
bool success = ABAddressBookSave(addressBook, NULL);
这种方法的一个问题是我不知道维持联系人链接的方法(交换,facebook ...)。
A Problem with this approach is that I dont know of a way to maintain the linking of contacts (exchange, facebook...).
这篇关于以编程方式备份完整的iPhone AddressBook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!