538

有人知道使用官方 SDK / Cocoa Touch 以编程方式发送 SMS 是否可行,以及如何iPhone

4

18 回答 18

414

限制

如果您可以在 iPhone 上的程序中发送 SMS,您将能够编写在后台向人们发送垃圾邮件的游戏。我敢肯定你真的很想收到朋友的垃圾邮件,“试试这个新游戏!它让我的 boxxers 感到兴奋,你的也会如此!roxxersboxxers.com!!!!如果你现在注册,你将获得 3,200 RB积分!!”

Apple 对自动化(甚至部分自动化)短信和拨号操作有限制。(想象一下,如果游戏在一天中的特定时间拨打 911)

您最好的选择是在 Internet 上设置使用在线 SMS 发送服务的中间服务器,如果您需要完全自动化,则通过该路线发送 SMS。(即,您在 iPhone 上的程序向您的服务器发送一个 UDP 数据包,该服务器发送真正的 SMS)

iOS 4 更新

然而,iOS 4 现在提供了一个viewController可以导入到应用程序中的功能。您预填充 SMS 字段,然后用户可以在控制器内启动 SMS 发送。与使用“SMS:...” url 格式不同,这允许您的应用程序保持打开状态,并允许您填充tobody字段。您甚至可以指定多个收件人。

这可以防止应用程序在用户没有明确意识到的情况下发送自动 SMS。您仍然无法从 iPhone 本身发送全自动短信,它需要一些用户交互。但这至少允许您填充所有内容,并避免关闭应用程序。

MFMessageComposeViewController类有很好的文档,并且教程显示了它是多么容易实现。

iOS 5 更新

iOS 5 包括用于 iPod touch 和 iPad 设备的消息传递,所以虽然我自己还没有对此进行测试,但可能所有 iOS 设备都能够通过 MFMessageComposeViewController 发送 SMS。如果是这种情况,那么 Apple 正在运行一个 SMS 服务器,它代表没有蜂窝调制解调器的设备发送消息。

iOS 6 更新

这个类没有变化。

iOS 7 更新

您现在可以检查您正在使用的消息媒体是否会接受主题或附件,以及它将接受什么样的附件。您可以在媒体允许的情况下编辑主题并向邮件添加附件。

iOS 8 更新

这个类没有变化。

iOS 9 更新

这个类没有变化。

iOS 10 更新

这个类没有变化。

iOS 11 更新

对此类没有重大变化

这个类的限制

请记住,这在没有 iOS 4 的手机上不起作用,在 iPod touch 或 iPad 上也不起作用,可能在 iOS 5 下除外。在使用它之前,您必须检测设备和 iOS 限制控制器,或冒险将您的应用程序限制为最近升级的 3G、3GS 和 4 iPhone。

但是,发送 SMS 的中间服务器将允许任何和所有这些 iOS 设备发送 SMS,只要它们可以访问 Internet,因此对于许多应用程序来说,它可能仍然是一个更好的解决方案。或者,两者都使用,并且仅在设备不支持时才回退到在线 SMS 服务。

于 2008-09-12T15:00:54.210 回答
146

这是一个教程,它完全符合您的要求:MFMessageComposeViewController.

http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/

本质上:

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];
}

以及文档的链接。

https://developer.apple.com/documentation/messageui/mfmessagecomposeviewcontroller

于 2010-07-24T19:09:07.580 回答
100
  1. 您必须将 MessageUI.framework 添加到您的 Xcode 项目中
  2. #import <MessageUI/MessageUI.h>在头文件中包含一个
  3. 将这些委托添加到您的头文件MFMessageComposeViewControllerDelegate &UINavigationControllerDelegate
  4. 在您的方法中声明say的IBAction实例MFMessageComposeViewControllermessageInstance
  5. 要检查您的设备是否可以在 if 条件下发送文本使用[MFMessageComposeViewController canSendText],它将返回 Yes/No
  6. 在这种if情况下,请执行以下操作:

    1. 首先为您设置身体messageInstance

      messageInstance.body = @"Hello from Shah";
      
    2. 然后将消息的收件人确定为:

      messageInstance.recipients = [NSArray arrayWithObjects:@"12345678", @"87654321",         nil];
      
    3. 将您的 messageInstance 的委托设置为:

      messageInstance.messageComposeDelegate = self;
      
    4. 在最后一行执行以下操作:

      [self presentModalViewController:messageInstance animated:YES];
      
于 2011-12-07T16:50:58.800 回答
50

您可以使用sms:[target phone number]URL 打开 SMS 应用程序,但没有说明如何使用文本预填充 SMS 正文。

于 2008-09-12T14:41:55.753 回答
25

MacOS 中的进程间通信系统之一是 XPC。该系统层已开发用于基于使用 libSystem 和 launchd 传输 plist 结构的进程间通信。事实上,它是一个允许通过交换诸如字典之类的结构来管理进程的接口。由于遗传,iOS 5 也拥有这种机制。

