iphone通讯录的备份与恢复_移动开发_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > 移动开发 > iphone通讯录的备份与恢复

iphone通讯录的备份与恢复

 2017/5/28 5:32:32  tylerzhang  程序员俱乐部  我要评论(0)
  • 摘要:最近在做iOS系统通讯录备份到服务器,并且可以从服务器中下载备份文件恢复到手机的功能,部分实现细节记录如下。将iphone系统通讯录生成.vcf文件ABAddressBookRefaddressBook=ABAddressBookCreate();CFArrayRefcontacts=ABAddressBookCopyArrayOfAllPeople(addressBook);CFDataRefvcards=(CFDataRef
  • 标签: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以上系统。

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

 

发表评论
用户名: 匿名