I have tried to convert this code to use ‘sendSynchronousRequest()‘ but have had no luck since most resources on SO are outdated.
I am trying to collect data from an API. It then creates an Array of Marvel Characters with the information I need. The whole code works fine, but the Array is empty because it returns the data before the request finishes. How can I wait for the data?
static func getCharacters() -> Array<MarvelCharModel>{
var CharactersFromApi = [MarvelCharModel]();
let baseUrl = "https://gateway.marvel.com";
let charUri = "/v1/public/characters";
let apiKey = "apikey=xxxxxxxxxxxxxxxxxxxx";
let url = URL(string: baseUrl + charUri + "?" + apiKey)!
var response: URLResponse?
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("developer.marvel.com", forHTTPHeaderField: "Referer")
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {(response, data, error) in
guard let data = data else { return }
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
if let dataInfo = responseJSON["data"] as? [String: Any] {
let results = dataInfo["results"] as! NSArray;
for dataCharacter in results {
let character = dataCharacter as? [String: Any];
let charId = character?["id"] as! Int;
let charName = character?["name"] as! String;
let charDesc = character?["description"] as! String;
let charPic = character?["thumbnail"] as! [String: Any];
let charPath = charPic["path"] as! String;
let charExt = charPic["extension"] as! String;
CharactersFromApi.append(MarvelCharModel(name: charName, desc: charDesc, pic: charPath + "." + charExt, id: charId));
// print(CharactersFromApi) <-- This shows correctly but clearly the return at the bottom is not waiting
}
}
}
}
return getFavourite(characters: CharactersFromApi); // CharactersFromAPI is empty
}