Retrive specific data from firebase in Swift - ios

Hi i have this structure of firebase database:
I need to retrive the specific data: Shane/DatiUtente/Password from the database and add it into a string var
please someone can tell me how is possible.
Sorry for my english if is bad i'm italian :)

You are going to need to parse through your database and retrieve the value you want. It would be something like this:
//At the top of your class set an empty variable like this:
var pass = String()
//Say for example you want to display that password to a label on your storyboard
#IBOutlet weak var passLbl: UILabel!
//Inside your viewDidLoad function you would want to add this:
DBRef.child("Shane").child("DatiUtente").child("Password").observeSingleEvent(of: .value, with: { (snaps) in
if let dictionary = snaps.value as? [String: AnyObject] {
self.passLbl.text = dictionary["pass"] as? String }
// IF you want it to the string as you asked
replace the self.passLbl.text with the empty pass variable you created at the top.

Related

How to convert Firebase result to List in SwiftUI

I wanted to make a list in swiftui from firebase data. So here's my UI
I've already make a data for that username "mike_one", and it's perfectly working,
this is my xcode result
{
IC2ol5bimucKu2d89u2YBz0Bqot2 = {
name = mike;
photo = "https://firebasestorage.googleapis.com/v0/b/instagram-ios-1ed09.appspot.com/o/photo%2Fa2.jpg?alt=media&token=9b6c58f1-eedc-4190-bc63-3f3325c84d77";
username = "mike_one";
};}
And this is my database
So what i'm asking right now is, How to make the result of the database to be a model? so I can use it as a list.
Please help me.
I appreciate your answer!
Strictly speaking, it would not be possible to convert textual firebase data to a List object. A SwiftUI List is defined as
A container that presents rows of data arranged in a single column
in other words it's a UI element, not a data element.
That being said a List is often backed by an Array or other data storage element. So you'll read Firebase data and store that in an array. Then that array backs your UI List object.
In this case, I would suggest creating a UserClass to hold the Firebase data
class UserClass {
var name = ""
var photoUrl = ""
var username = ""
}
and then array to store your users in
var userArray = [UserClass]()
then as data is read from Firebase, create the user objects and populate the array. Your Firebase code wasn't included so in brief
firebase.observe.... { snapshot in
let user = UserClass()
...populate user properites from the snapshot
self.userArray.append(user)
}
Then in your view, access the array elements to show them in the List object
struct ContentView: View {
var body: some View {
List(userArray) { user in
//do something with each user object
// like Text(user.username)
}
}
}

Avoid duplicates while adding in dictionary

I have a dictionary in which I'm adding values like so...
var mydictionary = ["id": "", "quantity": "","sellingPrice":""] as [String : Any]
dictionary["id"] = product?.id
dictionary["quantity"] = product?.quantity
dictionary["sellingPrice"] = product?.theRate
And these values I added to an array like so...
self.arrayOfDictionary.append(mydictionary)
But if arrayOfDictionary already contains mydictionary, I don't want to add it. Else, I want to add it.
The basic idea here is to add data from collection view items to array of dictionary. When I click on the buttons that I have on each collection view item the data on it is added to an array of dict. while at the same time showing those data in a tableviewcell. But when I navigate back from the tableview & visit the collectionview items again and click on some other collecn.view item, so as to add them to the array of dictionary as before, then the item that was added initially to the array of dictionary gets added again. This has to be somehow prevented.
As suggested by another SO user something like this was tried to prevent this duplication...
if self.arrayOfDictionary.contains(where: { (dict) -> Bool in
"\(dict["id"] ?? "")" != "\(dictionary["id"] ?? "")"}) {
self.arrayOfDictionary.append(dictionary)
}
But this doesn't seem to work. With this nothing is added to the array and its totally empty. Hope somebody can help...
Try this code to avoid duplication
I hope "id" value will be unique in your dictionary.
var mydictionary = ["id": "1", "quantity": "","sellingPrice":""] as [String : Any]
var arrayOfDictionary = [Dictionary<String, Any>]() //declare this globally
let arrValue = arrayOfDictionary.filter{ (($0["id"]!) as! String).range(of: mydictionary["id"]! as! String, options: [.diacriticInsensitive, .caseInsensitive]) != nil }
if arrValue.count == 0 {
arrayOfDictionary.append(mydictionary)
}
I've got better idea then every time you perform loop to check unique ness.
Maintain one Bool array of same size of your collectionView Items array with predefined false values each.
When you click on button of collection View item, change flag of Bool array with same index. And simultaneously you can disable the button also(if you want). Otherwise whenever user clicks on button, just check flag from Bool array and add Dictionary to new array as needed.
Here, your new array will be performed and you will same process and time of looping also.
One way to approach the problem could be to construct a structure which contains product details:
/// Details Of A Product
struct ProductDetails{
var id: String!
var quantity: Int!
var sellingPrice: Int!
}
Then create a dictionary which stores the product details with the key being the "ID" e.g:
var products = [String: ProductDetails]()
You could then create a product like so:
let productA = ProductDetails(id: "1", quantity: 100, sellingPrice: 10)
To add a unique product to your dictionary you could use a function like this:
/// Adds A Product To The Products Dictionary
///
/// - Parameter product: ProductDetails
func addProductDetails(_ product: ProductDetails){
//1. If A Product Exists Ignore It
if products[product.id] != nil{
print("Product With ID \(product.id!) Already Exists")
}else{
//2. It Doesn't Exist So Add It To The Dictionary
products[product.id] = product
}
}
I tested this quickly and it won't allow products which have duplicate ID's. although of course you could change the parameter as needed.

Swift 3, accessing user input Text Field values from ViewControler and used them in a model .swift file

This is my first question. I'm new to swift and programming in general so please don't laugh if I'm asking stupid question :)
So I hava a SettingsViewControler where users sets their values, lets say they set the temperature value. What i'm trying to do, is to take that temperature value that they input and pass it to my model.swift file, to introduce that value in the formula, to calculate the new value with the input temperature. I hope this make sense.
Is there a way to do that directly by calling the class form VC to the newData class that I created in model.swift file, or I should use some methods like UserDefaults to pass data.
Here is the code example:
First I created a Settings.swift file
// Settings.swift file
import Foundation
class Settings {
var inputTemperature: Float = 0
init(inputTemperature: Float) {
self.inputTemperature = inputTemperature
}
}
Here is the Settings View Controller
//Settings ViewCOntroller. swift file
import UIKit
class SettingsViewController: UIViewController {
#IBOutlet weak var inputTemperatureTextField: UITextField!
var getTemp = Settings(inputTemperature: 72)
override func viewDidLoad() {
super.viewDidLoad()
}
func getValues() {
getTemp.inputTemperature = (inputTemperatureTextField.text! as NSString).floatValue
}
}else if textField == inputTemperatureTextField {
textField.resignFirstResponder()
getValues()
}
So now I have another Calculations.swift file where I want to get the inputTemperature value to use it in the formula
//Calculation. swift file
import Foundation
class Calculations {
var inputA: Float = 0
var inputB: Float = 0
var resultC: Float = 0
init(inputA: Float, inputB: Float) {
self.inputA = inputA
self.inputB = inputB
}
// Here i want to add the temperature value
func calc() {
resutC = inputA * inputC // * inputTemperature
}
I want the get (inputTemperatureTextField.text! as NSString).floatValue value from SettingsView COntroller to introduce it in the formula located Calculation.swift file
Thanks
You should really post some of your code to give us some insight in what exactly it is you want.
Lets say in your model you have a temperature value like
var temp: Int?
Then you can initialize it in your VC, and access the temp value
var model = Model()
let model.temp = inputTextField.text
If you are using model.swift for calculation. You will create an object of the model-class in the View controller, after creating an object you can pass the test field value to the model.
var modelObject: model? = model();
modelObject.temprature = txtTemprature.text;

Save tableview textfields to an array of custom objects

I´m searching for a way to save the data a user enters in two textfields in a tableview. The user has to enter the name and the height of person in a tableview and I want to save it to a custom array.
struct PersonData {
var name: String
var height: Int
init(name: String, height: Int) {
self.name = name
self.height = height
}
}
I´ve searched and i found this Swift: retrieving text from a UITextField in a custom UITableViewCell and putting it in an array but still got two questions.
How i add item to my custom array? I try it with this:
personData[textField.tag].name = textField.text!
Isn´t a easier way to do it?
Thank you!!
If I understood your question properly then heres a possible solution.
You initialise an array of type PersonData. Then you make an object of type PersonData. Whenever you have some info, you store it in this object and append the object to the array created.
let array = [PersonData]()
let personDataObject = PersonData()
//After you store the values in the object you add the object to you array.
personDataObject.name = textField1.text
personDataObject.height = textField2.text //You need to convert this to Int. Try personDataObject.height = textField2.text as? Int or personDataObject.height = Int(textField2.text)
array.append(personDataObject)

Storing class in NSUserDefaults and accessing in next view

I created a swift class called UserDetails and below is the structure:
import Foundation
class UserDetailsClass {
var fullname: String!
var mobile: String!
var email: String!
var password: String!
}
In my current View controller , I create an instance and store the values I want to move to next view in the instance variables as shown below:
var userDetailsInstance = UserDetailsClass()
userDetailsInstance.fullname = fullNameTextField.text
userDetailsInstance.mobile = mobileTextField.text
userDetailsInstance.email = emailTextField.text
userDetailsInstance.password = passwordTextField.text
var prefs = NSUserDefaults.standardUserDefaults()
prefs.setObject(userDetailsInstance, forKey: "currentGuest")
prefs.synchronize()
In the next view (where there is segue connected, I try to do this:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var prefs = NSUserDefaults.standardUserDefaults()
var userDetailsClass: AnyObject? = prefs.valueForKey("currentGuest")
}
but the app immediately crashes. The objective here is that after user enters his/her details, i do not store them in server but rather in the NSUserDefault then take them to the next view where an SMS verification would take place. Once the verification is done, I would store the information on the server.
the error console is showing:
Attempt to insert non-property list object appName.UserDetailsClass
for key currentGuest'
Is there a better way to move the data than storing an object in NSUserDefault?
I am a beginner iOS developer so thanks for your help.
The reason you are unable to store the object in NSUserDefaults is because it is not a property list type (NSNumber, NSData, NSArray, NSDictionary, NSDate, String, Bool). To store it in NSUserDefaults, it must be one of these types so you could serialize it to NSData, but in order to do that it would need to be NSCoding compliant.
The better solution is to pass the object in prepareForSegue
NSUserDefaults doesn't support saving custom classes.
You should convert your UserDetailsClass to Dictonary and save dictionary to NSUserDefaults.

Resources