美文网首页
Alamofire的简单封装

Alamofire的简单封装

作者: 夏至樱花祭 | 来源:发表于2019-01-08 17:51 被阅读0次

    Alamofire的简单二次封装。这里数据解析使用swiftyJSON

    import SwiftyJSON
    import Alamofire
    
    enum RequestType {
        case Get
        
        case Post
        
        case Put
        
        case Delete
    }
    
    typealias complete = (Bool?,AnyObject?)->Void
    
    
    class JCNetTool {
        static let manage:SessionManager = {
            var defHeards = Alamofire.SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
            let defConf = URLSessionConfiguration.default
            
            defConf.timeoutIntervalForRequest = 10
            defConf.httpAdditionalHeaders = defHeards
            
            return Alamofire.SessionManager(configuration: defConf, delegate: SessionDelegate(), serverTrustPolicyManager: nil)
        }()
    }
    
    extension JCNetTool {
        
        static func requestData(requestType : RequestType,URLString : String,parameters : [String:Any]? = nil , successed : @escaping complete,failured:@escaping complete){
            
            
            //获取请求类型
            var method : HTTPMethod?
            
            switch requestType {
            case .Get:
                method = HTTPMethod.get
            case .Post:
                method = HTTPMethod.post
            case .Put:
                method = HTTPMethod.put
            case .Delete:
                method = HTTPMethod.delete
                
            }
            //当前时间的时间戳
            let timeInterval:TimeInterval = Date().timeIntervalSince1970
            let timeStamp = Int(timeInterval)
            let headers:HTTPHeaders = [
                "AccessCode"     : "AccessCode",
                "timeStamp"       : "\(timeStamp)",
                "Signature"         : "SHA1算法签名"
            ]
            //发送网络请求
            Alamofire.request(URLString, method: method!, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
                //获取返回结果
                
                switch response.result {
                case .success:
                    let json = JSON(response.result.value as Any)
                    if json["Code"] == "404"{
                        print("连接失败")
       
                    }else{
                        successed(true, response.result.value as AnyObject)
                        
                    }
                case .failure:
                    failured(false, "连接服务器失败" as AnyObject)
                }
                
            }
        }
     
    }
    

    如果headers没有特殊设置,可以在请求的地方设置为nil,在网络访问是只需要传入请求类型、URL地址、json参数就能很方便的使用。

    相关文章

      网友评论

          本文标题:Alamofire的简单封装

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