Error alert in uipickerview options - swift2

I'm working in these lines trying to show an "Error" message if the user forgot to fill the username label or choose an option from the PickerView ("-- Choose an option please --"), but, when I run this, it takes also the other options from the picker view as an error.
If the user choose A,B,C,D it's okay. I just want to define the first one ("-- Choose an option please --") as an error, but it doesn't works.
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
let userRole:[String] = ["-- Choose an option please --", "A", "B", "C", "D"]
var selectedOption:String?
#IBOutlet weak var usernameLabel: UITextField!
#IBOutlet weak var pickerRoleLabel: UIPickerView!
#IBAction func continueButton(sender: AnyObject) {
if usernameLabel.text == "" || userRole[0] == "-- Choose an option please --" {
let alert = UIAlertController(title: "Error in form", message: "Please fill the information", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
How can I improve this?
Thanks in advance!

You could always ensure your "-- Choose an option please --" string as first item. So you can just test if the value of the desired component with UIPickerView´s selectedRowInComponent method is bigger than "0".
If "0" is returned from this method, means your first position is selected, but if you receive "-1", no value was selected in your picker. Any value bigger than "0" you can considerate as a valid value.
selectedRowInComponent(_ component: Int)
#IBAction func continueButton(sender: AnyObject) {
//If you
if usernameLabel.text == "" || myPickerView.selectedRowInComponent(0) < 1 {
let alert = UIAlertController(title: "Error in form", message: "Please fill the information", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: 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/

My function in my main view controller is not working

I´m trying to use a function that I wrote in my main viewController, this is it.
func displayAlert(title: String, message: String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "Ok", style: .Default, handler:
{ (action) -> Void in
self .dismissViewControllerAnimated(true, completion: nil)
})))
self.presentViewController(alert, animated: true, completion: nil)
}
I´m trying to use it on other viewController call viewControllerRegistro, for some reason is not working. this is it...
#IBAction func signUp(sender: AnyObject)
{
//checar que el usuario copero al poner su correo electronico y su contraseña
if usernameRegistro.text == "" || correoRegistro.text == "" || contraseñaRegistro.text == ""
{
ViewController().displayAlert("Informando Error", message: "Porfavor completa los cuadros de registro")
}
any help?
I´m using xcode 7.0 beta 6 with swift 2
ViewController() creates a new ViewController instance. That view controller is not part of your view hierarchy (because you just created it, without adding it anywhere).
You have to call that method on the view controller that is currently visible. Because of that the function should not be part of your MainViewController class. It should be part of the ViewController class that needs it. Or if you need it in multiple view classes you could add the function to an extension of UIViewController:
extension UIViewController {
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "Ok", style: .Default, handler:
{ (action) -> Void in
self .dismissViewControllerAnimated(true, completion: nil)
})))
presentViewController(alert, animated: true, completion: nil)
}
}
With this extension you can call displayAlert on any UIViewController and UIViewController subclasses.

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.

Error when loading UIAlertController

I want to load an alert when internet connection is not available. The function for checking internet connection is ready but I cannot load the alert. So I just put the alert code in viewDidLoad without any conditions etc. and got this error:
Warning: Attempt to present UIAlertController: 0x12752d400 on x.ViewController: 0x127646f00 whose view is not in the window hierarchy!
Code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Delegates
verificationCode.delegate = self
let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default) { _ in }
alert.addAction(action)
self.presentViewController(alert, animated: true) {}
if (!Util.isConnectedToNetwork()) {
self.isConnected = false
}
}
Could you tell me how to fix it?
The error tells you what has gone wrong.
You are trying to present a view controller in viewDidLoad except the view, although loaded, is not in any hierarchy. Try putting the code in the viewDidAppear method, which is called after the view appears on screen, and is in a view hierarchy.
Swift 4 Update
I think this could help you for your problem :
override func viewDidLoad() {
super.viewDidLoad()
verificationCode.delegate = self
let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .alert)
let delete = UIAlertAction(title: "OK", style: .default) { (_) in }
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alert.addAction(cancelAction)
alert.addAction(delete)
alert.popoverPresentationController?.sourceView = sender as UIView
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
if (!Util.isConnectedToNetwork()) {
self.isConnected = false
}
}
Move the code to viewDidAppear from viewDidLoad
override func viewDidAppear(animated: Bool) {
// Delegates
verificationCode.delegate = self
let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default) { _ in }
alert.addAction(action)
self.presentViewController(alert, animated: true) {}
if (!Util.isConnectedToNetwork()) {
self.isConnected = false
}
}

Resources