I am trying to query a REST API and use a piece of that data in my UI.
Every example I can find of parsing Alamofire JSON data leaves you off at just printing sample data into the console. I'm trying to return this data so I can use it elsewhere.
My theory is that using Alamofire (or at least every example I've found) requires retrieving data from inside an anonymous function, and that I somehow need to extract those variables to the parent function?
This is from this sample response, with slight modifications by me to demonstrate the issue:
import Foundation
import Alamofire
import SwiftyJSON
public func getHostHeaderFromHttpBin() -> String
{
var returnval = "No response" // Setting an initial value in case of failure
AF.request("https://httpbin.org/get").validate().responseJSON { response in
switch response.result {
case .success:
if let json = response.data {
do {
let data = try JSON(data: json)
let str = data["headers"]["Host"]
print("DATA PARSED: \(str)") // Prints: DATA PARSED: httpbin.org
returnval = str.string!
}
catch {
print("JSON Error")
}
}
case .failure(let error):
print(error)
}
}
return returnval // Always returns "No response"
}
I also tried adding return returnval
at the end of the do
block, but that failed with "Error: Unexpected non-void return value in void function".