我正在使用Xcode 8.3.2中的Swift 3.0和IOS 10开发应用程序。但是当我尝试从此APIRest(http://schematic-ipsum.herokuapp.com/)中检索JSON时,我遇到了问题。问题是什么?或者你将如何打电话。如果您需要有关代码的更多信息,请告诉我,但基本上,我只想打电话到该页面来恢复传记。
我的代码是:
import AlamofireDomain
import Alamofire
import ObjectMapper
class AuthorDAO : SimpleDAO {
func getBiography(_ parameters: Dictionary<String, Int>,
callbackFuncionOK: @escaping
(PropertiesAuthorModel)->(),
callbackFunctionERROR: @escaping (Int,NSError)->()) {
let ulr = NSURL( string: "http://schematic-ipsum.herokuapp.com/" as String)
let request = NSMutableURLRequest(url: ulr! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Constent-Type")
let data = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue)
Alamofire.request(request as URLRequest)
.responseJSON { response in
if response.result.isSuccess{
if let status = response.response?.statusCode {
switch(status){
//MARK: CONTROL ON DIFERENTS KINDS OF RESPONSES ON SERVER
case 200:
if let value = response.result.value {
let biographyResponse = Mapper<PropertiesAuthorModel>().map(JSONObject: value)
callbackFuncionOK(biographyResponse!)
}
//case 400: {} ..., case 404: {} ...
default:
break
}
}
}
//MARK: ERROR ON SERVER
else {
var statusCode = -1
if let _response = response.response {
statusCode = _response.statusCode
}
var nsError: NSError = NSError(domain: Constants.UNKNOWN_HTTP_ERROR_MSG,
code: Constants.UNKNOWN_HTTP_ERROR_ID,
userInfo: nil)
if let _error = response.result.error {
nsError = _error as NSError
}
callbackFunctionERROR(statusCode,nsError)
}
}
}
错误是:“Error Domain = Alamofire.AFError Code = 4”由于错误,无法序列化JSON:由于格式不正确,无法读取数据。“400 “
问题是它没有进入“if response.result.isSuccess {”,因为响应的结果是“nil”并直接进入“else”。显示我评论过的错误。是不是因为我必须在httpBody请求中发送JSON格式?我该怎么办?
答案 0 :(得分:0)
你的问题应该更清楚。 “问题是什么?”没有更多信息就无法回答。
要发出HTTP请求,请查看Alamofire,一个用Swift编写的HTTP网络库:https://github.com/Alamofire/Alamofire
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}