Search code examples
jsonswiftalertalamofireuialertcontroller

How to make alert on Alamofire request swift 3


Hey I am trying to make alert message with error information from alamofire request, but it should display no matter which view is active, because this request is on separated class, How I can do that?

Request class:

       class Json {
var loginToken = ""

public func login(userName: String, password: String, loginCompletion: @escaping (_ JSONResponse : Any?, _ error: Error?) -> ()) {


    let loginrequest = JsonRequests.loginRequest(userName: userName, password: password)

    makeWebServiceCall(urlAddress: URL, requestMethod: .post, params: loginrequest, completion: { (json, error) in
        loginCompletion(json, error)

    })
}

public func device(token: String, loginCompletion: @escaping (_ JSONResponse : Any?, _ error: Error?) -> ()) {

    let deviceinfo = JsonRequests.getInformationFromConfig(token: token, config: "wireless", section: "@wifi-iface[0]", option: "mode")
    makeWebServiceCall(urlAddress: URL, requestMethod: .post, params: deviceinfo, completion: { (json, error) in
        loginCompletion(json, error)
    })
}

let manager = Alamofire.SessionManager.default

private func makeWebServiceCall (urlAddress: String, requestMethod: HTTPMethod, params:[String:Any], completion: @escaping (_ JSONResponse : Any?, _ error: Error?) -> ()) {

    manager.session.configuration.timeoutIntervalForRequest = 5


    manager.request(urlAddress, method: requestMethod, parameters: params, encoding: JSONEncoding.default).responseJSON{ response in

        print(response.timeline)

        switch response.result {
        case .success(let value):

            let json = JSON(value)

            if let message = json["error"]["message"].string, message == "Access denied" {
           // LoginVC.performLogin(UserDefaults.standard.value(forKey: "saved_username"),UserDefaults.standard.value(forKey: "saved_password"))
                print("Access denied")
            }

            if let jsonData = response.result.value {
                completion(json, nil)
            }


        case .failure(let error):

                completion(nil, error)

}

Call function:

public class LoginModel {

    var loginToken = ""

internal func JsonResult (param1: String, param2: String){

Json().login(userName: param1, password: param2) { (json, error) in
    print(json)
    print(error)

    if error != nil {
        //Show alert
        return
    }

    //Access JSON here
    if let jsonResponse = json {

        let jsonDic = JSON(jsonResponse)
          print(jsonDic)
        //Now access jsonDic to get value from the response
        for item in jsonDic["result"].arrayValue {

            self.loginToken = item["ubus_rpc_session"].stringValue}
        print(self.loginToken)
         if (jsonDic["result"].exists()){
        print(jsonDic["result"]["ubus_rpc_session"].stringValue)
          if (jsonDic["result"].arrayValue.contains("6")) {

           self.loginToken = "6"

        } else {

              for item in jsonDic["result"].arrayValue {

               self.loginToken = item["ubus_rpc_session"].stringValue
               UserDefaults.standard.setValue(self.loginToken, forKey: "saved_token")
               print(self.loginToken)

            }
    }
    }

        print("No result")
    }


}


self.JsonDevice(param1: (UserDefaults.standard.value(forKey: "saved_token")! as! String))

}

Solution

  • If you want to pass the error and show the alert from calling controller then you can use add one more type with your completionHandler.

    So instead of making completionHandler with type completion: @escaping (_ JSON : Any) make it like this completion: @escaping (_ JSONResponse : Any?, _ error: Error?).

    Now when you get response with your api then Error is nil so call completion handler like this way.

    completion(json, nil)
    

    When you get failure response then pass nil as response with error.

    completion(nil, error)
    

    Now when you call this function check for the error.

    retur.login(userName: userName.text!, password: password.text!) { (json, error) in {
         if error != nil {
              //Show alert
              return
         }
         //Access JSON here
         if let jsonDic = json as? JSON {
             //Now access jsonDic to get value from the response 
             print(jsonDic["field_that_you_want_to_access"])
         }
    }