Swift使用Alamofire

swift的简单网络请求,学艺不精,如果错了请指出

以下是我封装的一个方法,官方的地址直接copy过来的https://github.com/SwiftyJSON/SwiftyJSON,没有问题,因为没有写参数,所以没有任何问题

   func getRequestData(url:String,parame:[String:String]){
        Alamofire.request(url).responseJSON { response in
            print(response);
        };
    }

 一下是一个有参数的get请求数据,官方的代码直接拉过来的,

func getRequestData(url:String,parame:[String:String]){
        Alamofire.request(url, method: .get, parameters: parame, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
            if response.result.isSuccess{
                print("成功了")
                if let value = response.result.value as? [String: AnyObject]{
                    print("返回的结果:\(value) : \(value["msg"]!)")
                    
                    
                }
            }
    }

 后台一直得不到数据,还会报错FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0.” UserInfo={NSDebugDescription=Invalid value around character 0.})),查资料发现如果后请求的接收方式是以post时,后台接收方式是以 from 表单时 encoding 一定要为URLEncoding.queryString。不然后台接收不到数据

改成

        Alamofire.request(url, method: .get, parameters: parame, encoding: URLEncoding.queryString, headers: nil).responseJSON { (response) in
            if response.result.isSuccess{
                print("成功了")
                if let value = response.result.value as? [String: AnyObject]{
                    print("返回的结果:\(value) : \(value["msg"]!)")
                }
            }
        }

然后事情完美解决

猜你喜欢

转载自www.cnblogs.com/hualuoshuijia/p/11760371.html