I have a function that returns a response from an API call but doesn't wait for the actual response before returning. When it's called it returns nil because the API call is still processing.
@objc static func getPlan(firstID : String, secondID : String) -> NSArray {
var responseData : [[String : String]] = []
session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
if let data = data {
do {
let dataModel = try JSONDecoder().decode(DataModel.self, from: data)
responseData.append(dataModel)
} catch {
print("Error fetching data from API: \(error.localizedDescription)")
}
}
}).resume()
return responseData as NSArray
}
How can I clean up the function to return the ressponseData after the API call has completed? I'm also calling the function from an Objective C file...
NSArray *newPlan = [PlanService getPlan:@"3" ownerID:@"1000"];
You should change your function like below: