網(wǎng)絡(luò)請(qǐng)求

1.在新聞?lì)愔卸x屬性

```

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:----------請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)

? ? funcrequestData() ->Void{


? ? ? ? letURLM =URLModel()

? ? ? ? URLM.getNewsData(channel:"頭條", startNum:10) { (data, success)in


? ? ? ? ? ? //錯(cuò)誤情況

? ? ? ? ? ? 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

? ? ? ? ? ? }


? ? ? ? ? ? //正確情況,數(shù)據(jù)加載到表格上

? ? ? ? ? ? self.tabDataArr= dataas? [News]

? ? ? ? ? ? //刷新表格

? ? ? ? ? ? DispatchQueue.main.async(execute: {

? ? ? ? ? ? ? ? self.tab?.reloadData()

? ? ? ? ? ? })

? ? ? ? }


? ? }






? ? overridefuncdidReceiveMemoryWarning() {

? ? ? ? super.didReceiveMemoryWarning()

? ? ? ? // Dispose of any resources that can be recreated.

? ? }

}

````



3.在Model離封裝網(wǎng)絡(luò)請(qǐng)求

```

import UIKit

classURLModel:NSObject{


? ? funcgetNewsData(channel:String,startNum:Int,completion:@escaping(Any,Bool)->Void) ->Void{


? ? ? ? //把參數(shù)拼接到網(wǎng)址字符串

? ? ? ? var urlStr = "http://api.jisuapi.com/news/get?channel=\(channel)&start=\(startNum)&num=10&appkey=de394933e1a3e2db"

? ? ? ? //漢字進(jìn)行轉(zhuǎn)碼

? ? ? ? urlStr = urlStr.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlFragmentAllowed)!

? ? ? ? //封裝URL對(duì)象

? ? ? ? leturl =URL(string: urlStr)

? ? ? ? //封裝為URLRequest對(duì)象

? ? ? ? letreq =URLRequest(url: url!, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval:5.0)

? ? ? ? //網(wǎng)絡(luò)請(qǐng)求

? ? ? ? lettask:URLSessionDataTask=URLSession.shared.dataTask(with: req) { (data, respons, error)in


? ? ? ? ? ? //錯(cuò)誤判斷

? ? ? ? ? ? iferror !=nil{

? ? ? ? ? ? ? ? //參數(shù)閉包調(diào)用

? ? ? ? ? ? ? ? completion("網(wǎng)絡(luò)錯(cuò)誤",false)

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? //json數(shù)據(jù)解析

? ? ? ? ? ? letjsonData =try?JSONSerialization.jsonObject(with: data!, options: .allowFragments)




? ? ? ? ? ? //如果解析失敗,返回錯(cuò)誤信息

? ? ? ? ? ? ifjsonData ==nil{

? ? ? ? ? ? ? ? completion("網(wǎng)絡(luò)錯(cuò)誤",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)

? ? ? ? }

? ? ? ? //開啟任務(wù)

? ? ? ? task.resume()


? ? }


}


```


===================================================================

*4上下拉刷新

```

import UIKit

class ViewController: UIViewController,UITableViewDataSource,MJRefreshBaseViewDelegate {


? ? //表格屬性

? ? var tab:UITableView?


? ? vartableDataArr : [News]?


? ? varMJHeaderView :MJRefreshHeaderView?//下拉刷新控件

? ? varMJFooterView :MJRefreshFooterView?//上拉加載控件


? ? //記錄當(dāng)前的頁碼

? ? 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協(xié)議方法

? ? funcrefreshViewBeginRefreshing(_refreshView:MJRefreshBaseView!) {


? ? ? ? //如果是下拉,startNum置為0

? ? ? ? ifrefreshViewisMJRefreshHeaderView{

? ? ? ? ? ? startNum=0

? ? ? ? }else{

? ? ? ? ? ? //如果是上拉控件,讓startNum10個(gè)10個(gè)的添加

? ? ? ? ? ? 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!)


? ? ? ? //實(shí)例化刷新控件

? ? ? ? self.MJHeaderView = MJRefreshHeaderView(scrollView: self.tab!)

? ? ? ? self.MJHeaderView?.delegate = self


? ? ? ? //實(shí)例化上拉刷新控件

? ? ? ? self.MJFooterView = MJRefreshFooterView(scrollView: self.tab!)

? ? ? ? self.MJFooterView?.delegate = self

? ? }


? ? //MARK:請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)

? ? funcrequestNetWorkDataAndUpdataUI() ->Void{

? ? ? ? //轉(zhuǎn)動(dòng)菊花

? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = true



? ? ? ? //請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)

? ? ? ? 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()

? ? ? ? ? ? })

? ? ? ? ? ? //錯(cuò)誤情況,提示

? ? ? ? ? ? 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,將第一頁數(shù)據(jù)賦值給表格數(shù)組

? ? ? ? ? ? ifself.startNum==0{

? ? ? ? ? ? ? ? self.tableDataArr= dataas? [News]

? ? ? ? ? ? }else{// 如果不是第一頁,將得到的數(shù)據(jù)拼接到表格數(shù)組中

? ? ? ? ? ? ? ? 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!

? ? }



}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容