swift3.0下使用Alamofire调用Webservice遇到的一些问题以及解决方案。
首先是针对没有证书的https下的接口处理问题(ps:不推荐在正式版本中使用),manager.request替换掉了Alamofire.request。
let manager = Alamofire.SessionManager.default
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
return (disposition, credential)
}
针对soap协议,使用mutableURLRequest来进行请求。
mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
mutableURLRequest.setValue(action, forHTTPHeaderField: "SOAPAction")
mutableURLRequest.setValue(String(soapMsg.characters.count), forHTTPHeaderField: "Content-Length")
mutableURLRequest.httpMethod = "POST"
mutableURLRequest.httpBody = soapMsg.data(using: String.Encoding.utf8)
得到返回的值包含来xml命名空间和其中的有效结果。通过第三方库SWXMLHash来进行XML的解析,再针对解析得到的Json字符串利用JSONSerialization获得相应的字典。
manager.request(mutableURLRequest as URLRequest).responseData{ response in
//debugPrint(response)
let xml = SWXMLHash.parse(response.data!)
let a: String = (xml["soap:Envelope"]["soap:Body"]["FindUserNewResponse"]["FindUserNewResult"].element?.text)!
print(a)
if !a.isEmpty && a != "err:账号或密码有误!"{
let data = a.data(using: String.Encoding.utf8)! as Data
let a_dic = try? JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers)
if let dict = a_dic as? Dictionary<String, String> {
print(dict["姓名"]!)
print(dict["地区"]!)
callback?(true)
}
}else{
callback?(false)
}
}
注意上面使用了一个回调函数,这是因为Alamofire调用WebService是异步的方式,这里通过isOk来判定登陆是否成功。
func reqWebService(values: Dictionary<String, String>, callback: ((_ isOk: Bool)->Void)?){}