Alamofire调不通网络的坑

Swift开始重构项目

1.首先用Cocoapods导入Alamofire框架
然后cd到项目目录下面,然后pod install

2BA55ED2-362D-4CA3-861B-481912A73395.png

2.引入框架
import Alamofire

3.调接口

Alamofire.request(url, method: .post, parameters: dict, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
            
            if response.error == nil {
                print(response.request ?? "")  // original URL request
                print(response.response ?? "") // URL response
                print(response.data ?? "")     // server data
                print(response.result )   // result of response serialization
                
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                    
                    let dict:Dictionary = JSON as! Dictionary
                    print("dict:\(dict)")
                    
                    
                }
            }else {
                print(response.error as Any)
            }
        }

采坑

如果你报如下错误

Optional(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

试一下加上headers

let headers:HTTPHeaders = ["Content-type":"application/x-www-form-urlencoded",
                                   "Accept":"application/json",
                                   "systemtype":"ios",
                                   "channel":"00",
                                   "Authorization":""]
3588C986-90D3-4784-BE15-76751E1CF7CB.png

如果你的参数是字典里面包字典,多层字典包裹,后台接到的参数是这样的


2A631EC2-7DD3-465F-A81F-7D3EF386883B.png
300AF037-6D42-4F13-9076-A186A063F7A1.png

这样的参数后台可能解析不出来,导致你的参数无法解析
解决方法
JSONEncoding.default改成URLEncoding.default

这样就能正常解析了

如果你报如下错

Optional(Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x60000005fbf0 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://apimobile.xiaohe.com.cn/app/login/ParentsLogin/login, NSErrorFailingURLKey=http://apimobile.xiaohe.com.cn/app/login/ParentsLogin/login, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.})

试着打开http模式


ADE61FED-C30E-4BFF-B5C3-2F5682F1B0D7.png

OC能调通接口,Swift调不通接口的原因

主要的解决思路就是,你需要知道你的Swift参数在后台是什么样子的,因为OC能调通网络,Swift调不通,说明在后台的参数肯定不一样,已经确定不是域名的问题话,主要对参数进行排差

你可能感兴趣的:(Alamofire调不通网络的坑)