我正在尝试实现一个类,该类将呈现来自 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()
}
一开始一切正常——消息 View Controller 出现并且响应没有错误,但是每当按下发送或取消按钮时,消息 View Controller 不会关闭,屏幕变得无响应,委托(delegate) 未调用,我得到一个BAD_ACCESS
错误。
如果我将 MFMessageComposeViewControllerDelegate
放入 AppDelegate 并设置 messageVC。 messageVC.messageComposeDelegate = UIApplication.sharedApplication().delegate as! MFMessageComposeViewControllerDelegate
,然后一切正常, Controller 按预期关闭。
为什么 MFMessageComposeViewControllerDelegate
在 MyClass 对象中时未被调用?感谢阅读和帮助!
最佳答案
它正在崩溃,因为您的 handler
对象在调用 handler.sendMessage()
之后立即被释放和释放,然后现在尝试委托(delegate)回调 -当您尝试发送或点击取消时释放对象。该对象正在被释放和释放,因为在 application:didReceiveRemoteNotification:
结束时没有任何东西再持有对它的强引用。
由于您是在您的应用程序委托(delegate)中创建此对象,我建议您在您的应用程序委托(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()
}
关于ios - MFMessageComposeViewControllerDelegate 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30971574/