Gurjit Singh
Gurjit Singh

Reputation: 171

How to get key Value from post webservice API and fetch that to tableview

I got data from API in this format but the problem is that I want to get all questions and answers from the API but whenever I try to get the value by using the key value it returns nil value and application crashes.

This is my API data looks like after getting into a dictionary:

this is what my data looks like I want to show the "Options" key data into my tableView

enter image description here

Here's my code for getting data from API:

Alamofire.request(url, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: header ).responseJSON {
        response in
        switch response.result {
        case .success:
            
              print(response)
              
            if let result = response.result.value {
                
                print(result)
                
                let responseDict = result as! [String : Any]
                
                print(responseDict)
                
                
              let data = responseDict["Result"] as! [Any] 
                
                print(data)
            }
            break
        case .failure(let error):
            
            print(error)
        }
    }

Upvotes: 1

Views: 77

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

if let res = responseDict["Result"] as? [[String:Any]]  {

    for item in res {

          if let ques = item["Question"] as? String  {

             print(ques)

          }

          if let op = item["Options"] as? [[String:Any]]  {

             print(op)

          }
    }
}

Upvotes: 1

Related Questions