写这篇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的坑的更多相关文章

  1. ios MVVM实践 刷新网络请求+tableView展示数据

    [实现效果] [目录结构相关] 此示例展示用的是MVVM结构形式,表述如下 M:数据Model的存储,可以用来对属性进行处理.(即胖model概念,上图中xx万人订阅这个处理方法写在Model内) V ...

  2. iOS开发——实战篇Swift篇&UItableView结合网络请求,多线程,数据解析,MVC实战

    UItableView结合网络请求,多线程,数据解析,MVC实战 学了这么久的swift都没有做过什么东西,今天就以自己的一个小小的联系,讲一下,怎么使用swift在实战中应用MVC,并且结合后面的高 ...

  3. Swift基础之Demo包含刷新,加载,网络请求,MVC

    Swift中有一个Alamofire第三方是进行网络请求的,它是AFNetworking的作者写的Swift形式,今天先介绍一下,利用pod导入AFNetworking,SVProgressHUD,M ...

  4. iOS开发--Swift 基于AFNetworking 3.0的网络请求封装

    Swift和OC基于AFNetworking的网络请求流程相同, 就是语法不同, 对于Swift语法不是很清楚的同学, 建议多看看API文档, 自己多多尝试. 写过OC的应该都明白每句话做什么的, 就 ...

  5. swift中第三方网络请求库Alamofire的安装与使用

    swift中第三方网络请求库Alamofire的安装与使用 Alamofire是swift中一个比较流行的网络请求库:https://github.com/Alamofire/Alamofire.下面 ...

  6. Swift使用Alamofire实现网络请求

    Alamofire是一个用Swift编写的HTTP网络库,由此前热门开源项目AFNetworking的的作者mattt开发,可非常简单地用于异步网络通信. 要获取最新版本的 Alamofire,前往h ...

  7. 微信小程序 网络请求之re.request 和那些坑

    微信小程序有四种网络请求类型,下面只详细介绍普通HTTPS请求(wx.request) 普通HTTPS请求(wx.request) 上传文件(wx.uploadFile) 下载文件(wx.downlo ...

  8. Swift基础之使用Alamofire库进行网络请求和断点下载

    好久没有写过Swift相关的文章博客了,这里我就展示一下关于使用Alamofire库的方法 1.什么是Alamofire (1)Alamofire 的前身是 AFNetworking.AFNetwor ...

  9. post网络请求坑

    微信小程序开发中网络请求必不可少.GET.POST请求是最常用的.GET请求 POST请求的时候有好几个坑.我已经为大家填好了.

随机推荐

  1. python资料

    Python进阶 https://pythontips.com/ https://flyouting.gitbooks.io/learn-python-the-hard-way-cn/content/ ...

  2. JavaScript高级编程 (2) - HTML 与 JavaScript

    向HTML 页面中插入JavaScript 的主要方法,就是使用<script>元素.这个元素由Netscape 创造并在Netscape Navigator 2 中首先实现.后来,这个元 ...

  3. Log4net入门(回滚日志文件篇)

    在上一篇Log4net(日志文件篇)中,我们使用"log4net.Appender.FileAppender"将日志信息输出到一个单一的文件中,随着应用程序的持续使用,该日志文件会 ...

  4. WebComponent魔法堂:深究Custom Element 之 标准构建

    前言  通过<WebComponent魔法堂:深究Custom Element 之 面向痛点编程>,我们明白到其实Custom Element并不是什么新东西,我们甚至可以在IE5.5上定 ...

  5. ThreadLocal<T>的是否有设计问题

    一.吐槽 ThreadLocal<T>明显是.NET从JAVA中来的一个概念,但是这种设计是否出现了问题. 很明显,在JAVA中threadLocal直接是Thread的成员,当然随着th ...

  6. asp.net DataTable导出Excel 自定义列名

    1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...

  7. mybatis笔记1 基本的配置和操作

    mybatis比较轻量,适合开发比较小型的或者业务比较复杂的系统: 相对于hibernate来说可以灵活的写sql,更灵活的处理遇到的业务逻辑: 可以说hibernate是pojo实体对db的orm映 ...

  8. Struts+Spring+Hibernate项目的启动线程

    在Java Web项目中,经常要在项目开始运行时启动一个线程,每隔一定的时间就运行一定的代码,比如扫描数据库的变化等等.要实现这个功能,可以现在web.xml文件中定义一个Listener,然后在这个 ...

  9. 使用Maven私服的好处

    1.Maven仓库的分类 本地仓库:当Maven执行编译或测试时,如果需要使用到依赖文件,它总是基于坐标使用本地仓库的依赖文件.默认情况下,不管Linux还是Windows,每个用户在自己的用户目录下 ...

  10. js 隐式转换

    1.数字number与字符串string相加的就,最后会得到一个字符串string:'1'+3='13' 2.数字number与字符串string相减,最后会得到一个数字number:'1'-0=1, ...