I am trying to transfer a variable containing an array from my app delegate to a class that I call DataSource. But I am having trouble transferring the data. When I looked and tried to debug my app, it showed that the variable in my class, DataSource has no value while the variable from my app Delegate had values. Here is my code, can anyone help me out? [also, this I used swiftui in this app]
AppDelegate:
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)")
}
}
}
DataSource:
class DataSource {
let appDelegate = AppDelegate()
var arrayOfImages = [UIImage(named: "placeholder")]
}