如何将数据从应用程序委托传输到另一个 class

How do I transfer data from the app delegate to another class

我正在尝试将包含数组的变量从我的应用程序委托传输到我称为 DataSource 的 class。但是我在传输数据时遇到问题。当我查看并尝试调试我的应用程序时,它显示我的 class 中的变量没有值,而我的应用程序委托中的变量有值。这是我的代码,有人可以帮我吗? [另外,我在这个应用程序中使用了swiftui]

A​​ppDelegate:

import UIKit
import CoreData
import Moya
import Alamofire
import AlamofireImage

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

let service = MoyaProvider<YelpService.BusinessProvider>()
   let jsonDecoder = JSONDecoder()
var theViewModels = [RestrauntListViewModel]()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.



    loadBusinesses()


    return true
}


private func loadBusinesses () {
                    service.request(.search(lat: 34.0016, long: -117.8176)) { (result) in
                        switch result{
                        case.success(let response):
                            print("yaya")
                            let root = try? self.jsonDecoder.decode(Root.self, from: response.data)
                            let viewModels = root?.businesses.compactMap(RestrauntListViewModel.init)
                            let dataSource = DataSource()
                            dataSource.arrayOfImages.removeAll()
                            for image in viewModels! {

                                Alamofire.request(image.imageURL).responseImage { response in
                                    if let image = response.result.value {
                                        print("image downloaded appdelegate")
                                        dataSource.arrayOfImages.append(image)
                                        print(dataSource.arrayOfImages)
                                    } else {
                                        print("ERROR: image does not = response.result.value")
                                    }
                                }
                            }

                            self.theViewModels = (root?.businesses.compactMap(RestrauntListViewModel.init))!
                            print("the constant theViewModels in the appdelegate has \(self.theViewModels.count) values")

                        case .failure(let error):
                            print("Error: \(error)")
                        }
    }
}

数据源:

class DataSource {
    let appDelegate = AppDelegate()
    var arrayOfImages = [UIImage(named: "placeholder")]

}

这里有一个最小的例子来解释我的评论:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var arrayOfData = [Int]()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        arrayOfData.append(1)
        arrayOfData.append(2)
        arrayOfData.append(3)

        return true
    }

然后在您的 VC 中,您可以通过获取对应用委托的引用来访问您的数组:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Get the data from app delegate
        let appDelegate = UIApplication.shared.delegate as? AppDelegate
        print(appDelegate?.arrayOfData)
    }

}

在您的特定代码中,您可以将此行移动到您创建数据源的位置:

let dataSource = DataSource()

就在您声明视图模型 (theViewModels) 的上方,以便您可以从其他地方引用它,就像我对 arrayOfData 所做的那样。

您可能还想将 属性 设为私有并使用 getter 访问它,以遵循传统的编程习惯。

可以在此处找到更多示例,尽管已接受的答案适用于 Objective-C:

Passing Data from App delegate to View Controller

向下滚动,您会看到其他方法来完成您需要的操作,甚至可以在 App Delegate 和其他 VC 之间来回传递数据。