I have a strange bug with my delegate being nil and no clue where to check. Maybe someone else had the same issue.
I have this class and protocol:
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()
}
and in my 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
}
}
After the schedule notification is triggered, I’m clicking on it and didReceive
is called and self.delegate?.pushVC()
is somehow nil even though the delegate has been set ( message from didSet
was printed).
Delegate method from extension never triggered since delegate is nil.
I've also printed some messages in deinit
of each class to see if it's somehow deleted from memory but they weren't , only after I've pop them from vc stack.
Add
weak var delegate: NavigationProtocol? {
didSet {
print("was set")
notificationCenter.delegate = self
}
}
OR
localNotification = LocalNotification()
localNotification.delegate = self
localNotification.notificationCenter.delegate = localNotification
localNotification.scheduleNotification(title: "Loan Approval", message: "Congratulations! Your loan has been approved", type: "Loan Approval")