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)

            }

        }

    }





猜你喜欢

转载自blog.csdn.net/flg1554112450/article/details/79390448