【问题标题】:How to call method in ViewController from viewmodel in swift 5?如何在 swift 5 中从 viewmodel 调用 ViewController 中的方法?
【发布时间】:2020-06-02 07:56:30
【问题描述】:

我在 iOS 项目中使用 MVVM 设计模式。我正在尝试从 viewmodel 调用 viewcontroller 中的方法。

import Foundation

class NotificationViewModel {

    var onCompletion: ((_ success: Bool) -> ())?

    func saveNotification(notification: Dictionary<String, Any>) {
        print("notification save")
        //other logic
        onCompletion?(true)
    }
   }

收到通知时从appdelegate调用“saveNotification”方法

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        guard
            let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSMutableDictionary
            else {
                // handle any error here
                return
            }   

        NotificationViewModel().saveNotification(notification: alert as! Dictionary<String, Any>)
        }

在“saveNotification”触发时尝试调用视图控制器中的方法

     class AlertViewController: BaseViewController{


            var viewModel = NotificationViewModel()

            override func viewDidLoad() {
                super.viewDidLoad()

                self.viewModel.onCompletion = { success in
                    // this should be executed when `saveNotification()` will be called
// **** this is never getting called ******
                    print("calling from viewmodel")
                    methodToCall()
                }
            }

          func methodToCall(){
            //logic
          }
      }

但是 viewdidload 中的方法不会随时被调用。

请建议是否可能或任何其他方式来实现这一目标? 感谢您的帮助

【问题讨论】:

    标签: ios swift mvvm


    【解决方案1】:

    这是因为您在NotificationViewModel 的新实例上调用saveNotification 方法,而该实例的onCompletion 未设置,因此不会在AlertViewController 中调用methodToCall 方法。

    【讨论】:

    • 感谢您的帮助和澄清。有什么办法可以让我达到效果吗?
    • 这里的问题是为什么它不起作用,从技术上讲,我的工作已经完成。但是,仅仅因为您问过您可能想对 Notification 和 Observers 进行一些研究,以实现您可能正在寻找的东西。
    • 确定...谢谢指导
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    相关资源
    最近更新 更多