Swift UIAlertController Getting Text Field Text - xcode

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.

Related

Swift 4save recorded video to photo album

This is my first attempt at recording and saving a video with AVKit etc. and although I am able to display and record a video with the method:
#IBAction func recordVideo(_ sender: Any) {
// Check the camera is available
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
// present the camera
controller.sourceType = .camera
controller.mediaTypes = [kUTTypeMovie as String]
controller.delegate = self
present (controller,animated: true, completion: nil)
}else{
// No camera available so show alert
let alert = UIAlertController(title: "Oops!", message: "Can't access the camera!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Give up", style: .default, handler: nil))
self.present(alert, animated: true)
uploadButton.isHidden = true
}
}
I am having trouble saving the recorded video to the photo album. When I step through the code it jumps from the 'guard' line into the 'else' block and simply returns. So for some reason it's not able to assign anything to 'mediaType'
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo vidInfo: [UIImagePickerController.InfoKey : Any]){
dismiss(animated: true, completion: nil)
guard let mediaType = vidInfo[UIImagePickerController.InfoKey.mediaURL] as? String,
mediaType == (kUTTypeMovie as String),
let url = vidInfo[UIImagePickerController.InfoKey.mediaURL] as? URL,
UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(url.path)
else {
return
}
// Handle a movie capture
UISaveVideoAtPathToSavedPhotosAlbum(url.path, self, nil, nil)
}
Any help would be appreciated.

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

Attempt to present alertcontroller whose view is not in window hierarchy

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

Swift - UIAlertAction - could not find member named Default?

I'm trying to add an action sheet. From what I have read, UIActionSheet is depreciated in IOS 8, and one should use an Alert Controller instead. Here is my code snippet:
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let takePhoto = UIAlertAction(title: "Take Photo", style: .Default, handler: { (alert: UIAlertAction) -> Void in
//action goes here
})
However. I am getting an error which reads "Could not find member 'Default'". From what I understand it there are 3 styles possible for UIAlertAction: Default, Cancel & Destructive. What am I doing wrong?
Many thanks :)
The problem is actually with the closure, rather than with .Default, but that's what the compiler is complaining about. The type on alert is incorrect (just barely). You can change the closure definition to one of these to make it work:
... handler: { (alert: UIAlertAction!) -> Void in
... handler: { alert -> Void in
... handler: { _ -> Void in //Use this if you don't care about the alert object
Shameless plug: You could also use something like LKAlertController to make the action sheet creation really easy. It would turn into something like
ActionSheet().addAction(title: "Take Photo", style: .Default) {
//Action
}.addAction(/* Your other actions */).show()
This compiles but you have more to do like add the .addAction, etc.. Note that the preferred style in optionMenu is .Alert. There is an excellent explanation in IOS 8 Swift Cookbook by Vandad Nahavandipoor
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .Alert)
let takePhoto = UIAlertAction(title: "Take Photo",
style: UIAlertActionStyle.Default,
handler: {[weak self] (paramAction:UIAlertAction!) in
})

Multiple Feeds in a rss reader (swift)

I am creating a rss reader in xcode using swift. I am follwing this tut https://www.youtube.com/watch?v=jootsUaCvAU but in the tut he doesnt go over adding multiple feeds of your own for the user. Their is a slide out menu, but their is only a "add feed" button that the user can add their own feed.I have taken that out, and have put other feeds names on the slide out menu using "feedNames.append()", but all i need now is that the feed will open up after the user hits one of the feed names on the slide out menu. I think i know where the code goes, but i dont know what to put. Here is the code, for the slide out menu with the items. The code still has the "Add feed" implemented but just ignore that, cuz i am going to take that out.
func sideBarDidSelectMenuButtonAtIndex(index: Int) {
if index == 0{ // ADD FEED BUTTON
let alert = UIAlertController(title: "Add new feed", message: "Enter feed name and URL", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler({ (textField:UITextField!) -> Void in
textField.placeholder = "Feed name"
})
alert.addTextFieldWithConfigurationHandler({ (textField:UITextField!) -> Void in
textField.placeholder = "Feed URL"
})
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (alertAction:UIAlertAction!) -> Void in
let textFields = alert.textFields
let feedNameTextField = textFields?.first as UITextField
let feedURLTextField = textFields?.last as UITextField
if feedNameTextField.text != "" && feedURLTextField.text != "" {
let moc = SwiftCoreDataHelper.managedObjectContext()
let feed = SwiftCoreDataHelper.insertManagedObject(NSStringFromClass(Feed), managedObjectConect: moc) as Feed
feed.name = feedNameTextField.text
feed.url = feedURLTextField.text
SwiftCoreDataHelper.saveManagedObjectContext(moc)
self.loadSavedFeeds()
}
}))
So i'm sure, the code goes here, but i am not for sure what to put. Thanks for your help!
func sideBarDidSelectMenuButtonAtIndex(index: Int)
if index == 0{
let url = NSURL(string: "http://www.widadclub.tk/feed")
let feedParser = MWFeedParser(feedURL: url)
feedParser.delegate = self
feedParser.parse()
}

Resources