Attempt to present alertcontroller whose view is not in window hierarchy - xcode

I'm getting the following error in Swift 3:
Attempt to present alertcontroller whose view is not in window hierarchy
I have already referred to other posts on this topic to no avail. More specifically, I've implemented the change suggested in this post: AlertController is not in the window hierarchy
and I'm still receiving the same error.
What I've done is:
Create an AlertHelper.swift helper class:
class AlertHelper {
func showAlert(fromController controller: UIViewController) {
let alert = UIAlertController(title: "Please Try Again", message: "Email Already In Use", preferredStyle: .alert)
controller.present(alert, animated: true, completion: nil)
}
}
In my View Controller, under a function which is called when a button is pressed, I check to see if an email address entered by a user is already stored in my Firebase database, and if so, I try to present an "Email already in use" alert from the AlertHelper class:
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if error != nil {
if let errCode = AuthErrorCode(rawValue: error!._code) {
switch errCode {
case .emailAlreadyInUse:
let alert = AlertHelper()
alert.showAlert(fromController: self)
return
default:
print("other error")
}
}
}
else {
// Inputs user email into database
self.ref.child("Users").child((user?.uid)!).setValue(["Email": email, "Location": ""])
self.performSegue(withIdentifier: "todorm", sender: self)
}
}
The database stuff works, the only thing that isn't appearing is the alert. Any ideas? Thanks!!

It's sort of a strange practice to subclass your alert into a separate class.
You should try making a method in your ViewController class
func showAlert() {
let alert = UIAlertController(title: "Please Try Again", message: "Email Already In Use", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
}
Call the method using:
self.showAlert()

Related

Refresh/Reload Eureka PushRow's pushed ViewController options with button?

I am using Eureka forms in my project.
I have a PushRow that presents the default SelectorViewController with a list of options. In the pushed view, I have added a rightBarButtonItem that points to locationSelectorAddButton ... on click, this brings up a UIAlertController that should allow users to add options to this pushed controller.
Is it possible, without creating my own custom selector controller, to refresh the current controller with the newly saved options from UserDefaults?
let defaults = UserDefaults.standard
func setupForm() {
form
+++ PushRow<String>(K.SESSIONFIELD.location) {
$0.title = K.SESSIONFIELD.location
$0.options = defaults.array(forKey: K.SESSIONFIELD.location) as? [String]
$0.value = sessionResult?.sessionLocation ?? $0.options?.first
}
.onPresent { from, to in
to.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named:"add_20pt"), style: UIBarButtonItemStyle.plain, target: from, action: #selector(self.locationSelectorAddButton(_:)))
}
}
the locationSelectorAddButton is implemented as follows:
#objc func locationSelectorAddButton(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Location", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add", style: .default) { (action) in
var locArray = self.defaults.array(forKey: K.SESSIONFIELD.location) as? [String]
locArray?.append(textField.text!)
self.defaults.set(locArray, forKey: K.SESSIONFIELD.location)
///TODO: somehow refresh the pushed view controller here!!
// self.form.rowBy(tag: K.SESSIONFIELD.location)?.reload()
// print("this is the list of locations currently ...\(locArray)")
// self.tableView.reloadData()
///
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Location name ..."
textField = alertTextField
}
alert.addAction(action)
present(alert, animated:true, completion:nil)
}
Push row is not reloaded by using tag property. You need to implement the method
cellUpdate { cell, row in
row.options = (assign value here for updated options)
}

How to know if user rejected the Location Services in Swift 2

I'm trying to make location service app and i have the following code so when the user goes to that view controller he will get an alert of getting the current location.
This is the code
override func viewDidLoad() {
super.viewDidLoad()
// 1. status is not determined
if CLLocationManager.authorizationStatus() == .NotDetermined {
locationManager.requestAlwaysAuthorization()
}
// 2. authorization were denied
else if CLLocationManager.authorizationStatus() == .Denied {
SwiftSpinner.hide()
let alert = UIAlertController(title: "Error with Your Location" , message: "Location services were previously denied. Please enable location services for this app in Settings.", preferredStyle: UIAlertControllerStyle.Alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
alert.addAction(ok)
let cancel = UIAlertAction(title: "Back", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.movenav("arxiki")
}
alert.addAction(cancel)
self.presentViewController(alert, animated: true, completion: nil)
}
// 3. we do have authorization
else if CLLocationManager.authorizationStatus() == .AuthorizedAlways {
locationManager.startUpdatingLocation()
}
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.eventsTable.backgroundColor = UIColor.lightGrayColor()
// self.locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
My question is the following.
If the user pushes "Do not authorise" How can i get his option so i can send him back to the previous view controller or to alert him with the message that i have?
In order to catch the user selection you need to declare a CLLocationManager object and implement its delegate (CLLocationManagerDelegate) and use the following method for catching it.
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .Denied || status == .NotDetermined{
// User selected Not authorized
}
}
I assume you have already configured the info.plist with the suitable locations parameters.
Hope it helps!

Send email In-game using sprite kit in xcode 7 beta3?

I am making an iPad game in sprite kit using swift in xcode 7beta3 and I want the results of the game to be send to the users email after the game is completed. The user should press a button called send and redirect to where they can type in their email-address and send the message. But I have no idea how to make and send an email.
I have been searching all around the internet for an answer to this question, but all are older version answers. I hope you can help.
Thanks in advance
EDIT:
I have been searching some more and i found a solution (here: http://kellyegan.net/sending-files-using-swift/), but I still have a problem. In my GameViewController i have added:
override func viewDidLoad() {
super.viewDidLoad()
let scene = StartGameScene(size: view.bounds.size)
let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
scene.scaleMode = .ResizeFill
skView.presentScene(scene)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
internal func sendEmail() {
//Check to see the device can send email.
if( MFMailComposeViewController.canSendMail() ) {
print("Can send email.")
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
//Set the subject and message of the email
mailComposer.setSubject("Have you heard a swift?")
mailComposer.setMessageBody("This is what they sound like.", isHTML: false)
if let filePath = NSBundle.mainBundle().pathForResource("Math", ofType: "txt") {
print("File path loaded.")
if let fileData = NSData(contentsOfFile: filePath) {
print("File data loaded.")
mailComposer.addAttachmentData(fileData, mimeType: "text/plain", fileName: "Math")
}
}
self.presentViewController(mailComposer, animated: true, completion: nil)
}
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
The sendMail() is called in one of my gameScenes when you press a button.
The problem is that I get an error when I press that button. It prints out
Can send email.
File path loaded.
File data loaded.
as it should, but then it gives an error:
Could not cast value of type 'UIView' (0x1964ea508) to 'SKView' (0x19624f560).
I think the problem is the self.presentViewController(), but I have no idea how to fix it.

UIAlertController gone crazy, point to settings when it should cancel

Anyone ever had an alert controller with a "cancel" action and just a return in the handler that does something?
Mine goes to the app settings....
I have another alert controller in another viewcontroller that does that. But that shouldn't affect this one????
alertControl.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (alertAction) -> Void in
return
}))
update:
Commented all other alertController out. (They were all in other view controller) now it doesn't do it anymore. What is this??
These are also only declared in a function when something goes wrong. When there is no connection,... They shouldn't even exist, unless the function gets called.
update 2 :
func checkAllSettingsForLocation() {
if isTest != true {
//println("should show this")
let alertController = UIAlertController(title: "Scenix can't use your location", message: "Check Location Services under Privacy in the Settings App", preferredStyle: UIAlertControllerStyle.Alert)
let goToSettingsAction = UIAlertAction(title: "Go to Settings", style: .Default, handler: {
action in
UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)
return
}
)
alertController.addAction(goToSettingsAction)
let ignoreNoCamAction = UIAlertAction(title: "Cancel", style: .Default, handler: {
action in
self.launch = self.launch - 1
return
}
)
alertController.addAction(ignoreNoCamAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
Update 3:
Looks more and more like an Xcode Bug.
Building for release / through test flight and the bug is there.
Do a normal debug build and all is fine....
dirty fix =>
Wrap the action from any alert controller in an if statement that checks the alert controller title. Can never throw an exception or result in finding a nil and fixed my problem.
Try using nil instead of return,
let cancel = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
alertController.addAction(cancel)
I also have some other setting destination alert controllers, and this has worked fine for me.

Swift UIAlertController Getting Text Field Text

I need to get the text from the text fields in my alert view when the Input button is pressed.
func inputMsg() {
var points = ""
var outOf = ""
var alertController = UIAlertController(title: "Input View", message: "Please Input Your Grade", preferredStyle: UIAlertControllerStyle.Alert)
let actionCancle = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel) { ACTION in
println("Cacle")
}
let actionInput = UIAlertAction(title: "Input", style: UIAlertActionStyle.Default) { ACTION in
println("Input")
println(points)
println(outOf)
}
alertController.addAction(actionCancle)
alertController.addAction(actionInput)
alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
txtField.placeholder = "I got"
txtField.keyboardType = UIKeyboardType.NumberPad
points = txtField.text
})
alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
txtField.placeholder = "Out Of"
txtField.keyboardType = UIKeyboardType.NumberPad
outOf = txtField.text
})
presentViewController(alertController, animated: true, completion: nil)
}
As requested here is an implementation solution.
alertController.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default,handler: {
(alert: UIAlertAction!) in
if let textField = alertController.textFields?.first as? UITextField{
println(textField.text)
}
}))
As stated above, the alertController has a property called textFields. You can conditionally unwrap that property to safely access a text field if you have added one. In this case since there is only one text field I just did the unwrap using the first property. Hope it helps.
The UIAlertController has a textFields property. That's its text fields. Any of your handlers can examine it and thus can get the text from any of the text fields.

Resources