Firebase addition, subtraction, multiplication and division - ios

I want to multiply the two firebase values ​​and get the result to display in the Label, without success
Can anyone give me some advice
func UserInfo(){
let firestoreDB = Firestore.firestore()
firestoreDB.collection("Usermoney").whereField("email", isEqualTo: Auth.auth().currentUser!.email!).addSnapshotListener { snapshot, error in
if error != nil {
print(error?.localizedDescription ?? "Error while getting data from server!" )
}else{
if snapshot?.isEmpty != true && snapshot != nil {
for document in snapshot!.documents{
if let money = document.get("money") as? String{
if let q8 = document.get("q8") as? String{
self.money.text = money
self.q8.text = "+"+q8+"%"
let tip = money * q8
self.win.text = String(format: "$%.2f", tip)
}
}
}
}
}
}
}

Try This
func UserInfo(){
let firestoreDB = Firestore.firestore()
firestoreDB.collection("Usermoney").whereField("email", isEqualTo: Auth.auth().currentUser!.email!).addSnapshotListener { snapshot, error in
if error != nil {
print(error?.localizedDescription ?? "Error while getting data from server!" )
}else{
if snapshot?.isEmpty != true && snapshot != nil {
for document in snapshot!.documents{
if let money = document.get("money") as? String{
if let q8 = document.get("q8") as? String{
self.money.text = money
self.q8.text = "+"+q8+"%"
if let moneyDouble = Double(money), let q8Double = Double(q8){
let tip = moneyDouble * q8Double
self.win.text = String(format: "$%.2f", tip)
}
}
}
}
}
}
}
}

Related

Swift Firestore - TableView Button Bug

Please look at my TableView with custom Cell here. I fetched the data from Firestore (and sort it by date descendingly) real time and insert it into the meal array locally. When I clicked the 'eat' button and add a new meal, the 'eat' button isn't sorted correctly?
Here is my code for loadMenu() function and eatButtonPressed() function
loadMenu()
func loadMenu() {
let menuRef = db.collection("menu").document()
db.collection("menu").order(by: "date", descending: true).whereField("family_id", isEqualTo: "\(UserDefaults.standard.string(forKey: "family_id")!)")
.addSnapshotListener { querySnapshot, error in
self.menu = []
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
let name = documents.map { $0["name"] ?? [""] }
let family_id = documents.map { $0["family_id"] ?? [0] }
let portions = documents.map { $0["portions"] ?? [""] }
let menu_id = documents.map { $0["menu_id"] ?? [""]}
let isOpened = documents.map { $0["isOpened"] ?? [""]}
if name != nil || name[0] as! String != "" {
for i in 0..<name.count {
self.menu.append(Menu(menu_id: menu_id[i] as! String, name: name[i] as! String, family_id: family_id[i] as! String, portions: portions[i] as! Int, isOpened: isOpened[i] as! Bool))
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
eatButtonPressed()
func eatButtonPressed(cell: TopPartTableViewCell, send: UIButton) {
var likeRef = self.db.collection("like").document("\(Auth.auth().currentUser!.uid)_\(self.menu[send.tag].menu_id)")
self.db.collection("dislike").document("\(Auth.auth().currentUser!.uid)_\(self.menu[send.tag].menu_id)").delete() { err in
if let err = err {
print("Error removing document: \(err)")
} else {
print("Document successfully removed!")
}
}
likeRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
self.db.collection("like").document("\(Auth.auth().currentUser!.uid)_\(self.menu[send.tag].menu_id)").delete() { err in
if let err = err {
print("Error removing document: \(err)")
} else {
print("Document successfully removed!")
}
}
} else {
likeRef.setData([
"like_id": "\(likeRef.documentID)",
"user_id": "\(Auth.auth().currentUser!.uid)",
"menu_id": "\(self.menu[send.tag].menu_id)"
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
}
}
let user_liked = like.contains(where: {$0.menu_id == menu[send.tag].menu_id}) && like.contains(where: {$0.user_id == Auth.auth().currentUser!.uid})
if !user_liked {
send.backgroundColor = UIColor(named: "BrandOrange")
send.tintColor = UIColor.white
cell.dontEatButton.backgroundColor = UIColor.white
cell.dontEatButton.tintColor = UIColor.black
} else {
send.backgroundColor = UIColor.white
send.tintColor = UIColor.black
}
}
Anyone can help me solve this problem?
Thank you.
The above method doesn't seem to be relevant to the question.
You have added a new item and a cell has been added for that item.
If you look at the detailed structure of the cell, I think you can figure out the cause.
If the cell default button state is Eat, it is most likely not initialized properly.

In-App Purchase working or not when remove my account from iPhone?

I am using auto renewal subscription In-App Purchase in my application. I want to know what happened when i remove my apple account after purchase in iPhone. in app purchase is worked or not ?? I am using sandbox environment.
If not so how to know in-app apple account was removed ??
I have try to verifying the receipt and checked the in-app purchased is expire or not, but after remove apple account i always get receipt response true.
here is my get receipt request code :
#objc func loadreceipt() {
if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL,
FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {
if UD.getS(receiptdata).isEmpty == false {
Api.inAppPurchasecall(.receiptVarify(rdata: UD.getS(receiptdata), excludeInclude: true)) { response, error in
if error == nil {
self.checkresponse(response: response as! Map)
}else{
print(error)
}
}
}else{
do {
let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
let receiptString = receiptData.base64EncodedString(options: [])
Api.inAppPurchasecall(.receiptVarify(rdata: receiptString, excludeInclude: true)) { response, error in
if error == nil {
self.checkresponse(response: response as! Map)
}else{
print(error)
}
}
}
catch { print("Couldn't read receipt data with error: " + error.localizedDescription) }
}
}else{
requestrefreshreceipt = SKReceiptRefreshRequest()
requestrefreshreceipt?.delegate = self
requestrefreshreceipt?.start()
}
}
receipt response code :
func checkresponse(response : Map) {
if let rdata = response["latest_receipt"] as? String {
UD.setS(receiptdata, rdata)
}
if let latestreceiptinfo = response["latest_receipt_info"] as? [Map] {
if let lastinfo = latestreceiptinfo.first {
if let expiredate = lastinfo["expires_date"] as? String, let edate = Formatter.customDate.date(from: expiredate) {
if let strEdate = gmtToLocal(date: edate) {
self.nextBillingDate = strEdate
}
}
if let expiredate = lastinfo["purchase_date"] as? String, let edate = Formatter.customDate.date(from: expiredate) {
if let strEdate = gmtToLocal(date: edate) {
self.lastBillingDate = strEdate
}
}
if let expiretime = lastinfo["expires_date_ms"] as? String, let doubleexpiretime = Double(expiretime) {
expireTimeStamp = doubleexpiretime/1000
let currenttimestamp = Date().timeIntervalSince1970
if let etimestamp = expireTimeStamp {
if etimestamp > currenttimestamp {
UD.setS(AppConst.SUBSCRIPTION_STATUS, "true")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kRefreshServices), object:nil)
}else{
UD.setS(AppConst.SUBSCRIPTION_STATUS, "false")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kRefreshServices), object:nil)
if let expiredate = lastinfo["expires_date"] as? String, let edate = Formatter.customDate.date(from: expiredate) {
if let root = APP_DELEGATE.window?.rootViewController {
if let strEdate = gmtToLocal(date: edate) {
}
}
}
}
}
}
}
}
}

Firebase / Firestore not getting document and running code

