如何彻底解雇uialertcontroller?

时间:2015-06-17 07:24:39

标签: ios swift uialertcontroller

实际上我有一个带有4种方法的视图控制器。 3个方法用于显示UIAlertController没有操作按钮,例如" ok"或"取消"。标题和消息。解雇那些UIAlertController的最终方法。我的一个警报是在异步调用请求时显示。当我们得到结果时,它将被解雇并隐藏。

问题是当我的第一个警报显示并且突然连接丢失时,另一个警报将显示关于" Internet Lost"由于该警告,消息无法显示。

2015-06-17 13:49:04.787 myauction[2404:40506] Warning: Attempt to present <UIAlertController: 0x7f8d136bafa0> on <myauction.AuctionLatestViewController: 0x7f8d13771180> while a presentation is in progress!

这意味着我无法成功解除第一个警报。有什么帮助吗?

这是myAlertController

import UIKit

class MyAlertViewController:UIViewController{

var myAlertController : UIAlertController!

func displayLoadingAlert(viewController: UIViewController?) -> UIAlertController {

    var controllerToPresent = viewController
    if controllerToPresent == nil {
        controllerToPresent = self
    }

    //create an alert controller
    myAlertController = UIAlertController(title: "Loading...", message: "We are getting the data,Please Wait", preferredStyle: .Alert)

    let indicator = UIActivityIndicatorView()
    indicator.color = UIColor.redColor()
    indicator.setTranslatesAutoresizingMaskIntoConstraints(false)
    myAlertController.view.addSubview(indicator)

    let views = ["pending" : myAlertController.view, "indicator" : indicator]
    var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[indicator]-(7)-|", options: nil, metrics: nil, views: views)
    constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|[indicator]|", options: nil, metrics: nil, views: views)
    myAlertController.view.addConstraints(constraints)

    indicator.userInteractionEnabled = false
    indicator.startAnimating()

    controllerToPresent!.presentViewController(myAlertController, animated: true, completion: nil)

    return myAlertController
}

func connectionErrorAlert(viewController: UIViewController?) -> UIAlertController {

    var controllerToPresent = viewController
    if controllerToPresent == nil {
        controllerToPresent = self
    }

    //create an alert controller
    myAlertController = UIAlertController(title: "Not Connected", message: "No Internet Connection", preferredStyle: .Alert)
    let defaultAction = UIAlertAction(title: "OK", style: .Default,handler:nil)
    myAlertController.addAction(defaultAction)

    controllerToPresent!.presentViewController(myAlertController, animated: true, completion: nil)

    return myAlertController
}

func requestTimeOutErrorAlert(viewController: UIViewController?) -> UIAlertController {

    var controllerToPresent = viewController
    if controllerToPresent == nil {
        controllerToPresent = self
    }

    //create an alert controller
    myAlertController = UIAlertController(title: "Request Time Out", message: "Please Tap Retry to Get The Data", preferredStyle: .Alert)
    let defaultAction = UIAlertAction(title: "OK", style: .Default,handler:nil)
    myAlertController.addAction(defaultAction)

    controllerToPresent!.presentViewController(myAlertController, animated: true, completion: nil)

    return colayAlertController
}

func dismissLoadingAlert(){
    myAlertController.dismissViewControllerAnimated(true, completion: nil)
}

}

这是我的viewcontroller(注意我不会显示myAlertViewController的初始化)

func getResults{
     api.searchCar()
     //This is where i start to load my first alert every time it call
     self.myAlertViewController = displayLoadingAlert(self)
}

func didReceiveAPIResults(results: NSDictionary,headers:JSON) {
     dispatch_async(dispatch_get_main_queue(), {
          //do about showing the results....

          //Then i dismiss my first loading alert
          self.myAlertController.dismissViewControllerAnimated(true){}
     })
}

