-1

I am using this Alamofire request and returning a json

let todoEndpoint: String = "https://api.abc.com/api/v3/products?pid=uid8225&format=json&&offset=0&limit=10"
    Alamofire.request(todoEndpoint)
        .responseJSON { response in
            guard let json = response.result.value as? [String: Any] else {
                print("didn't get todo object as JSON from API")
                print("Error: \(response.result.error)")
                return
            }
            print(json)

}

Now i have do loop where i want to use this json value but i am getting:

error : Use of unresolved identifier json ?

do {

        for (index,subJson):(String, JSON) in  json {

print("Index :\(index) Title: \(subJson)" )

} catch
{

            print("there was an error")

}

As mentioned :

https://github.com/Alamofire/Alamofire#response-string-handler " the result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure."

How can i use this json value outside scope of response closure ?

Can you please suggest

Is there any completion handler i need to write and how can it be done ?

Thanks

Guri S
  • 1,083
  • 11
  • 12
  • Possible duplicate of [Parsing JSON using the new Swift 3 and Alamofire](http://stackoverflow.com/questions/39468516/parsing-json-using-the-new-swift-3-and-alamofire) –  Apr 12 '17 at 12:13
  • GS, did you try to search for the solution since this question has been asked like more than 30+ threads: https://www.google.se/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=alamofire+json+response+swift+stackoverflow –  Apr 12 '17 at 12:14
  • 1
    you `do` block should be ran right after the guard ie `guard let else {...} HERE`. Currently you're doing it in a scope that `json` doesn't exist – mfaani Apr 12 '17 at 12:19
  • Hi Honey, thanks for the reply , if i use in the scope then please suggest if i can use these values elsewhere once i parse all the json values e.g – Guri S Apr 12 '17 at 12:20
  • i have items.append(name:name1) and these values needs to be used in a different class e.g cell.titleLabel1.text = item.name1 , as i tried in the loop but i was not able to get the values – Guri S Apr 12 '17 at 12:30
  • can i use completion handler ? – Guri S Apr 12 '17 at 12:33

1 Answers1

1

Better use the SwiftyJson for easy json parsing with Almofire like bellow :

import Alamofire
import SwiftyJSON

 static func getRequest(urlString: URL?, Parameter:NSDictionary?, completion: @escaping (_ serverResponse: AnyObject?,_ error:NSError?)->()){

        Alamofire.request(urlString!, parameters:nil, headers: nil).responseJSON { response in

            if(response.result.value != nil){
                let serverResponse = JSON(response.result.value!)
                print("Array value is \(serverResponse.arrayValue)")


                     completion(serverResponse as AnyObject?, nil)
            }
            else{
                completion(nil, response.result.error as NSError?)
            }
        }

    }

You can write this function in a separate class like NetworkLayer and then call it from any class for the WebService call as given bellow :

let url = NSURL(string: yourWebServiceUrlString)
        NetworkLayer.getRequest(urlString: url as URL?, Parameter: nil) { (serverResponse, error) in

            if (error == nil){
            print("Server response: \(serverResponse)")
            }
        }

Note: You can also pass the parameter dictionary in it.

Aashish1aug
  • 795
  • 1
  • 8
  • 22