Mapping JSON data in a TableView using SwiftyJSON and Alamofire

I want to show JSON data captured from the server as a table. The problem is that I cannot make it appear on it. I tried several different methods and searched a lot to find a solution, but I can’t.

My code (all of this) is shown below, and I hope someone can help me. Thanks in advance.

import UIKit
import Alamofire
import SwiftyJSON

class MasterViewController: UITableViewController {

var tableTitle = [String]()
var tableBody = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    getJSON()

}

func getJSON(){

    Alamofire.request(.GET, "http://announcement.vassy.net/api/AnnouncementAPI/Get/").responseJSON { (Response) -> Void in

        // checking if result has value
        if let value = Response.result.value {

            let json = JSON(value)

            for anItem in json.array! {

                let title: String? = anItem["Title"].stringValue
                let body: String? = anItem["Body"].stringValue
                self.tableTitle.append(title!)
                self.tableBody.append(body!)

            }

        }

    }

    self.tableView.reloadData()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// Table View Stuff

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableTitle.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell

    // cell config
    cell.title!.text = tableTitle[indexPath.row]
    cell.body!.text = tableBody[indexPath.row]
    return cell

}

}
+4
source share
2 answers

The Alamofire network request is asynchronous, that is, you cannot know when the result will return.

The problem is that you are reloading the tableView outside the Alamofire request area, so it is executed before the data is returned.

, :

func getJSON(){

    Alamofire.request(.GET, "http://announcement.vassy.net/api/AnnouncementAPI/Get/").responseJSON { (Response) -> Void in

        // checking if result has value
        if let value = Response.result.value {

            let json = JSON(value)

            for anItem in json.array! {

                let title: String? = anItem["Title"].stringValue
                let body: String? = anItem["Body"].stringValue
                self.tableTitle.append(title!)
                self.tableBody.append(body!)

            }

            dispatch_async(dispatch_get_main_queue()) {
                self.tableView.reloadData()             
            }

        }

    }

}
+8

, @Eric , , , UITableViewController, , .

, . , -, , , , !!!.

, hanlde Alamofire passgin completionHandler , , , singleton ( , , ).

import AlamofireImage
import SwiftyJSON

class NetworkHandler { 

   /// The shared instance to define the singleton.
  static let sharedInstance = RequestManager()


  /**
  Private initializer to create the singleton instance.
  */
  private init() { }

  func getJSON(completionHandler: (json: JSON?, error: NSError?) -> Void) {

      Alamofire.request(.GET, http://announcement.vassy.net/api/AnnouncementAPI/Get/).responseJSON { response in

        switch(response.result) {
        case .Success(let value):

            let json = JSON(value)
            completionHandler(json: json, error: nil)

        case .Failure(let error):
            completionHandler(json: nil, error: error)
        }
    }
  }
}

UITableViewController Alamofire :

class MasterViewController: UITableViewController {

   var tableTitle = [String]()
   var tableBody = [String]()

   override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view, typically from a nib.

       NetworkHandler.sharedInstance.getJSON { [weak self] (json, error) -> Void in

         // request was made successful
         if error == nil {
            for anItem in json.array! {
               let title: String? = anItem["Title"].stringValue
               let body: String? = anItem["Body"].stringValue
               self.tableTitle.append(title!)
               self.tableBody.append(body!)
            }

            dispatch_async(dispatch_get_main_queue()) {
                self.tableView.reloadData()             
            }
         }
       }
    }

    // rest of your code
 }

, , .

,

0

All Articles