I am getting a document from firebase in swift. However the line isn't being run and is not getting the data.
This is my code:
let db = Firestore.firestore()
db.collection("chats").document(userDefaults.string(forKey: "currentGroup")!).collection("messages").document("variable").getDocument { (document, error) in
if error != nil{
print("error getting document")
}
else{
let documentData = document!.data()
let startNumOfMessages = documentData!["numOfMessages"] as! Int
var messageArray: Array<String> = []
if startNumOfMessages > 0 {
for message in 1...startNumOfMessages{
print(message)
//THIS LINE ISNT RUNNING
db.collection("chats").document(self.userDefaults.string(forKey: "currentGroup")!).collection("messages").document("\(message)").getDocument { (messageDoc, err) in
if err != nil{
print("Error getting message \(message)")
}
else{
if messageDoc!.exists && messageDoc != nil{
let messData = messageDoc!.data()
print(messData!["message"]!)
messageArray.append(messData!["message"] as! String)
}
else{
print("error in document")
}
}
}
}
//Display them
for num in 0...messageArray.count{
let label = UILabel()
label.text = messageArray[num]
self.stackView.addArrangedSubview(label)
}
}
}
}
The line below the comment is the line that isn't running. And the line that says label.text = messageArray[num] displays an error
Fatal error: Index out of range
Showing it doesn't get the data.
You miss the asynchronous way use DispatchGroup ( numbered from 1 to 4 )
let db = Firestore.firestore()
db.collection("chats").document(userDefaults.string(forKey: "currentGroup")!).collection("messages").document("variable").getDocument { (document, error) in
if error != nil{
print("error getting document")
}
else{
let documentData = document!.data()
let startNumOfMessages = documentData!["numOfMessages"] as! Int
var messageArray: Array<String> = []
if startNumOfMessages > 0 {
let g = DispatchGroup() /// 1
for message in 1...startNumOfMessages{
print(message)
//THIS LINE ISNT RUNNING
g.enter() /// 2
db.collection("chats").document(self.userDefaults.string(forKey: "currentGroup")!).collection("messages").document("\(message)").getDocument { (messageDoc, err) in
if err != nil{
print("Error getting message \(message)")
}
else{
if messageDoc!.exists && messageDoc != nil{
let messData = messageDoc!.data()
print(messData!["message"]!)
messageArray.append(messData!["message"] as! String)
}
else{
print("error in document")
}
}
g.leave() /// 3
}
}
g.notify(queue: .main) { /// 4
//Display them
for num in 0...messageArray.count{
let label = UILabel()
label.text = messageArray[num]
self.stackView.addArrangedSubview(label)
}
}
}
}
}

Getting incorrect value form firebase in swift

This is my code
let db = Firestore.firestore()
db.collection("chats").document(userDefaults.string(forKey: "currentGroup")!).collection("messages").document("variable").addSnapshotListener { (snapshot, error) in
if error != nil{
print("Error fetching document")
}
else{
let documentData = snapshot!.data()
print(documentData!["numOfMessages"])
self.numOfMessages = documentData!["numOfMessages"] as! Int
print(self.numOfMessages)
//Get texts and display them
db.collection("chats").document(self.userDefaults.string(forKey: "currentGroup")!).collection("messages").document("\(self.numOfMessages)").getDocument { (document, err) in
let newMessageData = document!.data()
let newMessage = newMessageData!["message"] as! String
let newAuthor = newMessageData!["author"] as! String
let authorLabel = UILabel()
authorLabel.text = newAuthor
self.stackView.addArrangedSubview(authorLabel)
let label = UILabel()
label.text = newMessage
self.stackView.addArrangedSubview(label)
}
}
}
This line self.numOfMessages = documentData!["numOfMessages"] as! Int has an error of
Could not cast value of type 'NSTaggedPointerString' (0x1ed6ed450) to 'NSNumber' (0x1ed6f98c8).
This is every since I deleted the collection messages and replaced it with one of the exact same name
The value that documentData!["numOfMessages"] returns is Optional(1) even though in firebase the value is 2.
This is how the Firestore looks:
Either you are listening to the wrong document (perhaps because of an incorrect user default) or you are unwrapping the value incorrectly. To debug this, try the following and see what the problem actually is. The following is a more idiomatic way of handling documents.
if let currentGroup = userDefaults.string(forKey: "currentGroup") {
print(currentGroup) // this could be your problem
Firestore.firestore().collection("chats").document(currentGroup).collection("messages").document("variable").addSnapshotListener { (snapshot, error) in
if let snapshot = snapshot {
if let numOfMessages = snapshot.get("numOfMessages") as? Int {
print(numOfMessages)
} else {
print("field error")
}
} else if let error = error {
print(error)
}
}
} else {
print("no current group")
}

AddSnapShotListener is repeating the document reading in one instance

When I am using addSnapshotListener for realtime updates, the documents are repeated which should not be the case, but when using getDocuments() the documents are repeated once only, I need to use addSnaphotListener but not want to duplicate the document reading, please assist where I am wrong in using snapshot listener.
I am using Firestore database in Swift iOS. Below is the code I am using
Code with addSnapShotListener():
func getComments() {
//print(postId + "received")
let commentsRef = Firestore.firestore().collection("posts").document(postId).collection("comments")
commentsRef.addSnapshotListener { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
// self.length = snapshot.count
let data = document.data()
let username = data["comment_author_username"] as? String ?? ""
let comment = data["comment_author_comment"] as? String ?? ""
let spinnerC = data["comment_author_spinnerC"] as? String ?? ""
let fullname = data["comment_author_fullname"] as? String ?? ""
let email = data["comment_author_email"] as? String ?? ""
let commentUserImageUrl = data["comment_user_image"] as? String ?? ""
let commentuser_id = data["comment_author_id"] as? String ?? ""
self.checkl1value = data["l1"] as? Bool
let newComment = Comment(_documentId: document.documentID, _commentAuthorUsername: username, _commentAuthorFullName: fullname, _commentAuthorComment: comment, _commentUserImage: commentUserImageUrl, _commentAuthorSpinnerC: spinnerC, _commentAuthorId:commentuser_id, _checkl1value: self.checkl1value)
self.comments.append(newComment)
// print(self.length!)
}
self.tableView.reloadData()
}
}
}
}
Code With getDocuments():
func getComments() {
//print(postId + "received")
let commentsRef = Firestore.firestore().collection("posts").document(postId).collection("comments")
commentsRef.getDocuments { (snapshot, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let snapshot = snapshot {
for document in snapshot.documents {
// self.length = snapshot.count
let data = document.data()
let username = data["comment_author_username"] as? String ?? ""
let comment = data["comment_author_comment"] as? String ?? ""
let spinnerC = data["comment_author_spinnerC"] as? String ?? ""
let fullname = data["comment_author_fullname"] as? String ?? ""
let email = data["comment_author_email"] as? String ?? ""
let commentUserImageUrl = data["comment_user_image"] as? String ?? ""
let commentuser_id = data["comment_author_id"] as? String ?? ""
self.checkl1value = data["l1"] as? Bool
let newComment = Comment(_documentId: document.documentID, _commentAuthorUsername: username, _commentAuthorFullName: fullname, _commentAuthorComment: comment, _commentUserImage: commentUserImageUrl, _commentAuthorSpinnerC: spinnerC, _commentAuthorId:commentuser_id, _checkl1value: self.checkl1value)
self.comments.append(newComment)
// print(self.length!)
}
self.tableView.reloadData()
}
}
}
}
You're probably looking to only handle the changes between the snapshots. To do that you'll want to loop over instead of, as shown in the documentation on viewing changes between snapshots:
db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
print("New city: \(diff.document.data())")
}
if (diff.type == .modified) {
print("Modified city: \(diff.document.data())")
}
if (diff.type == .removed) {
print("Removed city: \(diff.document.data())")
}
}
}
Initially your listener will get called with diff.type == .added for each existing document, and then when there are changes it'll get called with the right mix of types.

Resources