如何将模型的(json)值发送到视图控制器?

时间:2016-04-20 10:26:33

标签: swift api model-view-controller alamofire swifty-json

我正在尝试使用MVC模式,并使用Alamofire API将响应作为json数据获取。我无法发送数据来更新我的模型中的tableview。帮助我用json值更新我的表。

这是我的API:

Object.defineProperty(document, 'title', {
  set: function(){}
});

这是我的控制者:

class func showData(completionHandler:(model)->()){
         var arrRes = [[String:AnyObject]]()
        Alamofire.request(.GET, "http://api.androidhive.info/contacts/").responseJSON { (req, res, json) -> Void in
        let swiftyJsonVar = JSON(json.value!)
        if let resData = swiftyJsonVar["contacts"].arrayObject {
            arrRes = resData as! [[String:AnyObject]]
            print(arrRes)
            if  arrRes.count > 0 {
            let name = swiftyJsonVar["contacts"]["name"].stringValue
            let email = swiftyJsonVar["contacts"]["email"].stringValue

                let detail = model(name: name, email: email)
                completionHandler(detail)

            }
            }
        }
}

这是我的模特:

 @IBOutlet var appsTableView: UITableView!
  var tableData:[model] = [model]()


  override func viewDidLoad() {
    super.viewDidLoad()

    self.appsTableView.reloadData()
    self.appsTableView.backgroundColor = UIColor.orangeColor()
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = appsTableView.dequeueReusableCellWithIdentifier("MyTestCell") as! newTabelcell
    let dict = self.tableData[indexPath.row]
    cell.name.text = dict.name
    cell.mailid.text = dict.email
    return cell
}

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

func configureTableView() {
    appsTableView.rowHeight = UITableViewAutomaticDimension
    appsTableView.estimatedRowHeight = 100.0
    self.appsTableView.reloadData()
}

我只有tableview,并且在单元格中插入了两个标签;一个标签用于显示json名称,另一个用于显示json电子邮件。

2 个答案:

答案 0 :(得分:0)

我认为你会遇到一些问题,因为我之前已经使用过这个问题而且我打电话给你的是差异,这就是我使用Alamofire的方式:

Alamofire.request(.GET, "http://api.androidhive.info/contacts/").responseJSON { (responseData) -> Void in
            switch responseData.result {
            case .Success(let value):
                let swiftyJsonVar = JSON(value)
                // You can adjust here, because I didn't use Contact Model in my Project.
                if let resData = swiftyJsonVar["contacts"].arrayObject {
                    self.arrRes = resData as! [[String:AnyObject]]
                }
                if self.arrRes.count > 0 {
                    self.tblJSON.reloadData()
                }
            case .Failure(let error):
                print(error.description)
            }
        }

您可以在https://github.com/khuong291/Swift_Example_Series(项目11)下载我的项目。我已经完成了将JSON加载到tableView。

答案 1 :(得分:0)

这是我编辑过的具有itunessearch方法的API类。

    func itunesSearch(completionHandler:(songData)->()) {

    Alamofire.request(.GET, "http://itunes.apple.com/search?", parameters: ["term" : "tamil new songs", "media" : "music"])
        .responseJSON { (request, response, json) in

                let json = JSON(json.value!)
                if let jsonData = json["results"].arrayObject {
                self.array = jsonData as! [[String : AnyObject]]
                for num  in 1...5{
                let arraydata = json["results"][num]
                    //print([arraydata])
                let artistid = arraydata["artistId"].stringValue
                let trackname = arraydata["trackName"].stringValue

                let song = songData(country: artistid , currency: trackname)   // The parameter name country and currency of this method is just defined in the model class.Don't get confuse by those names which is just reference. 
                completionHandler(song)   }
             }
        }
 }

这对我来说很有用..