提问者:小点点

自定义协议委托为零


我有一个奇怪的错误,我的代表是零,也不知道在哪里检查。也许其他人也有同样的问题。

我有这个类和协议:

protocol NavigationProtocol: class {
    func pushVC()
}

class LocalNotification: NSObject, UNUserNotificationCenterDelegate {

    let notificationCenter = UNUserNotificationCenter.current()
    weak var delegate: NavigationProtocol? {
        didSet {
            print("was set")
        }
    }
.........

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        
        self.delegate?.pushVC()
        completionHandler()
    }

在我的VC里

class FinalDecisionViewController: UIViewController {

    var localNotification: LocalNotification!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNotification()
    }
    
    private func setupNotification() {
        localNotification = LocalNotification()
        localNotification.delegate = self
        localNotification.scheduleNotification(title: "Loan Approval", message: "Congratulations! Your loan has been approved", type: "Loan Approval")
    }


extension FinalDecisionViewController: NavigationProtocol {
    func pushVC() {
        canMoveToNextVC = true
    }
}
    

触发计划通知后,我单击它,调用DidReceive并且self.delegate?.pushvc()不知为何为零,即使已设置委托(打印了来自DidSet的消息)。

扩展中的委托方法从未触发,因为委托为nil。

我还在每个类的deinit中打印了一些消息,以查看它是否以某种方式从内存中删除了,但它们没有,只是在我从vc堆栈中弹出它们之后。


共1个答案

匿名用户

添加

weak var delegate: NavigationProtocol? {
    didSet {
        print("was set")
        notificationCenter.delegate = self
    }
}

localNotification = LocalNotification()
localNotification.delegate = self
localNotification.notificationCenter.delegate = localNotification
localNotification.scheduleNotification(title: "Loan Approval", message: "Congratulations! Your loan has been approved", type: "Loan Approval")