Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Handling JSON with Alamofire & SwiftyJSON

This is sure to be asked several times, but I have not yet found the right answer, although I have been looking very hard.

I use Alamofire and SwiftyJSON and my JSON data looks like that:

{
  "528" : {
    "name" : "Name 1",
    "id" : "528",
    "product_id" : null,
    "visible" : "0",
    "level" : "2"
  },
  "29" : {
    "name" : "Name 2",
    "id" : "29",
    "product_id" : null,
    "visible" : "1",
    "level" : "1"
  },
  "173" : {
    "name" : "Name 3",
    "id" : "173",
    "product_id" : null,
    "visible" : "0",
    "level" : "2"
  },
  "143" : {
    "name" : "Name 4",
    "id" : "143",
    "product_id" : null,
    "visible" : "1",
    "level" : "2"
  },

...with this code:

Alamofire.request(.GET, dataURL, parameters: nil, encoding: .JSON)

    .responseJSON { (request, response, jsonData, error) in

        let json = JSON(jsonData!) 

        println(json)

    }

...so everything should be fine with JSON

  1. How can i access to that data? I mean how can i get names, ids, product_ids etc

  2. How can i put that data (name) to my TableViewController?

like image 349
vk72 Avatar asked Oct 31 '14 10:10

vk72


People also ask

How do I parse JSON response from Alamofire API in Swift?

To parse the response in Alamofire API request, we will use JSONDecoder, which is an object that decodes instances of a data type from JSON objects. The decode method of JSONDecoder is used to decode the JSON response. It returns the value of the type we specify, decoded from a JSON object.


2 Answers

I am using both SwiftyJSON and Alamofire in one of my projects. Here is how I am using it.

  1. Create a protocol called APIProtocol.
  2. Setup an API class with a GET method that accepts a delegate of type APIProtocol.
  3. Setup TableViewController to implement the APIProtocol.
  4. Call API.get() from TableViewController

Code

// Step 1
protocol APIProtocol {
  func didReceiveResult(results: JSON)
}

// Step 2
func get(path: String, parameters: [String: AnyObject]? = nil, delegate: APIProtocol? = nil){
  let url = "\(self.hostname)\(path)"
  NSLog("Preparing for GET request to: \(url)")

  Alamofire.request(.GET, url, parameters: parameters)
    .responseJSON { (req, res, json, error) in
      if(error != nil) {
        NSLog("GET Error: \(error)")
        println(res)
      }
      else {
        var json = JSON(json!)
        NSLog("GET Result: \(json)")

        // Call delegate if it was passed into the call
        if(delegate != nil) {
            delegate!.didReceiveResult(json)
        }
      }
    }
}

// Step 3
class ActivityViewController: UITableViewController, APIProtocol {
  var activityModelList: NSMutableArray = [] // This is the array that my tableView is using.

  ... 

  func didReceiveResult(result: JSON) {
    var activities: NSMutableArray = []

    NSLog("Activity.didReceiveResult: \(result)")

    for (index: String, activity: JSON) in result {

      var activityModel = ActivityModel(
        id: activity["id"].intValue,
        message: activity["message"].stringValue
      )

      activities.addObject(activityModel)
    }

    // Set our array of new models
    activityModelList = activities

    // Make sure we are on the main thread, and update the UI.
    dispatch_sync(dispatch_get_main_queue(), {
      self.refreshControl!.endRefreshing()
      self.tableView.reloadData()
    })
  }
}

// Step 4
override func viewDidLoad() {
  MyAPI.get("/activities", delegate: self)
}
like image 200
Jonathan Avatar answered Nov 09 '22 22:11

Jonathan


The accessors (for SwiftyJSON at least) work like:

if let userName = json[0]["528"]["name"].string{
    println(userName) // "Name 1"
}

More information on how to use SwiftyJSOn can be found here in its official documentation: https://github.com/SwiftyJSON/SwiftyJSON

Regarding how to put that data into a UITableView, there are many methods. Set up a UITableView cell and then load in the JSON data in some sort of array for instance.

like image 39
Glynbeard Avatar answered Nov 10 '22 00:11

Glynbeard