名、姓、電話番号、電話番号の種類、メールアドレス、メールアドレスの種類などの情報を含む連絡先の詳細を iPhone で取得したい.
誰でもそれで私を助けることができますか?
特定の iPhone の連絡先の詳細から .csv ファイルを作成したいと考えています。iPhoneのアドレス帳データを取得したい。
名、姓、電話番号、電話番号の種類、メールアドレス、メールアドレスの種類などの情報を含む連絡先の詳細を iPhone で取得したい.
誰でもそれで私を助けることができますか?
特定の iPhone の連絡先の詳細から .csv ファイルを作成したいと考えています。iPhoneのアドレス帳データを取得したい。
以下は、iPhoneの連絡帳のすべての情報を取得するコードです...
-(void)collectContacts
{
NSMutableDictionary *myAddressBook = [[NSMutableDictionary alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0;i<ABAddressBookGetPersonCount(addressBook);i++)
{
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
// Get First name, Last name, Prefix, Suffix, Job title
NSString *firstName = (NSString *)ABRecordCopyValue(ref,kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(ref,kABPersonLastNameProperty);
NSString *prefix = (NSString *)ABRecordCopyValue(ref,kABPersonPrefixProperty);
NSString *suffix = (NSString *)ABRecordCopyValue(ref,kABPersonSuffixProperty);
NSString *jobTitle = (NSString *)ABRecordCopyValue(ref,kABPersonJobTitleProperty);
[myAddressBook setObject:firstName forKey:@"firstName"];
[myAddressBook setObject:lastName forKey:@"lastName"];
[myAddressBook setObject:prefix forKey:@"prefix"];
[myAddressBook setObject:suffix forKey:@"suffix"];
[myAddressBook setObject:jobTitle forKey:@"jobTitle"];
NSMutableArray *arPhone = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);
NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel (ABMultiValueCopyLabelAtIndex(phones, j));
NSString *phoneNumber = (NSString *)phoneNumberRef;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
[temp setObject:phoneNumber forKey:@"phoneNumber"];
[temp setObject:phoneLabel forKey:@"phoneNumber"];
[arPhone addObject:temp];
[temp release];
}
[myAddressBook setObject:arPhone forKey:@"Phone"];
[arPhone release];
CFStringRef address;
CFStringRef label;
ABMutableMultiValueRef multi = ABRecordCopyValue(ref, kABPersonAddressProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
CFStringRef readableLabel = ABAddressBookCopyLocalizedLabel(label);
address = ABMultiValueCopyValueAtIndex(multi, i);
CFRelease(address);
CFRelease(label);
}
ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
NSMutableArray *arEmail = [[NSMutableArray alloc] init];
for(CFIndex idx = 0; idx < ABMultiValueGetCount(emails); idx++)
{
CFStringRef emailRef = ABMultiValueCopyValueAtIndex(emails, idx);
NSString *strLbl = (NSString*) ABAddressBookCopyLocalizedLabel (ABMultiValueCopyLabelAtIndex (emails, idx));
NSString *strEmail_old = (NSString*)emailRef;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
[temp setObject:strEmail_old forKey:@"strEmail_old"];
[temp setObject:strLbl forKey:@"strLbl"];
[arEmail addObject:temp];
[temp release];
}
[myAddressBook setObject:arEmail forKey:@"Email"];
[arEmail release];
}
[self createCSV:myAddressBook];
}
-(void) createCSV :(NSMutableDictionary*)arAddressData
{
NSMutableString *stringToWrite = [[NSMutableString alloc] init];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[arAddressData valueForKey:@"firstName"]]];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[arAddressData valueForKey:@"lastName"]]];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[arAddressData valueForKey:@"jobTitle"]]];
//[stringToWrite appendString:@"fname, lname, title, company, phonetype1, value1,phonetype2,value,phonetype3,value3phonetype4,value4,phonetype5,value5,phonetype6,value6,phonetype7,value7,phonetype8,value8,phonetype9,value9,phonetype10,value10,email1type,email1value,email2type,email2value,email3type,email3value,email4type,email4value,email5type,email5value,website1,website2,website3"];
NSMutableArray *arPhone = (NSMutableArray*) [arAddressData valueForKey:@"Phone"];
for(int i = 0 ;i<[arPhone count];i++)
{
NSMutableDictionary *temp = (NSMutableDictionary*) [arPhone objectAtIndex:i];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[temp valueForKey:@"phoneNumber"]]];
[stringToWrite appendString:[NSString stringWithFormat:@"%@,",[temp valueForKey:@"phoneNumber"]]];
[temp release];
}
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *strBackupFileLocation = [NSString stringWithFormat:@"%@/%@", documentDirectory,@"ContactList.csv"];
[stringToWrite writeToFile:strBackupFileLocation atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
上記の iApple のコードを出発点として使用し、そこから機能するバージョンを作成しました。これは、アドレス帳のすべてのエントリを配列に収集するだけです。前述のように、オリジナルの iApple は動作しません。いくつかのバグがあります。これは動作し、テスト済みです。
注:これは、名前が設定されていない連絡先を返しません-独自のコードでそれを削除できます。名前が設定された連絡先のみが必要であり、NSMutableDictionaryはnilエントリが好きではないため、それを行いました(クラッシュ)。
私のアドレス帳には、単なる電子メールのエントリがいくつかあります。どうやってそこにたどり着いたのかはわかりませんが、アドレス帳に名前のないエントリが存在する可能性は確かにあります。アドレス帳を反復処理するときは、このことに注意してください。
私は Apple の推奨に従って氏名を使用しています。ABRecordCopyCompositeName は、ユーザーが指定した順序で名と姓の合成を返します。
最後に、これを静的メソッドにして、ヘルパー クラスに配置しました。
これはARCで使用するためのものです!
// returns an array of dictionaries
// each dictionary has values: fullName, phoneNumbers, emails
// fullName is a string
// phoneNumbers is an array of strings
// emails is an array of strings
+ (NSArray *)collectAddressBookContacts {
NSMutableArray *allContacts = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0;i<ABAddressBookGetPersonCount(addressBook);i++)
{
NSMutableDictionary *aPersonDict = [[NSMutableDictionary alloc] init];
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
NSString *fullName = (__bridge NSString *) ABRecordCopyCompositeName(ref);
if (fullName) {
[aPersonDict setObject:fullName forKey:@"fullName"];
// collect phone numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) {
NSString *phoneNumber = (__bridge NSString *) ABMultiValueCopyValueAtIndex(phones, j);
[phoneNumbers addObject:phoneNumber];
}
[aPersonDict setObject:phoneNumbers forKey:@"phoneNumbers"];
// collect emails - key "emails" will contain an array of email addresses
ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
NSMutableArray *emailAddresses = [[NSMutableArray alloc] init];
for(CFIndex idx = 0; idx < ABMultiValueGetCount(emails); idx++) {
NSString *email = (__bridge NSString *)ABMultiValueCopyValueAtIndex(emails, idx);
[emailAddresses addObject:email];
}
[aPersonDict setObject:emailAddresses forKey:@"emails"];
// if you want to collect any other info that's stored in the address book, it follows the same pattern.
// you just need the right kABPerson.... property.
[allContacts addObject:aPersonDict];
} else {
// Note: I have a few entries in my phone that don't have a name set
// Example one could have just an email address in their address book.
}
}
return allContacts;
}
まず、アドレス帳フレームワークを使用する必要があるため、これを Xcode プロジェクトに追加する必要があります。
次に、タスクをいくつかのステップに分割する必要があります。
1) アドレス帳の中の人を取得する
2) .csv ファイルを作成します。文字を使用してフィールドを区切るCSVファイルのフォーマットと、適切にフォーマットされたファイルを作成するためにいつ改行文字を追加するかについて、あなたが何か知っていると仮定しています。これについて助けが必要な場合、これはおそらく別の質問スレッドに残されています。
3) .csv ファイルをどこかに保存します
1) アドレス帳にあるすべての人の配列を取得するには、次のようにします。ABAddressBook のリファレンス ドキュメントはこちらです。データへのアクセスを支援するのに非常に役立つはずです。
ABAddressBook *sharedBook = [ABAddressBook sharedAddressBook];
NSArray *peopleList = [sharedBook people];
2) 各人を繰り返し処理し、全体的な csv データを作成する必要があります。通常、NSString で csv データを手動で作成し、それを NSData に変換して、NSData をファイルに保存します。これは、非常に大きなデータ セットを扱う場合には理想的ではありません。この場合、いくつかのコードで csv データをファイルにチャンクで書き込み、メモリを解放できるようにする必要があります。簡単にするために、私のコードでは、完全なファイルを作成してから作業全体を保存することを示しています。
NSString *csvString = @"";
for(ABPerson *aPerson in peopleList) {
//Do something here to write each property you want to the CSV file.
csvString = [csvString stringByAppendingFormat:@"'%@',"
[aPerson valueForProperty:kABFirstNameProperty]];
}
NSData *csvData = [csvString dataUsingEncoding:NSUTF8StringEncoding];
3) ファイルをどこかに書き込む
//This is an example of writing your csv data to a file that will be saved in the application's sand box directory.
//This file could be extracted using iTunes file sharing.
//Get the proper path to save the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"my_file.csv"];
//Actually write the data
BOOL isSuccessful = [csvData writeToFile:fullPath atomically:NO];
if(isSuccessful) {
//Do something if the file was written
} else {
//Do something if there was an error writing the file
}
アドレス帳 APIの詳細については、個人およびグループ レコードのインポートとエクスポートを参照してください。
このブログの Address Book Test の例も参照してください