// 获取网络数据
funcshowData(title:String) -> Void{
UIApplication.shared.isNetworkActivityIndicatorVisible = true
//<1>将请求网址字符串做成URL对象
let url = URL.init(string: "http://buluokes.huimor.com/api")
//<2>创建请求对象,同时设置缓存策略及超时时长
varreq =URLRequest.init(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 8.0)
req.httpMethod="POST"
let paramStr = "method=app.news.getarticlelist&class_id=\(title)&page=1&user_token="
//将参数字符串转换为二进制Data数据
letparamData = paramStr.data(using: .utf8)
//将参数二进制数据放入请求体中
req.httpBody= paramData
lettask =URLSession.shared.dataTask(with: req) { (data, response, error)in
// 停止等待指示器
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.mjHeader?.endRefreshing()
}
iferror !=nil
{
DispatchQueue.main.async {
self.view.showMB(msg:"网络连接超时")
}
return
}
letjsonData =try?JSONSerialization.jsonObject(with: data!, options: .allowFragments)
letjsonDic = jsonDataas!NSDictionary
letjsonDataDic = jsonDic["data"]as!NSDictionary
letjsonArr = jsonDataDic["list"]as!NSArray
self.tableData= []
foroneDicinjsonArr
{
letmodel =Model.init()
letdic = oneDicas!NSDictionary
// model.setValuesForKeys(oneDic as! [String:String])
model.title= dic["title"]as!String
model.author= dic["author"]as!String
model.img= dic["img"]as!String
self.tableData?.append(model)
}
DispatchQueue.main.async {
self.table?.reloadData()
self.mjHeader?.endRefreshing()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
// 运行
task.resume()
}
// 触发事件
@objcfuncSelectorSegTitile(seg:UISegmentedControl) ->Void{
self.showData(title: "\(seg.selectedSegmentIndex+1)")
}
}
网友评论