I am new in iPhone devlopment. I have an UITextView in a xib. There I displaying an email address link. I want to open iPhone's mail application while clicking on that email link. How can I achieve that?
As pointed out in this answer, you can set the dataDetectorTypes
property of the UITextView
:
textview.editable = NO;
textview.dataDetectorTypes = UIDataDetectorTypeAll;
You should also be able to set the detectorTypes in Interface Builder.
From Apple documentation:
UIDataDetectorTypes
Defines the types of information that can be detected in text-based content. enum { UIDataDetectorTypePhoneNumber = 1 << 0, UIDataDetectorTypeLink = 1 << 1, UIDataDetectorTypeAddress = 1 << 2, UIDataDetectorTypeCalendarEvent = 1 << 3, UIDataDetectorTypeNone = 0, UIDataDetectorTypeAll = NSUIntegerMax }; typedef NSUInteger UIDataDetectorTypes;
Clicking on the email address in your UITextView should then automatically open the Mail application.
On a side note, if you want to send the email from within your app itself, you can use the MFMailComposeViewController.
Note that for the MFMailComposeViewController to be shown, Mail app needs to be installed on the device, and have an account linked to it, otherwise your app will crash.
So you can check this with [MFMailComposeViewController canSendMail]
:
// Check that a mail account is available
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController * emailController = [[MFMailComposeViewController alloc] init];
emailController.mailComposeDelegate = self;
[emailController setSubject:subject];
[emailController setMessageBody:mailBody isHTML:YES];
[emailController setToRecipients:recipients];
[self presentViewController:emailController animated:YES completion:nil];
[emailController release];
}
// Show error if no mail account is active
else {
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"You must have a mail account in order to send an email" delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"OK") otherButtonTitles:nil];
[alertView show];
[alertView release];
}
MFMailComposeViewController Class Reference
In addition to the code above, once the user has pressed the send or cancel buttons you will need to dismiss the modal email view. The MFMailComposeViewControllerDelegate protocol includes a method called "didFinishWithResult". This method will be automatically called as the view closes. However, if you don't implement it, nothing will happen & the modal view will remain, bringing your app to a standstill!
The following code is required as a minimum:
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
// Close the Mail Interface
[self dismissViewControllerAnimated:YES completion:NULL];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With