MFMessageComposeViewControllerDelegate未被调用

时间:2015-06-22 03:02:53

标签: ios swift

我正在尝试实现一个将从AppDelegate呈现MFMessageComposeViewController的类。类声明如下所示:

import UIKit
import MessageUI

class MyClass: NSObject, MFMessageComposeViewControllerDelegate {

    func sendAMessage() {
        // message view controller
        let messageVC = MFMessageComposeViewController()
        messageVC.body = "Oh hai!"
        messageVC.recipients = ["8675309"]
        // set the delegate
        messageVC.messageComposeDelegate = self
        // present the message view controller
        UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(messageVC, animated: true, completion: nil)
    }

    // delegate implementation
    func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
        switch result.value {
        case MessageComposeResultCancelled.value:
            controller.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
        case MessageComposeResultFailed.value:
            controller.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
        case MessageComposeResultSent.value:
            controller.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
        default:
            break
        }
    }
}

在我的AppDelegate中,我在收到如下推送通知后创建并调用MyClass的实例:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // instance of class
    let handler = MyClass()
    // call method
    handler.sendAMessage()
}

一切正常 - 消息视图控制器出现并且响应没有错误,但每当按下发送或取消按钮时,消息视图控制器不会消失,屏幕变得无响应,代表,我收到BAD_ACCESS错误。

如果我将MFMessageComposeViewControllerDelegate放在AppDelegate中并设置messageVC. messageVC.messageComposeDelegate = UIApplication.sharedApplication().delegate as! MFMessageComposeViewControllerDelegate,那么一切正常,控制器会按预期解除。

为什么MFMessageComposeViewControllerDelegate在MyClass对象中不被调用?感谢阅读和帮助!

1 个答案:

答案 0 :(得分:2)

它崩溃了,因为你的handler对象在调用handler.sendMessage()之后就被释放并释放了,然后当你尝试对那个现已解除分配的对象进行委托回调发送或点击取消。该对象正在被释放和释放,因为在application:didReceiveRemoteNotification:结尾处没有任何内容可以强烈引用它。

由于您是在app delegate中创建此对象,我建议您在app delegate中创建一个属性以保留此对象:

var handler: MyClass?

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // instance of class
    handler = MyClass()
    // call method
    handler?.sendAMessage()
}