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

先上效果图



再上源码

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

import Foundation

class 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 UIKit

class 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 UIKit

class 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)
        }
 */
    }

}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值