2018-05-31 請求網(wǎng)絡(luò)數(shù)據(jù)GET/POST

NewsViewController 頁面

import UIKit

let scrWidth = UIScreen.main.bounds.size.width? // 寬度

let scrHeight = UIScreen.main.bounds.size.height? // 高度

// 給UIViewController 類添加擴展

extension UIViewController {

? ? funcshowAlert(msg:String,sec:TimeInterval) {

? ? ? ? // 實例化彈出控制器

? ? ? ? letalertVC =UIAlertController(title:nil, message: msg, preferredStyle: .alert)


? ? ? ? // 從vc 控制器彈出提示控制器

? ? ? ? self.present(alertVC, animated:true, completion:nil)


? ? ? ? // 延時執(zhí)行隱藏操作

? ? ? ? self.perform(#selector(hideAlertVC(sender:)), with: alertVC, afterDelay: sec)


? ? }


? ? @objcfunchideAlertVC(sender:UIAlertController)? {

? ? ? ? sender.dismiss(animated:true, completion:nil)

? ? }

}

class NewsViewController: UIViewController,UITextFieldDelegate {


? ? varnewsTF:UITextField?? // 菜譜輸入框

? ? varsearchBtn:UIButton?? // 搜索按鈕


? ? overridefuncviewDidLoad() {

? ? ? ? super.viewDidLoad()

? ? ? ? // 設(shè)置背景顏色

? ? ? ? self.view.backgroundColor = UIColor.white


? ? ? ? newsTF=UITextField(frame:CGRect(x:0, y:0, width:200, height:50))

? ? ? ? newsTF?.center=CGPoint(x:scrWidth/2, y:200)

? ? ? ? newsTF?.borderStyle= .line

? ? ? ? newsTF?.placeholder="請輸入查詢的新聞"

?? ? ? newsTF?.textColor = UIColor.blue

? ? ? ? newsTF?.textAlignment= .center

? ? ? ? newsTF?.clearButtonMode = .whileEditing

? ? ? ? newsTF?.delegate=self

? ? ? ? self.view.addSubview(newsTF!)


? ? ? ? searchBtn=UIButton(frame:CGRect(x:0, y:0, width:100, height:50))

? ? ? ? searchBtn?.center=CGPoint(x:scrWidth/2, y:300)

? ? ? ? searchBtn?.setTitle("點擊查詢", for: .normal)

? ? ? ? searchBtn?.backgroundColor = UIColor.yellow

? ? ? ? searchBtn?.setTitleColor(UIColor.black, for: .normal)

? ? ? ? searchBtn?.addTarget(self, action:#selector(btnDidPress(sender:)), for: .touchUpInside)

? ? ? ? self.view.addSubview(searchBtn!)

? ? }

? ? @objcfuncbtnDidPress(sender:UIButton) {

? ? ? ? if(newsTF?.text?.isEmpty)! {

? ? ? ? self.showAlert(msg:"信息不可為空", sec:2.5)

? ? ? ? return

? ? ? ? }


? ? ? ? // 實例化控制器對象

? ? ? ? let resultVC = NewsResultViewController()


? ? ? ? // 傳遞數(shù)據(jù)

? ? ? ? resultVC.passString=newsTF!.text!


? ? ? ? self.navigationController?.pushViewController(resultVC, animated:true)

? ? }


? ? // MARK -----------UITextFiledDelegate -------

? ? // 點擊return 隱藏鍵盤

? ? functextFieldShouldReturn(_textField:UITextField) ->Bool{


? ? ? ? // 放棄第一響應(yīng)這

? ? ? ? textField.resignFirstResponder()

? ? ? ? return true

? ? }


? ? // ------ touches Method ------

? ? overridefunctouchesEnded(_touches:Set, with event:UIEvent?) {

? ? ? ? super.touchesEnded(touches, with: event)

? ? ? ? newsTF?.resignFirstResponder()

? ? ? ? self.view.endEditing(true)

? ? }


}


NewsResultViewController 頁面

import UIKit

class NewsResultViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {


? ? vartable:UITableView?

? ? vartableData:[News]?


? ? varpassString:String=""


? ? overridefuncviewDidLoad() {

? ? ? ? super.viewDidLoad()


? ? ? ? self.view.backgroundColor = UIColor.white

? ? ? ? self.navigationItem.title = "\"\(passString)\"的搜索結(jié)果"


? ? ? ? table=UITableView(frame:CGRect(x:0, y:0, width:scrWidth, height:scrHeight),style: .plain)

? ? ? ? table?.rowHeight=260.0

? ? ? ? table?.delegate=self

? ? ? ? table?.dataSource=self

? ? ? ? self.view.addSubview(table!)



? ? }

? ? overridefuncviewWillAppear(_animated:Bool) {


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

? ? ? ? leturlSer =URLService()

? ? ? ? urlSer.getNewsBySearch(search:self.passString, vc:self) { (data, success)in

? ? ? ? ? ? if!success {

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }

? ? ? ? ? ? print(data)

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

? ? ? ? ? ? DispatchQueue.main.async {

? ? ? ? ? ? ? ? self.table?.reloadData()

? ? ? ? ? ? }


? ? ? ? }


? ? }


? ? functableView(_tableView:UITableView, numberOfRowsInSection section:Int) ->Int{

? ? ? ? ifletcount =tableData?.count{

? ? ? ? ? ? returncount

? ? ? ? }

? ? ? ? return0

? ? }


? ? functableView(_tableView:UITableView, cellForRowAt indexPath:IndexPath) ->UITableViewCell{

? ? ? ? letidentifier ="cell"

? ? ? ? varcell = tableView.dequeueReusableCell(withIdentifier: identifier)

? ? ? ? ifcell ==nil{

? ? ? ? ? ? cell =UITableViewCell.init(style: .value1, reuseIdentifier: identifier)

? ? ? ? ? ? letlab =UILabel(frame:CGRect(x:0, y:0, width:scrWidth, height:30))

? ? ? ? ? ? cell?.addSubview(lab)


? ? ? ? ? ? letlab2 =UILabel(frame:CGRect(x:0, y:40, width:scrWidth, height:30))

? ? ? ? ? ? cell?.addSubview(lab2)


? ? ? ? ? ? letlab3 =UILabel(frame:CGRect(x:0, y:80, width:scrWidth, height:80))

? ? ? ? ? ? lab3.numberOfLines=2

? ? ? ? ? ? cell?.addSubview(lab3)


? ? ? ? ? ? letone =self.tableData![indexPath.row]as?News

? ? ? ? ? ? lab.text= one?.city

? ? ? ? ? ? lab2.text= one?.address


? ? ? ? ? ? lab3.text= one?.content

? ? ? ? }


? ? ? ? returncell!

? ? }


}

Model類:

創(chuàng)建一些屬性:比如

import UIKit

classNews:NSObject{


? ? varprovince:String?

? ? vartown:String?

? ? varcity:String?

? ? varaddress:String?

? ? varnum:Int?

? ? varcontent:String?


}

URLSeivice類:

import UIKit

classURLService:NSObject{


? ? // 請求搜索的數(shù)據(jù)

? ? funcgetNewsBySearch(search:String,vc:UIViewController,completion:@escaping(Any,Bool) ->Void) {

? ? ? ? // 判斷無網(wǎng)狀態(tài)

? ? ? ? if Reachability.forLocalWiFi().currentReachabilityStatus() == NotReachable && Reachability.forInternetConnection().currentReachabilityStatus() == NotReachable? {

? ? ? ? ? ? vc.showAlert(msg:"網(wǎng)絡(luò)錯誤,請檢查網(wǎng)絡(luò)", sec:2.5)

? ? ? ? ? ? completion("error",false)

? ? ? ? ? ? return

? ? ? ? }


? ? ? ? // (2) 狀態(tài)欄中的菊花開始轉(zhuǎn)

? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = true


? ? ? ? // (3) 網(wǎng)址字符串封裝

? ? ? ? let url = URL.init(string: "http://api.jisuapi.com/illegaladdr/city")



? ? ? ? // 創(chuàng)建請求對象

? ? ? ? varreq =URLRequest.init(url: url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval:15.0)


? ? ? ? // 設(shè)置請求方式為POST

? ? ? ? req.httpMethod="POST"


? ? ? ? // 將所有的參數(shù)拼接成一個字符串

? ? ? ? let str = "city=\(search)&num=10&appkey=de394933e1a3e2db"


? ? ? ? // 設(shè)置請求對象的請求體

? ? ? ? req.httpBody= str.data(using: .utf8)


? ? ? ? //(5) 會話對象請求網(wǎng)絡(luò)數(shù)據(jù)

? ? ? ? URLSession.shared.dataTask(with: req) { (data:Data?, success:URLResponse?, error:Error?)in

? ? ? ? ? ? // 回到UI主線程停止菊花

? ? ? ? ? ? DispatchQueue.main.async {

? ? ? ? ? ? ? ? UIApplication.shared.isNetworkActivityIndicatorVisible = false

? ? ? ? ? ? }


? ? ? ? ? ? // 如果服務(wù)器連接失敗

? ? ? ? ? ? iferror !=? nil{

? ? ? ? ? ? ? ? DispatchQueue.main.async{

? ? ? ? ? ? ? ? ? ? vc.showAlert(msg:"服務(wù)器連接失敗", sec:2.5)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? // JSON解析

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

? ? ? ? ? ? ifjsonData ==nil{

? ? ? ? ? ? ? ? DispatchQueue.main.async{

? ? ? ? ? ? ? ? ? ? vc.showAlert(msg:"網(wǎng)絡(luò)數(shù)據(jù)錯誤", sec:2.5)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }

? ? ? ? ? ? // 如果正確將json解析數(shù)據(jù)回傳個controller

? ? ? ? ? ? letjsonDic = jsonDataas!NSDictionary

? ? ? ? ? ? letstatus = jsonDic.value(forKeyPath:"status")as!NSString


? ? ? ? ? ? letmsg = jsonDic.value(forKeyPath:"msg")as!String


? ? ? ? ? ? ifstatus.intValue!=0{

? ? ? ? ? ? ? ? DispatchQueue.main.async{

? ? ? ? ? ? ? ? ? ? vc.showAlert(msg: msg, sec:2.5)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? // 得到j(luò)son數(shù)據(jù)中result字段對應(yīng)的字典

? ? ? ? ? ? letresultDic = jsonDic.value(forKeyPath:"result")as!NSArray


? ? ? ? ? ? // Model封裝

? ? ? ? ? ? varmodelArr:[News] = []

? ? ? ? ? ? // 遍歷數(shù)組中的每個字典

? ? ? ? ? ? foriteminresultDic {

? ? ? ? ? ? ? ? letitemDic = itemas!NSDictionary

? ? ? ? ? ? ? ? letone =News()

? ? ? ? ? ? ? ? one.province= itemDic.value(forKey:"province")as?String

? ? ? ? ? ? ? ? one.city= itemDic.value(forKey:"city")as?String

? ? ? ? ? ? ? ? one.town= itemDic.value(forKey:"town")as?String

? ? ? ? ? ? ? ? one.address= itemDic.value(forKey:"address")as?String

? ? ? ? ? ? ? ? one.num= itemDic.value(forKey:"num")as?Int

? ? ? ? ? ? ? ? one.content= itemDic.value(forKey:"content")as?String

? ? ? ? ? ? ? ? modelArr.append(one)

? ? ? ? ? ? }

? ? ? ? ? ? completion(modelArr,true)

? ? ? ? }.resume()


? ? }



}

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

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

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