0

I am using this function in order to get a JSON in another function :

func getData(myUrl : String) -> JSON{
        var jsonFromAPI : JSON = [:]
        Alamofire.request(.GET, myUrl).responseJSON { (request, response, result) -> Void in
            switch result{
            case .Success(let data):
                jsonFromAPI = JSON(data)
                print("json filled")
            case .Failure(_, let errorType):
                print((errorType as NSError).localizedDescription)
            }
        }
        return jsonFromAPI
    }

When I build the code, the function returns an empty JSON as I initialized it, and a few moments later the lane "json filled" appears. I obviously want the json filled to be returned, not the empty one ! How can I correct this problem ? Thanks in advance !

  • 1
    I know you want to return the JSON, but you shouldn't, because this is an asynchronous function. You should adopt asynchronous patterns in your own code, adding a `completionHandler` parameter to your function and then calling that inside the `responseJSON` closure. – Rob Sep 21 '15 at 14:16
  • Or see http://stackoverflow.com/q/27390656/1271826 – Rob Sep 21 '15 at 14:19

0 Answers0