2016-11-11 52 views
0

您好,我正在開發一個應用程序,在我的應用程序中使用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???? 

} 

回答

0

當應用程序被切換到後臺

func applicationDidEnterBackground(application: UIApplication) { 

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

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

在控制器中您可以觸發通知爭奪w ^做負載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. 
} 
+0

我沒有使用過類似通知什麼....如何使用?什麼是 「notificationname」 你只要你的編碼,你解釋一下...抱歉@sahil – antonyraja

+0

從這裏閱讀https://www.andrewcbancroft.com/2014/10/08/fundamentals-of-nsnotificationcenter-in-swift/ – Sahil

+0

你有沒有試過這個? – Sahil

0

你想創建一個類裏面你的函數,然後從您的應用程序委託調用它,你可以做像這樣:

  • 用你的類的名字創建一個swift文件例如MyClass.swift
  • 然後你創建文件中的類,並在其中添加功能:

class MyClassName { Add your function in here }

  • 然後你從appDelegate.swift這樣稱呼它:

    let myClassVar: MyClassName?

  • 然後調用像這樣的功能 - >myClassVar.functionName

+0

我已經創建了swift文件併爲互聯網連接執行了一些其他功能......是否有可能將編碼添加到同一個文件 – antonyraja

+0

是的,如果你希望你可以在你之外的文件中創建一個類在它下面查看控制器類。然而,這不是一個好的做法,但它會解決您遇到的問題。 – RyanM

+0

是否有其他方法 – antonyraja

0

這樣,

func applicationDidEnterBackground(application: UIApplication) { 

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

謝謝:)

+0

我會嘗試這一個 – antonyraja

+0

不幫忙的人....感謝您的回覆 – antonyraja

+0

問題又是什麼? –

相關問題