skip to Main Content

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))

When user email is exist
and if user email is not exist, it will insert data to the database, and return nothing like this
enter image description here(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


  1. The response (as you shared) in fail-type case is:

    [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)
    

    Shows [Result]: success(nil) which means the response.data is literally nil.

    I propose the following solution:

    Alamofire
        .request("http://172.16.5.56:8081/User/InsertNewUser")
        .response { (response) in
            if let data = response.data,
               let string = String(data: data, encoding: .utf8) {
                if string == "Email address already exist" {
                    self.haptics.notificationOccurred(.error)
                    self.activeAlert = .first
                    self.showAlert = true
                }
                //else if ... {
                //handle other cases
                //}
            } else { 
                self.haptics.notificationOccurred(.success)
                self.activeAlert = .second
                self.showAlert = true
            }
        }
    

    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.

    Login or Signup to reply.
  2. @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 the failure case, return a failure status code (probably 403), and a JSON payload describing the error.
    • In the success case, you could return a 201, which indicates the new user has been created, in which case you should include the new user object JSON in the response, or a 204, which is the proper status code for an empty response.

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search