【Swift】Alamofile网络请求数据更新TableView的坑

写这篇BLOG前,有些话不得不提一下,就仅当发发恼骚吧。。。

今天下午为了一个Alamofire取得数据而更新TableView的问题,查了一下午的百度(360也是见鬼的一样),竟然没有一个简单明了的回答,

而唯一几个比较接近答案的,说要 self.tableView.reloadData(),也没有贴上代码,说要放在哪个函数内,

都犹抱琵琶半遮面,让初学者自己采坑,于是郁闷了一下午,刚刚回到家,试想想,要不试试英文网,毕竟Swift就是人家老外的,

说不定老外会告诉你,怎么取得数据并绑定TableView,果不其然,用了不到3份钟的时候就完美解决。

写这篇BLOG,如果后面的新手有幸看到这篇,也可以少走很多弯路。。。

还有

特别感谢英文网

http://blog.revivalx.com/2015/02/23/uitableview-tutorial-in-swift-using-alamofire-haneke-and-swiftyjson/

有一点特别注意的是,方法 self.tableView.reloadData() 要在变量wifi改变的时候立马加入

直接看以下的代码了。。。

【Swift】Alamofile网络请求数据更新TableView的坑

//
// TableViewController.swift
// MyTableView-1387
//
// Created by apiapia on 17/1/6.
// Copyright © 2017年 apiapia. All rights reserved.
//$ curl http://httpbin.org/get
//
//{
// "args": {},
// "headers": {
// "Accept": "*/*",
// "Connection": "close",
// "Content-Length": "",
// "Content-Type": "",
// "Host": "httpbin.org",
// "User-Agent": "curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3"
// },
// "origin": "24.127.96.129",
// "url": "http://httpbin.org/get"
//} // import UIKit
import Alamofire
import SwiftyJSON class TableViewController: UITableViewController { var wifi = ["StarBuck","MJ"]
// var wifi = [String]()
let url = "https://httpbin.org/get"
//上面wifi可以用 Alamofire获取远程数据,
//http://httpbin.org/get override func viewDidLoad() {
super.viewDidLoad() // Alamofire取得的网络数据是异步的
Alamofire.request(url, method: .get).validate().responseJSON { (response) in
// print (response.request)
switch response.result.isSuccess {
case true: if let value = response.result.value {
let json = JSON(value) let headers:Dictionary<String,Any>=json["headers"].dictionaryValue print (headers)
// populating tableview with json from url using Alamofire
// http://blog.revivalx.com/2015/02/23/uitableview-tutorial-in-swift-using-alamofire-haneke-and-swiftyjson/
// self.wifi = ["1","2","3","4"]
// self.tableView.reloadData() self.wifi = [String]() // 重新生成数组成功
// ["Accept-Language", "Host", "Accept", "User-Agent", "Accept-Encoding"]
for (index,_) in headers{ print (index)
self.wifi.append(index) } self.tableView.reloadData() } case false:
print ("网络请求失败") }
} print ("wifi现在是:",wifi) // Alamofire.request(url).validate().responseJSON { response in
// switch response.result.isSuccess {
// case true:
// if let value = response.result.value {
// let json = JSON(value)
// if let number = json[0]["phones"][0]["number"].string {
// // 找到电话号码
// print("第一个联系人的第一个电话号码:",number)
// }
// }
// case false:
// print("")
// }
// }
// //注册表格
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "wifiCell")
//去掉表格尾部空行
self.tableView.tableFooterView = UIView(frame: CGRect.zero) self.tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3 //共有三个分区
} //返回三个分区相应的表格行数
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 1 { return self.wifi.count }
else{
return 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "wifiCell", for: indexPath)
cell.textLabel?.text = self.wifi[indexPath.row] return cell
}else{
return super.tableView(tableView, cellForRowAt: indexPath)
} } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 1 { return 50 }else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
} //取消高亮直选
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true)
} // 当 override了一个静态表格的时候要用到 indentationLevelForRowAt这个方法
// 因为 数据源 对新加进来的 cell一无所知 ,所以要用这个代理方法
override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { if indexPath.section == 1 { let newIndexPath = IndexPath(row: 0, section: indexPath.section)
return super.tableView(tableView, indentationLevelForRowAt: newIndexPath) }else { return super.tableView(tableView, indentationLevelForRowAt: indexPath)
}
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} /*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/ /*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/ /*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { }
*/ /*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/ /*
// MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/ }
上一篇:python 类的属性__slots__ (了解一点点)


下一篇:67 个JavaScript和CSS实用工具、库与资源