Search code examples
swiftxcodeswiftuialamofireswift5

How to check if the API return nothing with Alamofire?


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

Solution

  • 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.