ios - iOS检测短信发送失败

标签 ios objective-c mfmessagecomposeviewcontroller

在我的应用程序中,了解是否已发送短信非常重要。为了进行检查,我使用了这个委托(delegate)方法:

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

    switch (result) {
        case MessageComposeResultCancelled: {
            [NSThread detachNewThreadSelector:@selector(SMScancelled) toTarget:self withObject:nil];
        }
            break;
        case MessageComposeResultSent: {
            [NSThread detachNewThreadSelector:@selector(SMSsent) toTarget:self withObject:nil];
        }
            break;
        case MessageComposeResultFailed: {
            [NSThread detachNewThreadSelector:@selector(SMSfailed) toTarget:self withObject:nil];
        }
            break;
        default:
            break;
    }

    [self dismissViewControllerAnimated:YES completion:nil];
}

我的问题是,在测试时,我在设置中打开飞行模式(以测试会发生什么),然后我尝试发送短信(使用我的应用程序)。自然,iOS 无法发送它,系统会通知我。在消息应用程序中,也显示我发送失败。但是委托(delegate)方法仍然返回 MessageComposeResultSent 而不是 MessageComposeResultFailed。我在另一部没有SIM卡的手机上测试时也会出现这种情况。

我正在 iOS 7 和 iOS 8 上测试这个。

在文档中,MessageComposeResultSent 表示“用户已成功排队或发送消息”。这意味着,我期望的行为是正确的。

那怎么知道,我的上一条短信是发送成功了,还是发送失败了呢?

最佳答案

您可以使用 MFMessageComposeViewControllercanSendText 方法验证设备是否允许发送文本消息。

发送消息时添加以下代码(此方法检测到您的设备不支持短信)

if(![MFMessageComposeViewController canSendText]) {
    UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Your device doesn't support SMS!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [warningAlert show];
    return;
}

您可以使用 MFMessageComposeViewController 的委托(delegate)方法检查 Message failed

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult) result
{
    switch (result) {
       case MessageComposeResultCancelled:
       break;

       case MessageComposeResultFailed:
       {
            UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to send SMS!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [warningAlert show];
            break;
       }

       case MessageComposeResultSent:
           break;

       default:
           break;
   }

   [self dismissViewControllerAnimated:YES completion:nil];
}

关于ios - iOS检测短信发送失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34894761/

相关文章:

ios - 为 BOOL 指针赋值时出现奇怪的警告问题

iphone - 开发者可以在邮件应用程序中访问未读邮件吗?

ios - 在呈现的 MFMessageComposeViewController 中打开 URL

ios - 介绍 MFMessageComposeViewController/理解 DispatchQueue.main.async

iphone - 如何将音频文件附加到 MFMessage Composer

ios - 在 IOS 中构建一个使用 node.js 服务器的聊天应用程序

ios - 锁定managedObjectContext

调用 openURL 后 iOS 9.3 卡住

ios - 当设备无法检索 SKProduct 价格时显示 IAP 价格

objective-c - Google Drive API - Objective C - 例子?