Alamofire調(diào)不通網(wǎng)絡(luò)的坑

Swift開始重構(gòu)項目

1.首先用Cocoapods導入Alamofire框架
然后cd到項目目錄下面,然后pod install

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

2.引入框架
import Alamofire

3.調(diào)接口

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<String,Any> = 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

如果你的參數(shù)是字典里面包字典,多層字典包裹,后臺接到的參數(shù)是這樣的


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

這樣的參數(shù)后臺可能解析不出來,導致你的參數(shù)無法解析
解決方法
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能調(diào)通接口,Swift調(diào)不通接口的原因

主要的解決思路就是,你需要知道你的Swift參數(shù)在后臺是什么樣子的,因為OC能調(diào)通網(wǎng)絡(luò),Swift調(diào)不通,說明在后臺的參數(shù)肯定不一樣,已經(jīng)確定不是域名的問題話,主要對參數(shù)進行排差

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容