//网络请求
//<1>拼接字符串
let UrlStr = "http://py.cmshop.net/tPyshNewnoticController.do?godongtai2&style2=\(titleIndex)"
//<2>转换成URL地址
let url = URL.init(string: UrlStr)
//<3>请求对象,并设置缓存策略和超时延长
let req = URLRequest.init(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 8.0)
//<4>连接服务器
let task = URLSession.shared.dataTask(with: req) { (data, response, error) in
//回到UI主线程停止指示器
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.mjHeader?.endRefreshing()
}
//如果服务器连接失败或超时
if error != nil{
DispatchQueue.main.async {
self.view.showMBAlert(msg: "服务器错误")
}
return
}
//如果连接服务器成功,将二进制转换为数组或字符串
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
//如果转换失败
if jsonData == nil{
DispatchQueue.main.async {
self.view.showMBAlert(msg: "网络数据错误")
}
return
}
//如果转换成功,将数据转换为字典
let jsonDic = jsonData! as! NSDictionary
let resultcode = jsonDic["resultcode"]as! String
//获取resultcode值
if resultcode != "0"{
let errmsg = jsonDic["errmsg"]as! String
//如果resultcode值不为0,表示有错误发生,给客户提示
DispatchQueue.main.async {
self.view.showMBAlert(msg: errmsg)
}
return
}
let dataArr = jsonDic["data"]as![[String:Any]]
self.tableDeta = News.createNEWSArray(arr: dataArr)
//回到主线程刷新表格
DispatchQueue.main.async {
self.table?.reloadData()
}
}
task.resume()
}
self.webView=WKWebView.init(frame:CGRect.init(x: 0, y: 64, width:scrW, height:scrH-64))
self.view.addSubview(self.webView!)
ifletnews =self.passNews{
leturl =URL.init(string: news.txturl)
letreq =URLRequest.init(url: url!)
//加载网页
self.webView?.load(req)
}else{
self.view.showMBAlert(msg:"数据错误")
}