Hi,
I am coding my first App and have never coded before and need some guidance with the @escaping completion handler logic.
I am trying to get the count of fires from a third party API and then pass the count using a shared Data Container class to my main View Controller.
The issue is that when I call the func loadInitialFireMapData on my main View Controller, I am getting an error "Expected expression in list of expressions"
This is because I don't quite understand yet how to call a function when there is a completion handler
The @escaping completion handler is necessary since the main View Controller needs to wait for the API call (func loadInitialFireMapData) to finish in order to get the fire count.
Any advice would be greatly appreciated!
See the code from the Main View Controller and the API call with the @ escaping function from my FireDataManager.swift file.
Here is the code from my Main View Controller:
// ViewController.swift
class DataContainer {
static let shared = DataContainer()
var fireCount: Int = 0
var fires: [Fire] = []
var totalFireCount: Int = 0
}
class ViewController: UIViewController, CLLocationManagerDelegate {
let dataContainer = DataContainer.shared
let fireDataManager = FireDataManager ()
override func viewDidLoad() {
super.viewDidLoad()
//Retrieve Fire API data from Fire Data Manager
fireDataManager.loadInitialFireMapData (completion: ([Fire]) -> return) {
self.FireStatusLabel.text = (String(DataContainer.shared.totalFireCount) + " fires within 100 miles of your location.")
}
Here is the FireDataManager.swift file with the API call/@escaping completion handler function.
// FireDataManager.swift
class FireDataManager {
func loadInitialFireMapData(completion: @escaping () -> Swift.Void) {
if let url = URL(string:
"https://opendata.arcgis.com/datasets/68637d248eb24d0d853342cba02d4af7_0.geojson")
{
URLSession.shared.dataTask(with: url) {data, response, error in
if let data = data {
do {
let features = try MKGeoJSONDecoder().decode(data)
.compactMap { $0 as? MKGeoJSONFeature }
let validWorks = features.compactMap(Fire.init)
DataContainer.shared.fires.append(contentsOf: validWorks)
DataContainer.shared.totalFireCount = validWorks.count
print("Fire Data Manager Count of Total Fires: ", DataContainer.shared.totalFireCount)
DispatchQueue.main.async {
completion()
}
}
catch let error {
print("FireMap URL Session error: ", error.localizedDescription)
}
}
}
.resume()
}
}
}