How to extract data from Firebase Cloud Firestore - ios

I'm trying to extract all objects(See picture below) from Firebase Firestore. How can I add the output result into a dictionary?
func getLinks() {
let user = Auth.auth().currentUser
let userID = user?.uid
let db = Firestore.firestore()
print(userID!)
let docRef = db.collection("files").document(userID!)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
}
Output Image

Fetch Data from Firebase and then Use it
Step:-1 Fetch Data
var dictData = [String:Any]()
let ref = Database.database().reference()
ref.observe(.childAdded, with: { (snapshot) in
print(snapshot.value!)
self.dictData = snapshot.value as! [String : Any]
print(self.dictData)
})
Step:- 2 Extract the Data from SnapShot
var arrFetchedData:NSMutableArray = NSMutableArray()
for data in dictData{
print(data.key) //Key will be printed here
var tempDict:NSMutableDictionary = NSMutableDictionary()
let innerData = data.value as! [String:Any]
let expires = innerData["expires"]
tempDict.setValue(expires, forKey: "expires")
let name = innerData["name"]
tempDict.setValue(name, forKey: "name")
let url = innerData["url"]
tempDict.setValue(url, forKey: "url")
arrFetchedData.add(tempDict)
}
print(arrFetchedData) //All the Fetched data will be here
Hope this Helps!

Related

Why does it overwritten data instead of adding more data in firebase?

I really want to know why the data is overwritten when the user types new data,
I want it to add more data to it not overwrite it the data
Also want to know how to read it
Thank you in advance
let oDB = Database.database().reference().child("Data")
let oDictionary = ["Data1" : strange.text! , "Data2" : stranger.text!]
let uid = Auth.auth().currentUser?.uid
oDB.child(uid!).setValue(oDictionary) {
(error, reference) in
if error != nil{
print(error!)
} else {
print("saved Sucessfully")
self.navigationController?.popViewController(animated: true)
}
}
//In another ViewController
func updateRequest() {
let uid = Auth.auth().currentUser?.uid
let yDb = Database.database().reference().child("Data").child(uid!)
postDb.observeSingleEvent(of: .value) { (snapShot) in
if let snapShotValue = snapShot.value as? Dictionary<String, String> {
let text = snapShotValue["Data1"]!
let case = snapShotValue["Data2"]!
let data = Data()
data.s= text
data.y = case
self.array.append(data)
self.table.reloadData()
}
}
}
setValue overwrites the old content , You may need childByAutoId
oDB.child(uid!).childByAutoId().setValue(oDictionary) {
(error, reference) in
if error != nil{
print(error!)
} else {
print("saved Sucessfully")
self.navigationController?.popViewController(animated: true)
}
This will give this structure
Data
> uid
> someKey1 <<<< auto generated
Data1:"---"
Data2:"---"
> someKey2 <<<< auto generated
Data1:"---"
Data2:"---"
Read
//In another ViewController
func updateRequest() {
let uid = Auth.auth().currentUser?.uid
let yDb = Database.database().reference().child("Data").child(uid!)
postDb.observeSingleEvent(of: .value) { (snapShot) in
if let snapShotValue = snapShot.value as? [String:[String:String]] {
Array(snapShotValue.values).forEach {
let data = Data()
data.s= $0["Data1"]!
data.y = $0["Data2"]!
self.array.append(data)
}
self.table.reloadData()
}
}
}

how to store image upload based on user id

func uploadImage(){
let storage = Storage.storage()
let storageRef = storage.reference()
let uploadData = self.imageView.image!.jpegData(compressionQuality: 0.75)
let imagesRef = storageRef.child("images/myImage.jpg") //not sure how is it done
let uploadTask = imagesRef.putData(uploadData!, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
return
}
let size = metadata.size
imagesRef.downloadURL { (url, error) in
guard let downloadURL = url else {
return
}
}
}
}
func retrieveData(){
let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let userData = snapshot.value as? NSDictionary
print("Welcome back,", userData?["username"])
}) { (error) in
print(error.localizedDescription)
}
}
Hi, I'm looking for a way for user to upload image onto firebase based on their user id. Can anyone suggest how this can be achieved? Thanks in advance.
You can do something like this:
func sendMessageWithProperties(properties: [String: Any]) {
let ref = Database.database().reference().child("messages")
let childRef = ref.childByAutoId()
let toId = self.user?.id
let fromId = Auth.auth().currentUser?.uid
let timestamp: Int = Int(NSDate().timeIntervalSince1970)
var values: [String: Any] = ["toId": toId!,
"fromId": fromId!,
"timestamp": timestamp]
// To append other properties into values
properties.forEach({values[$0] = $1})
childRef.updateChildValues(values) { (error, ref) in
if error != nil {
print(error!)
return
}
let userMessageRef = Database.database().reference().child("user-messages").child(fromId!).child(toId!)
let messageId = childRef.key
userMessageRef.updateChildValues([messageId: 1])
let receiverMessageRef = Database.database().reference().child("user-messages").child(toId!).child(fromId!)
receiverMessageRef.updateChildValues([messageId: 1])
}
}

