swift网络请求 URLRequest

                             Swift网络请求数据

viewController中
import UIKit

class ViewController: UIViewController,UITableViewDataSource,MJRefreshBaseViewDelegate {

//表格属性
var table:UITableView?
var tableDataArr:[News]?

var mjHeaderView:MJRefreshHeaderView?
var mjFooterView:MJRefreshFooterView?

var startNum = 0

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.requestNetWorkDataAndUpdateUI()
}

//MARK: ------MJRefreshBaseViewDelegate ----------

func refreshViewBeginRefreshing(_ refreshView: MJRefreshBaseView!) {
    //如果是下拉,startNum值为0
    if refreshView is MJRefreshHeaderView {
        startNum = 0
    }else {
        startNum += 10
    }
    self.requestNetWorkDataAndUpdateUI()
}

//MARK: ------请求网络数据 ----------
func requestNetWorkDataAndUpdateUI() {
    //转动菊花
    UIApplication.shared.isNetworkActivityIndicatorVisible = true

    //请求网络数据

    let urlService = URLService()
    urlService.getNewsData(channel: "头条", startNum: self.startNum) { (data, success) in

        //先停止指示器
        DispatchQueue.main.sync {
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            //把下拉控件停止
            self.mjHeaderView?.endRefreshing()
            //把上拉控件停止
            self.mjFooterView?.endRefreshing()
        }

        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: nil)
            }
            return
        }

        //正确情况,加载表格
        //如果startNum是0,将第一页数据复制给数组
        if self.startNum == 0 {
            self.tableDataArr = data as? [News]
        }
        //如果不是0,将得到的数据拼接到上一页数据的后面
        else{
            let arr = data as? [News]
            self.tableDataArr?.append(contentsOf: arr!)
        }

        DispatchQueue.main.async(execute: { 
            self.table?.reloadData()
        })
    }

}

override func viewDidLoad() {
    super.viewDidLoad()

    self.table = UITableView(frame: self.view.frame, style: .plain)
    self.table?.dataSource = self
    self.view.addSubview(self.table!)

    //初始化下拉控件
    self.mjHeaderView = MJRefreshHeaderView(scrollView: self.table)
    self.mjHeaderView?.delegate = self
    //初始化上拉控件
    self.mjFooterView = MJRefreshFooterView(scrollView: self.table)
    self.mjFooterView?.delegate = self

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let count = tableDataArr?.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 oneNew = self.tableDataArr![indexPath.row]

    cell?.textLabel?.text = oneNew.title
    cell?.detailTextLabel?.text = oneNew.content
    cell?.textLabel?.numberOfLines = 0

// cell?.detailTextLabel?.numberOfLines = 0

    return cell!
}

}

2.创建News文件
import UIKit

class News: NSObject {
var title = “”
var time = “”
var src = “”
var pic = “”
var content = “”
var url = “”
var weburl = “”
}
3.创建URLService.swift文件
import UIKit

class URLService: NSObject {
func getNewsData(channel:String,startNum:Int,completion:@escaping (Any,Bool) -> Void) {
//使用GET请求数据
//1.网址字符串拼接
var urlStr = “http://api.jisuapi.com/news/get?channel=(channel)&start=(startNum)&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: 15.0)

    //5.URLSession请求网络数据   //6.开启任务
    URLSession.shared.dataTask(with: req) { (data, response, error) in
        //如果发生错误
        if error != nil{
            //参数闭包的调用
            completion("网络服务器错误", false)
            return
        }
        //json数据解析
        let jsonData = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)

        //json解析失败 返回错误
        if jsonData == nil{
            completion("json解析错误",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 {
            completion(msg, false)
            return
        }
        let result = (jsonData as! NSDictionary).value(forKey: "result") as! NSDictionary

        let list = result.value(forKey: "list") as! NSArray

        var newsArr:[News] = []
        for item in list{
            let dic = item as! NSDictionary

            let oneNew = News()
            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.url = dic.value(forKey: "url") as! String
            oneNew.weburl = dic.value(forKey: "weburl") as! String
            newsArr.append(oneNew)
        }
        completion(newsArr, true)
    }.resume()
}

}

4.如果想要实现上下拉刷新,首先导入MJRefresh第三方文件夹,需要创建桥接文件,在桥接文件中导入#import “MJRefresh.h” 具体实现请参观以上代码注释

你可能感兴趣的:(swift网络请求 URLRequest)