代码之家  ›  专栏  ›  技术社区  ›  Marco

如何在iPhone上以编程方式发送短信?

  •  504
  • Marco  · 技术社区  · 17 年前

    有人知道是否有可能,以及如何通过编程发送 短讯服务 iPhone ,使用官方的SDK/Cocoa Touch?

    18 回复  |  直到 9 年前
        1
  •  406
  •   Cœur Gustavo Armenta    5 年前

    限制

    如果你能在iPhone上的程序中发送短信息,你就可以在后台编写发送垃圾邮件的游戏。我肯定你真的很想收到你朋友的垃圾邮件,“试试这个新游戏吧!它是我的盒子,你的也是!roxxersboxers.com网站!!!! 如果你现在报名,你将得到3200个篮板积分!!”

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

    你最好的办法是在互联网上建立一个中间服务器,使用在线短信发送服务,如果你需要完全自动化的话,就通过这个路由发送短信。(也就是说,你在iPhone上的程序会向你的服务器发送UDP包,服务器会发送真正的短信)

    viewController 您可以导入到应用程序中。预先填充SMS字段,然后用户可以在控制器内启动SMS发送。不像使用“短讯服务:。。。“url格式,这允许您的应用程序保持打开状态,并允许您填充 以及 身体

    MFMessageComposeViewController 类有很好的文档记录,并且 tutorials 展示它是多么容易实现。

    iOS5包括iPod touch和iPad设备的消息传递,所以虽然我还没有亲自测试过,但可能所有iOS设备都可以通过MFMessageComposeViewController发送短信。如果是这样,那么苹果正在运行一个SMS服务器,它代表没有蜂窝调制解调器的设备发送消息。

    iOS 6更新

    此类没有更改。

    现在,您可以检查正在使用的消息媒体是否接受一个或多个主题,以及它将接受哪种类型的附件。您可以编辑主题并在媒体允许的情况下向邮件添加附件。

    iOS 8更新

    此类没有更改。

    iOS 9更新

    iOS 10更新

    此类没有更改。

    iOS 11更新

    No significant changes to this class

    此类的限制

        2
  •  143
  •   Cœur Gustavo Armenta    8 年前

    下面是一个教程,它完全符合您的需要: 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

        3
  •  99
  •   Alex Zavatone    10 年前
    1. 包括 #import <MessageUI/MessageUI.h> 在头文件中
    2. MFMessageComposeViewControllerDelegate &安培; UINavigationControllerDelegate
    3. 在你的 IBAction MFMessageComposeViewController messageInstance
    4. 检查您的设备是否可以发送文本使用 [MFMessageComposeViewController canSendText] 在if条件下,它将返回Yes/No
    5. if 条件如下:

      1. 消息实例 作为:

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

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

        [self presentModalViewController:messageInstance animated:YES];
        
        4
  •  50
  •   Cœur Gustavo Armenta    6 年前

    你可以使用 sms:[target phone number] 打开SMS应用程序的URL,但没有指示如何用文本预先填充SMS正文。

        5
  •  25
  •   Alex Zavatone    10 年前

    你可能已经明白我的介绍是什么意思了。是的,iOS中有一些系统服务包括用于XPC通信的工具。我想举例说明用守护进程发送短信的工作。不过,需要指出的是,该功能在iOS 6中是固定的,但与iOS 5.05.1.1相关。越狱、私有框架和其他非法工具不需要对其进行利用。只需要目录/usr/include/xpc/*中的一组头文件。

    好吧,让我们试着建立一种联系。

    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_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");
    });
    

        6
  •  23
  •   Alex Zavatone    10 年前

    添加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];
     }
    
        7
  •  21
  •   Alex Zavatone    10 年前

    您可以使用以下方法:

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


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

        8
  •  12
  •   Rushabh    13 年前
    //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]; 
    }
    
        9
  •  12
  •   Tunvir Rahman Tusher    10 年前

    遵循以下步骤

    MessageUI.Framework 到项目 enter image description here

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

    三。复制此代码以发送消息

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

    快跑吧!

        10
  •  5
  •   thomasdao    10 年前

    以下是在iOS中发送短信的Swift版本代码。请注意,它只适用于实际设备。在iOS7+中测试的代码。你可以读更多 here

    1) 创建继承MFMessageComposeViewController和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.")
        }
    }
    
        11
  •  3
  •   logancautrell    13 年前

    iOS4中有一个类支持从应用程序发送带有body和recipient的消息。它的工作原理与发送邮件相同。您可以在此处找到文档: link text

        12
  •  3
  •   mandeep    12 年前
    - (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
    {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        UIImage *ui =resultimg.image;
        pasteboard.image = ui;
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:"]];
    }
    
        13
  •  3
  •   ALOK KUMAR    10 年前

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

    -(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];
     }
    }
    
        14
  •  2
  •   Paras Joshi    12 年前

    如果需要,可以使用私有框架 CoreTelephony 哪个打电话来的 CTMessageCenter 班级。有几种发送短信的方法。

        15
  •  1
  •   Rock    13 年前

    使用这个:

    - (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];
    }
    
        16
  •  1
  •   brasofilo Gary    11 年前
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms:number"]] 
    

        17
  •  1
  •   Максуд Даудов    7 年前

    您可以显示MFMessageComposeViewController,它可以发送短信,但有用户提示(他点击send按钮)。没有用户许可是不可能的。在ios11上,你可以做一个扩展,就像过滤收到的信息一样,告诉iOS是否有垃圾邮件。没有更多的短信不能做

        18
  •  0
  •   Alex Zavatone    10 年前

    你需要使用 MFMessageComposeView控制器 如果你想显示在你自己的应用中创建和发送消息。

    否则,您可以使用 共享应用程序