簡體   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