[英]how to call all methods and functions from view controller to app delegate?
Hi am developing a app using swift2 in my app i want to track location for every 5 minutes when user successfully logged in now i can successfully track location of the user now i want to track when the app is in backgrounded for that i have to use app delegate but all functions and methods are i wrote in view controllers only so how can i call view controllers method and function to app delegate. 嗨,我正在我的应用程序中使用swift2开发一个应用程序,我想在用户成功登录后每5分钟跟踪一次位置,现在我可以成功跟踪用户的位置,现在我想跟踪该应用程序何时在后台运行,我必须使用应用程序委托,但所有函数和方法仅在视图控制器中编写,因此如何调用应用程序委托的视图控制器方法和函数。
code in viewController : 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 //////
}
In my appDelegate : 在我的appDelegate中 :
func applicationDidEnterBackground(application: UIApplication) {
if UIApplication.sharedApplication().applicationState != .Active{
//here i have to call that timer function execute how to do that????
}
You can fire notification when app goes to background 您可以在应用程序进入后台时触发通知
func applicationDidEnterBackground(application: UIApplication) {
if UIApplication.sharedApplication().applicationState != .Active{
NSNotificationCenter.defaultCenter().postNotificationName("Notificationname", object: nil)
}
}
in your controller view did load dd observer for notification 在控制器视图中是否加载了dd观察器以进行通知
// add observer for notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.notificationReceived), name: "Notificationname", object: nil)
Method handler for received Notification 收到通知的方法处理程序
func notificationReceived() {
// do what you want to do here.
}
You would want to create a class with your function inside it and then call it from your app delegate, you can do this like this: 您可能想要创建一个包含函数的类,然后从您的应用程序委托中调用它,您可以像这样进行操作:
MyClass.swift
MyClass.swift
class MyClassName { Add your function in here }
Then you call it from appDelegate.swift
like this: 然后从
appDelegate.swift
调用它,如下所示:
let myClassVar: MyClassName?
Then call the function like this -> myClassVar.functionName
然后像这样调用函数->
myClassVar.functionName
Like this, 像这样,
func applicationDidEnterBackground(application: UIApplication) {
if UIApplication.sharedApplication().applicationState != .Active{
let thirdViewController = ThirdViewController()
thirdViewController.functionYouWantToCall()
}
Thanks :) 谢谢 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.