如何对 Alamofire 请求发出警报 swift 3

How to make alert on Alamofire request swift 3

嘿,我正在尝试使用来自 alamofire 请求的错误信息制作警报消息,但无论哪个视图处于活动状态,它都应该显示,因为这个请求是分开的 class,我该怎么做?

请求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)

}

调用函数:

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

}

首先创建全局函数:

func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }

        if let tab = base as? UITabBarController {
            let moreNavigationController = tab.moreNavigationController

            if let top = moreNavigationController.topViewController , top.view.window != nil {
                return topViewController(base: top)
            } else if let selected = tab.selectedViewController {
                return topViewController(base: selected)
            }
        }

        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }

        return base
    }

你可以这样做:

struct ErrorShower {
    static func showErrorWith(title:String? = nil, message:String? = nil, complition:(() -> ())?){
        if let _ = topViewController() as? UIAlertController {
            return
        }

        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { _ in
            complition?()
        }))
       topViewController()?.present(alert, animated: true, completion: nil)
    }
}

然后从你想要的地方简单调用:

ErrorShower.showErrorWith(message: err.message, complition: nil)

如果您想传递错误并显示来自调用控制器的警报,那么您可以在 completionHandler.

中再添加一种类型

因此,与其使用 completion: @escaping (_ JSON : Any) 类型创建 completionHandler,不如像这样 completion: @escaping (_ JSONResponse : Any?, _ error: Error?).

现在,当您收到 api 的响应时,Error 为 nil,因此请像这样调用完成处理程序。

completion(json, nil)

当您收到失败响应时,将 nil 作为响应传递给错误。

completion(nil, 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"])
     }
}