How do I launch the Mac Address Book from my app and select a specific person?
I have an app and I am reading in the address book information using the ABAddressBook APIs and selecting a person. I would like to provide a link from my app to launch the Mac address book and pre-select a specific user.
I'm sure there are several ways to do it - I came up with one that seems to work but it feels a little clunky. I launch the "Address Book.ap开发者_运维百科p", if successful it calls a bit of AppleScript to select the "currentPerson" uniqueId (from the ABRecord object).
- (void) notifyABSelect
{
NSString *src = [NSString stringWithFormat:@"tell application \"Address Book\"\r\n\tset selection to first person whose id is \"%@\" \r\nend tell", [currentPerson uniqueId]];
NSMutableDictionary *err = [NSMutableDictionary dictionary];
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:src];
[script executeAndReturnError:&err];
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
[src release];
[err release];
[script release];
}
- (IBAction) launchAddressBook:(id)sender
{
[[[NSWorkspace sharedWorkspace] notificationCenter]
addObserver:self
selector:@selector(notifyABSelect)
name:NSWorkspaceDidLaunchApplicationNotification
object:nil];
if ([[NSWorkspace sharedWorkspace] launchApplication:@"Address Book.app"] == YES)
{
[self notifyABSelect];
}
else
{
NSLog(@"Unable to launch address book");
}
}
Where this falls down is if the Address Book had previously had a group other than "All Contacts" selected; it may or may not be able to find the person based on whether or not they are in the selected group. However, clicking the link a second time in the app does correctly go to "All Contacts" and find the person.
What are alternatives to accomplishing this behavior?
You can use a URL instead.
[[NSWorkspace sharedWorkspace] openURL:
[NSURL URLWithString:
[NSString stringWithFormat:
@"addressbook://%@", [currentPerson uniqueId]]]];
May be not relevant for you, but worth pointing out because I only came across it by chance. If you have got your person from an ABPeoplePicker it's a one-liner. With the person selected in the PeoplePicker, call
[myPeoplePicker selectInAddressBook: self];
You can use nil
instead of self
.
Address Book launches on that person's page.
You can also use editInAddressBook:
to launch Address Book with the person ready to be edited.
Seems to me this should be a method of ABPerson, not ABPeoplePicker.
精彩评论