Swift-OC网络数据请求包装

2018-05-31  本文已影响0人  YQ_苍穹

首页获取数据

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)

        }

    }

}

上一篇下一篇

猜你喜欢

热点阅读