因为手机要越狱,用91等导出的不是txt格式的文件,所以简单的写了个导出的工具,因为只是自己用,没考虑内存等问题。
在Info.plist中增加下面项,并设为YES,在iTunes中就可以看到生成的文件了。
Application supports iTunes file sharing
导出的代码:
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
-(void)exportAction{
ABAddressBookRef addressBook;
CFErrorRef error = nil;
addressBook = ABAddressBookCreateWithOptions(NULL,&error);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
// callback can occur in background, address book must be accessed on thread it was created on
dispatch_async(dispatch_get_main_queue(), ^{
if(!error && granted){
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = [paths objectAtIndex:0];
NSString *path = [NSString stringWithFormat:@"%@/Contacts.txt",basePath];
CFArrayRef peopleRef = ABAddressBookCopyArrayOfAllPeople(addressBook);
[@"开始" writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:path ];
int i = 0;
NSArray *people = (__bridge_transfer NSArray *)peopleRef;
for (id record in people) {
i += 1;
[myHandle seekToEndOfFile];
[myHandle writeData:[ [NSString stringWithFormat:@"\n\n%d",i] dataUsingEncoding:NSUnicodeStringEncoding]];
ABRecordRef recordRef = (__bridge_retained ABRecordRef)record;
NSString* firstName = (__bridge_transfer NSString *)ABRecordCopyValue(recordRef, kABPersonFirstNameProperty);
[myHandle seekToEndOfFile];
[myHandle writeData:[[NSString stringWithFormat:@"\nfirstName:%@",firstName] dataUsingEncoding:NSUnicodeStringEncoding]];
NSString* lastName = (__bridge_transfer NSString *)ABRecordCopyValue(recordRef, kABPersonLastNameProperty);
[myHandle seekToEndOfFile];
[myHandle writeData:[[NSString stringWithFormat:@"\nlastName:%@",lastName] dataUsingEncoding:NSUnicodeStringEncoding]];
NSLog(@"firstName:%@",firstName);
ABMultiValueRef telefonos =ABRecordCopyValue(recordRef, kABPersonPhoneProperty);
NSString* mobile=@"";
NSString* mobileLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(telefonos); i++) {
mobileLabel = (NSString*)CFBridgingRelease(ABMultiValueCopyLabelAtIndex(telefonos, i));
mobile = ( NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(telefonos, i));
[myHandle seekToEndOfFile];
[myHandle writeData:[[NSString stringWithFormat:@"\n%@:%@",mobileLabel,mobile] dataUsingEncoding:NSUnicodeStringEncoding]];
}
if (telefonos)
{
CFRelease(telefonos);
}
}
CFRelease(addressBook);
}
});
});
}