iOS 应用内吊起短信发送功能
2017-12-12 本文已影响216人
灯红酒绿映不出的落寞
产品又提需求啦。要在应用内吊起苹果系统短信功能发送定义好的文本内容。
这样,本篇文章就应运而生了,
虽说苹果代码没有开源出来供大家学习,但是不得不说,人家即使不开源代码,只是系统.h头文件开放出来的函数,基本都能满足我们日常的开发。
就拿短信发送功能来举例
vc中导入系统文件在.m中导入系统文件的方式
@import MessageUI;
导入我们吊起系统短信功能的系统库
看下我们今天的主角MFMessageComposeViewController
image.png判断设备是否可以发送信息
/*!
@method canSendText
@abstract Returns <tt>YES</tt> if the user has set up the device for sending text only messages.
@discussion If the return value is YES, the client can set the recipients and body of the message.
If the return value is NO, the client may notify the user of the failure, or the
client may open an SMS URL via <tt>-[UIApplication openURL:]</tt>.
*/
+ (BOOL)canSendText;
image.png
创建系统短信界面,上图是写好的代码,就这么一点
- (void)sendMessage{
if (![MFMessageComposeViewController canSendText]) {
[self ocrOnFail:@"该设备不支持发送短信功能"];
return;
}
MFMessageComposeViewController *messageViewController = [[MFMessageComposeViewController alloc]init];
messageViewController.messageComposeDelegate =self;
messageViewController.body = @"我是一只大白兔";
[self presentViewController:messageViewController animated:YES completion:nil];
}
设置代理的意义在于我们吊起系统短信之后,往往想知道最后结果。所以,可以看下messageComposeDelegate里边的方法
image.png我仿佛看到了@required,这可是声明代理的时候必须实现的协议,不多说赶紧撸代码
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
NSString *alertMessage = nil;
switch (result) {
case MessageComposeResultCancelled:{
alertMessage = @"取消发送";
break;
}
case MessageComposeResultSent:{
alertMessage = @"发送成功";
break;
}
case MessageComposeResultFailed:{
alertMessage =@"发送失败";
break;
}
}
[controller dismissViewControllerAnimated:YES completion:^{
[self ocrOnFail:alertMessage];
}];
}
短信功能代理回调给我们传递过来了一个枚举值,可以点进去看看
image.png
/*!
@enum MessageComposeResult
@abstract Composition result sent to the delegate upon user completion.
@discussion This result will inform the client of the user's message composition action. If the
user cancels the composition, <tt>MessageComposeResultCancelled</tt> will be sent to the delegate.
Typically <tt>MessageComposeResultSent</tt> will be sent, but <tt>MessageComposeResultFailed</tt> will
be sent in the case of failure. </p>Send may only be interpreted as a successful queueing of
the message for later sending. The actual send will occur when the device is able to send.
@constant MessageComposeResultCancelled User canceled the composition.
@constant MessageComposeResultSent User successfully sent/queued the message.
@constant MessageComposeResultFailed User's attempt to save or send was unsuccessful.
*/
typedef NS_ENUM(NSInteger, MessageComposeResult) {
MessageComposeResultCancelled,
MessageComposeResultSent,
MessageComposeResultFailed
} API_AVAILABLE(ios(4.0));