从AppDelegate调用ViewController的成员函数

Mar*_*s K 1 ios swift

我想叫ViewController"s中的成员函数AppDelegateS" applicationWillResignActive功能.不确定最好的方法是什么.我试过这样做:

let landmark = LandmarkViewController()
landmark.test()
Run Code Online (Sandbox Code Playgroud)

但它似乎不合适.我实际上是在创建控制器的新实例,而不是使用已经存在的实例.

tan*_*one 6

我认为实现所需内容的最佳方法是将此通知的观察者设置UIApplicationWillResignActiveNotification到视图控制器本身.

override func viewDidLoad() {
    super.viewDidLoad()
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appDidResign), name: Notification.Name.UIApplicationWillResignActive, object: nil)
}

func appDidResign() {
    // do your stuff
}

deinit {
    NotificationCenter.default.removeObserver(self) //always remember to remove any observers (you can do this in deinit in this case)
}
Run Code Online (Sandbox Code Playgroud)