【发布时间】:2019-03-12 16:47:24
【问题描述】:
我有一个名为 mapViewController 的 ViewController。在那个控制器里面我有一个按钮,它是一个播放按钮。如果单击按钮,名为“Play”的布尔值将从 false 变为 true。
让我们跳到这个线程的重点:
按下按钮后,我希望将布尔值更改为 true。如果用户离开应用程序。 (进入背景)我想打印一个显示它的文本。 (一旦我知道它是如何工作的,我就会将它用于其他目的。)
那么,让我们看看我的AppDelegate
func applicationDidEnterBackground(_ application: UIApplication)
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
let mapVC = UIApplication.shared.delegate as! MapViewController
if (mapVC.play == true)
{
print("The play-bool is true, and application did enter the background")
}
}
一旦我按下按钮并离开应用程序,我就会收到如下所示的错误:
无法将“MyDogwalk.AppDelegate”(0x28093e230) 类型的值转换为“MyDogwalk.MapViewController”(0x104f99d98)。
警告:无法执行支持代码来读取 Objective-C 类数据 进行中。这可能会降低类型信息的质量 可用。
正如您在我的代码中看到的,我正在尝试从 ViewController 中获取一个布尔值,并在我的 AppDelegate 中检查它的语句。
一旦手机在后台,我将使用此信息来跟踪位置,但这是我第一次。我需要/想了解这实际上是如何工作的,以及我该如何做到这一点。
【问题讨论】:
-
无关,但您可以只使用
if mapVC.play -
您希望如何从 App Delegate 获取 MapViewController?
UIApplication.shared.delegate将返回当前的AppDelegate,即您当前所在的班级。 -
首先:您不能将委托转换为 UIViewController (
delegate as! MapViewController),这显然是不正确的。第二:是MapViewController根还是可见视图控制器?此外,我鼓励避免从AppDelegate访问视图控制器,检查:stackoverflow.com/questions/24675907/… -
@TomQDRS 我什么都不期待。我尝试了一些方法,但找不到一个好的答案。所以这就是我现在的位置。而且我不知道代码会返回当前的 AppDelegate,否则我不会使用那种代码。对不起。 :)
-
这毫无意义:
let mapVC = UIApplication.shared.delegate as! MapViewController。您的应用委托是 AppDelegate,不是 MapViewController。你想用那条线做什么?
标签: ios swift viewcontroller appdelegate