How can I wait for the api call to complete before returning the function?

1.3k Views Asked by At

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"];
1

There are 1 best solutions below

0
Ali Moazenzadeh On

You should change your function like below:

@objc static func getPlan(firstID : String, secondID : String, completion: @escaping ((Result<[[String : String]], Error>) -> Void)) {
    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)
                completion(.success(dataModel))
            } catch {
                print("Error fetching data from API: \(error.localizedDescription)")
                completion(.failure(error))
            }
        }
    }).resume()
}