swiftネットワークリクエストパッケージ

5817 ワード

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
    }
}