Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert error in swift [duplicate]

Tags:

ios

swift

I writing this code in swift and Xcode 6

@IBAction func Alert(sender : UIButton) {
  var alert : UIAlertView = UIAlertView(title: "Hey", message: "This is  one Alert",       delegate: nil, cancelButtonTitle: "Working!!")

    alert.show()
}

Xcode doesn't show error in compilation.

but in Simulator the APP fails and return the error:

(lldb)
thread 1 EXC_BAD_ACCESS(code 1 address=0x20)
like image 830
rickdecard Avatar asked Jun 08 '14 17:06

rickdecard


People also ask

How do I set an alert 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.

How do I add an alert in AppDelegate Swift?

@OrkhanAlizade create a ViewController , put your code into the ViewControllers viewDidAppear method, and in your AppDelegate , set that ViewController as the windows rootViewController (and also don't forget to create the window itself). @DánielNagy it works!


1 Answers

There is a bug in the Swift shim of the UIAlertView convenience initializer, you need to use the plain initializer

let alert = UIAlertView()
alert.title = "Hey"
alert.message = "This is  one Alert"
alert.addButtonWithTitle("Working!!")
alert.show()

This style code feels more true to the Swift Language. The convenience initializer seems more Objective-C'ish to me. Just my opinion.

Note: UIAlertView is deprecated (see declaration) but Swift supports iOS7 and you can not use UIAlertController on iOS 7

View of UIAlertView Declaration in Xcode

// UIAlertView is deprecated. Use UIAlertController with a preferredStyle of   UIAlertControllerStyleAlert instead
class UIAlertView : UIView {

An Alert in Swift iOS 8 Only

var alert = UIAlertController(title: "Hey", message: "This is  one Alert", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Working!!", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

Update for Swift 4.2

let alert = UIAlertController(title: "Hey", message: "This is  one Alert", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Working!!", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
like image 126
GayleDDS Avatar answered Oct 05 '22 18:10

GayleDDS