|
I've been sticking pretty closely to this tutorial so far, but I finally decided I felt intrepid enough to try extending the application a bit.
Specifically, I wanted to be able to select a row or rows from the address book, click a button, and open an email with the right recipient(s) in the To: field. Turns out it isn't too hard, once I found out how to open a URL. Here's how I did it, feel free to add to or comment on this approach.
In Interface Builder: Create an action in the Controller class called sendMail. Then add a button wherever you like and connect it to the controller, using the sendMail message as the target for the button. I added a "Send Email" button to the right of the "Delete" button in the main application window.
Once you have that connected up, add the line
- (IBAction)sendMail:(id)sender;
to your Controller.h file, and add the following code to the implementation in Controller.m:
- (IBAction)sendEmail:(id)sender
{
NSMutableString *url = [NSMutableString stringWithString:@"mailto:"];
NSString *str;
NSEnumerator *enumerator;
NSNumber *index;
enumerator = [tableView selectedRowEnumerator];
if((index = [enumerator nextObject])) {
str = [[records objectAtIndex:[index intValue]] objectForKey:@"Email"];
[url appendString:str];
while ( (index = [enumerator nextObject]) ) {
str = [[records objectAtIndex:[index intValue]] objectForKey:@"Email"];
[url appendString:@","];
[url appendString:str];
}
}
[[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString:url]];
}
Note that if you're familiar with the mailto: URL format standard, you can make the new message open with a starting subject, body, and various other headers, using the query syntax. Try out "mailto:somebody@company.com?subject=MyApp&body=Hello" and find out more info about the mailto: URL options at
http://www.faqs.org/rfcs/rfc2368.html
Note that you have to encode any characters that aren't allowed in URLs - particularly blank spaces (%20) and such. I'm sure there are Cocoa methods to encode and decode URL strings, I just haven't found them yet.
Good Luck!
-schmeldog
|
// For sending mail
- (IBAction) sendMail: (id) sender
{
NSMutableString *url = [NSMutableString stringWithString: @"mailto:"];
NSString *str;
NSEnumerator *enumerator;
NSNumber *index;
// Check if there is a selected row
if ([tableView numberOfSelectedRows] == 0)
{
return;
}
// Enumerate all selected rows
enumerator = [tableView selectedRowEnumerator];
// Traverse the selected rows with enumerator
while ( ( index = [enumerator nextObject] ) )
{
// Retrieve the email field
str = [[records objectAtIndex: [index intValue]]
objectForKey: @"Email"];
// Add a comma to separate email addresses if this is not the first one
if (![url isEqualToString: @"mailto:"])
{
[url appendString: @","];
}
// Add the email address to the previously built string
[url appendString: str];
}