首页 > 代码库 > iphone通讯录的备份与恢复

iphone通讯录的备份与恢复

最近在做iOS系统通讯录备份到服务器,并且可以从服务器中下载备份文件恢复到手机的功能,部分实现细节记录如下。

将iphone系统通讯录生成.vcf文件

ABAddressBookRef addressBook = ABAddressBookCreate();CFArrayRef contacts = ABAddressBookCopyArrayOfAllPeople(addressBook);CFDataRef vcards = (CFDataRef)ABPersonCreateVCardRepresentationWithPeople(contacts);NSString *vcardString = [[NSString alloc] initWithData:(__bridge NSData *)vcards encoding:NSUTF8StringEncoding];NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *folderPath = [paths objectAtIndex:0];NSString *filePath = [folderPath stringByAppendingPathComponent:@"contacts.vcf"];
[vcardString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

运行后系统沙盒Document目录下会生成contacts.vcf文件,上传至服务器即可。

通讯录恢复:

从服务器下载contents.vcf文件,用系统通讯录程序打开即可恢复至手机。或者代码解析.vcf文件更新通讯录即可。

 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *plistPath = [paths objectAtIndex:0]; NSString *filePath =[plistPath stringByAppendingPathComponent:@"contacts.vcf"]; CFDataRef vCardData = (CFDataRef)[filePath dataUsingEncoding:NSUTF8StringEncoding];  ABAddressBookRef book = ABAddressBookCreate(); ABRecordRef defaultSource = ABAddressBookCopyDefaultSource(book); CFArrayRef vCardPeople = ABPersonCreatePeopleInSourceWithVCardRepresentation(defaultSource, vCardData); for (CFIndex index = 0; index < CFArrayGetCount(vCardPeople); index++) {     ABRecordRef person = CFArrayGetValueAtIndex(vCardPeople, index);     ABAddressBookAddRecord(book, person, NULL);     CFRelease(person); } CFRelease(vCardPeople); CFRelease(defaultSource); ABAddressBookSave(book, NULL); CFRelease(book);

注意:ABPersonCreateVCardRepresentationWithPeople只适用ios5.0以上系统。

有什么问题可以留言问我哟??

 

iphone通讯录的备份与恢复