繁体   English   中英

如何调用从视图控制器到应用程序委托的所有方法和函数?

[英]how to call all methods and functions from view controller to app delegate?

嗨,我正在我的应用程序中使用swift2开发一个应用程序,我想在用户成功登录后每5分钟跟踪一次位置,现在我可以成功跟踪用户的位置,现在我想跟踪该应用程序何时在后台运行,我必须使用应用程序委托,但所有函数和方法仅在视图控制器中编写,因此如何调用应用程序委托的视图控制器方法和函数。

viewController中的代码:

class ThirdViewController: UIViewController{

In view did load:

 {

  //////   i created timer scheduled with time internal  /////

 }

 //////   Here am fetched current locations and performed some function for timer to execute   //////

 }

在我的appDelegate中

func applicationDidEnterBackground(application: UIApplication) {

 if UIApplication.sharedApplication().applicationState != .Active{

 //here i have to call that timer function execute how to do that????

}

您可以在应用程序进入后台时触发通知

func applicationDidEnterBackground(application: UIApplication) {

 if UIApplication.sharedApplication().applicationState != .Active{

  NSNotificationCenter.defaultCenter().postNotificationName("Notificationname", object: nil)
}
}

在控制器视图中是否加载了dd观察器以进行通知

// add observer for notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.notificationReceived), name: "Notificationname", object: nil)

收到通知的方法处理程序

func notificationReceived() {
// do what you want to do here.
}

您可能想要创建一个包含函数的类,然后从您的应用程序委托中调用它,您可以像这样进行操作:

  • 用您的班级名称创建一个swift文件,例如MyClass.swift
  • 然后,在文件中创建类并在其中添加函数:

class MyClassName { Add your function in here }

  • 然后从appDelegate.swift调用它,如下所示:

    let myClassVar: MyClassName?

  • 然后像这样调用函数-> myClassVar.functionName

像这样,

func applicationDidEnterBackground(application: UIApplication) {

    if UIApplication.sharedApplication().applicationState != .Active{
      let thirdViewController = ThirdViewController()
      thirdViewController.functionYouWantToCall()
 }

谢谢 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM