waits until the user finishes responding to the popup dialog in Swift - swift2

I want the user to type up the text in the pop up dialog, but I want the program to wait until the user finished writing the text in the pop up dialog

Use UIAlertController:
let alertController = UIAlertController(title: "title", message: nil, preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in }
alertController.addAction(UIAlertAction(title: "cancel", style: UIAlertActionStyle.Cancel, handler: nil))
logInAlertController.addAction(UIAlertAction(title: "go", style: UIAlertActionStyle.Default, handler: { (action) -> Void in }

Swift 4
It sounds like you are doing your completion handling when presenting the controller instead of when the user selects an alert action.
You'll want to try something like this:
import UIKit
class MyViewController: UIViewController
{
var someStringVariable:String = ""
func presentAnAlert()
{
let alert = UIAlertController(
title: "Title",
message: "Message",
preferredStyle: .actionSheet //choose which style you prefer
)
alert.addTextField()
{ (textField) in
//this is for configuring the text field the user will see
textField.borderStyle = UITextField.BorderStyle.bezel
}
alert.addAction(UIAlertAction(title: "OK", style: .default)
{ action in
//use this space to transfer any data
let textField = alert.textFields![0]
self.someStringVariable = textField.text ?? ""
})
self.present(alert, animated: true)
{
//this will run once the action of **presenting** the view
//is complete, rather than when the presented view has been
//dismissed
}
}
override viewDidLoad()
{
super.viewDidLoad()
self.presentAnAlert()
print(self.someStringVariable)
//prints whatever the user input before pressing the OK button
}
}
I hope that helped!

Related

Changing Title via Alert Controller

I want to be able to change the title displayed in the navigationBar. I have the alertController setup and it appears fine, however after inputting the newTitle text, the current title disappears but the new title doesn't appear. I have tried reloading data in the viewDidLoad, viewWillAppear, as well as in the button press event itself (as shown in code). Any input is appreciated.
#IBAction func changeTitleBarButtonPressed(_ sender: UIBarButtonItem) {
let titleChange = UIAlertController(
title: "Change Title",
message: "Please input text to change the title",
preferredStyle: .alert)
titleChange.addTextField { (textField) in
textField.placeholder = "Input new title"
}
titleChange.addAction(UIAlertAction(
title: "Cancel",
style: .cancel,
handler: { (cancelAction) in
titleChange.dismiss(animated: true)
}))
titleChange.addAction(UIAlertAction(
title: "Change Title",
style: .default,
handler: { (changeAction) in
let newTitle = self.textField?.text
titleChange.dismiss(animated: true)
self.navigationItem.title = newTitle
self.imagesTableView.reloadData()
}))
self.present(titleChange, animated: true)
}
The only problem is you read the text value from unrelated textField (And its probably nil or empty). You may want to use the first textField of the alert instead of self.textField?.text:
titleChange.addAction(UIAlertAction(
title: "Change Title",
style: .default,
handler: { (changeAction) in
let newTitle = titleChange.textFields![0].text // instead of `self.textField?.text`
titleChange.dismiss(animated: true) // this line is not required. You can get rid of it freely.
self.navigationItem.title = newTitle
}))
Make sure you are no setting the navigationItem.title elsewhere (like viewWillAppear or etc.)

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/

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
}
}

EXC_BAD_ACCESS crash on didSelectRowAtIndexPath

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)
})
}
}
}

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