ios 如何以编程方式在 iPhone 上发送短信?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically send SMS on the iPhone?
提问by
Does anybody know if it's possible, and how, to programmatically send a SMSfrom the iPhone
, with the official SDK / Cocoa Touch?
有人知道是否有可能,以及如何使用官方 SDK/Cocoa Touch以编程方式从发送短信iPhone
?
回答by Adam Davis
Restrictions
限制
If you could send an SMS within a program on the iPhone, you'll be able to write games that spam people in the background. I'm sure you really want to have spams from your friends, "Try out this new game! It roxxers my boxxers, and yours will be too! roxxersboxxers.com!!!! If you sign up now you'll get 3,200 RB points!!"
如果您可以在 iPhone 上的程序中发送短信,您就可以编写在后台向人们发送垃圾邮件的游戏。我相信你真的很想收到来自你朋友的垃圾邮件,“试试这个新游戏!它让我的拳击手们乐此不疲,你的也会如此!roxxersboxxers.com!!!!如果你现在注册,你将获得 3,200 RB积分!!”
Apple has restrictions for automated (or even partially automated) SMS and dialing operations. (Imagine if the game instead dialed 911 at a particular time of day)
Apple 对自动(甚至部分自动)短信和拨号操作有限制。(想象一下,如果游戏在一天中的特定时间拨打 911)
Your best bet is to set up an intermediate server on the internet that uses an online SMS sending service and send the SMS via that route if you need complete automation. (ie, your program on the iPhone sends a UDP packet to your server, which sends the real SMS)
最好的办法是在互联网上设置一个使用在线短信发送服务的中间服务器,如果需要完全自动化,则通过该路由发送短信。(即,您在 iPhone 上的程序向您的服务器发送一个 UDP 数据包,该数据包会发送真正的短信)
iOS 4 Update
iOS 4 更新
iOS 4, however, now provides a viewController
you can import into your application. You prepopulate the SMS fields, then the user can initiate the SMS send within the controller. Unlike using the "SMS:..." url format, this allows your application to stay open, and allows you to populate both the toand the bodyfields. You can even specify multiple recipients.
但是,iOS 4 现在提供了一个viewController
可以导入到应用程序中的方法。您预先填充 SMS 字段,然后用户可以在控制器内启动 SMS 发送。与使用“SMS:...” url 格式不同,这允许您的应用程序保持打开状态,并允许您填充to和body字段。您甚至可以指定多个收件人。
This prevents applications from sending automated SMS without the user explicitly aware of it. You still cannot send fully automated SMS from the iPhone itself, it requires some user interaction. But this at least allows you to populate everything, and avoids closing the application.
这可以防止应用程序在用户没有明确意识到的情况下发送自动 SMS。您仍然无法从 iPhone 本身发送全自动短信,它需要一些用户交互。但这至少允许您填充所有内容,并避免关闭应用程序。
The MFMessageComposeViewControllerclass is well documented, and tutorialsshow how easy it is to implement.
该MFMessageComposeViewController类是有据可查的,和教程显示它是多么容易实现。
iOS 5 Update
iOS 5 更新
iOS 5 includes messaging for iPod touch and iPad devices, so while I've not yet tested this myself, it may be that all iOS devices will be able to send SMS via MFMessageComposeViewController. If this is the case, then Apple is running an SMS server that sends messages on behalf of devices that don't have a cellular modem.
iOS 5 包括 iPod touch 和 iPad 设备的消息传递,所以虽然我自己还没有测试过,但可能所有 iOS 设备都可以通过 MFMessageComposeViewController 发送 SMS。如果是这种情况,则 Apple 正在运行 SMS 服务器,该服务器代表没有蜂窝调制解调器的设备发送消息。
iOS 6 Update
iOS 6 更新
No changes to this class.
这个类没有变化。
iOS 7 Update
iOS 7 更新
You can now check to see if the message medium you are using will accept a subject or attachments, and what kind of attachments it will accept. You can edit the subject and add attachments to the message, where the medium allows it.
您现在可以检查您正在使用的消息媒体是否会接受一个主题或附件,以及它将接受什么样的附件。您可以在媒体允许的情况下编辑主题并向邮件添加附件。
iOS 8 Update
iOS 8 更新
No changes to this class.
这个类没有变化。
iOS 9 Update
iOS 9 更新
No changes to this class.
这个类没有变化。
iOS 10 Update
iOS 10 更新
No changes to this class.
这个类没有变化。
iOS 11 Update
iOS 11 更新
No significant changes to this class
Limitations to this class
此类限制
Keep in mind that this won't work on phones without iOS 4, and it won't work on the iPod touch or the iPad, except, perhaps, under iOS 5. You must either detect the device and iOS limitations prior to using this controller, or risk restricting your app to recently upgraded 3G, 3GS, and 4 iPhones.
请记住,这不适用于没有 iOS 4 的手机,也不适用于 iPod touch 或 iPad,除非在 iOS 5 下。您必须在使用此之前检测设备和 iOS 限制控制器,或将您的应用程序限制为最近升级的 3G、3GS 和 4 部 iPhone 的风险。
However, an intermediate server that sends SMS will allow any and all of these iOS devices to send SMS as long as they have internet access, so it may still be a better solution for many applications. Alternately, use both, and only fall back to an online SMS service when the device doesn't support it.
然而,发送短信的中间服务器将允许任何和所有这些 iOS 设备发送短信,只要它们可以访问互联网,因此它可能仍然是许多应用程序的更好解决方案。或者,两者都使用,并且仅在设备不支持时才回退到在线 SMS 服务。
回答by Daniel Amitay
Here is a tutorial which does exactly what you are looking for: the MFMessageComposeViewController
.
这是一个教程,它完全符合您的要求:MFMessageComposeViewController
.
http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/
http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/
Essentially:
本质上:
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = @"SMS message here";
controller.recipients = [NSArray arrayWithObjects:@"1(234)567-8910", nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
And a link to the docs.
以及指向文档的链接。
https://developer.apple.com/documentation/messageui/mfmessagecomposeviewcontroller
https://developer.apple.com/documentation/messageui/mfmessagecomposeviewcontroller
回答by Najeebullah Shah
- You must add the MessageUI.framework to your Xcode project
- Include an
#import <MessageUI/MessageUI.h>
in your header file - Add these delegates to your header file
MFMessageComposeViewControllerDelegate
&UINavigationControllerDelegate
- In your
IBAction
method declare instance ofMFMessageComposeViewController
saymessageInstance
- To check whether your device can send text use
[MFMessageComposeViewController canSendText]
in an if condition, it'll return Yes/No In the
if
condition do these:First set body for your
messageInstance
as:messageInstance.body = @"Hello from Shah";
Then decide the recipients for the message as:
messageInstance.recipients = [NSArray arrayWithObjects:@"12345678", @"87654321", nil];
Set a delegate to your messageInstance as:
messageInstance.messageComposeDelegate = self;
In the last line do this:
[self presentModalViewController:messageInstance animated:YES];
- 您必须将 MessageUI.framework 添加到您的 Xcode 项目中
#import <MessageUI/MessageUI.h>
在头文件中包含一个- 将这些委托添加到您的头文件中
MFMessageComposeViewControllerDelegate
&UINavigationControllerDelegate
- 在你的
IBAction
方法中声明MFMessageComposeViewController
say 的实例messageInstance
- 要检查您的设备是否可以
[MFMessageComposeViewController canSendText]
在 if 条件下发送文本使用,它将返回 Yes/No 在
if
条件下做这些:首先为您设置 body 为
messageInstance
:messageInstance.body = @"Hello from Shah";
然后将消息的收件人确定为:
messageInstance.recipients = [NSArray arrayWithObjects:@"12345678", @"87654321", nil];
将您的 messageInstance 的委托设置为:
messageInstance.messageComposeDelegate = self;
在最后一行执行以下操作:
[self presentModalViewController:messageInstance animated:YES];
回答by millenomi
You can use a sms:[target phone number]
URL to open the SMS application, but there are no indications on how to prefill a SMS body with text.
您可以使用sms:[target phone number]
URL 打开 SMS 应用程序,但没有关于如何用文本预填充 SMS 正文的指示。
回答by isox
One of the systems of inter-process communication in MacOS is XPC. This system layer has been developed for inter-process communication based on the transfer of plist structures using libSystem and launchd. In fact, it is an interface that allows managing processes via the exchange of such structures as dictionaries. Due to heredity, iOS 5 possesses this mechanism as well.
MacOS 中进程间通信的系统之一是 XPC。该系统层已开发用于基于使用 libSystem 和 launchd 传输 plist 结构的进程间通信。事实上,它是一个允许通过交换诸如字典之类的结构来管理进程的接口。由于遗传,iOS 5 也具有这种机制。
You might already understand what I mean by this introduction. Yep, there are system services in iOS that include tools for XPC communication. And I want to exemplify the work with a daemon for SMS sending. However, it should be mentioned that this ability is fixed in iOS 6, but is relevant for iOS 5.0—5.1.1. Jailbreak, Private Framework, and other illegal tools are not required for its exploitation. Only the set of header files from the directory /usr/include/xpc/* are needed.
你可能已经明白我说的这个介绍的意思。是的,iOS 中有系统服务,其中包括用于 XPC 通信的工具。我想用一个用于 SMS 发送的守护进程来举例说明这项工作。但是,应该提到的是,此功能在 iOS 6 中是固定的,但与 iOS 5.0—5.1.1 相关。其利用不需要越狱、私有框架和其他非法工具。只需要目录 /usr/include/xpc/* 中的头文件集。
One of the elements for SMS sending in iOS is the system service com.apple.chatkit, the tasks of which include generation, management, and sending of short text messages. For the ease of control, it has the publicly available communication port com.apple.chatkit.clientcomposeserver.xpc. Using the XPC subsystem, you can generate and send messages without user's approval.?
iOS 发送短信的要素之一是系统服务 com.apple.chatkit,其任务包括生成、管理和发送短文本消息。为了便于控制,它具有公开可用的通信端口com.apple.chatkit.clientcomposeserver.xpc。使用 XPC 子系统,您可以生成和发送消息而无需用户批准。
Well, let's try to create a connection.
好吧,让我们尝试创建一个连接。
xpc_connection_t myConnection;
dispatch_queue_t queue = dispatch_queue_create("com.apple.chatkit.clientcomposeserver.xpc", DISPATCH_QUEUE_CONCURRENT);
myConnection = xpc_connection_create_mach_service("com.apple.chatkit.clientcomposeserver.xpc", queue, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);
Now we have the XPC connection myConnection set to the service of SMS sending. However, XPC configuration provides for creation of suspended connections —we need to take one more step for the activation.
现在我们将 XPC 连接 myConnection 设置为 SMS 发送服务。但是,XPC 配置提供了创建挂起连接的功能——我们需要再执行一个激活步骤。
xpc_connection_set_event_handler(myConnection, ^(xpc_object_t event){
xpc_type_t xtype = xpc_get_type(event);
if(XPC_TYPE_ERROR == xtype)
{
NSLog(@"XPC sandbox connection error: %s\n", xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
}
// Always set an event handler. More on this later.
NSLog(@"Received a message event!");
});
xpc_connection_resume(myConnection);
The connection is activated. Right at this moment iOS 6 will display a message in the telephone log that this type of communication is forbidden. Now we need to generate a dictionary similar to xpc_dictionary with the data required for the message sending.
连接已激活。就在此时,iOS 6 将在电话日志中显示禁止此类通信的消息。现在我们需要生成一个类似于 xpc_dictionary 的字典,其中包含消息发送所需的数据。
NSArray *recipient = [NSArray arrayWithObjects:@"+7 (90*) 000-00-00", nil];
NSData *ser_rec = [NSPropertyListSerialization dataWithPropertyList:recipient format:200 options:0 error:NULL];
xpc_object_t mydict = xpc_dictionary_create(0, 0, 0);
xpc_dictionary_set_int64(mydict, "message-type", 0);
xpc_dictionary_set_data(mydict, "recipients", [ser_rec bytes], [ser_rec length]);
xpc_dictionary_set_string(mydict, "text", "hello from your application!");
Little is left: send the message to the XPC port and make sure it is delivered.
剩下的很少:将消息发送到 XPC 端口并确保它被传递。
xpc_connection_send_message(myConnection, mydict);
xpc_connection_send_barrier(myConnection, ^{
NSLog(@"The message has been successfully delivered");
});
That's all. SMS sent.
就这样。短信已发送。
回答by Bharat Gulati
Add the MessageUI.Framework and use the following code
添加 MessageUI.Framework 并使用以下代码
#import <MessageUI/MessageUI.h>
And then:
进而:
if ([MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController *messageComposer =
[[MFMessageComposeViewController alloc] init];
NSString *message = @"Your Message here";
[messageComposer setBody:message];
messageComposer.messageComposeDelegate = self;
[self presentViewController:messageComposer animated:YES completion:nil];
}
and the delegate method -
和委托方法 -
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
didFinishWithResult:(MessageComposeResult)result {
[self dismissViewControllerAnimated:YES completion:nil];
}
回答by Dinesh Reddy Chennuru
You can use this approach:
您可以使用这种方法:
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms:MobileNumber"]]
iOS will automatically navigate from your app to the messages app's message composing page. Since the URL's scheme starts with sms:, this is identified as a type that is recognized by the messages app and launches it.
iOS 会自动从您的应用导航到消息应用的消息撰写页面。由于 URL 的方案以 sms: 开头,这被标识为消息应用程序识别并启动它的类型。
回答by Tunvir Rahman Tusher
Follow this procedures
遵循此程序
1 .Add MessageUI.Framework
to project
1.添加MessageUI.Framework
到项目
2 . Import #import <MessageUI/MessageUI.h>
in .h file.
2 . 导入#import <MessageUI/MessageUI.h>
.h 文件。
3 . Copy this code for sending message
3 . 复制此代码以发送消息
if ([MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController *messageComposer =
[[MFMessageComposeViewController alloc] init];
NSString *message = @"Message!!!";
[messageComposer setBody:message];
messageComposer.messageComposeDelegate = self;
[self presentViewController:messageComposer animated:YES completion:nil];
}
4 . Implement delegate
method if you want to.
4 . delegate
如果你想实现方法。
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
///your stuff here
[self dismissViewControllerAnimated:YES completion:nil];
}
Run And GO!
奔跑吧!
回答by Rushabh
//Add the Framework in .h file
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
//Set the delegate methods
UIViewController<UINavigationControllerDelegate,MFMessageComposeViewControllerDelegate>
//add the below code in .m file
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
MFMessageComposeViewController *controller =
[[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
NSString *str= @"Hello";
controller.body = str;
controller.recipients = [NSArray arrayWithObjects:
@"", nil];
controller.delegate = self;
[self presentModalViewController:controller animated:YES];
}
}
- (void)messageComposeViewController:
(MFMessageComposeViewController *)controller
didFinishWithResult:(MessageComposeResult)result
{
switch (result)
{
case MessageComposeResultCancelled:
NSLog(@"Cancelled");
break;
case MessageComposeResultFailed:
NSLog(@"Failed");
break;
case MessageComposeResultSent:
break;
default:
break;
}
[self dismissModalViewControllerAnimated:YES];
}
回答by grandagile
Here is the Swift version of code to send SMS in iOS. Please noted that it only works in real devices. Code tested in iOS 7+. You can read more here.
这是在 iOS 中发送短信的 Swift 版本代码。请注意,它仅适用于真实设备。在 iOS 7+ 中测试的代码。您可以在此处阅读更多内容。
1) Create a new Class which inherits MFMessageComposeViewControllerDelegate and NSObject:
1) 创建一个继承 MFMessageComposeViewControllerDelegate 和 NSObject 的新类:
import Foundation
import MessageUI
class MessageComposer: NSObject, MFMessageComposeViewControllerDelegate {
// A wrapper function to indicate whether or not a text message can be sent from the user's device
func canSendText() -> Bool {
return MFMessageComposeViewController.canSendText()
}
// Configures and returns a MFMessageComposeViewController instance
func configuredMessageComposeViewController(textMessageRecipients:[String] ,textBody body:String) -> MFMessageComposeViewController {
let messageComposeVC = MFMessageComposeViewController()
messageComposeVC.messageComposeDelegate = self // Make sure to set this property to self, so that the controller can be dismissed!
messageComposeVC.recipients = textMessageRecipients
messageComposeVC.body = body
return messageComposeVC
}
// MFMessageComposeViewControllerDelegate callback - dismisses the view controller when the user is finished with it
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
2) How to use this class:
2)如何使用这个类:
func openMessageComposerHelper(sender:AnyObject ,withIndexPath indexPath: NSIndexPath) {
var recipients = [String]()
//modify your recipients here
if (messageComposer.canSendText()) {
println("can send text")
// Obtain a configured MFMessageComposeViewController
let body = Utility.createInvitationMessageText()
let messageComposeVC = messageComposer.configuredMessageComposeViewController(recipients, textBody: body)
// Present the configured MFMessageComposeViewController instance
// Note that the dismissal of the VC will be handled by the messageComposer instance,
// since it implements the appropriate delegate call-back
presentViewController(messageComposeVC, animated: true, completion: nil)
} else {
// Let the user know if his/her device isn't able to send text messages
self.displayAlerViewWithTitle("Cannot Send Text Message", andMessage: "Your device is not able to send text messages.")
}
}