-3

I have a main function (buttonPressed), that should print out a Jsonfile.

func buttonPressed {
    var jasonFile = JSON()
    jasonFile = getInfo(parA: 5, parB: 10) //1. takes some time
    print(jsonFile) //prints before the JSON is get from the internet
}

To get the Jsonfile I made a function, which accepts parameters and downloads the information and returns the Jsonfile. Of course this takes quite a while so the code in myFunction is already executed even though it haven't received the data.

(I am using Alamofire and SwiftyJSON)

func getInfo(parA: Int, parB: Int) -> [Int] {
var thisJsonFile = JSON()
Alamofire.request(url, method: .get).validate().responseJSON { response in
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            thisJsonFile = json
        case .failure(let error):
            print(error)
        }
    }
return thisJsonFile //returns an empty File
}

Is there a way to return the JsonFile after it has been finished loading?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Possible duplicate of [How can I get the Data from NSURLSession.sharedSession().dataTaskWithRequest](https://stackoverflow.com/questions/31264172/how-can-i-get-the-data-from-nsurlsession-sharedsession-datataskwithrequest) – matt Oct 07 '18 at 16:17
  • 2
    Possible duplicate of [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – rmaddy Oct 07 '18 at 17:47
  • As a suggestion, you might consider using the `Codable` protocol instead of SwiftyJSON. – Adrian Oct 07 '18 at 17:53
  • Back to basics and learn closures first. https://docs.swift.org/swift-book/LanguageGuide/Closures.html. – ugur Oct 07 '18 at 19:17

1 Answers1

-1

Thank you for your answers, I found a solution, that is workin for me:

I additionally installed Alamofire_Synchronous. The codefor my function is now is now:

func getInfo(parA: Int, parB: Int) -> [Int] {
    let response = Alamofire.request(url).responseJSON()
    switch response.result {
    case .success(let value):
        let json = JSON(value)
        return json
    case .failure(let error):
        print(error)
        return JSON()
    }
}