iphone通讯录的备份与恢复

Posted Steve Jobs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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通讯录的备份与恢复的主要内容,如果未能解决你的问题,请参考以下文章

备份联系人示例代码或来自 iPhone 的示例

gitlab基于阿里云OSS自动备份与恢复

iphone开发 中文转码问题

苹果手机突然出现激活

安卓智能手机怎样导入通信录/联系人

新iphone恢复备份可以中断吗?