0

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".

Allen Ellis
  • 269
  • 2
  • 9
  • What you normally do is to assign the downloaded data to a class property, `self.myData = str` or that you use a completion handler in your closure and send your downloaded data as an argument to that completion handler. – Joakim Danielson May 10 '20 at 16:11
  • Thanks, that put me on a track where I hacked a solution together for now by having my script sleep for two seconds and then redraw the variable on screen. I'll read more about async :) – Allen Ellis May 11 '20 at 00:30

0 Answers0