Swift-OC網絡數據請求包裝

首頁獲取數據

class NewsListViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {


? ? vartableDataArr:[Any]?? //用于給表格賦值于的數組

? ? vartable:UITableView?? ? //表格視圖



? ? overridefuncviewDidLoad() {

? ? ? ? super.viewDidLoad()

? ? ? ? self.table=UITableView(frame:CGRect.init(origin:SCR_Origin, size:SCR_Size), style: .plain)

? ? ? ? self.table?.delegate=self

? ? ? ? self.table?.dataSource=self

? ? ? ? self.table?.rowHeight=65

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


? ? }


? ? overridefuncviewWillAppear(_animated:Bool) {


? ? ? ? leturlHandle =URLHandle()

? ? ? ? urlHandle.getNewsData(channel:"頭條", start:0, vc:self) { (jsonData:Any, success:Bool)in


? ? ? ? ? ? ifsuccess ==false{

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }

? ? ? ? ? ? print(jsonData)

? ? ? ? ? ? // 給表格數組賦值,刷新表格

? ? ? ? ? ? self.tableDataArr= jsonDataas? [Any]

? ? ? ? ? ? // 回UI主線程刷新表格

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

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

? ? ? ? ? ? }

? ? ? ? }


? ? }


? ? // MARK: - ------------------ UITableViewDataSource -----------

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


? ? ? ? ifletcount =self.tableDataArr?.count{

? ? ? ? ? ? returncount

? ? ? ? }

? ? ? ? return0

? ? }

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

? ? ? ? letcellIdentifier ="cell"

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

? ? ? ? ifcell ==nil{

? ? ? ? ? ? cell =UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)

? ? ? ? }


? ? ? ? //得到每個cell對應的字典

? ? ? ? letcellDic =self.tableDataArr![indexPath.row]as!NSDictionary


? ? ? ? cell?.textLabel?.text= cellDic["title"]as?String



? ? ? ? returncell!


? ? }

}


網絡數據請求(GET)封裝

classURLHandle:NSObject{


? ? //菊花等待指示器

? ? private var indicatorView:UIActivityIndicatorView?


? ? //私有方法,判斷有無網絡連接

? ? privatefuncconnectNetWork(vc:UIViewController) ->Bool{

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

? ? ? ? ? ? self.showAlert(message:"網絡連接失敗,請檢查網絡", vc: vc)

? ? ? ? ? ? returnfalse

? ? ? ? }

? ? ? ? return true

? ? }


? ? //顯示提示框

