美文网首页
Swift 记录-- 网络封装 Alamofire + Hand

Swift 记录-- 网络封装 Alamofire + Hand

作者: 8a420e49153d | 来源:发表于2018-07-31 17:13 被阅读190次

废话不多少 直接上代码
首先是网络请求类: NetworkRequest.swift

上部分代码是对 Alamofire的基本方法封装.
下面的两个是具体使用,主要是想吧所有的数据处理都在这里做,你也可以直接在具体类里面直接调用.

//
//  NetworkRequest.swift
//  beierquan
//
//  Created by 刘龙 on 2018/7/11.
//  Copyright © 2018年 刘龙. All rights reserved.
//

import UIKit
import Alamofire
import HandyJSON

typealias successBlock = (Any)->()
typealias faildBlock = (Any)->()

enum MethodType {
    case GET
    case POST
}
enum RequestType:Int{
    case JSON = 0
    case FORM
}
class NetworkTools {  //设置单例
    static let sharedInstance = NetworkTools()
    private init() {}
}


//设置请求头

let headers: HTTPHeaders = [
    "": ""
]

extension NetworkTools {
    
    func request(type: MethodType,url:String,parameters:Parameters? = nil, success: @escaping (_ response: String) -> (),faild: @escaping (_ error: String) -> ()){
        
        print("\(type)"+"/"+"API:"+url)
        
        let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
        
        var encodingMethod:ParameterEncoding?
        //表单还是json
//        if tempRequestType == RequestType.JSON {

//            encodingMethod = JSONEncoding.default
//        }else{
            encodingMethod = URLEncoding.default

//        }
        
        Alamofire.request(url, method:method,parameters: parameters,encoding:encodingMethod!, headers:headers)//TODO 请求数据json格式
            //HandyJSON需要序列化的是字符串这里是responseString
            .responseString { (response) in
                
                switch response.result {
                    
                case .success:
                    
                    if let value = response.result.value {
                        
                        success(value)
                    }
                    
                case .failure(let error):
                    
                    print("GetErrorUrl:\(String(describing: response.request))")
                    
                    print("GetError:\(error)")
                        faild(error.localizedDescription)
                }
                //                print(response)
        }
        
    }
    
    
    /*
     - homepic
     - parameter paramters:  参数
     - parameter success:    闭包
     - parameter faild:      闭包
     */
   
    func homepicRequst(success: @escaping (_ response: NSMutableArray) -> (),faild: @escaping (_ error: String) -> ()) {
        
        self.request(type: .POST, url: API_homepic, parameters: nil, success: { (respond) in
            
            if let models = [LLHomePicModel].deserialize(from: respond,designatedPath:"data") {
                let urlArr = NSMutableArray()
                models.forEach({ (model) in
                    // ...
                    urlArr.add(model?.car_picurl as Any)
                })
                success(urlArr)
            }
            
        }) { (error) in
            faild(error)
        }
        
    }
    
    /*
     - TTList
     - parameter paramters:  参数
     - parameter success:    闭包
     - parameter faild:      闭包
     */
    
    func TTListRequst(ishot:String,pageSize:String,pageNum:Int,success: @escaping successBlock ,faild: @escaping faildBlock) {
        
        var parameter = Parameters()
        parameter["ishot"] = ishot
        parameter["pageSize"] = pageSize
        parameter["pageNum"] = "\(pageNum)"
        
        self.request(type: .POST, url: API_TTList, parameters: parameter, success: { (respond) in
            
            if let models = [LLTTModel].deserialize(from: respond,designatedPath:"data.list") {
                success(models)
            }
            
        }) { (error) in
            faild(error)
        }
        
    }

    
    
    
}

HandyJSON 创建model

//
//  LLHomePicModel.swift
//  beierquan
//
//  Created by 刘龙 on 2018/7/13.
//  Copyright © 2018年 刘龙. All rights reserved.
//

import Foundation
import HandyJSON

struct LLHomePicModel: HandyJSON {
    
    var car_id: String?
    var car_title: String?
    var car_picurl: String?
    var car_url: String?
    var car_time: String?
    var car_show: String?

}

struct LLTTModel: HandyJSON {
    
    var ta_id: String?
    var ta_title: String?
    var ta_content: String?
    var ta_time: String?
    var ta_source: String?
    var ta_sort: String?
    var ta_status: String?
    var ta_thum_img: String?
    var ta_hot: String?
}

在具体类里面调用
自己看情况做处理

func getData(){
        
        NetworkTools.sharedInstance.homepicRequst( success: { (objs) in
            self.picArr = objs
            if self.picArr.count > 1 {
                self.pagerControl.numberOfPages = self.picArr.count
                self.viewPager.automaticSlidingInterval = 4.0
            }else{
                self.viewPager.isUserInteractionEnabled = false
            }
            self.viewPager.reloadData()
        }) { (error) in
            print(error)
        }
        
        
        NetworkTools.sharedInstance.TTListRequst(ishot: "1", pageSize: "3", pageNum: 1, success: { (objs) in
            print("成功")
        }) { (error) in
            print(error)
        }
        

    }
    

基本的网络请求封装用法就这样,其实就是按照之前OC的写法来的.
就是语言不一样而已.

相关文章

网友评论

      本文标题:Swift 记录-- 网络封装 Alamofire + Hand

      本文链接:https://www.haomeiwen.com/subject/uvfhvftx.html