// 首先网络请求首先得去inof.plist文件中添加Allow Arbitrary Loads in Web Content允许网络请求
// 然后创建一个继承与uiviewcontroller的类 和 继承与nsobject的model类
// 接下来就是代码了
// 一. 在你新建的继承viewcontroller类里面 view
class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
var tableview:UITableView?
var tabArr:[SwiftMoel]?
// MARK : pragam mark =============== 创建表格 ===============
override func viewDidLoad() {
super.viewDidLoad()
self.tableview = UITableView (frame: self.view.frame, style: .plain)
self.tableview?.delegate = self
self.tableview?.dataSource = self
self.view .addSubview(tableview!)
}
// MARK: pragam mark ================ 调用请求的数据 ===============
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.requestNetWorlDataAndUpdata()
}
// MARK : pragam mark =============== 实现代理协议方法 ===============
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let count = tabArr?.count {
return count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "cell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if cell == nil{
cell = UITableViewCell(style: .subtitle, reuseIdentifier: identifier)
}
let dic = self.tabArr![indexPath.row]
cell?.textLabel?.text = dic.title
cell?.detailTextLabel?.text = dic.content
cell?.textLabel?.numberOfLines = 0
cell?.detailTextLabel?.numberOfLines = 0
return cell!
}
func requestNetWorlDataAndUpdata() -> Void {
// 转动菊花
UIApplication.shared.isNetworkActivityIndicatorVisible = true
// 请求网络数据
let urlService = UIheadle()
urlService.getNewsData(channel: "头条", startSum: 0) { (data, success) in
// 停止指示器
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// 如果不成功
if !success{
// 异步执行
DispatchQueue.main.async {
let alertVC = UIAlertController(title: nil, message: data as? String, preferredStyle: .alert)
let confirmBtn = UIAlertAction(title: "确定", style: .default, handler: nil)
alertVC.addAction(confirmBtn)
self.present(alertVC, animated: true, completion: {
})
}
return
}
self.tabArr = data as? [SwiftMoel]
DispatchQueue.main.async {
self.tableview?.reloadData()
}
}
}
}
// 二. 再次创建一个继承nsobject的类做model ,model中写一些的属性名
class SwiftMoel: NSObject {
var time:String = ""
var title:String = ""
var pic:String = ""
var content:String = ""
var weburl:String = ""
}
// 三 .在新建一个继承与nsobject的类 做 controller
class UIheadle: NSObject {
func getNewsData(channel:String,startSum:Int,complation:@escaping (Any,Bool) -> Void) -> Void {
// get 请求网络数据
// (1) 网址字符串拼接
var urlStr = "http://api.jisuapi.com/news/get?channel=\(channel)&start=\(startSum)&num=10&appkey=de394933e1a3e2db"
// (2) 转码
urlStr = urlStr.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!
// (3) 分装为URL对象
let url = URL(string: urlStr)
// (4) 分装为urlrequest对象
let req = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10.0)
// (5) 使用urlsession请求网络数据
let task:URLSessionDataTask = URLSession.shared.dataTask(with: req) { (data, response, error) in
// 如果发生错误
if error != nil{
// 参数闭包的调用
complation("网络服务错误",false)
return
}
// json 数据解析
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
// json 解析失败 返回错误
if jsonData == nil{
complation("网络数据错误",false)
return
}
let status = (jsonData as! NSDictionary) .value(forKey: "status")as! String
let msg = (jsonData as! NSDictionary).value(forKey: "msg") as! String
if Int(status)! != 0{
complation(msg,false)
return
}
let result = (jsonData as! NSDictionary).value(forKey: "result") as! NSDictionary
let list = (result.value(forKey: "list") as! NSArray)
var arr:[SwiftMoel] = []
for item in list{
let dic = (item as! NSDictionary)
let oneNew = SwiftMoel()
oneNew.title = dic.value(forKey: "title") as! String
oneNew.content = dic.value(forKey: "content") as! String
oneNew.time = dic.value(forKey: "time") as! String
oneNew.pic = dic.value(forKey: "pic") as! String
oneNew.weburl = dic.value(forKey: "weburl") as! String
arr.append(oneNew)
}
complation(arr,true)
}
// (6)开启任务
task .resume()
}
}