swift network request URLRequest

Keywords: network JSON Swift Attribute

                             Swift network request data

viewController
import UIKit

class ViewController: UIViewController,UITableViewDataSource,MJRefreshBaseViewDelegate {

//Table attribute
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!) {
    //If it is a drop-down, startNum value is 0
    if refreshView is MJRefreshHeaderView {
        startNum = 0
    }else {
        startNum += 10
    }
    self.requestNetWorkDataAndUpdateUI()
}

//MARK: ------ request network data----------
func requestNetWorkDataAndUpdateUI() {
    //Turn chrysanthemums
    UIApplication.shared.isNetworkActivityIndicatorVisible = true

    //Request network data

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

        //Stop indicator first
        DispatchQueue.main.sync {
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            //Stop the dropdown
            self.mjHeaderView?.endRefreshing()
            //Stop the pull-up control
            self.mjFooterView?.endRefreshing()
        }

        if !success {
            DispatchQueue.main.async {
                let alertVC = UIAlertController(title: nil, message: data as?String, preferredStyle: .alert)
                let confirmBtn = UIAlertAction(title: "Determine", style: .default, handler: nil)
                alertVC .addAction(confirmBtn)
                self.present(alertVC, animated: true, completion: nil)
            }
            return
        }

        //Correct case, load table
        //If startNum is 0, copy the first page of data to the array
        if self.startNum == 0 {
            self.tableDataArr = data as? [News]
        }
        //If it is not 0, splice the data to the back of the previous page
        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!)

    //Initialize drop-down control
    self.mjHeaderView = MJRefreshHeaderView(scrollView: self.table)
    self.mjHeaderView?.delegate = self
    //Initialize pull-up control
    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. Create News file
import UIKit

class News: NSObject {
var title = ""
var time = ""
var src = ""
var pic = ""
var content = ""
var url = ""
var weburl = ""
}
3. Create URLService.swift file
import UIKit

class URLService: NSObject {
func getNewsData(channel:String,startNum:Int,completion:@escaping (Any,Bool) -> Void) {
//Use GET to request data
//1. URL string splicing
var urlStr = "http://api.jisuapi.com/news/get?channel=(channel)&start=(startNum)&num=10&appkey=de394933e1a3e2db"
//2. Transcoding (transcoding Chinese)
urlStr = urlStr.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!
//3. Encapsulate as URL object
let url = URL(string: urlStr)
//4. Encapsulated as URLRequest object (purpose: set request timeout)
let req = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15.0)

    //5.URLSession requests network data / / 6. Start task
    URLSession.shared.dataTask(with: req) { (data, response, error) in
        //If an error occurs
        if error != nil{
            //Call to parameter closure
            completion("Network server error", false)
            return
        }
        //json data analysis
        let jsonData = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)

        //json parsing failure returned error
        if jsonData == nil{
            completion("json Parsing error",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. If you want to implement the pull-down refresh, first import the MJRefresh third-party folder, and you need to create a bridge file. For the specific implementation of importing "MJRefresh.h" in the bridge file, please visit the above code comments

Posted by nickadeemus2002 on Sat, 04 Jan 2020 04:34:15 -0800