我正在将Objective C项目转换为快速项目,因此,我需要使用Alamofire而不是AFNetworking。我需要进行HTTP调用的服务器需要JSON格式的参数,但以text / html响应。当我在Objc中测试请求时,它可以工作,但是在swift和alamofire上,响应数据为nil。我之前使用AFNetworking responseSerializer进行了此操作,并将可接受的内容类型设置为所有4种可能的类型。我似乎无法与Alamofire配合使用。我在那里使用过任何帮助和教程,但每次都将自己的头撞到天花板。我收到的错误通常无法确定字节大小或responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength。
这里是我到目前为止使用的示例代码:
let urlString = "\(K.APIKs.kInsecureProtocol)\(K.APIKs.KBaseURL)\(K.APIKs.kSignupURL)"
let parameters: Parameters = [K.SignUPKs.kMSISDN: number]
AF.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default).responseJSON { (response) in
switch response.result {
case .success:
self.authorisingSignUpDelegate?.onAuthorisingSignUpSuccess()
break
case .failure(let error):
self.authorisingSignUpDelegate?.onAuthorisingSignUpFailed(error: error)
break
}
}
然后尝试设置可接受的内容类型:
if let url = URL(string: urlString) {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.post.rawValue
urlRequest.addValue("application/json", forHTTPHeaderField: "content-type")
urlRequest.addValue("text/html", forHTTPHeaderField: "accept")
urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
let request = AF.request(urlRequest)
.response { response in
print("Request: \(String(describing: response.request))") // original URL request
print("---------------------------")
print("HTTP URL response: \(String(describing: response.response))") // HTTP URL response
print("---------------------------")
print("Data: \(String(describing: response.data))") // server data
print("---------------------------")
print("Result of Reponse Serialization \(response.result)") // result of response serialization
print("---------------------------")
print("Error \(response.error)") // result of response serialization
print("---------------------------")
print("JSON: \(response.result)")
}
}
我没有尝试过的方法。谁能帮我吗?谢谢一百万!
对于那些有类似问题的人,我将修复程序编写如下:
if let returnedData = JSONData {
do {
let dict = try JSONSerialization.jsonObject(with: returnedData, options: []) as? [String: String]
DataManager().synchronisePassword(from: dict!)
} catch {
print(error.localizedDescription)
}
}