iosswiftalamofireswifty-json

Swift 2 - how to get data from Alamofire.responseJSON


I'm reading Design+Code course and Ihave 2 files:

  1. DNService.swift
  2. StoriesTableViewController.swift

Form the DNService I'm loading data from DesignerNews API, here is the function who get the data :

static func storiesForSection(section: String, page: Int, response: (JSON) ->()) {

    let urlString = baseURL + ResourcePath.Stories.description + "/" + section
    let parameters = [
        "page": String(page),
        "client_id": clientID
    ]



    Alamofire.request(.GET, urlString, parameters: parameters).responseJSON { (response) -> Void in
        let swiftyData = JSON(response.result.value ?? [])
        //print(swiftyData)
    }


}

In the StoriesTableViewController, I call the function storiesForSection() but it don't retrieve the data :

var stories: JSON! = []

func loadStories(section: String, page: Int) {
    DNService.storiesForSection(section, page: page) { (JSON) -> () in
        self.stories = JSON["stories"]
        self.tableView.reloadData()
    }
}

I don't know how to fill self.stories in my StoriesTableViewcontroller...

I tried to store swiftyData in a var of DNService and make a getStoredSwiftyData() in StoriesTableViewCtler but it doesn't works too.


Solution

  • storiesForSection:page:response has a callback function, just call it with the JSON object as parameter.

    Alamofire.request(.GET, urlString, parameters: parameters).responseJSON { (response) -> Void in
        let swiftyData = JSON(response.result.value ?? [])
        response(swiftyData)
    }