Swift网络请求,数据模型,图片缓存,自动布局,上拉刷新下拉加载

来源:互联网 发布:武汉淘宝产品拍摄 编辑:程序博客网 时间:2024/05/20 06:56


       这是用Swift写的一个小Demo,主要用到的框架有Alamofire,D3Model,Kingfisher,SnapKit,ZLSwiftRefresh。下面将一一介绍它们在该demo中如何使用的。
       1.Alamofire 在OC中网络请求一般都用AFNetworking(https://github.com/AFNetworking/AFNetworking),而在Swift中用Alamofire(https://github.com/Alamofire/Alamofire)。

 Alamofire.request(.POSTurl, parameters:parameters).responseJSON{response in

            self.firstTableView.doneRefresh()

            self.isLoading=false

            switch response.result {

            case .Success:

                if let dict = response.result.value {

                    let errorCount:String=dict["error"asString

                    self.pages = dict["totalPages"asInt

                    if errorCount=="0"{

                        if self.page==1{

                        self.dataArray.removeAllObjects()

                        }

                       let array = ProductModel.jsonToModelList(dict["rows"]) asArray<ProductModel>

                        self.dataArray.addObjectsFromArray(array)

                        self.firstTableView.reloadData()

                    }

                }

            case .Failure(let error):

                print(error)

            }

        }


       2. D3Modelhttps://github.com/mozhenhau/D3Json功能相当于JSONModel,但是与JSONModel相比功能太少
  let array = ProductModel.jsonToModelList(dict["rows"]) as!   Array<ProductModel>
使用方法却和JSONModel差不多
       3. Kingfisherhttps://github.com/onevcat/Kingfisher 是做图片缓存的,用法和SDWebImage极像

 let URL = NSURL(string: "http://www.bysuper.com/"+newValue.ProductImage!)!

            productImageView.kf_setImageWithURL(URL, placeholderImage: nil,

                optionsInfo: [.Transition(ImageTransition.Fade(1))],

                progressBlock: { receivedSize, totalSize in

                   // print("\(indexPath.row + 1): \(receivedSize)/\(totalSize)")可以用来显示图片加载的进度

                },

                completionHandler: { image, error, cacheType, imageURL in

                   // print("\(indexPath.row + 1): Finished")

            })

清楚图片缓存的方法:

 KingfisherManager.sharedManager.cache.clearMemoryCache()

 KingfisherManager.sharedManager.cache.clearDiskCache()

  4. SnapKithttps://github.com/SnapKit/SnapKit自动布局框架和Masonry是出自同一个作者的手

 override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        super.init(style: style, reuseIdentifier: reuseIdentifier)

        //商品图片

        productImageView=UIImageView()

        self.contentView.addSubview(productImageView)

        //商品名称

        titleLabel=UILabel()

        titleLabel.numberOfLines=0

        self.contentView.addSubview(titleLabel)

        //商品价格

        priceLabel=UILabel()

        priceLabel.textColor=UIColor.redColor()

        self.contentView.addSubview(priceLabel)

        //商品销量

        countLabel=UILabel()

        countLabel.textColor=UIColor.lightGrayColor()

        countLabel.textAlignment=NSTextAlignment.Right

        self.contentView.addSubview(countLabel)

        

        productImageView.snp_makeConstraints("", line: 0) { (make) -> Void in

            make.width.lessThanOrEqualTo(80)

            make.height.lessThanOrEqualTo(80)

            make.left.equalTo(self.contentView).offset(padding)

            make.top.equalTo(self.contentView).offset(padding)

        }

        titleLabel.snp_makeConstraints("", line: 0) { (make) -> Void in

            make.width.lessThanOrEqualTo(screenWidth-3*padding-80)

            make.height.lessThanOrEqualTo(50)

            make.left.equalTo(productImageView.snp_right).offset(padding)

            make.top.equalTo(self.contentView).offset(padding)

        }

        priceLabel.snp_makeConstraints("", line: 0) { (make) -> Void in

            make.width.lessThanOrEqualTo((screenWidth-4*padding)/2.0)

            make.height.lessThanOrEqualTo(50)

            make.left.equalTo(productImageView.snp_right)

            make.bottom.equalTo(self.contentView.snp_bottom).offset(-padding)

        }


        countLabel.snp_makeConstraints("", line: 0) { (make) -> Void in

            make.width.lessThanOrEqualTo((screenWidth-4*padding)/2.0)

            make.height.lessThanOrEqualTo(30)

            make.right.equalTo(self.contentView.snp_right).offset(-padding)

            make.bottom.equalTo(self.contentView.snp_bottom).offset(-padding)

        }


    }

     5. ZLSwiftRefreshhttps://github.com/MakeZL/ZLSwiftRefresh)使用这个框架你会看到MJRefresh的身影,它们相似的地方非常多

      weak var weakSelf = self as FirstViewController

        // 及时上拉刷新

        firstTableView.nowRefresh({ () -> Void in

            if  weakSelf!.isLoading{

                self.firstTableView.doneRefresh()

                return

            };

                weakSelf?.page = 1

                weakSelf?.isLoading=true

                weakSelf?.initData()

        })

    

        // 上啦加载更多

        firstTableView.toLoadMoreAction({ () -> Void in

            if  weakSelf!.isLoading{

                self.firstTableView.doneRefresh()

                return

            };

            if (weakSelf?.page < weakSelf?.pages){

                weakSelf?.isLoading=true

                weakSelf?.page += 1

                weakSelf?.initData()

            }else{

                weakSelf?.firstTableView.endLoadMoreData()

                weakSelf?.isLoading=false

            }

        })


    世界有多大,互联网就有多大。星星编程,可以点缀世界!

0 0
原创粉丝点击