简体   繁体   English

如何从AppDelegate中的ViewController调用函数?

[英]How does one call a function from ViewController in AppDelegate?

I am making an app that uses iBeacon. 我正在制作一个使用iBeacon的应用程序。 When the iBeacon is detected (inside AppDelegate), the app detects the phone's coordinates and forwards them to an API. 当检测到iBeacon时(在AppDelegate内部),该应用程序将检测手机的坐标并将其转发给API。

I have a function called runGPS() set up in ViewController which does the above and am trying to get it to execute when the iBeacon is detected. 我在ViewController中设置了一个名为runGPS()的函数,该函数可以执行上述操作,并试图在检测到iBeacon时使其执行。

When I do ViewController().runGPS(), I get an error: Missing parameter for 'coder' in call 当我执行ViewController()。runGPS()时,出现错误:调用中缺少“编码器”的参数

I've looked up this issue and keep going around in circles on resolving it. 我已经查找了此问题,并一直在圈中解决此问题。 One correction leads to another error etc. etc. etc. 一种纠正会导致另一种错误等,等等。

How does one correct this or is my overall strategy for this wrong? 如何纠正这个错误?或者我的总体策略是错误的?

func locationManager(manager: CLLocationManager,
    didEnterRegion region: CLRegion) {
        manager.startRangingBeaconsInRegion(region as! CLBeaconRegion)
        manager.startUpdatingLocation()

        NSLog("You entered the region")

        ViewController(NSCoder)!.runGPS()

}

I have also implemented iBeacon in my application. 我还在我的应用程序中实现了iBeacon。 You have to add this location manager delegate in that viewcontroller and set delegate there like 您必须在该viewcontroller中添加此位置管理器委托,并在其中设置委托,例如

locationManager.delegate = self
locationManager.requestAlwaysAuthorization()

and you can check in viewController if any user enter to your beacon region then this delegate method will run 并且您可以在viewController中检查是否有任何用户输入到您的信标区域,然后将运行此委托方法

 func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {

    }

you can check your beacon in beacons array received in parameter. 您可以在参数中收到的信数组中检查信

You should separate out the runGPS() code from the ViewController class if its not meant to be there. 如果不打算将runGPS()代码从ViewController类中分离出来,则应将其分开。 Is it using any of the ViewController's functionality? 它使用ViewController的任何功能吗? If not then you should move it to a separate class meant for passing data to API. 如果不是,则应将其移至用于将数据传递到API的单独的类。 If you cannot do that then you can declare runGPS as a static method and called ViewController.runGPS() provided you are not using any of the properties of the ViewController in runGPS() method 如果您不能这样做,则可以将runGPS声明为静态方法,并称为ViewController.runGPS()前提是您未在runGPS()方法中使用ViewController任何属性runGPS()

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

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