IOS study notes 28-system services (I) text messages and emails

Source: Internet
Author: User

IOS study notes 28-system services (I) text messages and emails
I. System Application

When developing some applications, we may want to call the built-in phone, SMS, email, and browser applications of iOS, or directly call the installed third-party applications. How can we achieve this?

Here, we use an object method of UIApplication for implementation:
// Open different system applications-(void) openUrl :( NSURL *) url;

How can I tell whether I want to call or send text messages?
Before we learned about the network, was the URL used at the beginning?http://To use a local file.file://This is the URL protocol. We control the URL protocol to open different applications.

Some System Application URL protocols are listed below: tel://And tel:: Call without prompt telprompt://And telprompt:: Call. A prompt is displayed before the call. sms://And sms:: Text message mailto://And mailto:: Send email http://And http:: Open a browserThe following is an example: 1. Call is prompted.
// Call-(void) telpromptTest {// telephone number NSString * phoneNumber = @ "18500138888"; // 1. create the call URL path. In this way, the user is prompted to confirm whether to call NSString * urlStr = [NSString stringWithFormat: @ "telprompt: // % @", phoneNumber]; // 2. generate url nsurl * url = [NSURL URLWithString: urlStr]; // 3. open the system application UIApplication * application = [UIApplication sharedApplication]; [application openURL: url];}
2. send text messages
// Send a text message-(void) sendMessageTest {// phone number NSString * phoneNumber = @ "18500138888"; // 1. create a text message URL path NSString * urlStr = [NSString stringWithFormat: @ "sms: // % @", phoneNumber]; // 2. generate url nsurl * url = [NSURL URLWithString: urlStr]; // 3. open the system application UIApplication * application = [UIApplication sharedApplication]; [application openURL: url];}
3. Send an email
// Send mail-(void) sendEmailTest {NSString * mailAddress = @ "850192964@qq.com"; // 1. create the mail URL path NSString * urlStr = [NSString stringWithFormat: @ "mailto: // % @", mailAddress]; // 2. generate url nsurl * url = [NSURL URLWithString: urlStr]; // 3. open the system application UIApplication * application = [UIApplication sharedApplication]; [application openURL: url];}
4. Open the browser
// Browse the webpage-(void) browserTest {// 1. create open browser URL path NSString * urlStr = @ "http://www.baidu.com"; // 2. generate url nsurl * url = [NSURL URLWithString: urlStr]; // 3. open the system application UIApplication * application = [UIApplication sharedApplication]; [application openURL: url];}

The system application is opened above. In factopenUrlThis function can be enabled for any application installed by the system. For example, if you have developed application A and the application has been installed on your machine, in addition, in application B, A can be opened directly.openUrlImplementation, but some configuration is required.

Step for configuring A third-party application: Modify info.plistFile, add URL typesUnder this node, configure the specific Protocol URL SchemasAnd Unique id of application URL identifierSuch:
In application A's AppDelegateFile Processing AppDelegateA proxy method
/* It is called when it is opened by another application through a URL. Here, parameters can be received and parsed to return whether it can be opened by another application */-(BOOL) application :( UIApplication *) application // openURL of the current application :( NSURL *) url // URL sourceApplication used by other applications :( NSString *) sourceApplication // annotation (id) annotation {NSLog (@ "url: % @", url); NSLog (@ "source: % @", sourceApplication ); NSLog (@ "params: % @", [url host]); return YES; // whether to open}
After configuring application A, we can use it in application B. openUrlApplication A is opened.
// Open a third-party application-(void) thirdPartyApplicationTest {// use the third-party application protocol NSString * urlStr = @ "cmj: // myparams"; NSURL * url = [NSURL URLWithString: urlStr]; // determines whether the application can open UIApplication * application = [UIApplication sharedApplication]; if (! [Application canOpenURL: url]) {NSLog (@ "cannot open \" % @ \ ", please ensure that this application has been correctly installed. ", url); return;} [application openURL: url];}
Ii. system services

Calling built-in applications of the system to send text messages and emails is quite simple, but such operations also have some drawbacks:

After you click send SMS (or email), the system's SMS (or email) application is started directly. Our application is in a suspended status, after sending (SMS or email), you cannot return to the application interface automatically.

If you want to complete these operations within the application, you can useMessageUI.frameworkIt provides the UI interface for text messages and emails to be called by developers within the application.

MessageUI.frameworkA ready-made text message and email editing interface is provided. Developers only need to set the corresponding parameters for the text message and email controller through programming.

1. SMS

InMessageUI.frameworkUsed inMFMessageComposeViewControllerSend SMS

Follow these steps: Import MessageUI.frameworkAnd add the header file.
#import 
  
