我是一个有用的助手,可以为您翻译文本。
我正在尝试使用iBeacons在AppDelegate.swift内实现CoreLocation方法(这些方法在AppDelegate中实现,以确保应用程序具有后台功能)。
在带有“ViewController.swift”的SingleView应用程序中,从AppDelegate传递数据到ViewController以更新视图,例如UIImages、UILabels或UITableViews,哪种最佳实践?
我已经成功地实现了两种不同的方法:
1)委托,在AppDelegate.swift内触发Viewcontroller委托方法:
protocol BeaconLocationDelegate { func minorBeaconChanged(minorValue:NSNumber) }
var locationDelegate: BeaconLocationDelegate
locationDelegate?.minorBeaconChanged(nearestBeacon.minor)
ViewController.swift:
在viewDidLoad方法中:
(UIApplication.sharedApplication().delegate as AppDelegate).locationDelegate = self
我觉得这种写法有些难看 - 是否有更好的方式来声明属性为代理?
协议实现:
func minorBeaconChanged(minorValue: NSNumber) {
// do fancy stuff here
}
2)通过在AppDelegate内创建对ViewController的引用:
let viewController:ViewController = window!.rootViewController as ViewController
viewController.doSomethingFancy()
这两种方法对我来说都可以,但是我认为通过委托的第一种方法更加优雅,在你有多个视图控制器时也是更好的选择。
有什么建议吗?