? ? privatefuncshowAlert(message:String,vc:UIViewController) ->Void{

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

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

? ? ? ? //彈出

? ? ? ? vc.present(alertCtl, animated:true, completion:nil)

? ? ? ? //2.5秒后自動消失

? ? ? ? self.perform(#selector(hideAlertVC(sender:)), with: alertCtl, afterDelay:2.5)

? ? }


? ? //隱藏提示框

? ? @objcfunchideAlertVC(sender:UIAlertController) ->Void{

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

? ? }


? ? //顯示菊花

? ? privatefuncshowIndicationView(v:UIViewController) {

? ? ? ? ifindicatorView==nil{

? ? ? ? ? ? indicatorView=UIActivityIndicatorView(activityIndicatorStyle: .gray)

? ? ? ? ? ? //設置位置

? ? ? ? ? ? indicatorView?.frame=CGRect(origin:CGPoint(x:SCR_Width/2-10, y:SCR_Height/2-10), size:CGSize(width:30, height:30))

? ? ? ? ? ? //設置停止自動隱藏效果

? ? ? ? ? ? indicatorView?.hidesWhenStopped=true

? ? ? ? }

? ? ? ? v.view.addSubview(indicatorView!)

? ? ? ? indicatorView?.startAnimating()

? ? }


? ? //隱藏菊花

? ? privatefunchideIndicatorView() ->Void{

? ? ? ? if indicatorView != nil && (indicatorView?.isAnimating)! {

? ? ? ? ? ? indicatorView?.startAnimating()

? ? ? ? ? ? indicatorView?.removeFromSuperview()

? ? ? ? ? ? indicatorView=nil

? ? ? ? }

? ? }


? ? // 私有方法,使用GET請求數據

? ? privatefuncGET(url:String,paramDic:[String:String]?,vc:UIViewController,pass:@escaping(Any,Bool)->Void) {


? ? ? ? //判斷沒有網絡連接,直接跳出方法調用

? ? ? ? if!self.connectNetWork(vc: vc) {

? ? ? ? ? ? pass("error",false)? //調用閉包,返回數據

? ? ? ? ? ? return

? ? ? ? }


? ? ? ? //開始轉動菊花

? ? ? ? self.showIndicationView(v: vc)


? ? ? ? //須要將所有的參數拼接到網址字符串上

? ? ? ? varurlStr = url

? ? ? ? ifletpDic = paramDic {

? ? ? ? ? ? //拼接?

? ? ? ? ? ? urlStr.append("?")

? ? ? ? ? ? //遍歷參數再點,將鍵值對拼接到字符串上

? ? ? ? ? ? for(key,value)inpDic {

? ? ? ? ? ? ? ? urlStr.append("\(key)=\(value)&")

? ? ? ? ? ? }

? ? ? ? ? ? //去掉最后一個無用的&

? ? ? ? ? ? urlStr.remove(at: urlStr.index(before: urlStr.endIndex))

? ? ? ? ? ? //如果帶漢字,做轉碼處理

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

? ? ? ? }


? ? ? ? //將字符串轉換為url

? ? ? ? letMURL =URL.init(string: urlStr)

? ? ? ? //將URL封裝為Request對象

? ? ? ? letreq =URLRequest(url: MURL!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval:10.0)


? ? ? ? //網絡會話對象,請求網絡數據

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

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

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

? ? ? ? ? ? ? ? self.hideIndicatorView()

? ? ? ? ? ? }


? ? ? ? ? ? //如果服務器錯誤給客戶提示,結束執行

? ? ? ? ? ? iflet_= error {

? ? ? ? ? ? ? ? //回到UI主線程給客戶彈框提示

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

? ? ? ? ? ? ? ? ? ? self.showAlert(message:"服務器連接超時", vc: vc)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? pass("error",false)? //調用閉包,返回數據

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? //JSON解析

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


? ? ? ? ? ? ifjsonData ==nil{

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

? ? ? ? ? ? ? ? ? ? self.showAlert(message:"網絡數據錯誤", vc: vc)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? pass("error",false)

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }

? ? ? ? ? ? pass(jsonData!,true)


? ? ? ? }.resume()


? ? }

? ? // 私有方法,使用POST請求數據

? ? privatefuncPOST(url:String,paramDic:[String:String],vc:UIViewController,pass:(Any,Bool)->Void) {


? ? }


? ? // 接口,用于獲取新聞數據

? ? publicfuncgetNewsData(channel:String,start:Int,vc:UIViewController,completion:@escaping(Any,Bool)->Void) {

? ? ? ? //請求網址字符串

? ? ? ? let url = "http://api.jisuapi.com/news/get"

? ? ? ? // 將請求參數做成字典

? ? ? ? letparamDic = ["channel":channel,

? ? ? ? ? ? ? ? ? ? ? ? "start":"\(start)",

? ? ? ? ? ? ? ? ? ? ? ? "num":"20",

? ? ? ? ? ? ? ? ? ? ? ? "appkey":"de394933e1a3e2db"]

? ? ? ? //使用get請求網絡數據

? ? ? ? self.GET(url: url, paramDic: paramDic, vc: vc) { (jsonData, success)in


? ? ? ? ? ? if!success {

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

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }

?? ? ? ? ? //獲取status字段,判斷值不為0,表示失敗,給客戶提示

? ? ? ? ? ? letstatus = (jsonDataas!NSDictionary).value(forKey:"status")as!NSString


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

? ? ? ? ? ? ? ? letmsg = (jsonDataas!NSDictionary).value(forKey:"msg")as!String

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

? ? ? ? ? ? ? ? ? ? self.showAlert(message: msg, vc: vc)

? ? ? ? ? ? ? ? }

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

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }


? ? ? ? ? ? //獲取result字典

? ? ? ? ? ? letresultDic = (jsonDataas!NSDictionary).value(forKey:"result")as!NSDictionary

? ? ? ? ? ? //獲取result字典中的list數組

? ? ? ? ? ? letlistArr = resultDic.value(forKey:"list")as!NSArray

? ? ? ? ? ? //

? ? ? ? ? ? completion(listArr,true)

? ? ? ? }

? ? }


? ? //請求學生名單數據

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

? ? ? ? //網址字符串

? ? ? ? let urlStr = "http:127.0.0.1/Students.json"

? ? ? ? self.GET(url: urlStr, paramDic:nil, vc: vc) { (data, success)in

? ? ? ? ? ? if!success {

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

? ? ? ? ? ? ? ? return

? ? ? ? ? ? }

? ? ? ? ? ? completion(data,true)

? ? ? ? }


? ? }


}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容