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ù)進行排差