News

作者: 一万个小时_66d9 | 来源:发表于2018-06-01 08:12 被阅读0次

URLHandle

import UIKit

class URLHandle:NSObject{

    //菊花等待指示器

    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)

    }

    //显示菊花

    funcshowIndecatorView(v:UIViewController) {

        ifindicatorView==nil{

            indicatorView=UIActivityIndicatorView(activityIndicatorStyle: .gray)

            indicatorView?.frame=CGRect.init(origin:CGPoint.init(x:scrWidth/2, y:scrHeight/2), size:CGSize(width:30, height:30))

            //设置停止自动隐藏效果

            indicatorView?.hidesWhenStopped=true

        }

        v.view.addSubview(indicatorView!)

        indicatorView?.startAnimating()

    }

    //隐藏菊花

    privatefunchideIndicatoryView() ->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.showIndecatorView(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.hideIndicatoryView()

            }

            //如果服务器错误,给客户提示框,结束执行

            ifletmyError = error {

                print(myError)

                //回到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)

        }

    }

    //

}

相关文章

  • NO NEWS IS GOOD NEWS

    从客户那传来一个噩耗:要求每个表单在保存之后,要在页面上弹一个 “ 保存成功 ” 的对话框。 客户代表志得意满地说...

  • No news is good news

    星云大师说:他一生遭到无数误解,他看报,别人说:和尚也看报?他写字,别人惊讶:和尚也用钢笔?他看时间,别人不满:和...

  • no news is good news

    无事便是福 世间各种福,能享的了清闲才是最大的福吧,不管王公贵族财势骄人,世人奔波忙碌思虑不休,古往今来,真的有几...

  • Good News and Bad News

    An artist asked the gallery owner if there had been any i...

  • Good News And Bad News

    Good News And Bad News 好消息和坏消息 Good news: Two boys went o...

  • List集合转json

    List news = new ArrayList<>();news.add("a");news.add("b"...

  • Idiomatic Colloquialism

    news:No news is good news.没有消息就是好消息。不闻凶信便是吉。Good news goe...

  • 每日新闻 & 每周时评10月9号

    ABC World News , BBC News at One.1010 / World News / Busi...

  • News

    URLHandle import UIKit class URLHandle:NSObject{ //菊花等待...

  • news

    Bookies have slashed the odds of Donald Trump being impea...

网友评论

      本文标题:News

      本文链接:https://www.haomeiwen.com/subject/smkhsftx.html