John511 John511 - 5 months ago 70
iOS Question

Swift UIAlertController showing custom message

I have a ViewController class thats only purpose is to display an alert message with a custom message and title that is passes in through a custom init message. This is done as soon as the view appears, in viewDidLoad. My problem however is that when it comes to this view it pops up and is stuck in this view forever, instead of just putting the view over the other. I am not sure how to fix this. Here is the code for my alertVC class

import UIKit

class AlertVC: UIViewController {

var myMessage: String?
var myTitle: String?

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


override func viewDidAppear(animated: Bool){
let alertController = UIAlertController(title: myTitle, message: myMessage, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) {
(action: UIAlertAction) in print("Youve pressed OK Button")
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
}

convenience init(title: String, message: String){
self.init()
self.myTitle = title
self.myMessage = message
}
}


This is the code for how I create an object for this and try and show it.

let alert = AlertVC(title: "Error", message: "error")
presentViewController(alert, animated: true, completion: nil)


Any help is appreciated, leave a comment if you need more info. Thanks!

Answer

Why not simply an extension?

extension UIViewController {

  func presentAlertWithTitle(title: String, message : String)
  {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    let OKAction = UIAlertAction(title: "OK", style: .Default) {
      (action: UIAlertAction) in print("Youve pressed OK Button")
    }
    alertController.addAction(OKAction)
    self.presentViewController(alertController, animated: true, completion: nil)
  }
}

and call it with

presentAlertWithTitle("Error", message: "error")

in any UIViewController class