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)
}
}
//
}