IOS swift UICollectionView 网络请求

// (1) 在view中创建controlllerview 并且新建一个继承controlllerviewcell的类 两个继承nsobject类一个做model一个做请求数据的类

import UIKit

 

class ViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{

   

    var readID = "readID"

    

    var flowlayout = UICollectionViewFlowLayout()

    var collection: UICollectionView?

    var collecArr:[SwiftModel]?

//    var collecArr = ["3","1","2"]

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // 设置网格的大小

        flowlayout.itemSize = CGSize(width:self.view.frame.size.width/4, height: 100)

        //设置最小行间距

        flowlayout.minimumLineSpacing = 1

        

        //设置最小列间距

        flowlayout.minimumInteritemSpacing = 40

        

        //设置分区缩进量

        flowlayout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 20, right: 10)

        

 

        // 设置滚动方向

        flowlayout.scrollDirection = UICollectionViewScrollDirection.vertical

        

        // 网格对象

        collection = UICollectionView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) , collectionViewLayout: flowlayout)

        // 设置代理协议

        collection?.delegate = self

        collection?.dataSource = self

        collection?.backgroundColor = UIColor.blue

        collection?.register(NewsCollectionViewCell  .self, forCellWithReuseIdentifier: readID)

 

        // 添加网格

        self.view .addSubview(collection!)

        

    }

// 实现网格的协议代理

    func numberOfSections(in collectionView: UICollectionView) -> Int {

        return 4

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

//        return collecArr.count

        return 6

    }

    

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // 重用cell

        let cell:NewsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: readID, for: indexPath) as! NewsCollectionViewCell

        

        if self.collecArr != nil{

            let dic = self.collecArr![indexPath.item]

 

            cell.titlelabel?.text = dic.title

        }

        

        

        

        return cell

        

    }

   

 

    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

 

        self.requestNetWorlDataAndUpdata()

    }

    func requestNetWorlDataAndUpdata() -> Void {

        // 转动菊花

        UIApplication.shared.isNetworkActivityIndicatorVisible = true

        

        // 请求网络数据

        let urlService = Network()

        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.collecArr = data as? [SwiftModel]

            print(self.collecArr)

            DispatchQueue.main.async {

                self.collection?.reloadData()

            }

        }

    }

    }

(2)  model里的代码

 

class SwiftModel: NSObject {

    var time:String = ""

    var title:String = ""

    var pic:String = ""

    var content:String = ""

    var weburl:String = ""

}

(3) 请求数据

 

import UIKit

 

class Network: 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:[SwiftModel] = []

            

            for item in list{

                let dic = (item as! NSDictionary)

                let oneNew = SwiftModel()

                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

                print(oneNew.title)

                arr.append(oneNew)

            }

            complation(arr,true)

            

            

        }

        // (6)开启任务

        task .resume()

        

        

    }

}

(7) controllerviewcell中的代码

import UIKit

 

class NewsCollectionViewCell: UICollectionViewCell {

    // 创建两个label

    var  titlelabel:UILabel?

    var handlabel:UILabel?

    override init(frame: CGRect) {

        super .init(frame: frame)

        self.titlelabel = UILabel()

        self.addSubview(titlelabel!)

        self.handlabel = UILabel()

        self.addSubview(handlabel!)

        setTitle()

        sethand()

    }

    func setTitle(){

        self.titlelabel?.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: 20)

        self.titlelabel?.font = UIFont .systemFont(ofSize: 14.0)

        self.titlelabel?.backgroundColor = UIColor.red

        self.titlelabel?.numberOfLines = 0

    }

    func sethand()  {

        self.handlabel?.frame = CGRect(x: 0, y: 20, width: self.frame.size.width, height: 80)

        self.handlabel?.font = UIFont .systemFont(ofSize: 12.0)

        self.handlabel?.backgroundColor = UIColor.green

        self.handlabel?.numberOfLines = 0

    }

    required init?(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值