ios - 在 api 类之外显示与 alamofire 相关的警报

标签 ios swift xcode 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.")
            }
        }
    }

最佳答案

您想显示自定义错误消息吗?

如果是这样,请在完成闭包中添加错误字符串

func loginApiCall(电子邮件:字符串,密码:字符串,完成:@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")

}

然后在您的登录 View Controller 中处理它

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

    }
} 

关于ios - 在 api 类之外显示与 alamofire 相关的警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51027041/

相关文章:

ios - 更改 Skobblers SKMaps for iOS 中的路线宽度

ios - Storyboard中的横向和纵向方向

ios - 使用 Firebase 3 和 Swift 注销用户仍然显示 `currentUser`

ios - 在iOS中将多个图像上传为文件

iphone - 通过 iOS 6 为 iOS 4.2 构建/编译应用程序?

ios - 如何在 Swift 中为我的应用制作自定义键盘?

ios - Swift CoreData 从 JSON 创建或更新实体

swift - 迭代类型数组时出现 "Use of undeclared type "错误

xcode - 如何在 xcode 6 中调整 xib 文件的大小?

ios - 如何在自定义动画中访问 toView 对象的框架