Create MFMessageComposeViewControllerSet the recipient, information body, and other content attributes of the object, and set the proxy messageComposeDelegateThe View Controller processing proxy method is displayed in the mode to obtain the sending status:
/* Call the message after the message is sent, whether it is successful or not */-(void) messageComposeViewController :( MFMessageComposeViewController *) controller didFinishWithResult :( MessageComposeResult) result;/* Send result */
The following is an example:
# Import "KCSendMessageViewController. h" # import
  
   
@ Interface KCSendMessageViewController ()
   
    
@ Property (weak, nonatomic) IBOutlet UITextField * receivers; // recipient text box @ property (weak, nonatomic) IBOutlet UITextField * body; // information text box @ property (weak, nonatomic) IBOutlet UITextField * subject; // subject text box @ property (weak, nonatomic) IBOutlet UITextField * attachments; // attachment text box @ end @ implementation KCSendMessageViewController # pragma mark-controller view method-(void) viewDidLoad {[super viewDidLoad];} # pragma mark-UI event-(I BAction) sendMessageClick :( UIButton *) sender {// if the text information cannot be sent, if (! [MFMessageComposeViewController canSendText]) {return;} // create the SMS sending View Controller MFMessageComposeViewController * messageController = [[MFMessageComposeViewController alloc] init]; // set the recipient messageController. recipients = [self. receivers. text componentsSeparatedByString: @ ","]; // sets the message body messageController. body = self. body. text; // set proxy. Note that messageComposeDelegate messageController is not delegate. messageComposeDelegate = self; // determines whether the topic is supported. if ([MFMessageComposeViewController canSendSubject]) {// sets the topic messageController. subject = self. subject. text;} // determine whether attachments are supported if ([MFMessageComposeViewController canSendAttachments]) {// Add attachments. Be sure to specify the suffix of the attachment file, otherwise, the NSArray * attachments = [self. attachments. text componentsSeparatedByString: @ ","]; if (attachments. count> 0) {for (NSString * attachment in attachments) {NSString * path = [[NSBundle mainBundle] pathForResource: attachment ofType: nil]; NSURL * url = [NSURL fileURLWithPath: path]; // Add an attachment. You need to set the attachment URL and the attachment identifier [messageController addAttachmentURL: url withAlternateFilename: attachment] ;}}} // In the modal pop-up interface [self presentViewController: messageController animated: YES completion: nil] ;}# pragma mark-MFMessageComposeViewController proxy method/* sent completely, whether it succeeds or not */-(void) messageComposeViewController :( MFMessageComposeViewController *) controller didFinishWithResult :( MessageComposeResult) result {switch (result) {case when: NSLog (@ "sent successfully. "); break; case MessageComposeResultCancelled: NSLog (@" cancel sending. "); break; default: NSLog (@" failed to send. "); break;} // The displayed interface [self dismissViewControllerAnimated: YES completion: nil];} @ end
   
  

2. Email

InMessageUI.frameworkUsed inMFMailComposeViewControllerTo send an email

Usage steps [similar to text message]: Import MessageUI.frameworkAnd add the header file.
#import 
  
Create MFMailComposeViewControllerSet the recipient, CC, body, and other attributes of the object, and set the proxy mailComposeDelegateThe View Controller processing proxy method is displayed in the mode to obtain the sending status:
/* The message will be called after sending is complete, regardless of whether the message is sent successfully */-(void) mailComposeController :( MFMailComposeViewController *) controller didFinishWithResult :( MFMailComposeResult) result/* Sending result */error :( nser; /* error message */
The following is an example:
# Import "KCSendEmailViewController. h" # import
  
   
@ Interface KCSendEmailViewController ()
   
    
@ Property (weak, nonatomic) IBOutlet UITextField * toTecipients; // recipient text box @ property (weak, nonatomic) IBOutlet UITextField * ccRecipients; // CC text box @ property (weak, nonatomic) IBOutlet UITextField * bccRecipients; // BCC text box @ property (weak, nonatomic) IBOutlet UITextField * subject; // subject text box @ property (weak, nonatomic) IBOutlet UITextField * body; // text box @ property (weak, nonatomic) IBOutlet UITextField * attachments; // attachment text box @ end @ implementation KCSendEmailViewController-(void) viewDidLoad {[super viewDidLoad];} # pragma mark-UI event-(IBAction) sendEmailClick :( UIButton *) sender {// determine whether the current email can be sent if ([MFMailComposeViewController canSendMail]) {return ;} // create the send mail View Controller MFMailComposeViewController * mailController = [[MFMailComposeViewController alloc] init]; // set the proxy. Note that this is not delegate, but mailComposeDelegate mailController. mailComposeDelegate = self; // set the recipient NSArray * recipients = [self. toTecipients. text componentsSeparatedByString: @ ","]; [mailController setToRecipients: recipients]; // sets the CC if (self. ccRecipients. text. length> 0) {NSArray * ccRecipients = [self. ccRecipients. text componentsSeparatedByString: @ ","]; [mailController setCcRecipients: ccRecipients];} // sets the BCC if (self. bccRecipients. text. length> 0) {NSArray * bccRecipients = [self. bccRecipients. text componentsSeparatedByString: @ ","]; [mailController setBccRecipients: bccRecipients];} // set the topic [mailController setSubject: self. subject. text]; // set the subject content [mailController setMessageBody: self. body. text isHTML: YES]; // Add the attachment if (self. attachments. text. length> 0) {NSArray * attachments = [self. attachments. text componentsSeparatedByString: @ ","]; for (NSString * attachment in attachments) {NSString * file = [[NSBundle mainBundle] pathForResource: attachment ofType: nil]; NSData * data = [NSData dataWithContentsOfFile: file]; // The first parameter is the attachment data, and the second parameter is the mimeType type. The jpgimage corresponds to image/jpeg [mailController addAttachmentData: data mimeType: @ "image/jpeg" fileName: attachment];} // The view [self presentViewController: mailController animated: YES completion: nil] is displayed.} # The pragma mark-MFMailComposeViewController proxy method/* is called after the message is sent. Whether the message is sent successfully or not */-(void) mailComposeController :( MFMailComposeViewController *) controller didFinishWithResult :( warn) result error *) error {switch (result) {case MFMailComposeResultSent: NSLog (@ "sent successfully. "); break; case MFMailComposeResultSaved: // when you click Cancel, the system prompts whether the file is saved as a draft. After saving the file, you can find NSLog in the draft box of the system email application (@" the email has been saved. "); break; case MFMailComposeResultCancelled: NSLog (@" cancel sending. "); break; default: NSLog (@" failed to send. "); break;} if (error) {NSLog (@" An error occurred while sending the email. error message: % @ ", error. localizedDescription);} [self dismissViewControllerAnimated: YES completion: nil];} @ end
   
  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.