1.在新闻类中定义属性
```
import UIKit
classNews:NSObject{
vartitle:String=""
vartime =""
varcontent =""
varurl =""
varweburl =""
}
```
2.ViewColler里初始化表格
```
import UIKit
class ViewController: UIViewController,UITableViewDataSource{
var tab:UITableView?
vartabDataArr : [News]?
overridefuncviewDidLoad() {
super.viewDidLoad()
self.tab=UITableView(frame:self.view.frame, style: .plain)
self.tab?.dataSource=self
self.view.addSubview(self.tab!)
}
overridefuncviewWillAppear(_animated:Bool) {
self.requestData()
}
functableView(_tableView:UITableView, numberOfRowsInSection section:Int) ->Int{
ifletcount =tabDataArr?.count{
returncount
}
return0
}
functableView(_tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{
letidentfier ="cell"
varcell = tableView.dequeueReusableCell(withIdentifier: identfier)
ifcell ==nil{
cell =UITableViewCell(style: .subtitle, reuseIdentifier: identfier)
}
letone =self.tabDataArr![indexPath.row]
cell?.textLabel?.text= one.title
cell?.textLabel?.numberOfLines = 0
cell?.detailTextLabel?.text= one.content
cell?.detailTextLabel?.numberOfLines = 0
returncell!
}
//MARK:----------请求网络数据
funcrequestData() ->Void{
letURLM =URLModel()
URLM.getNewsData(channel:"头条", startNum:10) { (data, success)in
//错误情况
if!success{
DispatchQueue.main.async(execute: {
letalertVC =UIAlertController(title:nil, message: dataas?String, preferredStyle: .alert)
letconfirmBtn =UIAlertAction(title:"确定", style: .default, handler:nil)
alertVC.addAction(confirmBtn)
self.present(alertVC, animated:true, completion:nil)
})
return
}
//正确情况,数据加载到表格上
self.tabDataArr= dataas? [News]
//刷新表格
DispatchQueue.main.async(execute: {
self.tab?.reloadData()
})
}
}
overridefuncdidReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
````
3.在Model离封装网络请求
```
import UIKit
classURLModel:NSObject{
funcgetNewsData(channel:String,startNum:Int,completion:@escaping(Any,Bool)->Void) ->Void{
//把参数拼接到网址字符串
var urlStr = "http://api.jisuapi.com/news/get?channel=\(channel)&start=\(startNum)&num=10&appkey=de394933e1a3e2db"
//汉字进行转码
urlStr = urlStr.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlFragmentAllowed)!
//封装URL对象
leturl =URL(string: urlStr)
//封装为URLRequest对象
letreq =URLRequest(url: url!, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval:5.0)
//网络请求
lettask:URLSessionDataTask=URLSession.shared.dataTask(with: req) { (data, respons, error)in
//错误判断
iferror !=nil{
//参数闭包调用
completion("网络错误",false)
return
}
//json数据解析
letjsonData =try?JSONSerialization.jsonObject(with: data!, options: .allowFragments)
//如果解析失败,返回错误信息
ifjsonData ==nil{
completion("网络错误",false)
return
}
letstatus = (jsonDataas!NSDictionary).value(forKey:"status")as!String
letmsg = (jsonDataas!NSDictionary).value(forKey:"msg")as!String
ifInt(status)! !=0{
completion(msg,false)
return
}
letresult = (jsonDataas!NSDictionary).value(forKey:"result")as!NSDictionary
letlist = result.value(forKey:"list")as!NSArray
varnewsArr:[News] = []
foriteminlist{
letdic = itemas!NSDictionary
letoneNew =News()
oneNew.title= dic.value(forKey:"title")as!String
oneNew.content= dic.value(forKey:"content")as!String
newsArr.append(oneNew)
}
completion(newsArr,true)
}
//开启任务
task.resume()
}
}
```
===================================================================
*4上下拉刷新
```
import UIKit
class ViewController: UIViewController,UITableViewDataSource,MJRefreshBaseViewDelegate {
//表格属性
var tab:UITableView?
vartableDataArr : [News]?
varMJHeaderView :MJRefreshHeaderView?//下拉刷新控件
varMJFooterView :MJRefreshFooterView?//上拉加载控件
//记录当前的页码
varstartNum =0
functableView(_tableView:UITableView, numberOfRowsInSection section:Int) ->Int{
ifletcount =tableDataArr?.count{
returncount
}
return0
}
functableView(_tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{
letidentfier ="cell"
varcell = tableView.dequeueReusableCell(withIdentifier: identfier)
ifcell ==nil{
cell =UITableViewCell(style: .subtitle, reuseIdentifier: identfier)
}
letoneNew =self.tableDataArr![indexPath.row]
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.text= oneNew.title
cell?.detailTextLabel?.text= oneNew.content
// cell?.detailTextLabel?.numberOfLines = 0
returncell!
}
overridefuncviewWillAppear(_animated:Bool) {
super.viewWillAppear(animated)
self.requestNetWorkDataAndUpdataUI()
}
//MARK:MJRefresh协议方法
funcrefreshViewBeginRefreshing(_refreshView:MJRefreshBaseView!) {
//如果是下拉,startNum置为0
ifrefreshViewisMJRefreshHeaderView{
startNum=0
}else{
//如果是上拉控件,让startNum10个10个的添加
startNum+=10
}
self.requestNetWorkDataAndUpdataUI()
}
overridefuncviewDidLoad() {
super.viewDidLoad()
self.tab=UITableView(frame:self.view.frame, style: .plain)
self.tab?.dataSource=self;
self.view.addSubview(self.tab!)
//实例化刷新控件
self.MJHeaderView = MJRefreshHeaderView(scrollView: self.tab!)
self.MJHeaderView?.delegate = self
//实例化上拉刷新控件
self.MJFooterView = MJRefreshFooterView(scrollView: self.tab!)
self.MJFooterView?.delegate = self
}
//MARK:请求网络数据
funcrequestNetWorkDataAndUpdataUI() ->Void{
//转动菊花
UIApplication.shared.isNetworkActivityIndicatorVisible = true
//请求网络数据
leturlSerive =URL_Service()
urlSerive.getNewsData(channel:"头条", startNum:self.startNum) { (data, success)in
//先停止指示器
DispatchQueue.main.async(execute: {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
//把下拉刷新控件也停止
self.MJHeaderView?.endRefreshing()
//吧上拉也停止
self.MJFooterView?.endRefreshing()
})
//错误情况,提示
if!success{
DispatchQueue.main.async(execute: {
letalertVC =UIAlertController(title:nil, message: dataas?String, preferredStyle: .alert)
letconfirmBtn =UIAlertAction(title:"确定", style: .default, handler:nil)
alertVC.addAction(confirmBtn)
self.present(alertVC, animated:true, completion:nil)
})
return
}
//正确情况,加载表格
// 如果startNum是0,将第一页数据赋值给表格数组
ifself.startNum==0{
self.tableDataArr= dataas? [News]
}else{// 如果不是第一页,将得到的数据拼接到表格数组中
letarr = dataas? [News]
self.tableDataArr?.append(contentsOf: arr!)
}
DispatchQueue.main.async(execute: {
self.tab?.reloadData()
})
}
}
overridefuncdidReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
```
===========================================================
*5.AFNetWorking,表格方法
extension ViewController : UITableViewDataSource {
functableView(_tableView:UITableView, numberOfRowsInSection section:Int) ->Int{
return dataSource.count
}
functableView(_tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{
letcell = tableView.dequeueReusableCell(withIdentifier:"cell")
cell?.textLabel?.text=dataSource[indexPath.row].title
cell?.detailTextLabel?.text=dataSource[indexPath.row].content
cell?.detailTextLabel?.numberOfLines = 2
returncell!
}
}