i've read many documents about getting the response object from the api , but cant derive how to extract the data. I've used alamofire for api call . The api call is like
AF.request("http://10.177.41.163:9000/signup",
method: .post,
parameters: parameters,
encoder: JSONParameterEncoder.default).responseJSON{ response in
print(response.result)
in my print statement i get the responses as
`success({
error = {
code = PC05;
message = "User already exsists";
};
payload = {
};
success = 0;
})`
which is fine , but i want to extract suppose the error code, how to achieve that? and in general how to extract data from responses in swift.
AF.request("http://10.177.41.163:9000/signup",
method: .post,
parameters: parameters,
encoder: JSONParameterEncoder.default).responseJSON{ response in
print(response.result)
let responseJSON = JSON(response.result) // response converted in json format
let statusCode = responseJSON["error"]["code"].stringValue // You can get status code
Note : Install pod 'SwiftyJSON' to convert response.result in JSON format.
You need to decode the jSON response, so create a Model to decode this, of course also check the response if it was successful before, you'll set an example:
Declare yourself a model:
struct RootResponse : Decodable {
var error: ErrorStruct
var payload: PayloadStruct
var success: Int
}
struct ErrorStruct: Decodable {
var code: String
var message: String
}
struct PayloadStruct : Decodable {
var ?
}
Once you've declared your model based on your jSON response, then you can switch to the function that makes the request to you:
AF.request("http://10.177.41.163:9000/signup",
method: .post,
parameters: parameters,
encoder: JSONParameterEncoder.default).responseJSON{ response in
print(response.result)
switch response.result {
case .success:
if let data = response.data {
print(data)
// Convert This in JSON
do {
let responseDecoded = try JSONDecoder().decode(RootResponse.self, from: data)
print("USER: ", responseDecoded.error.code, "Etc...")
}catch let error as NSError{
print(error)
}
}
case .failure(let error):
print("Error:", error)
}
}
I hope that's been helpful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.