开发者

Get a random name and number (same contact) from an iPhone users address book

开发者 https://www.devze.com 2023-01-02 05:18 出处:网络
I have had only very little experience using the address book in the iPhone SDK. Does anyone have a code snippet or knows the code to get a persons name and number Eg \'Fred Smith - 027 292 2112\".

I have had only very little experience using the address book in the iPhone SDK.

Does anyone have a code snippet or knows the code to get a persons name and number Eg 'Fred Smith - 027 292 2112". I haven't had much luck with the stuff I've tried.

I want to achieve this programmatically, and not let the user decide (random pick of the person). I also don't want to display the contact picker either

any tutorial links, or anything would be appreciated.

Thanks in advance

开发者_Go百科

Sam


This code will get a random contact from your address book. And then it will add the first name and the last name, and the first phone number to UILabel properties (first, last and phone).

To make this work, you must first import these header files:

#import <AddressBook/AddressBook.h>
#import <stdlib.h>

stdlib.h is imported to be able to use arc4random.

- (IBAction)randomContact:(id)sender {
    ABAddressBookRef addressBook = ABAddressBookCreate();
    NSArray *people = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);

    // randomize an index
    NSInteger i = [people count];
    i = arc4random() % i;

    // get first and last name
    first.text = (NSString *)ABRecordCopyValue([people objectAtIndex:i], kABPersonFirstNameProperty);
    last.text = (NSString *)ABRecordCopyValue([people objectAtIndex:i], kABPersonLastNameProperty);


    // get first phonenumber
    ABMultiValueRef multi = ABRecordCopyValue([people objectAtIndex:i], kABPersonPhoneProperty);
    phone.text = (NSString*)ABMultiValueCopyValueAtIndex(multi, 0);


    [people release];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消