Search code examples
swiftios8swift2alertview

"Application tried to present modally an active controller" iOS8 - When i want to present an AlertView in logging out


Well, I am really a beginner in terms of swift 2 and I am having an error in presentViewController, this is just an alert view before logging out. But I am receiving an application tried to present modally an active conroller. Well I have a menu bar using the SWRevealViewController and MenuBarTableViewController class that holds the menu bar. Logout button was on the last selection of the menu bar, and I am browsing every single menu and it works fine but this Logout AlertView makes it to crash and gets that error. Here is the code.

class MenuBarTableViewController: UITableViewController {
    private struct PMText {
       static let logoutBody = "Are you sure you want to log out?"
    }

    var alert = UIAlertController(title: "Logout", message: PMText.logoutBody, preferredStyle: UIAlertControllerStyle.Alert)

    override func viewDidLoad() {
        super.viewDidLoad()

        alert.addAction(UIAlertAction(
             title: "No",
             style: UIAlertActionStyle.Cancel)
        { (action: UIAlertAction) -> Void in
             //do nothing just to close the alertView
            }
        )

        alert.addAction(UIAlertAction(
             title: "Yes",
             style: UIAlertActionStyle.Default)
        { (action: UIAlertAction) -> Void in
             self.performSegueWithIdentifier("log out", sender: nil)
            }
        )

        tableView.separatorColor = UIColor.clearColor()
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
         for index in 0..<tableView.numberOfRowsInSection(indexPath.section) {
         let cellIndexPath = NSIndexPath(forRow: index, inSection: indexPath.section)
         let cell = tableView.cellForRowAtIndexPath(cellIndexPath)!
         if index == indexPath.row {
            cell.backgroundColor = UIColor(red: 254/255, green: 255/255, blue: 197/255, alpha: 1)
         } else {
             cell.backgroundColor = UIColor.whiteColor()
         }


         if (indexPath.row == 6) {
             presentViewController(alert, animated: true, completion: nil)
         }
       }
    }



}

Well I am not sure what makes my code crash and received this kind of exception since I am doing Alert View Controller a lot of times in my other View Controller. But this is the first time i tried this in MenuBarTableViewController


Solution

  • I've found out a solution for this by creating a plain swift file for menubar using the SWReveal rather than creating a cocoa touch file. So it will now import Foundation rather than import UIKit. It is having trouble with the menu bar slider because the slider is considered as controller when it is a cocoa touch and the AlertView is another view controller to be presented.