首页 > 解决方案 > 在 api 类之外显示 alamofire 相关警报

问题描述

我有包含 api 调用的 API 模型文件,我在 api 调用上得到不同的响应,然后我正在解析调用并比较代码中的解析键并显示警报。我不想在 api 模型类中显示警报,我想在包含 Loginpressed 的 IBAction 的其他 LoginVC 类中显示警报。请看下面的代码。

//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.")
            }
        }
    }

标签: iosswiftxcodeapialamofire

解决方案


是否要显示自定义错误消息?

如果是这样,将错误字符串添加到您的完成闭包中

func loginApiCall(email : String,password : String, completion:@escaping (_ isSuccesfull :Bool, _ errorMessage :String?) ->())

然后当您的 API 类中的登录失败时,将失败更改为

if msg == "error" {
    // show alert in Login VC during api call
    completion(false, "Your Error Message!")

    print("Validation error")

}

然后在您的登录视图控制器中处理它

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

    }
} 

推荐阅读