【问题标题】:How to make alert on Alamofire request swift 3如何在 Alamofire 请求 swift 3 上发出警报
【发布时间】:2017-02-08 14:26:45
【问题描述】:

嘿,我正在尝试使用来自 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))

}

【问题讨论】:

  • 您在问如何显示警报吗?不清楚。
  • 是的,我需要显示警报,但是这个alamofire请求在类中是分开的,所以无论打开哪个视图都应该显示警报
  • @EgleMatutyte 你为什么不使用你的completionHandler
  • 我认为您的问题不直接与 alamofire 有关,而是与显示警报有关。您可能需要查看the documentation
  • 我该怎么做?我很困惑,因为我想在失败后立即发出警报,如何在完成处理程序中识别错误?

标签: json swift alert alamofire uialertcontroller


【解决方案1】:

如果您想传递错误并显示来自调用控制器的警报,那么您可以使用 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"])
     }
}

【讨论】:

    【解决方案2】:

    首先创建全局函数:

    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)
    

    【讨论】:

    • 出现错误,UIApplication 没有成员 topviewcontroller
    • UIApplication.topViewController()?... 从那里删除UIApplication
    • 仍然报错:Use of instance member 'topViewController' on type 'Json'; did you mean to use a value of type 'Json' instead?
    • 你确定你创建func topViewController 像一个全局函数?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    相关资源
    最近更新 更多