【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改变的时候立马加入
直接看以下的代码了。。。
//
// 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.
}
*/ }
【Swift】Alamofile网络请求数据更新TableView的坑的更多相关文章
- ios MVVM实践 刷新网络请求+tableView展示数据
[实现效果] [目录结构相关] 此示例展示用的是MVVM结构形式,表述如下 M:数据Model的存储,可以用来对属性进行处理.(即胖model概念,上图中xx万人订阅这个处理方法写在Model内) V ...
- iOS开发——实战篇Swift篇&UItableView结合网络请求,多线程,数据解析,MVC实战
UItableView结合网络请求,多线程,数据解析,MVC实战 学了这么久的swift都没有做过什么东西,今天就以自己的一个小小的联系,讲一下,怎么使用swift在实战中应用MVC,并且结合后面的高 ...
- Swift基础之Demo包含刷新,加载,网络请求,MVC
Swift中有一个Alamofire第三方是进行网络请求的,它是AFNetworking的作者写的Swift形式,今天先介绍一下,利用pod导入AFNetworking,SVProgressHUD,M ...
- iOS开发--Swift 基于AFNetworking 3.0的网络请求封装
Swift和OC基于AFNetworking的网络请求流程相同, 就是语法不同, 对于Swift语法不是很清楚的同学, 建议多看看API文档, 自己多多尝试. 写过OC的应该都明白每句话做什么的, 就 ...
- swift中第三方网络请求库Alamofire的安装与使用
swift中第三方网络请求库Alamofire的安装与使用 Alamofire是swift中一个比较流行的网络请求库:https://github.com/Alamofire/Alamofire.下面 ...
- Swift使用Alamofire实现网络请求
Alamofire是一个用Swift编写的HTTP网络库,由此前热门开源项目AFNetworking的的作者mattt开发,可非常简单地用于异步网络通信. 要获取最新版本的 Alamofire,前往h ...
- 微信小程序 网络请求之re.request 和那些坑
微信小程序有四种网络请求类型,下面只详细介绍普通HTTPS请求(wx.request) 普通HTTPS请求(wx.request) 上传文件(wx.uploadFile) 下载文件(wx.downlo ...
- Swift基础之使用Alamofire库进行网络请求和断点下载
好久没有写过Swift相关的文章博客了,这里我就展示一下关于使用Alamofire库的方法 1.什么是Alamofire (1)Alamofire 的前身是 AFNetworking.AFNetwor ...
- post网络请求坑
微信小程序开发中网络请求必不可少.GET.POST请求是最常用的.GET请求 POST请求的时候有好几个坑.我已经为大家填好了.
随机推荐
- 阿里云服务器的坑=====部署EF+MVC
异常处理汇总 ~ 修正果带着你的Net飞奔吧!http://www.cnblogs.com/dunitian/p/4599258.html 先参考:http://www.cnblogs.com/dun ...
- T-SQL:毕业生出门需知系列(九)
<SQL 必知必会>读书笔记 -- 第9课 汇总数据 9.1 聚集函数:对某些行运行的函数,计算并返回一个值 案例: -- 确定表中函数 -- 获得表中某些行的和 -- 找出表列的最大值. ...
- ASP.NET 页面禁止被 iframe 框架引用
两个站点: a.sample.com b.sample.com a.sample.com 站点中的一段示例 JS 代码: var iframe = document.createElement(&qu ...
- 谈谈iOS Animation
零.前言 这里没有太多的代码细节,只是探索iOS动画的基本概念,以及其抽象模型,数学基础等.我们学习一个知识的时候一般有两个部分,抽象部分和形象部分,抽象好比语言的语法,是规则,形象好比具体的句子,可 ...
- 从xfire谈WebService接口化编程
前段时间有博友在看我的博文<WebService入门案例>后,发邮件问我关于WebService 接口在java中的开发,以及在实际生产环境中的应用.想想自己入职也有一段时间了,似乎也该总 ...
- 【分布式】Zookeeper会话
一.前言 前面分析了Zookeeper客户端的细节,接着继续学习Zookeeper中的一个非常重要的概念:会话. 二.会话 客户端与服务端之间任何交互操作都与会话息息相关,如临时节点的生命周期.客户端 ...
- LinqToDB 源码分析——生成表达式树
当我们知道了Linq查询要用到的数据库信息之后.接下就是生成对应的表达式树.在前面的章节里面笔者就已经介绍过.生成表达式树是事实离不开IQueryable<T>接口.而处理表达式树离不开I ...
- Kafka无消息丢失配置
Kafka到底会不会丢数据(data loss)? 通常不会,但有些情况下的确有可能会发生.下面的参数配置及Best practice列表可以较好地保证数据的持久性(当然是trade-off,牺牲了吞 ...
- Java之多态(一)
package test05; public class DuoTai_Test { /** * 一个对象,多种形态 * WQQ → Student.Worker.Friend 1).一个对象,多种形 ...
- 【原】EasyUI ComboGrid 集成分页、按键示例
需求: 1.下拉框下拉时出现表格: 2.表格带分页功能: 3.可以使用向上键.向下键在表格中移动选择行数据: 4.可以使用回车键在表格中选中行数据: 5.在下拉框的文本框中输入内容,能查询表格: 6. ...