I have file of API model which contains API call and I am getting different responses on API call and then I am parsing the call and comparing the parsing keys in code and show the alert. I do not want to show alert in API model class, I want to show alert in that other class of LoginVC which contains IBAction of Loginpressed. Please see the following code:
//API.swift
func loginApiCall(email : String,password : String, completion:@escaping (Bool) -> ()){
let urlString = "\(ApiServiceProvider.BASE_URL + ApiServiceProvider.LOGIN_ENDPOINT)"
let parameters = [
"user_email": "\(email)",
"user_password": "\(password)"
]
Alamofire.request(urlString, method:.post, parameters: parameters, encoding: URLEncoding.default).validate().responseJSON {
response in
switch response.result {
case .failure(let error):
print(error)
completion(false)
case .success(let responseObject):
print("response is success: \(responseObject)")
if let JSON = response.result.value {
let result = JSON as! [String:AnyObject]
let msg = result["status"] as! String
print(msg)
let message = result["message"] as! String
let fullNameArr = message.components(separatedBy: " ")
print(fullNameArr)
if msg == "error" {
// show alert in Login VC during api call
print("Validation error")
} else {
if msg == "NotVerified" {
} else {
print("Success login")
completion(true)
}
if let data = result["data"] {
print(data)
let user = data["user_id"]
let userdefault = UserDefaults.standard
userdefault.set(user!, forKey: KeyValues.userIdkey)
}
}
print("json: \(msg)")
}
}
}
}
// LoginVC
@IBAction func LoginPressed(_ sender: LoginButton) {
guard let email = emailField.text else {
// improper
return
}
guard let password = passField.text else {
return
}
if email == "" || password == "" {
let otherAlert = UIAlertController(title: "Fields Error!", message: "\(KeyValues.multiFieldsError)", preferredStyle: UIAlertControllerStyle.alert)
let dismiss = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
otherAlert.addAction(dismiss)
present(otherAlert, animated: true, completion: nil)
} else {
if Connectivity.isConnectedToInternet {
showActivityIndicator(uiView: self.view)
mainView.isHidden = false
let apiCall = ApiServiceProvider()
apiCall.loginApiCall(email: email, password: password) { success in
if success {
// show alert here which is highlighted in api class
print("successful")
self.hideActivityIndicator(uiView: self.view)
self.mainView.isHidden = true
self.networkView.isHidden = true
self.performSegue(withIdentifier: "LogToWorkSpace", sender: nil)
} else {
let otherAlert = UIAlertController(title: "Error!", message: "Login failed!", preferredStyle: UIAlertControllerStyle.alert)
let dismiss = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
otherAlert.addAction(dismiss)
self.present(otherAlert, animated: true, completion: nil)
print("not successful")
}
}
}else{
networkView.isHidden = false
//print("No internet connection.")
}
}
}
Do you want to display a custom error message?
if so add an error string to your completion closure
func loginApiCall(email : String,password : String, completion:@escaping (_ isSuccesfull :Bool, _ errorMessage :String?) ->())
then when login fails in your API class change failure to
if msg == "error" {
// show alert in Login VC during api call
completion(false, "Your Error Message!")
print("Validation error")
}
then in your Login View Controller handle it
apiCall.loginApiCall(email: email, password: password) { success,errorMessage in
if success {
// show alert here which is highlighted in api class
print("successful")
self.hideActivityIndicator(uiView: self.view)
self.mainView.isHidden = true
self.networkView.isHidden = true
self.performSegue(withIdentifier: "LogToWorkSpace", sender: nil)
} else {
if let message = errorMessage
{
DispatchQueue.main.async {
let otherAlert = UIAlertController(title: "Error!", message: message, preferredStyle: UIAlertControllerStyle.alert)
let dismiss = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
otherAlert.addAction(dismiss)
self.present(otherAlert, animated: true, completion: nil)
print("not successful")
}
}
}
}