How can I add alert button till my data count? How can I save my data choose from a action index? - swift

I'm present a alert when I click the button. I choose from a list (if how much data is available.) How can I save my data choose from a list index?
You can see UI in here
My AccountServices
class AccountServices {
static let databaseReference = Database.database().reference(withPath: "Accounts").child((Auth.auth().currentUser?.uid)!)
static var account = Account()
static func saveChanges() {
databaseReference.setValue(try! FirebaseEncoder().encode(AccountServices.account))
}
static func getAccount() {
databaseReference.observeSingleEvent(of: .value, andPreviousSiblingKeyWith: { (snapshot, _) in
account = try! FirebaseDecoder().decode(Account.self, from: snapshot.value!)
})
}
}
Variable
var product: ProductViewModel?
addButton Tapped
#IBAction func addToCartButtonTapped(_ sender: UIButton) {
let alert = UIAlertController(title: "Bu ürünü hangi sepetinize eklemek istersiniz ?", message: "", preferredStyle: .actionSheet)
var indexer = 0
for cart in AccountServices.account.cart! {
if cart.product == nil{
AccountServices.account.cart![indexer].product = [Product]()
}
let action = UIAlertAction(title: cart.name , style: .default, handler: { (sender) in
if let index = alert.actions.firstIndex(where: { $0 === sender }) {
AccountServices.account.cart?[index].product?.append(self.product) `//Error: Cannot convert value of type 'ProductViewModel?' to expected argument type 'Product'`
AccountServices.saveChanges()//TODO...
}
let addAlert = UIAlertController(title: "Sepetinize Eklendi.", message: "Ürününüz sepetinize eklendi.", preferredStyle: .alert)
let okButton = UIAlertAction(title: "Tamam", style: .default, handler: nil)
addAlert.addAction(okButton)
self.present(addAlert, animated: true, completion: nil)
})
alert.addAction(action)
indexer += 1
}
let cancelaction = UIAlertAction(title: "Vazgeç", style: .cancel, handler: nil)
alert.addAction(cancelaction)
present(alert, animated: true, completion: nil)
}
}

Related

How to create extension for UIAlertController in swift?

I am trying to modulraise my code I am able to create extension for alertController without target
extension UIViewController {
func showAlert(title: String, message: String) {
let alertController = UIAlertController(title: title, message:
message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {_ in
}))
self.present(alertController, animated: true, completion: nil)
}
}
but I am not sure how to create extension which have target and textfield(how to create and call that in viewcontroller)
my code for which i am trying to create extension
let alertController = UIAlertController(title: "enter name", message: nil, preferredStyle: .alert)
let addAction = UIAlertAction(title: "Ok", style: .default) {_ in
guard let name = alertController.textFields?.first?.text else { return }
let newTask = Task(name: name)
self.toDoStore?.add(newTask, at: 0)
let indexPath = IndexPath(row: 0, section: 0)
self.tableView.insertRows(at: [indexPath], with: .automatic)
}
addAction.isEnabled = false
let cancelAction = UIAlertAction(title: CANCEL_ACTION, style: .cancel, handler: nil)
alertController.addTextField { textField in
textField.placeholder = "enter name.."
textField.addTarget(self, action: #selector(self.handleTextChanged), for: .editingChanged)
}
alertController.addAction(addAction);
alertController.addAction(cancelAction);
present(alertController, animated: true, completion: nil)
You could try the below extension that I'm using made a few changes according to your requirements.
extension UIViewController {
func showAlert(_ title: String?,
message: String?,
actions: [String: UIAlertAction.Style] = [:],
handler: ((UIAlertAction) -> Void)? = nil,
textFields: [((UITextField) -> Void)] = []) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
if actions.isEmpty {
alert.addAction(UIAlertAction(title: "Okay", style: .default))
} else {
for action in actions {
alert.addAction(UIAlertAction(title: action.key, style: action.value, handler: handler))
}
}
for textField in textFields {
alert.addTextField(configurationHandler: textField)
}
present(alert, animated: true)
}
}
A bit of advise you can always check how the parameters that you pass are accepted by the system API and customize your own function in a similar way.

Firebase Phone Auth Swift

I would like to add the ability to register with the phone number while registering. I wrote a function but it doesn't work. Can you examine the code? What should I do?
func sendCode(_ sender: Any) {
let alert = UIAlertController(title: "Phone number", message: "Is this your phone number? \n \(emailField.text!)", preferredStyle: .alert)
let action = UIAlertAction(title: "Yes", style: .default) { (UIAlertAction) in
PhoneAuthProvider.provider().verifyPhoneNumber(self.emailField.text!, uiDelegate: nil) { (verificationID, error) in
if error != nil {
print("eror: \(String(describing: error?.localizedDescription))")
} else {
let defaults = UserDefaults.standard
defaults.set(verificationID, forKey: "authVID")
let navController = UINavigationController(rootViewController: CodeEntryView())
self.present(navController, animated: true, completion: {
})
}
}
}
let cancel = UIAlertAction(title: "No", style: .cancel, handler: nil)
alert.addAction(action)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}

