Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error showing a UIAlertView in swift

Im trying to show a UIAlertView in my swift App

    alert = UIAlertView(title: "",
        message: "bla",
        delegate: self,
        cancelButtonTitle: "OK")
    alert!.show()

=> BAD_ACESS error in: -[_UIAlertViewAlertControllerShim initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:] ()

so I suspected self. I set it to nil

    alert = UIAlertView(title: "",
        message: "bla",
        delegate: nil,
        cancelButtonTitle: "OK")
    alert!.show()

=> ARM_DA_ALIGN error in: -[_UIAlertViewAlertControllerShim initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:] ()


the full code

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UIAlertViewDelegate {

    @lazy var window = UIWindow(frame: UIScreen.mainScreen().bounds)
    @lazy var locationManager = CLLocationManager()
    var alert: UIAlertView? = nil

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        //setup dummy window
        self.window.backgroundColor = UIColor.whiteColor()
        self.window.rootViewController = UIViewController()
        self.window.makeKeyAndVisible()

        alert = UIAlertView(title: "",
            message: "bla",
            delegate: nil,
            cancelButtonTitle: "OK")
        alert!.show()

    return true
    }
}

How to do it right? :)

like image 620
Daij-Djan Avatar asked Jun 04 '14 14:06

Daij-Djan


People also ask

How would I create a UIAlertView in Swift?

var alertView = UIAlertView(); alertView.

How do I show a popup message in Swift?

Adding Action Buttons to Alert Dialog To create an action button that the user can tap on, we will need to create a new instance of an UIAlertAction class and add it to our alert object. To add one more button to UIAlertController simply create a new UIAlertAction object and add it to the alert.


2 Answers

Swift 5

You should do it this way:

let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Button", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
like image 113
dibi Avatar answered Nov 16 '22 20:11

dibi


Even though UIAlertView is depreciated in iOS8, you can get away with using it but not through it's init function. For example:

    var alert = UIAlertView()
    alert.title = "Title"
    alert.message = "message"
    alert.show()

Atleast this is the only way so far I've been able to successfully use an UIAlertView. I'm unsure on how safe this is though.

like image 42
John Riselvato Avatar answered Nov 16 '22 20:11

John Riselvato