Swift 2, нераспознанный селектор отправлен экземпляру для UIAlertController

Я получаю сообщение об ошибке, как показано ниже, когда я нажимаю TableView после нажатия «Поиск».

Ошибка ниже 2016-06-03 11:20:31.578 ContactPLUS[1724:678512] Предупреждение: Попытка представить, на котором уже присутствует (null) st >> 2016-06-03 11:20: 32.001 ContactPLUS[1724:678512] -[_UIAlertControllerAlertPresentationController AdaptivePresentationController]: нераспознанный селектор отправлен экземпляру 0x1616570d0

2016-06-03 11:20:32.001 ContactPLUS[1724:678512] *** Завершение работы приложения из-за неперехваченного исключения «NSInvalidArgumentException», причина: «-[_UIAlertControllerAlertPresentationController AdaptivePresentationController]: нераспознанный селектор отправлен экземпляру 0x1616570d0»

*** First throw call stack: (0x182876e38 0x181edbf80 0x18287dccc 0x18287ac74 0x182778d1c 0x18836433c 0x1880117f8 0x187d20740 0x187c72fd8 0x187c80990 0x1879b24a4 0x18282c7b0 0x18282a554 0x18282a984 0x182754d10 0x18403c088 0x187a29f70 0x1000f8070 0x1822f28b8) libc++abi.dylib: terminating with uncaught exception of type NSException

Мой код ниже

Переход к функции

dispatch_async(dispatch_get_main_queue()) {
                                   self.searchActivityLoader.stopAnimating()
                                   self.searchActivityLoader.hidden = true
                                    self.showError(self.noDataFound)
                                }

Логика для отображения контроллера предупреждений:

func showError(errorStr: String){

    dispatch_async(dispatch_get_main_queue(), {

        if(!errorStr.isEmpty){
            let alertController =  self.controllerUtil!.customOkAlert("Fail",buttonTitle:"OK" , alertMessage: errorStr)
            self.presentViewController(alertController, animated: true, completion: nil) 
            //**Error comes after executing  above two lines**
        }
        self.genericArr = []

        self.contactsTableView.dataSource = self
        self.contactsTableView.reloadData()
        self.searchActivityLoader.stopAnimating()
        self.searchActivityLoader.hidden = true
    })

}

///CustomeOkAlert

//Предупреждение контроллера для управления действиями по умолчанию и пользовательскими сообщениями

func customOkAlert(alertPageTitle: String,buttonTitle: String, alertMessage: String) -> UIAlertController
{
    let customeAlert = UIAlertController(title: alertPageTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)

    customeAlert.view.layer.cornerRadius = 10
    customeAlert.view.backgroundColor = utility.uicolorFromHex(0xEBEBED)
    customeAlert.view.tintColor = utility.uicolorFromHex(0x70B420)
    let cancelAction: UIAlertAction = UIAlertAction(title: buttonTitle, style: .Default){action in
        //do nothing
    }
    customeAlert.addAction(cancelAction)


    return customeAlert
}

person dhaval shah    schedule 03.06.2016    source источник
comment
Вы можете опубликовать метод customOkAlert()?   -  person Mathews    schedule 03.06.2016
comment
Можете ли вы поместить print("someText") в свою функцию showError, чтобы увидеть, вызывается ли она дважды?   -  person Laffen    schedule 03.06.2016


Ответы (1)


Причина Attempt to present <UIAlertController which is already presenting - частые ошибки, вам нужно добавить проверку, если сообщение об ошибке уже представлено. Следующий код помог мне воспроизвести вашу проблему. Комментирование проверки в методе handleError запустит воспроизведение задачи:

class ViewController: UIViewController {

    var alertController: UIAlertController!

    override func viewDidLoad() {
        super.viewDidLoad()

        handleError()
        handleError()
    }

    func handleError() {

        dispatch_async(dispatch_get_main_queue(), {

            //commenting this check will start issue reproduction
            if self.alertController != nil {
                print("alert is already presented")
                return
            }
            self.alertController =  self.customOkAlert("Fail",buttonTitle:"OK" , alertMessage: "qweqwe")
            self.presentViewController(self.alertController, animated: true, completion: nil)
        })
    }

    func customOkAlert(alertPageTitle: String,buttonTitle: String, alertMessage: String) -> UIAlertController
    {
        let customeAlert = UIAlertController(title: alertPageTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)

        customeAlert.view.layer.cornerRadius = 10

        let cancelAction: UIAlertAction = UIAlertAction(title: buttonTitle, style: .Default){action in

            self.alertController = nil
        }
        customeAlert.addAction(cancelAction)


        return customeAlert
    }
}
person Igor B.    schedule 03.06.2016
comment
B, Пробовал то же самое ... но, похоже, я получаю ту же ошибку. - person dhaval shah; 03.06.2016