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

Json 如何对Alamofire请求swift 3发出警报,json,swift,alert,alamofire,uialertcontroller,Json,Swift,Alert,Alamofire,Uialertcontroller,嘿,我正试图从alamofire请求中发出带有错误信息的警报消息,但无论哪个视图处于活动状态,它都应该显示,因为此请求位于单独的类上,我如何才能做到这一点 请求类: class Json { var loginToken = "" public func login(userName: String, password: String, loginCompletion: @escaping (_ JSONResponse : Any?, _ error: Error?) ->

嘿,我正试图从alamofire请求中发出带有错误信息的警报消息,但无论哪个视图处于活动状态,它都应该显示,因为此请求位于单独的类上,我如何才能做到这一点

请求类:

       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
中使用“添加更多类型”

因此,不要将completionHandler的类型设置为
completion:@escaping(\ujson:Any)
而是将其设置为
completion:@escaping(\ujsonresponse:Any?,\uerror: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"])
     }
}

您是否询问如何显示警报?不清楚。是的,我需要显示警报,但是这个alamofire请求在类中是分开的,所以无论使用哪个视图,警报都应该显示opened@EgleMatutyte你为什么不使用你的
completionHandler
呢?我想你的问题不是直接关于alamofire的,而是关于发出警报的。你可能想看看,我怎么能做到?我很困惑,因为我想在失败后立即发出警报,如何识别我的完成处理程序中的错误?出现错误,UIApplication没有成员topviewcontroller
UIApplication.topviewcontroller()?…
delete
UIApplication
从中仍然会得到错误:
在类型“Json”上使用实例成员“topViewController”;您的意思是使用“Json”类型的值吗?
u确保像创建全局函数一样创建
func topViewController