如何从视图控制器调用所有方法和功能到应用程序委托?
您好,我正在开发一个应用程序,在我的应用程序中使用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)
}
}
在控制器中您可以触发通知争夺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.
}
你想创建一个类里面你的函数,然后从您的应用程序委托调用它,你可以做像这样:
- 用你的类的名字创建一个swift文件例如
MyClass.swift
- 然后你创建文件中的类,并在其中添加功能:
class MyClassName { Add your function in here }
-
然后你从
appDelegate.swift
这样称呼它:let myClassVar: MyClassName?
然后调用像这样的功能 - >
myClassVar.functionName
我已经创建了swift文件并为互联网连接执行了一些其他功能......是否有可能将编码添加到同一个文件 – antonyraja
是的,如果你希望你可以在你之外的文件中创建一个类在它下面查看控制器类。然而,这不是一个好的做法,但它会解决您遇到的问题。 – RyanM
是否有其他方法 – antonyraja
这样,
func applicationDidEnterBackground(application: UIApplication) {
if UIApplication.sharedApplication().applicationState != .Active{
let thirdViewController = ThirdViewController()
thirdViewController.functionYouWantToCall()
}
谢谢:)
我没有使用过类似通知什么....如何使用?什么是 “notificationname” 你只要你的编码,你解释一下...抱歉@sahil – antonyraja
从这里阅读https://www.andrewcbancroft.com/2014/10/08/fundamentals-of-nsnotificationcenter-in-swift/ – Sahil
你有没有试过这个? – Sahil