2015-06-22 101 views
1

我想实现一个类,它将从AppDelegate中提供一个MFMessageComposeViewController。类的声明看起来是这样的:MFMessageComposeViewControllerDelegate没有被调用

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对象中时不会被调用?感谢您的阅读和帮助!

回答

2

它崩溃了,因为您的handler对象在handler.sendMessage()的调用之后立即被释放并释放,然后尝试发送或点击取消时尝试在该即时释放对象上进行委托回调。该对象正在被释放和释放,因为在application:didReceiveRemoteNotification:的结尾没有任何内容被强制引用。

因为要创建在您的应用程序委托这个对象,我建议让您的应用程序委托财产守住这个对象:

var handler: MyClass? 

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

是非常合情合理的,和它的工作就像一个魅力!谢谢 – gmh