以编程方式备份完整的iPhone地址簿
我需要以编程方式备份所有logging(数字,名称,图像…)的所有联系人。 我读了AddressBook.framework,但有一个简单的方法来备份所有联系人?
1.这样做的一个方法是创build一个vCardstring与您的所有联系人。 喜欢这个:
ABAddressBookRef addressBook = ABAddressBookCreate(); CFArrayRef peopleForBackup = ABAddressBookCopyArrayOfAllPeople(addressBook); CFDataRef vcards = (CFDataRef)ABPersonCreateVCardRepresentationWithPeople(peopleForBackup); vcardString = [[NSString alloc] initWithData:(NSData *)vcards encoding:NSUTF8StringEncoding];
并把这个string写入一个文件进行备份。
2.从地址簿中删除当前的联系人:
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文件读入string,并通过vcard中的个人logging进行访问,然后将其作为logging添加到地址簿中,然后保存。
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);
这种方法的一个问题是,我不知道一种方法来维护联系人(交stream,脸谱…)的链接。
这取决于您要备份的联系人的属性。 如果你想备份他们的名字和姓氏,做这样的事情:
//CREATE ARRAYS STORING FIRST NAMES AND LAST NAMES NSMutableArray *firstNames = [[NSMutableArray alloc] init]; NSMutableArray *lastNames = [[NSMutableArray alloc] init]; ABAddressBookRef addressBook = ABAddressBookCreate(); NSArray *arrayOfPeople = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook); CFRelease(addressBook); for(NSUInteger index = 0; index <= ([arrayOfPeople count]-1); index++){ ABRecordRef currentPerson = (__bridge ABRecordRef)[arrayOfPeople objectAtIndex: index]; [firstNames addObject: (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonFirstNameProperty)]; [lastNames addObject: (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonLastNameProperty)]; } //BACKUP THE ARRAYS IN A PLIST NSArray *array=[NSArray arrayWithObjects: firstNames, lastNames, nil]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *location = [[paths objectAtIndex:0] stringByAppendingString:@"/somefilename.plist"]; [array writeToFile:location atomically:YES];
如果您对代码有任何疑问,请在评论中提问。 希望这可以帮助!