Created
August 15, 2018 02:08
-
-
Save izzuddin91/b348c1084df2d2f6fcb391760114d21b to your computer and use it in GitHub Desktop.
swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getLatestCounterNumber() { | |
var int = 0 | |
ref = Database.database().reference() | |
ref.observeSingleEvent(of: .value, with: { snapshot in | |
if !snapshot.exists() { return } | |
//print(snapshot) | |
if let userName = snapshot.value!["counter"] as? String { | |
print("asjghdvfashdfsauduhdbvasudfasugdfa") | |
print(userName) | |
} | |
// can also use | |
// snapshot.childSnapshotForPath("full_name").value as! String | |
}) | |
self.ref.child("latest_counter").observeSingleEvent(of: .value, with: { (snapshot) in | |
// Get user value | |
print(snapshot) | |
let latest_counter = Int("\(snapshot.value!)") | |
int = latest_counter! + 1 | |
self.policy_number = Int64(latest_counter!) | |
self.ref.child("latest_counter").setValue("\(int)") { | |
(error:Error?, ref:DatabaseReference) in | |
if let error = error { | |
print("Data could not be saved: \(error).") | |
} else { | |
print("Data saved successfully!") | |
} | |
} | |
}) { (error) in | |
print(error.localizedDescription) | |
} | |
var new_number = 0 | |
let db = Firestore.firestore() | |
var counterRef = db.collection("counter") | |
//get the last 3 counter number | |
counterRef.order(by: "number", descending: false).limit(to: 1) | |
counterRef.getDocuments() { (querySnapshot, err) in | |
if let err = err { | |
print("Error getting documents: \(err)") | |
} else { | |
for document in querySnapshot!.documents { | |
print("COUNTER NUMBER\(document.documentID) => \(document.data())") | |
self.policy_number = document.data()["counter"] as! Int64 | |
print("policy number is \(self.policy_number)") | |
new_number = Int(self.policy_number) + 1 | |
print("new number is \(new_number)") | |
db.collection("counter").addDocument(data: [ | |
"counter": Int(new_number) | |
]) { err in | |
if let err = err { | |
print("Error adding document: \(err)") | |
} else { | |
print("counter number generated") | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment