swift 网络----利用URLSession的Block模式下载多张图片

来源:互联网 发布:点对点网速测试软件 编辑:程序博客网 时间:2024/06/07 17:34

先上效果图



再上源码

1. 对于URLSession做了个简单的封装,用来请求网络数据

import Foundationclass LJDownLoadNetImage: NSObject {    static func request(_ method: String, url: String, callback: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {        let session = URLSession.shared        let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)        request.httpMethod = method        let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in            callback(data, response, error)        })        task.resume()    }}


2. 上面效果图的代码

import UIKitclass TFNetImageViewController: TFBaseViewController, UITableViewDataSource, UITableViewDelegate{    var TFTableView:UITableView!    var titleItemArray = ["姓名","账号","爱好","职业","年薪"]        var imageUrlArray =  ["http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg",                         "http://hangge.com/blog/images/logo.png",                            "https://www.iphonetrain.com/core/res/images/logo.png",                            "http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg",                            "http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];        override func viewDidLoad() {        super.viewDidLoad()        self.setTopNavBarTitle("个人信息")        self.setTopNavBackButton()        self.view.backgroundColor = UIColor.lightGray        self.creatTable()    }        func creatTable(){        TFTableView = UITableView(frame: CGRect(x: 0, y: 64, width: AppWidth, height: AppHeight - 64),style:UITableViewStyle.grouped);        TFTableView.delegate = self;        TFTableView.dataSource = self;        self.view.addSubview(TFTableView);                TFTableView.register(TFNetImageTableViewCell.self, forCellReuseIdentifier: "identtifier")    }        //MARK: UITableViewDataSource    func numberOfSections(in tableView: UITableView) -> Int {        return 1;    }        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {            return 5;    }        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{            return 55;    }        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {        return 10;    }        func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {        return 1;    }    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {          let cellIdentifier : String = "identtifier"        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! TFNetImageTableViewCell                let urlStr = "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-\(indexPath.row + 1).jpg"        //cell.setCellData((titleItemArray[indexPath.row] as NSString) as String , imageUrlStr: imageUrlArray[indexPath.row])                cell.setCellData(titleItemArray[indexPath.row], imageUrlStr: urlStr)        return cell    }        //MARK: UITableViewDelegate    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {                tableView.deselectRow(at: indexPath, animated: true);    } }

cell的代码

import UIKitclass TFNetImageTableViewCell: UITableViewCell {    var titleImage : UIImageView!    var titleLabel : UILabel!        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {        super.init(style: style, reuseIdentifier: reuseIdentifier)                self.creatCell()    }    required init?(coder aDecoder: NSCoder) {        fatalError("init(coder:) has not been implemented")    }        override func setSelected(_ selected: Bool, animated: Bool) {        super.setSelected(selected, animated: animated)        self.selectionStyle = UITableViewCellSelectionStyle.none        // Configure the view for the selected state    }            func creatCell(){       //http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg        //设置label        titleLabel = UILabel(frame: CGRect(x: 60, y: 18, width: 40, height: 14))        titleLabel.textAlignment = NSTextAlignment.center        titleLabel.font = UIFont.systemFont(ofSize: 14.0)        self.contentView.addSubview(titleLabel)                /*           1. 直接加载本地的图片         */                /*        titleImage = UIImageView(frame: CGRect(x: 0, y: 5, width: 40, height: 40))        titleImage.image = UIImage(named: "unicorn.png")        titleImage.backgroundColor = UIColor.red;        self.contentView.addSubview(titleImage)         */                /*           2. 加载网络图片         */                /*        //定义NSURL对象        let url = NSURL.init(string: "http://hangge.com/blog/images/logo.png")        //从网络获取数据流        let data = NSData(contentsOf: url! as URL)                //此处如果data有值的话,才去初始化image        if (data != nil) {            //通过数据流初始化图片            let newImage = UIImage(data: data! as Data)            let  titleImage = UIImageView(frame: CGRect(x: 0, y: 5, width: 40, height: 40))            titleImage.image = newImage            self.contentView.addSubview(titleImage)        }        else{            /*              直接加载本地的图片             */            titleImage = UIImageView(frame: CGRect(x: 0, y: 5, width: 40, height: 40))            titleImage.image = UIImage(named: "unicorn.png")            titleImage.backgroundColor = UIColor.red;            self.contentView.addSubview(titleImage)        } */    }        func setCellData(_ labelNameStr:String,  imageUrlStr:String)    {       titleLabel.text = labelNameStr as String                /*         3. 利用封装的URLSession加载网络图片         */        LJDownLoadNetImage.request("GET", url: imageUrlStr) { (data, response, error) in                        //此处如果data有值的话,才去初始化image            if (data != nil) {                let newImage = UIImage(data: data! as Data)                let  titleImage = UIImageView(frame: CGRect(x: 0, y: 5, width: 40, height: 40))                titleImage.image = newImage                self.contentView.addSubview(titleImage)            }        }                /*        //定义NSURL对象        let url = NSURL.init(string: imageUrlStr)        //从网络获取数据流        let data = NSData(contentsOf: url! as URL)                //此处如果data有值的话,才去初始化image        if (data != nil) {            //通过数据流初始化图片            let newImage = UIImage(data: data! as Data)            let  titleImage = UIImageView(frame: CGRect(x: 0, y: 5, width: 40, height: 40))            titleImage.image = newImage            self.contentView.addSubview(titleImage)        }        else{            /*             直接加载本地的图片             */            titleImage = UIImageView(frame: CGRect(x: 0, y: 5, width: 40, height: 40))            titleImage.image = UIImage(named: "unicorn.png")            titleImage.backgroundColor = UIColor.red;            self.contentView.addSubview(titleImage)        } */    }}



原创粉丝点击