Swift开始重构项目
1.首先用Cocoapods导入Alamofire框架
然后cd
到项目目录下面,然后pod install
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<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":""]
如果你的参数是字典里面包字典,多层字典包裹,后台接到的参数是这样的
这样的参数后台可能解析不出来,导致你的参数无法解析
解决方法
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模式
OC能调通接口,Swift调不通接口的原因
主要的解决思路就是,你需要知道你的Swift参数在后台是什么样子的,因为OC能调通网络,Swift调不通,说明在后台的参数肯定不一样,已经确定不是域名的问题话,主要对参数进行排差