Swift 3 - 问题创建简单的请求方法POST(URLRequestVonvertible)
我正在Xcode 8.3.2中使用Swift 3.0和IOS 10开发应用程序。但是当我尝试从这个APIRest(http://schematic-ipsum.herokuapp.com/)中检索JSON时,我遇到了问题。问题是什么?或者你会怎么打电话。如果您需要更多关于代码的信息,请告诉我,但基本上,我只是想拨打该页面来恢复传记。Swift 3 - 问题创建简单的请求方法POST(URLRequestVonvertible)
我的代码是这样的:
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)
}
}
}
和错误是: “错误域= Alamofire.AFError代码= 4” JSON不能因为错误的序列化:数据couldn “400”
问题在于它没有进入“if response.result.isSuccess {”,因为响应的结果是“nil “和g直接到“其他”。显示我评论过的错误。是否因为我必须在httpBody请求中发送JSON格式?我该怎么做?
你的问题应该更清楚。 “问题是什么?”没有更多的信息就无法回答。
要发出HTTP请求,看看Alamofire,写在斯威夫特的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)")
}
}
对不起,我不清楚。我只想向POST发出请求并使用参数[“n”:2]发送给API。其中“n”是将以JSON格式返回API的结果总数。但我不能以任何方式。 –
到目前为止你做了什么? –
我的实际代码是:http://es.zimagez.com/zimage/capturadepantalla2017-06-12alas225042.php,它显示这个错误“Error Domain = Alamofire.AFError Code = 4”由于错误,JSON无法序列化: 无法读取数据,因为数据格式不正确。“ 400”您知道问题所在吗? –
您需要提供您使用的访问此API的代码。此外,发布尝试访问REST服务时收到的任何错误消息。 – birwin
感谢您的回答!我添加了更多信息,如代码和错误。 –