最近在做iOS系統通訊錄備份到伺服器,並且可以從伺服器中下載備份文件恢復到手機的功能,部分實現細節記錄如下。 將iphone系統通訊錄生成.vcf文件 運行後系統沙盒Document目錄下會生成contacts.vcf文件,上傳至伺服器即可。 通訊錄恢復: 從伺服器下載contents.vcf文件, ...
最近在做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以上系統。
有什麼問題可以留言問我喲