无法转换'AppName.AppDelegate'类型的值[重复]

问题描述 投票:-1回答:2

我有一个名为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中检查它的语句。

我将使用此信息在手机处于后台时跟踪位置,但这是我第一次。我需要/想要了解这实际上是如何工作的,以及我如何能够做到这一点。

ios swift viewcontroller appdelegate
2个回答
4
投票

请不要尝试从AppDelegate访问控制器,这不是它的预期目的。

如果您将当前的ViewController注册到正确的NSNotification,您可以检查应用程序是否会从任何地方进入后台。然后,您将定义一个在应用程序进入后台状态时执行的功能,您可以在其中打印出文本。

请看看https://stackoverflow.com/a/9012734/4442731如何做到这一点。一个快速的解决方案是在链接答案下面的答案。这段代码需要在你的MapViewController中。


2
投票

也许你应该重新考虑你的申请:

  • 一种方法是添加某些Notification名称的观察者,如UIApplication.didEnterBackgroundNotification。所以你会在你的UIViewController课程中注意到你的应用程序转到后台
  • 或者如果play是应该存储的东西,你可以使用UserDefaultsFileManager或一些数据库来存储这个值,然后你可以在applicationDidEnterBackground(_:)中检索这个值
© www.soinside.com 2019 - 2024. All rights reserved.