Swift 網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求與解析:
1、創(chuàng)建一個(gè)繼承于NSObject的類URLService,在URLService中寫Get請(qǐng)求。定義成一個(gè)方法方便調(diào)用
funcgetNewsData(channel:String,startNum:Int,completion:@escaping(Any,Bool)->(Void)) ->Void{
? ? ? ? // 使用Get請(qǐng)求數(shù)據(jù)
? ? ? ? // (1)網(wǎng)址字符串
? ? ? ? var urlStr = "網(wǎng)址字符串"
? ? ? ? // (2)轉(zhuǎn)碼
? ? ? ? urlStr = urlStr.addingPercentEncoding(withAllowedCharacters:.urlFragmentAllowed)!
? ? ? ? // (3)封裝為URL對(duì)象
? ? ? ? varurl =URL(string: urlStr)
? ? ? ? // (4)封裝為URLRequest對(duì)象
? ? ? ? letreq =URLRequest(url: url!, cachePolicy:.reloadIgnoringCacheData, timeoutInterval:5.0)
? ? ? ? // (5)URLSession請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)
? ? ? ? lettask:URLSessionDataTask=URLSession.shared.dataTask(with: req) { (data, response, error)in
? ? ? ? ? ? // 如果發(fā)生錯(cuò)誤
? ? ? ? ? ? iferror !=nil{
? ? ? ? ? ? ? ? // 參數(shù)閉包的調(diào)用
? ? ? ? ? ? ? ? completion("網(wǎng)絡(luò)服務(wù)器錯(cuò)誤",false)
? ? ? ? ? ? ? ? return
? ? ? ? ? ? }
? ? ? ? ? ? // json數(shù)據(jù)解析
? ? ? ? ? ? let jsonData = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
? ? ? ? ? ? // json數(shù)據(jù)解析失敗,返回錯(cuò)誤
? ? ? ? ? ? ifjsonData ==nil{
? ? ? ? ? ? ? ? completion("網(wǎng)絡(luò)數(shù)據(jù)器錯(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
? ? ? ? ? ? }
// 根據(jù)網(wǎng)址進(jìn)行數(shù)據(jù)解析
// ? ? ? ? ? ?letresult = (jsonDataas!NSDictionary).value(forKey:"result")as!NSDictionary
? // ? ? ? ? ?letlist = result.value(forKey:"list")as!NSArray
? ? ? ? ? ? var newsArr:[NewsModel] = []
? ? ? ? ? ? for item in list{
? ? ? ? ? ? ? ? letdic = itemas!NSDictionary
? ? ? ? ? ? ? ? letoneNew =NewsModel()
// 根據(jù)Model類進(jìn)行賦值
? ? ? ? ? ? ? ? oneNew.title= dic.value(forKey:"title")as!String
? ? ? ? ? ? ? ? newsArr.append(oneNew)
? ? ? ? ? ? }
? ? ? ? ? ? completion(newsArr,true)
}
? ? ? ? // (6)開(kāi)啟任務(wù)
? ? ? ? task.resume()
? ?}
2、創(chuàng)建模型Model類
在類中定義解析出網(wǎng)址中的字段
例:vartitle:String=""
3、在ViewControll
定義表格,對(duì)表格進(jìn)行賦值,把解析出來(lái)的數(shù)據(jù)賦值給cell
var table:UITableView?
vartableDataArr:[NewsModel]?
創(chuàng)建表格
self.table=UITableView(frame:self.view.frame, style: .plain)
? ? ? ? table?.delegate=self
? ? ? ? table?.dataSource=self
? ? ? ? self.view.addSubview(table!)
// MARK:UITableViewDelegate
? ? functableView(_tableView:UITableView, numberOfRowsInSection section:Int) ->Int{
? ? ? ? ifletcount =tableDataArr?.count{
? ? ? ? ? ? returncount
? ? ? ? }
? ? ? ? return0
? ? }
? ? functableView(_tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{
? ? ? ? letidentifier ="cell"
? ? ? ? varcell = tableView.dequeueReusableCell(withIdentifier: identifier)
? ? ? ? ifcell ==nil{
? ? ? ? ? ? cell =UITableViewCell(style: .subtitle, reuseIdentifier: identifier)
// cell的內(nèi)容自動(dòng)換行
//? ? ? ? ? ? cell?.textLabel?.numberOfLines = 0;
//? ? ? ? ? ? cell?.detailTextLabel?.numberOfLines = 0;
// 根據(jù)模型當(dāng)中的數(shù)據(jù),進(jìn)行賦值
? ? ? ? ? ? letoneNew =self.tableDataArr![indexPath.row]
? ? ? ? ? ? cell?.textLabel?.text= oneNew.title
? ? ? ? }
? ? ? ? returncell!
? ? }
// MARK:請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)
? ? funcrequestNetWorkDataAndUpdateUI() ->Void{
? ? ? ? // 轉(zhuǎn)動(dòng)菊花
? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = true
? ? ? ? // 請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)
? ? ? ? leturlService =URLService()
// 調(diào)用URLService中的Get方法
? ? ? ? urlService.getNewsData(channel:"頭條", startNum:self.startNum) { (data, success) -> (Void)in
? ? ? ? ? ? // 先停止指示器
? ? ? ? ? ? DispatchQueue.main.async {
? ? ? ? ? ? ? ? // 停止菊花
? ? ? ? ? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = false
? ? ? ? ? ? }
? ? ? ? ? ? // 錯(cuò)誤情況,提示
? ? ? ? ? ? if!success{
? ? ? ? ? ? ? ? DispatchQueue.main.async{
? ? ? ? ? ? ? ? ? ?// 如果網(wǎng)絡(luò)出錯(cuò),給用戶一個(gè)提示
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? return
? ? ? ? ? ? }
? ? ? ? ? ? // 正確情況,加載表格
? ? ? ? ? ? // 如果startNum是0,將第一頁(yè)數(shù)據(jù)賦值給表格數(shù)據(jù)
? ? ? ? ? ? ifself.startNum==0{
? ? ? ? ? ? ? ? self.tableDataArr= dataas? [NewsModel]
? ? ? ? ? ? }else{? // 如果不是0,將得到的數(shù)據(jù)拼接到表格數(shù)組當(dāng)中
? ? ? ? ? ? ? ? letarr = dataas? [NewsModel]
? ? ? ? ? ? ? ? self.tableDataArr?.append(contentsOf: arr!)
? ? ? ? ? ? }
? ? ? ? ? ? DispatchQueue.main.async {
// 回到主線程刷新表格
? ? ? ? ? ? ? ? self.table?.reloadData()
? ? ? ? ? ? }
? ? ? ? }
? ? }