iOS开发中利用MFMessageComposeViewController发送短信

By | 2012 年 11 月 7 日

从SDK4.0开始,就可以在程序内使用MFMessageComposeViewController来发送短信了(如果设备支持的话)。

废话少说,代码如下:

self.msgCtrl = [[MFMessageComposeViewController alloc] init];
            [self.msgCtrl release];
            if (![MFMessageComposeViewController canSendText]) {
                UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"设备不支持短信发送" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
                [av show];
                [av release];
                return;
            }
            [self.msgCtrl setBody:@"短信内容"];
            [self.msgCtrl setRecipients:[self.selectedContactPhoneDict allKeys]];
!!!:            self.msgCtrl.messageComposeDelegate = self;
            [self presentModalViewController:self.msgCtrl animated:YES];

特别是标注了!!!的这一行,坑爹的delegate名字是messageComposeDelegate,这样才会触发下面的回调:

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    switch (result) {
        case MessageComposeResultCancelled:
            [[TKAlertCenter defaultCenter] postAlertWithMessage:@"已取消短信发送"];
            break;
        case MessageComposeResultSent:
            [[TKAlertCenter defaultCenter] postAlertWithMessage:@"成功发送短信"];
            break;
        case MessageComposeResultFailed:
            [[TKAlertCenter defaultCenter] postAlertWithMessage:@"短信发送失败"];
            break;
        default:
            break;
    }
    [self dismissModalViewControllerAnimated:YES];
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注