I am using Alamofire to make an API request to insert user data to my database, if the user email is exist, the response will return
[Response]:
[Status Code]: 200
[Headers]:
Connection: Keep-Alive
Content-Length: 27
Content-Type: text/html; charset=UTF-8
Date: Thu, 22 Apr 2021 06:39:05 GMT
Keep-Alive: timeout=5, max=99
Server: Apache/2.4.25 (Debian)
[Body]:
Email address already exist
[Network Duration]: 0.013917088508605957s
[Serialization Duration]: 0.0s
[Result]: success(Optional(27 bytes))
and if user email is not exist, it will insert data to the database, and return nothing like this
(literally nothing, there’s no character or whatsoever, just a blank page if I open the api in the web browser)
And here is the response
[Response]:
[Status Code]: 200
[Headers]:
Connection: Keep-Alive
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Date: Thu, 22 Apr 2021 06:54:43 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.25 (Debian)
[Body]: None
[Network Duration]: 0.8882529735565186s
[Serialization Duration]: 0.0s
[Result]: success(nil)
Now I want to make a validation to check if user email is exist or not by checking the response body. if the response body is Email address already exist, it will display an error alert. and if response body is None, it will display a successful alert. My question is, how do I check if the response body is None? here is validation code
let parameters = ["USERNAME": "(USERNAME)", "EMAIL": "(EMAIL)", "FULL_NAME": "(FULL_NAME)", "NO_TELEPON": "(NO_TELEPON)", "PASSWORD": "(PASSWORD)", "USER_TOKEN": "(USER_TOKEN)"]
AF.request("http://172.16.5.56:8081/User/InsertNewUser", parameters: parameters).response{ response in
debugPrint(response)
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8){
print(utf8Text)
postResponse = utf8Text
if postResponse == "Email address already exist" {
self.haptics.notificationOccurred(.error)
self.activeAlert = .first
self.showAlert = true
}else if postResponse == "None"{ // This is not working
self.haptics.notificationOccurred(.success)
self.activeAlert = .second
self.showAlert = true
}
}
}
2
Answers
The response (as you shared) in fail-type case is:
Shows
[Result]: success(nil)
which means theresponse.data
is literallynil
.I propose the following solution:
NOTE: I would advise against direct string comparisons unless unavoidable.
Atleast agree on a common response template and ensure the responses are not prone to typos or silly mistakes.
@staticVoidMan has already provided a solution for your current backend setup. However, if you update your backend to return more appropriate responses, Alamofire can do a lot more for you automatically.
In short, you need to make your backend behave in a standard fashion following JSON API best practices. These include:
In these cases you can define proper
Decodable
payloads which Alamofire can parse for you, as well as a proper value for the empty responses, and Alamofire will ensure it’s returned in the 204 case.