"Type 'UIAlertController' has no member 'Style' " - uikit

Trying to create an alert box but an issue comes along saying "Type 'UIAlertController' has no member 'Style'"
#IBAction func showMessage (sender: UIButton) {
let alertController = UIAlertController(title: "Welcome to My First App",
message: "Hello World", preferredStyle: UIAlertController.Style.alert);
alertController.addAction(UIAlertAction(title: "OK", style:
UIAlertAction.Style.default, handler:nil))
present(alertController, animated:true, completion: nil)

UIAlertController has the following parameters:
convenience init(title: String?,
message: String?,
preferredStyle: UIAlertController.Style)
The constants for UIAlertController.Style are actionSheet and alert.
Thus you can just do the following (same applies for UIAlertAction):
let alertController = UIAlertController(
title: "Welcome to my First App",
message: "Hello World",
preferredStyle: .alert)
alertController.addAction(UIAlertAction(
title: "OK",
style: .default,
handler: nil))

Related

Add a second text field to UIAlert Swift 2

I am having problems in adding a second text field to my completion block.
Can someone please show me on how to add one more textfield please.
I am trying to add a self.newFirstNameInput = // this is the part that I do not understand?
func insertNewObject(sender: AnyObject) {
let newNameAlert = UIAlertController(title: "Add New User", message: "What's the user's name?", preferredStyle: UIAlertControllerStyle.Alert)
newNameAlert.addTextFieldWithConfigurationHandler { (alertTextField) -> Void in
self.newLastNameInput = alertTextField
}
newNameAlert.view.setNeedsLayout()
newNameAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
newNameAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: addNewUser))
presentViewController(newNameAlert, animated: true, completion: nil)
}
var txtField1: UITextField!
var txtField2: UITextField!
override func viewDidLoad()
{
let alert = UIAlertController(title: "Enter Input", message: "", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(addTextField1)
alert.addTextFieldWithConfigurationHandler(addTextField2)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (UIAlertAction)in
print("Cancel")
}))
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
print("Done")
print("First Name : \(self.txtField1.text!)")
print("Last Name : \(self.txtField2.text!)")
}))
self.presentViewController(alert, animated: true, completion: nil)
}
func addTextField1(textField: UITextField!)
{
textField.placeholder = "Enter first name"
txtField1 = textField
}
func addTextField2(textField: UITextField!)
{
textField.placeholder = "Enter last name"
txtField2 = textField
}
i hope my answer help you...

Alert message button, with restrictions to go further to next viewcontroller