你可能已经明白我所说的这个介绍的意思了。是的,iOS 中有包含 XPC 通信工具的系统服务。我想用一个用于 SMS 发送的守护进程来举例说明这项工作。不过需要说明的是,这个能力在 iOS 6 中是固定的,但与 iOS 5.0—5.1.1 相关。越狱、私有框架和其他非法工具都不需要它的利用。只需要目录 /usr/include/xpc/* 中的一组头文件。

iOS 中短信发送的要素之一是系统服务 com.apple.chatkit,其任务包括生成、管理和发送短信。为了便于控制,它具有公开可用的通信端口 com.apple.chatkit.clientcomposeserver.xpc。使用 XPC 子系统,您可以在未经用户批准的情况下生成和发送消息。</p>

好吧,让我们尝试创建一个连接。

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);

现在我们将 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);

连接已激活。就在此时,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!");

所剩无几:将消息发送到 XPC 端口并确保它已送达。

xpc_connection_send_message(myConnection, mydict);
xpc_connection_send_barrier(myConnection, ^{
NSLog(@"The message has been successfully delivered");
});

就这样。短信发送。

于 2012-10-25T07:17:31.843 回答
24

添加 MessageUI.Framework 并使用以下代码

#import <MessageUI/MessageUI.h> 

接着:

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];
}

和委托方法 -

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
             didFinishWithResult:(MessageComposeResult)result {
      [self dismissViewControllerAnimated:YES completion:nil];
 }
于 2013-05-10T21:38:08.053 回答
21

您可以使用这种方法:

[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms:MobileNumber"]]


iOS 会自动从您的应用导航到消息应用的消息撰写页面。由于 URL 的方案以 sms: 开头,因此这被标识为消息应用程序识别并启动它的类型。

于 2014-02-26T07:13:20.487 回答
14

遵循此程序

1.MessageUI.Framework添加到项目在此处输入图像描述

2. 导入#import <MessageUI/MessageUI.h>.h 文件。

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. delegate如果您愿意,请实施方法。

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{


   ///your stuff here 

    [self dismissViewControllerAnimated:YES completion:nil];
}

奔跑吧!

于 2014-07-29T10:32:29.250 回答
12
//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]; 
}
于 2012-08-27T12:33:43.430 回答
6

这是在 iOS 中发送 SMS 的 Swift 版本代码。请注意,它仅适用于真实设备。在 iOS 7+ 中测试的代码。你可以在这里阅读更多。

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)如何使用这个类:

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.")
    }
}
于 2015-05-23T07:40:59.003 回答
3

iOS 4 中有一个类支持从您的应用程序发送带有正文和recipents 的消息。它的工作原理与发送邮件相同。您可以在此处找到文档:链接文本

于 2010-09-10T08:32:07.300 回答
3

//使用名称和号码调用方法。

-(void)openMessageViewWithName:(NSString*)contactName withPhone:(NSString *)phone{

CTTelephonyNetworkInfo *networkInfo=[[CTTelephonyNetworkInfo alloc]init];

CTCarrier *carrier=networkInfo.subscriberCellularProvider;

NSString *Countrycode = carrier.isoCountryCode;

if ([Countrycode length]>0)     //Check If Sim Inserted
{

    [self sendSMS:msg recipientList:[NSMutableArray arrayWithObject:phone]];
}
else
{

    [AlertHelper showAlert:@"Message" withMessage:@"No sim card inserted"];
}

}

//发送消息的方法

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSMutableArray *)recipients{  
 MFMessageComposeViewController *controller1 = [[MFMessageComposeViewController alloc] init] ;
 controller1 = [[MFMessageComposeViewController alloc] init] ;
 if([MFMessageComposeViewController canSendText])
{
    controller1.body = bodyOfMessage;
    controller1.recipients = recipients;
    controller1.messageComposeDelegate = self;
    [self presentViewController:controller1 animated:YES completion:Nil];
 }
}
于 2015-03-10T12:48:03.400 回答
3
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    UIImage *ui =resultimg.image;
    pasteboard.image = ui;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:"]];
}
于 2013-09-09T11:17:09.503 回答
2

如果需要,可以使用CoreTelephony称为CTMessageCenter类的私有框架。有几种发送短信的方法。

于 2010-01-29T02:15:13.963 回答
1
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms:number"]] 

这将是最好和最简单的方法。

于 2014-08-04T12:36:30.317 回答
1

用这个:

- (void)showSMSPicker
{
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));

    if (messageClass != nil) {          
        // Check whether the current device is configured for sending SMS messages
        if ([messageClass canSendText]) {
           [self displaySMSComposerSheet];
        }   
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{       
    //feedbackMsg.hidden = NO;
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MessageComposeResultCancelled:
        {   
            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"SMS sending canceled!!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert1 show];
            [alert1 release];
        }   

        // feedbackMsg.text = @"Result: SMS sending canceled";
        break;

        case MessageComposeResultSent:
        {
            UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"SMS sent!!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert2 show];
            [alert2 release];
        }   

        // feedbackMsg.text = @"Result: SMS sent";
        break;

        case MessageComposeResultFailed:
        {   
            UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"SMS sending failed!!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert3 show];
            [alert3 release];
        }   

        // feedbackMsg.text = @"Result: SMS sending failed";
        break;

        default:
        {   
            UIAlertView *alert4 = [[UIAlertView alloc] initWithTitle:@"Message" message:@"SMS not sent!!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert4 show];
            [alert4 release];
        }   

        // feedbackMsg.text = @"Result: SMS not sent";
        break;
    }

    [self dismissModalViewControllerAnimated: YES];
}
于 2012-05-18T05:47:57.230 回答
1

You can present MFMessageComposeViewController, which can send SMS, but with user prompt(he taps send button). No way to do that without user permission. On iOS 11, you can make extension, that can be like filter for incoming messages , telling iOS either its spam or not. Nothing more with SMS cannot be done

于 2017-11-26T01:33:14.047 回答
0

如果您想在自己的应用程序中显示创建和发送消息,则需要使用MFMessageComposeViewController 。

否则,您可以使用sharedApplication方法。

于 2015-03-30T06:31:19.730 回答