Steven Schafer
Steven Schafer

Reputation: 862

How can I grab the correct JSON response using SwiftyJSON?

I am making a GET request using alamofire and attempting to convert to JSON using SwiftyJSON. I can successfully make the request, but I'm unable to convert the response into a usable JSON object.

I am trying to grab data from a foursquare venue detail response, and update a UITableView (the detail page) with appropriate information about the venue. The UITableView has 3 different sections.

Here is my makeRequest code for VenueDetailViewController (UITableViewController).

func makeRequest() {

    Alamofire.request(.GET, self.foursquareEndpointURL, parameters: [

        "client_id" : self.foursquareClientID,
        "client_secret" : self.foursquareClientSecret,
        "v" : "20140806"
        ])
        .responseJSON { (request, response, data, error) in
            println(request)
            println(response)
            println(error)
            println(data)
            if data != nil {
                var jsonObj = JSON(data!)
                // response is not in the form of an array? I think... thats why data is not setting .. I think "arrayValue" below is incorrect. should be something like dictionaryValue or stringValue
                if let obj = jsonObj["response"]["venue"].arrayValue as [JSON]? {
                    self.responseitems = obj
                    self.tableView.reloadData()
                    println("Objis: \(obj)")
                }

            }
    }
}

When I println("Obis: \(obj)") I get a console output of Objis: [] telling me that I'm grabbing the wrong data from the JSON response? Here is the url for the Foursquare Venue Detail API request

Oh and self.responseitems is var responseitems:[JSON] = []

Please help! Thanks

Upvotes: 0

Views: 513

Answers (1)

valzevul
valzevul

Reputation: 127

Check out this code:

let url = "Foursquare Venue Detail API request goes here"
    Alamofire .request(.GET, url) .responseJSON(options: nil) { (_, _, data, error) -> Void in
        if error != nil {
            println(error?.localizedDescription)
        } else if let data: AnyObject = data {
            let jObj = JSON(data)
            if let venue = jObj["response"]["venue"].dictionary {
                println(venue)
            }

        }
    }

So the main difference here is that the data is a dict, not an array.

By the way, consider reloading the table view in the main queue as this affects the UI:

dispatch_async(dispatch_get_main_queue()) {
    self.tableView.reloadData() // Update UI
}

Upvotes: 1

Related Questions