Hello I am making a ViewController with a PickerView that has age restrictions. I made it with the alert and age restrictions but I need it to deny access to next ViewController if the user isn't old enough.
Made my code like this, I guess its in the Else true I need some more code, but I'm not sure tho. I hope a kind soul can help me :)
#IBAction func verificerKnap(sender: AnyObject) {
// Creating the age restriction for the datepicker
let dateOfBirth = datoPicker.date
let today = NSDate()
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let age = gregorian.components([.Year], fromDate: dateOfBirth, toDate: today, options: [])
if age.year < 18 {
// Alert controller som sender en advarsel hvis personen er under 18år
let alertController = UIAlertController(title: "Age restriction", message:
"This app requires an age of 18+", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
} else {
true
You can present an UIAlertController which asks if you are 18 years or older. Than link 2 buttons "Ok" and "Cancel" and add delegates for those:
let alertController = UIAlertController(title: "Default Style", message: "Are you 18 years or older?", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {
(action) in
print("User is not yet >18")
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) {
(action) in
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(desired_view_controller, animated: true, completion: nil)
})
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
based on: http://nshipster.com/uialertcontroller/

Swift 2.1 - Call can throw, but it is not marked with 'try' and the error is not handled

I am having errors with the following code, how do I fix this?
'Call can throw, but it is not marked with 'try' and the error is not handled'
let reachability = Reachability.reachabilityForInternetConnection() // - Error Here
reachability.whenReachable = { reachability in
if reachability.isReachableViaWiFi() {
let alertController = UIAlertController(title: "Alert", message: "Reachable via WiFi", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
else {
let alertController = UIAlertController(title: "Alert", message: "Reachable via Cellular", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
reachability.whenUnreachable = { reachability in
let alertController = UIAlertController(title: "Alert", message: "Not Reachable", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
reachability.startNotifier() // - Error Here
}
If you take a look at the example, you need to wrap the call with try.
let reachability = try Reachability.reachabilityForInternetConnection()
Swift's try/catch system is designed to be clear to developers, which means you need to mark any methods that can throw using the try keyword.
When a function throws an error, it changes the flow of your program, so it’s important that you can quickly identify places in your code that can throw errors. To identify these places in your code, write the try keyword—or the try? or try! variation—before a piece of code that calls a function, method, or initializer that can throw an error.
You can read more at Apple reference site.

UIAlertController fails to show UIAlertView

I want to show a UIAlertView when login credentials are wrong, but instead it just goes to the next view and doesn't show the UIAlertView?
It says invalid login credentials but seems to ignore the error. I tried a custom segue but it was calling itself when the button was pressed. I didnt do not self.presentsegue so is it the code. If reachability is not the problem, just checking if the user is connected to the internet, thats not a problem.
func login()
{
if Reachability.isConnectedToNetwork()
{
activityLoader.alpha = 1
activityLoader.startAnimating()
let emailText = EmailTextBox.text
PFUser.logInWithUsernameInBackground(EmailTextBox.text!, password: PasswordTextBox.text!){(user: PFUser?, error: NSError?) -> Void in
if user != nil
{
//Login Successfully
NSUserDefaults.standardUserDefaults().setObject(emailText, forKey: "UserSaved")
NSUserDefaults.standardUserDefaults().synchronize()
self.activityLoader.alpha = 0
self.activityLoader.stopAnimating()
let title = "Successfully logged in"
let message = "Enjoy"
let okText = "OK"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let OKbutton = UIAlertAction(title: okText, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(OKbutton)
self.presentViewController(alert, animated: true, completion: nil)
}
else
{
self.activityLoader.alpha = 0
self.activityLoader.stopAnimating()
let title = "Please try again"
let message = "Check your login credentials"
let okText = "OK"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let OKbutton = UIAlertAction(title: okText, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(OKbutton)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
else
{
self.activityLoader.alpha = 0
self.activityLoader.stopAnimating()
let title = "No Internet Connection"
let message = "Please ensure you are connected to the Internet"
let okText = "OK"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let OKbutton = UIAlertAction(title: okText, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(OKbutton)
self.presentViewController(alert, animated: true, completion: nil)
}
}
#IBAction func LogInPressed(sender: AnyObject)
{
if self.EmailTextBox.text == "" || self.PasswordTextBox.text == ""
{
let title = "Please try again"
let message = "Check your login credentials"
let okText = "OK"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let OKbutton = UIAlertAction(title: okText, style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(OKbutton)
self.presentViewController(alert, animated: true, completion: nil)
}
else
{
login()
}
}
Check to see in your Storyboard file that there is no segue from the button to the next view controller.

Swift alert view with OK and Cancel: which button tapped?

I have an alert view in Xcode written in Swift and I'd like to determine which button the user selected (it is a confirmation dialog) to do nothing or to execute something.
Currently I have:
#IBAction func pushedRefresh(sender: AnyObject) {
var refreshAlert = UIAlertView()
refreshAlert.title = "Refresh?"
refreshAlert.message = "All data will be lost."
refreshAlert.addButtonWithTitle("Cancel")
refreshAlert.addButtonWithTitle("OK")
refreshAlert.show()
}
I'm probably using the buttons wrong, please do correct me since this is all new for me.
If you are using iOS8, you should be using UIAlertController — UIAlertView is deprecated.
Here is an example of how to use it:
var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
presentViewController(refreshAlert, animated: true, completion: nil)
As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift):
http://hayageek.com/uialertcontroller-example-ios/
Swift 3 update:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
Swift 5 update:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
Swift 5.3 update:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
refreshAlert .dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(refreshAlert, animated: true, completion: nil)
You can easily do this by using UIAlertController
let alertController = UIAlertController(
title: "Your title", message: "Your message", preferredStyle: .alert)
let defaultAction = UIAlertAction(
title: "Close Alert", style: .default, handler: nil)
//you can add custom actions as well
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
.
Reference: iOS Show Alert
Updated for swift 3:
// function defination:
#IBAction func showAlertDialog(_ sender: UIButton) {
// Declare Alert
let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to Logout?", preferredStyle: .alert)
// Create OK button with action handler
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
print("Ok button click...")
self.logoutFun()
})
// Create Cancel button with action handlder
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
print("Cancel button click...")
}
//Add OK and Cancel button to dialog message
dialogMessage.addAction(ok)
dialogMessage.addAction(cancel)
// Present dialog message to user
self.present(dialogMessage, animated: true, completion: nil)
}
// logoutFun() function definaiton :
func logoutFun()
{
print("Logout Successfully...!")
}
Hit Upvote :)
Step # 1: Make a new Separate Class
import Foundation
import UIKit
class AppAlert: NSObject {
//Singleton class
static let shared = AppAlert()
//MARK: - Delegate
var onTapAction : ((Int)->Void)?
//Simple Alert view
public func simpleAlert(view: UIViewController, title: String?, message: String?){
ToastManager.show(title: title ?? "", state: .error)
}
//Alert view with Single Button
public func simpleAlert(view: UIViewController, title: String, message: String, buttonTitle: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
//okButton Action
let okButton = UIAlertAction(title: buttonTitle, style: UIAlertAction.Style.default) {
(result : UIAlertAction) -> Void in
self.onTapAction?(0)
}
alert.addAction(okButton)
view.present(alert, animated: true, completion: nil)
}
//Alert view with Two Buttons
public func simpleAlert(view: UIViewController, title: String, message: String, buttonOneTitle: String, buttonTwoTitle: String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
//Button One Action
let buttonOne = UIAlertAction(title: buttonOneTitle, style: UIAlertAction.Style.default) {
(result : UIAlertAction) -> Void in
self.onTapAction?(0)
}
//Button Two Action
let buttonTwo = UIAlertAction(title: buttonTwoTitle, style: UIAlertAction.Style.default) {
(result : UIAlertAction) -> Void in
self.onTapAction?(1)
}
alert.addAction(buttonOne)
alert.addAction(buttonTwo)
view.present(alert, animated: true, completion: nil)
}
}
Step # 2: Call As
AppAlert.shared.simpleAlert(view: self, title: "Register First", message: "Please Register to Proceed", buttonOneTitle: "Cancel", buttonTwoTitle: "OK")
AppAlert.shared.onTapAction = { [weak self] tag in
guard let self = self else {
return
}
if tag == 0 {
// DO YOUR WORK
} else if tag == 1 {
// DO YOUR WORK
}
}
You may want to consider using SCLAlertView, alternative for UIAlertView or UIAlertController.
UIAlertController only works on iOS 8.x or above, SCLAlertView is a good option to support older version.
github to see the details
example:
let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
print("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")
small update for swift 5:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
self.present(refreshAlert, animated: true, completion: nil)

Resources