swift 网络请求封装

swift 网络请求封装

Alamofire 请求网络数据,Haneke 完成缓存, ObjectMapper 自动映射到模型。
JLToast 类似Android的Toast优雅提醒。

//
//  SQRequest.swift
//  ban
//
//  Created by mba on 16/7/28.
//  Copyright © 2016年 mbalib. All rights reserved.
//

import UIKit
import Alamofire
import Haneke
import JLToast
import ObjectMapper


public enum CachePolicy: String {
    case Default,// *** 不提供缓存
    ReturnCache_ElseLoad,// *** 如果有缓存则返回缓存不加载网络,否则加载网络数据并且缓存数据
    ReturnCache_DontLoad,// *** 如果有缓存则返回缓存并且不加载网络
    ReturnCache_DidLoad,// *** 如果有缓存则返回缓存并且都加载网络
    ReturnCacheOrNil_DidLoad,// *** 如果有缓存则返回缓存,没有缓存就返回空的,并且都加载网络
    Reload_IgnoringLocalCache// *** 忽略本地缓存并加载 (使用在更新缓存)
}

class SQRequest : NSObject{
    
    
    /// T?:实体 error:错误信息
    typealias finished = (T?, NSError?)-> ()
    
    /**
     通用请求方法
     
     - parameter method:            OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
     - parameter url:               url
     - parameter cache:             缓存策略
     - parameter params:            params 可选
     - parameter headers:           headers 可选
     - parameter completionHandler: 回调
     */
    static func go(method: Alamofire.Method,
                    url: String,
                     cache: CachePolicy = .Default,
                     params: [String: AnyObject]? = Dictionary(),
                     completionHandler:finished) {
        let fullUrl = getFullUrl(url,params)
//        debugPrint(fullUrl)
        let stringCache = Haneke.Shared.stringCache

        switch cache {
            
        case .Default:
            req(method, url, cache: cache, params: params, completionHandler: completionHandler)
            
        case .ReturnCache_ElseLoad:
            
            stringCache.fetch(key: fullUrl).onSuccess({ (data) in
                print("cache")
                let object = Mapper().map(data)
                completionHandler(object, nil)
            }).onFailure({ (error) in
                req(method, url, cache: cache, params: params, completionHandler: completionHandler)
            })
            
        case .ReturnCache_DontLoad:
            stringCache.fetch(key: fullUrl).onSuccess({ (data) in
                print("cache")
                let object = Mapper().map(data)
                completionHandler(object, nil)
            }).onFailure({ (error) in})
            
        case .ReturnCache_DidLoad:
            stringCache.fetch(key: fullUrl).onSuccess({ (data) in
                let object = Mapper().map(data)
                completionHandler(object, nil)
            }).onFailure({ (error) in})
            
            req(method, url, cache: cache, params: params, completionHandler: completionHandler)
        case .ReturnCacheOrNil_DidLoad:
            stringCache.fetch(key: fullUrl).onSuccess({ (data) in
                let object = Mapper().map(data)
                completionHandler(object, nil)
            }).onFailure({ (error) in
                completionHandler(nil, nil)
            })
            req(method, url, cache: cache, params: params, completionHandler: completionHandler)
        case .Reload_IgnoringLocalCache: 
            req(method, url, cache: cache, params: params, completionHandler: completionHandler)
        }
        
    }
    
    
    
    private static func req(method: Alamofire.Method,
                            _ url: String,
                              cache: CachePolicy = .Default,
                              params: [String: AnyObject]? = Dictionary(),
                              completionHandler:finished)
    {
        Alamofire.request(method, url, parameters: params).responseString { (response) in
            if response.result.isFailure {
                var domain:String?
                switch response.result.error?.domain{
                case NSURLErrorDomain?:
                    domain = "网络不佳"
                default :
                    domain = "未知错误"
                }
                
                let error = NSError(domain: domain!, code: (response.result.error?.code)!, userInfo: nil)
                completionHandler(nil, error)
                return
            }
            
            debugPrint(response.result.value as String!)
            
            let object = Mapper().map(response.result.value)
            if cache != .Default && checkResult(object, nil) {
                let stringCache = Haneke.Shared.stringCache
                stringCache.set(value: response.result.value!, key: getFullUrl(url,params))
            }
            print(object)
            completionHandler(object, nil)
        }
    
    }
    
    /**
     检查返回数据是否正确
     
     - parameter obj:   result
     - parameter error: error
     
     - returns: true/false
     */
    static func checkResult(obj:T? ,_ error:NSError?) -> Bool{
        if error != nil {
            JLToast.makeText((error?.domain)!).show()
            return false
        }
        if obj?.errNum != 0 {
//            JLToast.makeText((obj?.errMsg)!)
            JLToast.makeText("出错").show()
            return false
        }
        
        return true
    }
    
    // 获取全路径
    private static func getFullUrl(url: String,_ params: [String: AnyObject]? = Dictionary()) -> String {
        var fullUrl = ""
        if params?.count > 0{
            var str: String = "?"
            for param in params! {
                str += "\(param.0)=\(param.1)&"
            }
            str = (str as NSString).substringToIndex(str.characters.count - 1)
            fullUrl = url + str
        }else {
            fullUrl = url
        }
        return fullUrl
    }
}


你可能感兴趣的:(swift 网络请求封装)