在Swift中何时何地关闭UIAlertController?

时间:2019-06-28 02:58:34

标签: ios swift uialertcontroller

我正在调用一个执行URLSession的方法,但在执行任何操作之前,会出现一个UIAlertController阻止UI,直到实现来自请求的某种响应。逻辑告诉我,在主线程上调用UIAlertController的方法的完成代码块中,将是最好的选择。我认为这是错误的吗?显然,如此呈现的UIAlertController确实会显示,但永远不会消失。帮助吗?

阻止:

getCostandIV { output in

            let cost = output["ask"] as! NSNumber
            let IV = output["IV"] as! NSNumber

            self.enteredCost = cost.stringValue
            self.enteredIV = IV.stringValue

            DispatchQueue.main.async {

                self.progress.dismiss(animated: true, completion: nil)
                self.tableView.reloadSections(IndexSet(integer: 1), with: UITableView.RowAnimation.none)
                self.canWeSave()

            }

        }

功能:

 func getCostandIV (completionBlock: @escaping (NSMutableDictionary) -> Void) -> Void {

    DispatchQueue.main.async {


        self.progress = UIAlertController(title: "Retrieving ask price and volatility...", message: nil, preferredStyle: UIAlertController.Style.alert)
        self.present(self.progress, animated: true, completion: nil)

    }

    guard let url = URL(string: "https://api.tdameritrade.com/v1/marketdata/chains?apikey=test&symbol=\(symbol)&contractType=\(type)&strike=\(selectedStrike)&fromDate=\(selectedExpiry)&toDate=\(selectedExpiry)") else {
        return
    }

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let dataResponse = data,
            error == nil else {
                //print(error?.localizedDescription ?? "Response Error")

                DispatchQueue.main.async {


                        self.presentedViewController?.dismiss(animated: true, completion: {

                        let alert = UIAlertController(title: "There was an error retrieving ask price and volatility.", message: "Please try again later.", preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .default))
                        self.present(alert, animated: true)

                    })

                }

                return }
        do{
            //here dataResponse received from a network request
            let jsonResponse = try JSONSerialization.jsonObject(with:
                dataResponse, options: [])
            //                //print(jsonResponse) //Response result

            guard let jsonDict = jsonResponse as? NSDictionary else {
                return
            }
            //                //print(jsonDict)

            var strikeMap : NSDictionary = [:]

            if self.type == "CALL" {
                strikeMap = jsonDict["callExpDateMap"] as! NSDictionary

            } else {
                strikeMap = jsonDict["putExpDateMap"] as! NSDictionary

            }

            self.strikes.removeAllObjects()

            let inner = strikeMap.object(forKey: strikeMap.allKeys.first ?? "<#default value#>") as! NSDictionary
            let innerAgain = inner.object(forKey: inner.allKeys.first ?? "<#default value#>") as! NSArray
            let dict : NSDictionary = innerAgain[0] as! NSDictionary

            let dict2 = ["ask" : dict["ask"] as! NSNumber, "IV" : dict["volatility"] as! NSNumber] as NSMutableDictionary



            completionBlock(dict2)


        } catch let parsingError {
            print("Error", parsingError)
        }
    }
    task.resume()
}

编辑:使用self.presentedViewController?.dismiss(animated: true, completion: nil)不能解决问题。此外,未调用用于self.progress的dismiss函数的完成块。

编辑2:,即使在撤消之前在警报控制器上调用了present,在回调函数中的撤消代码之前是否存在presentedViewController吗?

3 个答案:

答案 0 :(得分:1)

只有一切顺利,您的警报才会被取消。 我建议您将功能更改为以下形式:

 func getCostandIV (completionBlock: @escaping (NSMutableDictionary?, Error?) -> Void) -> Void

,并确保在completionBlock语句失败或引发错误时调用guard。在您当前的代码中,只有在网络请求失败时才会关闭警报,而在解析JSON时出现问题时则不会关闭警报。

答案 1 :(得分:0)

如果您多次调用getCostandIV方法,则不会显示第二个警报,并且self.progress将引用未显示的警报。

更改

self.progress.dismiss(animated: true, completion: nil)

收件人

self.presentedViewController?.dismiss(animated: true, completion: nil)

答案 2 :(得分:0)

使用此方法,要消除警报,应在异步块中添加dismiss方法,并为此设置计时器,应告诉异步块从现在开始到5秒开始异步,然后再做一些事情:

        alert.addAction(UIAlertAction(title: "ok", style: .default,
                                      handler: nil))
        viewController.present(alert, animated: true, completion: nil)

        // change to desired number of seconds (in this case 5 seconds)
        let when = DispatchTime.now() + 5
        DispatchQueue.main.asyncAfter(deadline: when){
            // your code with delay
            alert.dismiss(animated: true, completion: nil)
        }