我正在尝试使用 MVC 模式,并使用 Alamofire API 将响应作为 json 数据获取。我无法发送数据以从我的模型更新 TableView 。帮我用 json 值更新我的表。
这是我的 API:
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)
}
}
}
}
这是我的 Controller :
@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()
}
这是我的模型:
class model: NSObject {
var name:String!
var email:String!
init(name:String , email:String){
super.init()
self.name = name
self.email = email
}
}
我只有表格 View ,单元格中插入了两个标签;一个标签用于显示 json 名称,另一个标签用于显示 json 电子邮件。
最佳答案
我想你会遇到一些问题,因为我以前处理过这个问题,我调用了与你的调用不同的方法,这就是我使用 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。
关于swift - 如何将模型的 (json) 值发送到 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36740940/