alertview textField returning empty string

class x: UIViewController {
let fromLocationLbl = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
let editTextField = UITextField()
let alertController = UIAlertController(title: "Alert!", message: "Please enter from location", preferredStyle: .alert)
alertController.addTextField { editTextField in
editTextField.placeholder = "Enter correct name"
// editTextField.text = self.fromLocationLbl.text
}
let confirmAction = UIAlertAction(title: "Change", style: UIAlertActionStyle.default) { (UIAlertAction) in
print(editTextField.text) ///////printing optional("")
self.fromLocationLbl.text = editTextField.text
}
alertController.addAction(confirmAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
}
editTextField isn't the same UITextField as you're adding to alert. In addTextField closure, editTextField is just name for parameter of closure which can be replaced with any other name
alertController.addTextField { textField in
textField.placeholder = "Enter correct name"
// textField.text = self.fromLocationLbl.text
}
You need to get reference for first text field in your alertController
let confirmAction = UIAlertAction(title: "Change", style: .default) { _ in
self.fromLocationLbl.text = alertController.textFields?.first?.text
}

Unable to merge two firebase arrays in Firebase Database

Hello I am relatively new to Swift/Firebase and I am struggling to merge two arrays so that the downloadURL is seen amongst both the name and the email fields. One function adds the name and the email through the button click the other is another function to save the URL. When I try and merge them I get this (as seen in the image below). Here is my code:
#IBAction func createAccountAction(_ sender: AnyObject) {
let Users = Database.database().reference().child("Users")
let userDictionary : NSDictionary = ["email" : emailTextField.text as String!, "Name": nameTextField.text!]
Users.childByAutoId().setValue(userDictionary) {
(error, ref) in
if self.emailTextField.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().createUser(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
if error == nil {
print("You have successfully signed up")
//Goes to the Setup page which lets the user take a photo for their profile picture and also chose a username
var imgData: NSData = NSData(data: UIImageJPEGRepresentation((self.profilePicture?.image)!, 0.8)!)
self.uploadProfileImageToFirebase(data: imgData)
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.present(vc, animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
}
func addImageURLToDatabase(uid:String, values:[String:AnyObject]){
let Users = Database.database().reference().child("Users")
let ref = Database.database().reference(fromURL: "https://example.firebaseio.com/")
Users.updateChildValues(values) { (error, ref) in
if(error != nil){
print(error)
return
}
self.parent?.dismiss(animated: true, completion: nil)
}
}
Something like this is what you want. I removed a few variables from your function but you can add them back. I just wanted to make sure the code compiles.
#IBAction func createAccountAction(_ sender: AnyObject) {
let usersRef = Database.database().reference().child("Users")
let userDictionary : NSDictionary = ["email" : emailTextField.text!, "Name": nameTextField.text!]
if emailTextField.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().createUser(withEmail: self.emailTextField.text ?? "", password: self.passwordTextField.text ?? "") { (result, error) in
if error != nil {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
return
}
guard let user = result?.user else { return }
// HERE YOU SET THE VALUES
usersRef.child(user.uid).setValue(userDictionary, withCompletionBlock: { (error, ref) in
if error != nil { print(error); return }
self.addImageURLToDatabase(uid: user.uid, values: ["Put": "Your Values Here" as AnyObject])
})
}
}
}
func addImageURLToDatabase(uid:String, values:[String:AnyObject]){
let usersRef = Database.database().reference().child("Users").child(uid)
usersRef.updateChildValues(values) { (error, ref) in
if(error != nil){
print(error)
return
}
self.parent?.dismiss(animated: true, completion: nil)
}
}

Swift: Insert Alert Box with Text Input (and Store Text Input )

In one of my viewController, I want to make an alert box appear that prompts the user to type this information.Then, I want the user to store this input using NSUserDefaults. How can I achieve this?
Thank you in advance!
Check this out:
let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
guard let textFields = alertController.textFields,
textFields.count > 0 else {
// Could not find textfield
return
}
let field = textFields[0]
// store your data
UserDefaults.standard.set(field.text, forKey: "userEmail")
UserDefaults.standard.synchronize()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = "Email"
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
SWIFT 3
func presentAlert() {
let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
if let emailTextField = alertController.textFields?[0] {
// do your stuff with emailTextField
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = "Email"
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
In swift 3
let alertController = UIAlertController(title: "SecureStyle", message: "SecureStyle AlertView.", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField) -> Void in
textField.secureTextEntry = true
textField.placeholder = "Password"
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (result : UIAlertAction) -> Void in
print("Cancel")
}
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
print(alertController.textFields?.first?.text)
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)