swift网络请求工具Alamofire 的使用



1.get请求

func get(geturl:String,body:[String:Any],headerFile:[String:String],finished :@escaping (_ result : AnyObject?, _ error : NSError?)-> ()){
       
        Alamofire.request(geturl, method: .get, parameters: body, encoding: URLEncoding.default, headers: headerFile).responseJSON { (response) in
            //是否请求成功

            switch response.result{
               
            case .success(_):
                finished(response.result.value as AnyObject?, nil)
            case .failure(_):
                finished(nil, response.result.error as NSError?)
            }
           
           
        }
    }

2.post请求


func post(posturl:String,body:[String:Any],headerFile:[String:String],finished :@escaping (_ result : AnyObject?, _ error : NSError?)-> ()){

        Alamofire.request(posturl, method: .post, parameters: body, encoding: URLEncoding.default, headers: headerFile).responseJSON { (response) in
            switch response.result{
               
            case .success(_):
                finished(response.result.value as AnyObject?, nil)
            case .failure(_):
                finished(nil, response.result.error as NSError?)
            }
           
        }
    }


body 和 headerFile是字典 字典为空时 写为 [:]

引用实例:


 /// 获取推荐==========

    func loadShouYeTuiJianWithstart(start: NSInteger,limit:NSInteger,finished :@escaping (_ result : FLGTuijianModel?)-> ()){

        let input = String(format:"%@/homePage/getHomePageData?start=%ld&limit=%ld",arguments:[BASEADDRESS,start,limit])

        let tol = FLGAlamofireTool()

        tol.get(geturl: input, body: [:], headerFile: [:]) { (result:AnyObject?, error:NSError?) in

            if error != nil{

                /// 请求失败的处理 根据error.code 获取错误码

            }else{

                //// 请求成功处理,,json转为model(工具:HandyJSON)

                let jsonString = result as! NSDictionary

                let model = FLGTuijianModel.deserialize(from: jsonString)

                finished(model, nil)

            }

        }

    }





阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