retrieve values from firestore's struct in swift

I'm querying some data from my firestore,and I put it in my Usersdata,
but I dont know how to get my values from Usersdata.
Please help me to query my data!
This is my struct base on Firestroe example
struct Usersdata {
let uid:String?
let facebook:String?
let google:String?
let name:String?
let age:Int?
let birthday:String?
let smokeage:Int?
let smokeaddiction:Int?
let smokebrand:String?
let gold:Int?
let score:Int?
let fish:Int?
let shit:Int?
let userimage:String?
init?(dictionary: [String: Any]) {
guard let uid = dictionary["uid"] as? String else { return nil }
self.uid = uid
self.facebook = dictionary["facebook"] as? String
self.google = dictionary["google"] as? String
self.name = dictionary["name"] as? String
self.age = dictionary["age"] as? Int
self.birthday = dictionary["birthday"] as? String
self.smokeage = dictionary["smokeage"] as? Int
self.smokeaddiction = dictionary["smokeaddiction"] as? Int
self.smokebrand = dictionary["smokebrand"] as? String
self.gold = dictionary["gold"] as? Int
self.score = dictionary["score"] as? Int
self.fish = dictionary["fish"] as? Int
self.shit = dictionary["shit"] as? Int
self.userimage = dictionary["userimage"] as? String
}
}
this is my function to query data from firebase
func test(schema:String , collection:String , document : String){
let queryRef = db.collection("Users").document(userID).collection(collection).document(document)
queryRef.getDocument { (document, error) in
if let user = document.flatMap({
$0.data().flatMap({ (data) in
return Usersdata(dictionary: data)
})
}) {
print("Success \(user)")
} else {
print("Document does not exist")
}
}
}
I think you are asking how to work with a structure with Firebase data. Here's a solution that will read in a known user, populate a structure with that data and then print the uid and name.
Assume a stucture
Users
uid_0
name: "Henry"
and then a structure to hold that data
struct Usersdata {
let uid:String?
let user_name:String?
init(aDoc: DocumentSnapshot) {
self.uid = aDoc.documentID
self.user_name = aDoc.get("name") as? String ?? ""
}
}
and a function to read that user, populate the struct and print out data from the struct
func readAUser() {
let docRef = self.db.collection("Users").document("uid_0")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let aUser = Usersdata(aDoc: document)
print(aUser.uid, aUser.user_name)
} else {
print("Document does not exist")
}
}
}
and the output
uid_0 Henry

want to fetch data from firebase

I can fetch all data but don't know how to go inside the nodes
and fetch values. Here is the structure of my database want to fetch all data
func fetchData(){
ref = Database.database().reference()
let userid = Auth.auth().currentUser?.uid
ref.child(Constants.NODE_MAINTENANCE).child(userid!).child(Constants.NODE_MAINTENANCE_DATE).child(self.lastMaintenanceDateLbl.text ?? "").observe(DataEventType.value) { (snap) in
guard snap.exists()
else {
print("no data found at this date")
AppUtils.showAlert(title: "Alert", message: "No data found at this date!", viewController: self)
return}
// let maintenanceType = snapshot.value as? [String] ?? [""]
// print(maintenanceType)
if let snapshot = snap.children.allObjects as? [DataSnapshot]{
for snap in snapshot{
let maintenanceType = snap.value as? [String:Any]
for type in (maintenanceType?.values)!{
print(type)
}
}
}
}

How to import data from Firebase only once at login

My code is kind of buggy lately and I wonder if the methods I am using to retrieve data from Firebase are the correct methods to use. In short, I am retrieving data from firebase and than storing it inside an SQLite database.
This is my code:
FirebaseStore.rootRef.childByAppendingPath("users/"+FirebaseStore.rootRef.authData.uid+"/forums").observeSingleEventOfType(.Value, withBlock:{
snapshot in
guard let firebaseData = snapshot.value as? NSDictionary else {return}
guard let uids = firebaseData.allKeys as? [String] else {return}
importContext.performBlock{
for uid in uids{
guard let forum = NSEntityDescription.insertNewObjectForEntityForName("Forum", inManagedObjectContext: importContext) as? Forum else {return}
FirebaseStore.rootRef.childByAppendingPath("forums/"+uid+"/posts").queryOrderedByKey().observeSingleEventOfType(.Value, withBlock: {
snapshot in
// Saving the chat's messages
guard let data = snapshot.value as? NSDictionary else {return}
importContext.performBlock{
guard let posts = NSEntityDescription.insertNewObjectForEntityForName("Post", inManagedObjectContext: importContext) as? Post else {return}
do{
try importContext.save()
}catch let error{
// Error
}
}
})
}
}
})
}
I am not sure if I have to call this observeSingleEventOfType.

Resources