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/
Related
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...
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.
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
}
}
My application suddenly started crashing and after four hours I still can't figure out why. It worked perfectly last Friday and I haven't changed anything to the code since.
I have tried:
Stepping through code with breakpoints.
Adding an Exception Breakpoint.
Enabling Zombie objects.
Turning static analyser on.
None of these made me any wiser or pointed me to a more exact error message.
The crash happens when I select a cell. It then points to the AppDelegate with the message "Thread 1: EXC_BAD_ACCESS". Continueing the program execution does not give a more clear error message.
Some images of the error and my code can be seen below. I am really at a loss here so any help will be much appreciated.
Code:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
var dealer : DealerList
var alldealer : TotalDealerList
var id : String
if scAll.selectedSegmentIndex == 0
{
if scMatur.selectedSegmentIndex == 0
{
if (self.resultSearchController.active)
{
dealer = filtereddealers[indexPath.row]
}
else
{
dealer = dealers[indexPath.row]
}
}
else
{
if (self.resultSearchController.active)
{
dealer = filtereddealers[indexPath.row]
}
else
{
dealer = sorteddealers[indexPath.row]
}
}
//Create a message box with actions for the user.
let actionSheetController: UIAlertController = UIAlertController(title: "What to do with:", message: "'\(dealer.dlName)'?", preferredStyle: .ActionSheet)
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the action sheet
}
//starts a phonecall to the selected dealer
let callAction: UIAlertAction = UIAlertAction(title: "Call", style: .Default) { action -> Void in
var phonenr = "0634563859"
let alert2 = UIAlertController(title: "Please confirm", message: "Call '\(dealer.dlName)' at \(phonenr)?", preferredStyle: UIAlertControllerStyle.Alert)
alert2.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.Default, handler: nil))
alert2.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default) { UIAlertAction in
self.callNumber(phonenr)
})
self.presentViewController(alert2, animated: true, completion: nil)
}
//action that opens the DealCustView. Pass data from this view to the next. ID is used in the next view.
let showcustomersAction: UIAlertAction = UIAlertAction(title: "Customers", style: .Default) { action -> Void in
let reportview = self.storyboard?.instantiateViewControllerWithIdentifier("dealcustList") as! DealCustView
reportview.id2 = dealer.dlSCode
reportview.sourceid = self.id
self.navigationController?.pushViewController(reportview, animated: true)
}
//add the actions to the messagebox
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(showcustomersAction)
actionSheetController.addAction(callAction)
//present the messagebox
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(actionSheetController, animated: true, completion: nil)
})
}
else
{
if scMatur.selectedSegmentIndex == 0
{
if (self.resultSearchController.active)
{
alldealer = filteredalldealers[indexPath.row]
}
else
{
alldealer = alldealers[indexPath.row]
}
}
else
{
if (self.resultSearchController.active)
{
alldealer = filteredalldealers[indexPath.row]
}
else
{
alldealer = sortedalldealers[indexPath.row]
}
}
///
//Create a message box with actions for the user.
let actionSheetController: UIAlertController = UIAlertController(title: "What to do with:", message: "'\(alldealer.tdlName)'?", preferredStyle: .ActionSheet)
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the action sheet
}
//starts a phonecall to the selected dealer
let callAction: UIAlertAction = UIAlertAction(title: "Call", style: .Default) { action -> Void in
var phonenr = "0634563859"
let alert2 = UIAlertController(title: "Please confirm", message: "Call '\(alldealer.tdlName)' at \(phonenr)?", preferredStyle: UIAlertControllerStyle.Alert)
alert2.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.Default, handler: nil))
alert2.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default) { UIAlertAction in
self.callNumber(phonenr)
})
self.presentViewController(alert2, animated: true, completion: nil)
}
//action that opens the DealCustView. Pass data from this view to the next. ID is used in the next view.
let showcustomersAction: UIAlertAction = UIAlertAction(title: "Customers", style: .Default) { action -> Void in
let reportview = self.storyboard?.instantiateViewControllerWithIdentifier("dealcustList") as! DealCustView
reportview.id2 = alldealer.tdlSCode
reportview.sourceid = self.id
self.navigationController?.pushViewController(reportview, animated: true)
}
//add the actions to the messagebox
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(showcustomersAction)
actionSheetController.addAction(callAction)
//present the messagebox
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(actionSheetController, animated: true, completion: nil)
})
}
}
}
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)