ios 10+,Swift 3+ - 无法从 Singleton 实例中关闭 UIAlertController [英] ios 10+, Swift 3+ - Cannot dismiss UIAlertController from Singleton instance

查看:13
本文介绍了ios 10+,Swift 3+ - 无法从 Singleton 实例中关闭 UIAlertController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向服务器运行异步数据抓取时,我创建了一个叠加层,以便用户在数据抓取完成之前不会继续按下 UI 中的按钮.我已将该函数放入一个全局单例类中,并在传入一个布尔值时调用它来说明我是否要显示或隐藏.我可以让它显示,但我不能让它隐藏.代码如下:

I have created an overlay to run while I run an async data grab to the server so that users won't continue pressing buttons in the UI until the data grab is done. I have put the function into a global singleton class and I call it while passing in a bool to say whether or not I want to show or hide. I can get it to show but I cannot get it to hide. Here is the code:

class DataModel {
    static let sharedInstance = DataModel()
    func accessNetworkData(vc: UIViewController, params: [String:Any], wsURLPath: String, completion: @escaping (_ response: AnyObject) -> ()) {
        DataModel.sharedInstance.toggleModalProgess(show: true)
        // SHOW THE MODAL HERE ONCE THE DATA IS REQUESTED.
        let url = URL(string: wsURLPath)!
        let session = URLSession.shared
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        do { request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted) } catch let error { print(error.localizedDescription) }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
            DataModel.sharedInstance.toggleModalProgess(show: false)
            // NOW SINCE THE NETWORK ACTIVITY IS DONE, HIDE THE UIALERTCONTROLLER
            guard error == nil else {
                print("WEB SERVICE ERROR <----------------------------<<<<<< " + wsURLPath)
                print(error!)
                let resp: [String: String] = [ "conn": "failed" ]

                DispatchQueue.main.async { completion(resp as NSDictionary) }
                return
            }
            guard let data = data else {
                print("WEB SERVICE ERROR <----------------------------<<<<<< " + wsURLPath)
                return
            }
            do {
                if let parsedJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                    print("WEB SERVICE SUCCESS <----------------------------<<<<<< "+wsURLPath+" "+String(describing:params))
                    if let parsedResponseDict = parsedJSON["d"] as? NSDictionary {
                        DispatchQueue.main.async {
                            completion(parsedResponseDict)
                        }
                    }else if let parsedResponseArr = parsedJSON["d"] as? NSArray {
                        DispatchQueue.main.async {
                            completion(parsedResponseArr)
                        }
                    }else {
                        print("INVALID KEY <----------------------------<<<<<< " + wsURLPath)
                        DispatchQueue.main.async {
                            completion(parsedJSON as AnyObject)
                        }
                    }
                }
            } catch let error {
                print("Error with JSON Serialization")
                print(error.localizedDescription)
            }
        })
        task.resume()
    }

这里是我设置 UIALERTController 的地方

HERE IS WHERE I SET UP THE UIALERTCONTROLLER

    let modalAlert = UIAlertController(title: "Please Wait...", message: "Loading Data...", preferredStyle: UIAlertControllerStyle.alert)
    let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))

    func toggleModalProgess(show: Bool) -> Void {
        print("toggleModalProgess: show = " + String(describing: show))
        if (show) {
            print("let's turn it on")
            loadingIndicator.hidesWhenStopped = true
            loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
            loadingIndicator.startAnimating()
            modalAlert.view.addSubview(loadingIndicator)
            modalAlert.show()
        }else {
            print("let's turn it off")
            modalAlert.hide()
        }
    }

    private init() { }
}

现在是魔法发生的地方

public extension UIAlertController {
    func show() {
        let win = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        win.rootViewController = vc
        win.windowLevel = UIWindowLevelAlert + 1
        win.makeKeyAndVisible()
        vc.present(self, animated: true, completion: nil)
    }
    func hide() {
        // HERE IS WHERE I NEED TO HIDE IT BUT I AM HAVING ISSUES 
    }
}

推荐答案

为了关闭 UIAlertController(它是 UIViewController 的子类),它应该足够了调用 dismiss 方法:

In order to dismiss the UIAlertController (which is a subclass of UIViewController), it should be sufficient to call the dismiss method:

func hide() {
    dismiss(animated: true, completion: nil)
}

它在我的示例项目中运行良好.

It works fine in my sample project.

这篇关于ios 10+,Swift 3+ - 无法从 Singleton 实例中关闭 UIAlertController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