func didNotReceiveAPIResults(results: Bool,error:NSError){
    dispatch_async(dispatch_get_main_queue(), {
        //I did dismiss the first alert before i gonna show another one
        self.myAlertController.dismissViewControllerAnimated(true){
        if (results) {
            if error.localizedDescription == "The Internet connection appears to be offline."{
                self.myAlertViewController = connectionErrorAlert(self)
                self.carTableView.hidden=true
                self.retryButton?.hidden=false
                self.retryButton?.enabled=true
            }
            if error.localizedDescription == "Request Time Out."{
                self.myAlertViewController = requestTimeOutErrorAlert(self)
                self.carTableView.hidden=true
                self.retryButton?.hidden=false
                self.retryButton?.enabled=true
            }

        }else{
            //self.myAlertController.displayLoadingAlert(self)
            self.retryButton?.hidden=true
            self.retryButton?.enabled=false
            self.carTableView.hidden=false
            self.carTableView.reloadData()
        }
      }
    })
}

2 个答案:

答案 0 :(得分:2)

您应该在completion方法的dismissViewControllerAnimated块中插入代码,然后再以模态方式呈现另一个ViewController

查看我已更新的代码:

func didNotReceiveAPIResults(results: Bool,error:NSError){
    dispatch_async(dispatch_get_main_queue(), {
        //
        // I'm calling your error message in the completion block of the
        // dismissViewControllerAnimated Method
        //
        self.myAlertController.dismissViewControllerAnimated(true) {
        if (results) {
            if error.localizedDescription == "The Internet connection appears to be offline."{
                self.myAlertController.connectionErrorAlert(self)
            }

            if error.localizedDescription == "Request Time Out."{
                self.myAlertController.requestTimeOutErrorAlert(self)
            }

            //
            // Moved this code out of your if-statements since they are called
            // no matter which case is true
            //
            self.carTableView.hidden=true
            self.retryButton?.hidden=false
            self.retryButton?.enabled=true
        } else {
            //self.myAlertController.displayLoadingAlert(self)
            self.retryButton?.hidden=true
            self.retryButton?.enabled=false
            self.carTableView.hidden=false
            self.carTableView.reloadData()
        }
        }
    })
}

答案 1 :(得分:0)

首先,我犯了一个错误,因为我正在创建新的viewcontroller而不是定义extension.So,如果有些初学者正在搜索结果,请不要像上面的代码那样。所以这就是答案。< / p>

如果您想添加自定义提醒,请使用此类扩展程序。

import UIKit

extension UIAlertController {

class func displayLoadingAlert() -> UIAlertController {

    //create an alert controller
    let myAlertController = UIAlertController(title: "Loading...", message: "We are getting the data,Please Wait...", preferredStyle: .Alert)

    let indicator = UIActivityIndicatorView()
    indicator.color = UIColor.redColor()
    indicator.setTranslatesAutoresizingMaskIntoConstraints(false)
    myAlertController.view.addSubview(indicator)

    let views = ["pending" : myAlertController.view, "indicator" : indicator]
    var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[indicator]-(7)-|", options: nil, metrics: nil, views: views)
    constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|[indicator]|", options: nil, metrics: nil, views: views)
    myAlertController.view.addConstraints(constraints)

    indicator.userInteractionEnabled = false
    indicator.startAnimating()

    return myAlertController
}

class func connectionErrorAlert() -> UIAlertController {

    let myAlertController = UIAlertController(title: "Not Connected", message: "No Internet Connection", preferredStyle: .Alert)
    let defaultAction = UIAlertAction(title: "OK", style: .Default,handler:nil)
    myAlertController.addAction(defaultAction)
    return myAlertController
}

class func requestTimeOutErrorAlert() -> UIAlertController {
    // same as above
}
}

然后如何从其他视图控制器中使用它(用于显示和解除)

class ViewController : UIViewController{

       var myAlert : UIAlertController!
       //For displaying the one of the alert
       func getResults(){
            myAlert = UIAlertController.displayLoadingAlert()
            self.presentViewController(myAlert, animated: true, completion: nil)
       }
       //For dismissing the alert,please add the code in the completion that will do after dismiss
      func afterGettingResults(){
           self.myAlert.dismissViewControllerAnimated(true){
               //do your job after dismiss is done
           }
      }
} 

希望每个人都能得到这个帮助。感谢@ezCoding试图帮助我摆脱我的这个黑暗错误并向我展示成功之光。