How can i upload a row in Parse.com?
This is my query code:
func queryFromParse(){
self.arrayOfDetails.removeAll()
let query = PFQuery(className: "currentUploads")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil
{
if let newObjects = objects as? [PFObject] {
for oneobject in newObjects {
let text = oneobject["imageText"] as! String
let username = oneobject["username"] as! String
let deviceID = oneobject["identifierForVendor"] as! String
let reportedCount = oneobject["reportedCount"] as! String
let time = oneobject.createdAt!
if let userImage = oneobject["imageFile"] as? PFFile {
let userImage = oneobject["imageFile"] as! PFFile
let imageURL = userImage.url // <- Bruker nĂ¥ userImage.URL, henter ikke bildefilen med en gang
let OneBigObject = Details(username: username, text: text, CreatedAt: time, image: imageURL!, deviceID: deviceID, reportedCount: reportedCount)
//let OneBigObject = Details(username: username, text: text, CreatedAt: time, image: imageURL!)
self.arrayOfDetails.append(OneBigObject)
dispatch_async(dispatch_get_main_queue()) { self.collectionView.reloadData() }
}
}
}
}
}
}
Image here
I want to update the "reportedCount" when the image is reported. I have a code that i have been using, but that created new rows in another class for each report, and I want only to update the "reportedCount":
#IBAction func reportContentAction(sender: AnyObject) {
let buttonPosition = sender.convertPoint(CGPointZero, toView: self.collectionView)
let indexPath = self.collectionView.indexPathForItemAtPoint(buttonPosition)
////
println(indexPath?.item)
////
let post = self.arrayOfDetails[indexPath!.item]
var alertMessage = NSString(format:"*User: %#\r *Text: %#\r *Created at %#", post.username, post.text, post.CreatedAt)
var reportAlert = UIAlertController(title: "Report Content", message:alertMessage as String, preferredStyle: UIAlertControllerStyle.Alert)
reportAlert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action: UIAlertAction!) in
println("Handle Report Logic here")
var currentUploads = PFObject(className: "banned")
currentUploads["username"] = post.username
currentUploads["imageText"] = post.text
currentUploads["imageFile"] = post.image
currentUploads["identifierForVendor"] = post.deviceID
currentUploads["flaggedBy"] = PFUser.currentUser()?.username
currentUploads["flaggedByUUID"] = UIDevice.currentDevice().identifierForVendor.UUIDString
currentUploads.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error == nil{
//**Success saving, now save image.**//
currentUploads.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if error == nil{
// Take user home
print("Data uploaded")
// Show UIAlertView
let alert = UIAlertView()
alert.title = "Message"
alert.message = "You report has been sent. Thank you for your support."
alert.addButtonWithTitle("Close")
alert.show()
}
else{
print(error)
}
})
}
else{
print(error)
}
})
}))
reportAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
println("Handle Cancel Logic here")
}))
presentViewController(reportAlert, animated: true, completion: nil)
}
You should be keeping a reference to oneobject, or more broadly, all of the objects returned from the query. Now when something changes you can get the appropriate instance from the objects array and then update and save it to modify the existing 'row'.
Related
I have an app that takes in user input that is stored in core data. To simplify things, I combined 5 strings from the user inputs, separated them with a comma and then this long string is stored in core data as 1 entity. The comma is separating the individual 'strings' is what makes it a CSV. However, when I tried exporting the csv file, I only managed to get the header.
The two components of code that is involved in this are as follows. The part collecting the strings and combining them:
#objc func addAlarmItem(_ sender: AnyObject) {
let alertController = UIAlertController(title: "Add New Item", message: "Please fill in the blanks", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in
//combined string of attributes
let myStrings: [String] = alertController.textFields!.compactMap { $0.text }
let myText = myStrings.joined(separator: ",")
self.save(myText)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
alertController.addTextField { (textField) in
textField.placeholder = "Enter Name of Engineer"
}
alertController.addTextField { (textField) in
textField.placeholder = "Enter Date of Alarm in DD/MM/YYYY"
}
alertController.addTextField { (textField) in
textField.placeholder = "Enter Time of Alarm in 24h (eg: 2300)"
}
alertController.addTextField { (textField) in
textField.placeholder = "Please indicate True/False (type True or False)"
}
alertController.addTextField { (textField) in
textField.placeholder = "Insert comments (if any), or NIL"
}
func save(_ itemName: String) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "AlarmItem", in: managedContext)!
let item = NSManagedObject(entity: entity, insertInto: managedContext)
item.setValue(itemName, forKey: "alarmAttributes")
do {
try managedContext.save()
tableView.reloadData()
} catch let err as NSError {
print("Failed to save an item", err)
}
}
And the part that does the exporting core data entry as csv:
#objc func exportCSV(_ sender: AnyObject) {
exportDatabase()
}
func exportDatabase() {
let exportString = createExportString()
saveAndExport(exportString: exportString)
}
func saveAndExport(exportString: String) {
let exportFilePath = NSTemporaryDirectory() + "itemlist.csv"
let exportFileUrl = NSURL(fileURLWithPath: exportFilePath)
FileManager.default.createFile(atPath: exportFilePath, contents: NSData() as Data, attributes: nil)
var fileHandle: FileHandle? = nil
do {
fileHandle = try FileHandle(forUpdating: exportFileUrl as URL)
} catch {
print("filehandle has error")
}
if fileHandle != nil {
fileHandle!.seekToEndOfFile()
let csvData = exportString.data(using: String.Encoding.utf8, allowLossyConversion: false)
fileHandle!.write(csvData!)
fileHandle!.closeFile()
let firstActivityItem = NSURL(fileURLWithPath: exportFilePath)
let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: [firstActivityItem], applicationActivities: nil)
activityViewController.excludedActivityTypes = [
UIActivity.ActivityType.assignToContact,
UIActivity.ActivityType.saveToCameraRoll,
UIActivity.ActivityType.postToFlickr,
UIActivity.ActivityType.postToVimeo,
UIActivity.ActivityType.postToTencentWeibo
]
activityViewController.popoverPresentationController?.sourceView = self.view
activityViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection()
activityViewController.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
self.present(activityViewController, animated: true, completion: nil)
}
}
func createExportString() -> String {
var alarmAttributes: String?
var export: String = NSLocalizedString("Engineer Name,Date of Alarm,Time of Alarm,True or False,Engineer Comments \n", comment: "")
for (index, AlarmItem) in fetchedStatsArray.enumerated() {
if index <= fetchedStatsArray.count - 1 {
alarmAttributes = AlarmItem.value(forKey: "alarmAttributes") as! String?
let alarmAttributeStrings = alarmAttributes
export += "\(alarmAttributeStrings ?? "0") \n"
}
}
print("the app will now print: \(export) ")
return export
}
I cannot for the life of me figure out why my fetchedStatsArray is empty . I have attached to entire code in my github.
The full code is located here: https://github.com/danialaqil/TFAApp/blob/master/AlarmChartsApp/HistoryController.swift if you need to see the entire thing in more detail
func teacherExists(teacherName: String) -> Bool
{
var dataBaseRef2: DatabaseReference!
dataBaseRef2 = Database.database().reference()
let teachersTableRef = dataBaseRef2.child("teachers")
self.teachersList.removeAll()
teachersTableRef.observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
// teachersTableRef.observe(.value)
//{
// snapshot in
let teachersNamesDictionary = snapshot.value as? [String: Any] ?? [:]
for(key, _) in teachersNamesDictionary
{
if let teacherDict = teachersNamesDictionary[key] as? [String: Any]
{
if let teacher = Teacher(dictionary: teacherDict)
{
//print(teacher.teacher_name)
self.teachersList.append(teacher.teacher_name)
}
}
}
print(self.teachersList.count)
})
print("Outside \(self.teachersList)")
return false
}
Because Firebase APIs are all asynchronous. It would be bad for your app if they blocked your code path, because that could cause your app to hang indefinitely.
observeSingleEvent returns immediately, and the passed observer gets invoked some time later, whenever the data is finally ready. Execution continues on the next line, which prints to the console.
getting error upon calling teacherExists function
let OKAction = UIAlertAction(title: "OK", style: .default, handler:
{
(action: UIAlertAction!) ->Void in
let textfield = alert.textFields![0] as UITextField
newTeacherName = textfield.text!.uppercased()
if !(newTeacherName.isEmpty)
{
//checking if teacher already exists using function teacherExists
let exists = self.teacherExists(teacherName: newTeacherName, completion:
if exists == true //if duplicate teacher is found
{
let alert = UIAlertController(title: "Duplicate Teacher", message: "Teacher \(newTeacherName) has been added earlier", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
else
{
//add teacher to database here
let dict = ["teacher_name" : newTeacherName]
let newTeacher = Teacher(dictionary: dict)
let tableRef = self.dataBaseRef.child("teachers") //getting reference of node with name teachers
let recordRef = tableRef.childByAutoId() //creating a new record in teachers node
recordRef.setValue(newTeacher!.toDictionary())//adding data to new record in teachers node
}
}
})
You can use closure to callback after check for duplicate
func teacherExists(teacherName: String, completion: #escaping ((Bool) -> Void)) -> Void {
var dataBaseRef2: DatabaseReference!
dataBaseRef2 = Database.database().reference()
let teachersTableRef = dataBaseRef2.child("teachers")
self.teachersList.removeAll()
teachersTableRef.observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
let teachersNamesDictionary = snapshot.value as? [String: Any] ?? [:]
for(key, _) in teachersNamesDictionary
{
if let teacherDict = teachersNamesDictionary[key] as? [String: Any]
{
if let teacher = Teacher(dictionary: teacherDict)
{
//print(teacher.teacher_name)
self.teachersList.append(teacher.teacher_name)
}
}
}
let exists = self.teachersList.contains(teacherName)
completion(exists)
})
}
And call function as below
teacherExists(teacherName: newTeacherName) { (exists) in
if exists {
// show alert
} else {
// add new teacher to db
}
}
Hope it help!
Everything was working fine, then I deleted some old messages and conversations from My Firebase Database. Now every time I send a message I get a crash. I deleted all old users and created new users and tried to send messages and I still keep getting a crash. I am not sure what can be causing this. Any suggestions will be helpful. It first happened after I tested out this function to delete the table cell...
func deleteConversation(_ conversation:Conversation) {
guard let user = Auth.auth().currentUser else { return }
let ref = Database.database().reference()
let obj = [
"conversations/users/\(user.uid)/\(conversation.partner_uid)/muted": true
] as [String:Any]
print("OBBJ: \(obj)")
ref.updateChildValues(obj, withCompletionBlock: { error, ref in
if error != nil {
let alert = UIAlertController(title: "Error deleting conversation!", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
} else {
let alert = UIAlertController(title: "Conversation deleted!", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
}
})
}
func downloadMessages() {
self.messages = []
downloadRef?.observe(.childAdded, with: { snapshot in
let dict = snapshot.value as! [String:AnyObject]
if let sender = dict["sender"] as! String!, let recipient = dict["recipient"] as! String!, let text = dict["text"] as! String!, text.characters.count > 0 {
let timestamp = dict["timestamp"] as! Double
let date = NSDate(timeIntervalSince1970: timestamp/1000)
let message = JSQMessage(senderId: sender, senderDisplayName: "", date: date as Date!, text: text)
self.messages.append(message!)
self.reloadMessagesView()
self.finishReceivingMessage(animated: true)
}
else if let id = dict["sender"] as! String!,
let photoURL = dict["imageUrl"] as! String!, photoURL.characters.count > 0 { // 1
// 2
if let mediaItem = JSQPhotoMediaItem(maskAsOutgoing: id == self.senderId) {
// 3
let timestamp = dict["timestamp"] as! Double
let date = NSDate(timeIntervalSince1970: timestamp/1000)
if let message = JSQMessage(senderId: id, senderDisplayName: "", date: date as Date!, media: mediaItem) {
self.messages.append(message)
if (mediaItem.image == nil) {
self.photoMessageMap[snapshot.key] = mediaItem
}
self.collectionView.reloadData()
}
if photoURL.hasPrefix("gs://") {
self.fetchImageDataAtURL(photoURL, forMediaItem: mediaItem, clearsPhotoMessageMapOnSuccessForKey: nil)
}
}
}
else {
print("Error! Could not decode message data")
}
})
// We can also use the observer method to listen for
// changes to existing messages.
// We use this to be notified when a photo has been stored
// to the Firebase Storage, so we can update the message data
updatedMessageRefHandle = downloadRef?.observe(.childChanged, with: { (snapshot) in
let key = snapshot.key
let messageData = snapshot.value as! Dictionary<String, String> // 1
if let photoURL = messageData["imageUrl"] as String! { // 2
// The photo has been updated.
if let mediaItem = self.photoMessageMap[key] { // 3
self.fetchImageDataAtURL(photoURL, forMediaItem: mediaItem, clearsPhotoMessageMapOnSuccessForKey: key) // 4
}
}
})
}
It's very likely the error is a result of force casting - as!
Instead of
let messageData = snapshot.value as! Dictionary<String, String>
do
guard let messageData = snapshot.value as? Dictionary<String, String> else { return }
Your snapshot.value is either nil, or is not an instance of Dictionary<String, String>, and force casting it to such will result in crash.
You should also read more about optionals and type casting in Swift, because you use ! a lot, and not once in your program is it used correctly.
I'm trying to use a func I extended UIViewController with. I added self to the different func's arguments but the func not gives me "Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit" error. Tried even to apply a weak self reference. The func seems to be never running anyway
te array is declared
var managedComicsArray = [NSManagedObject]()
in viewDidLoad :
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
managedContext = appDelegate.persistentContainer.viewContext
the button
#IBAction func addComicButtonTapped(_ sender: UIBarButtonItem) {
print("add button tapped")
weak var weakSelf = self // ADD THIS LINE AS WELL
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "Some default text"
textField.keyboardType = .numberPad
}
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
// let textField = alert.textFields![0] // Force unwrapping because we know it exists.
let textField = alert!.textFields![0]
print("Text from textField: \(textField.text)")
guard let grabbedNumber = Int16(textField.description) else {return}
//the func below gives the error
weakSelf?.addRecordIfnotPresent(newIssueNumber: grabbedNumber, theManagedContext: self.managedContext, theEntityName: self.kComicEntityName, managedArray: &self.managedComicsArray)
self.myTableView.reloadData()
}))
alert.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))
// 4. Present the alert.
self.present(alert, animated: true, completion: nil)
//end of button
}
the extended method:
func addRecordIfnotPresent(newIssueNumber: Int16, theManagedContext: NSManagedObjectContext, theEntityName: String, managedArray: inout [NSManagedObject]) {
print("adding func started")
let comicFetch: NSFetchRequest<Comic> = Comic.fetchRequest()
var isPresent = true
do {
managedArray = try theManagedContext.fetch(comicFetch)
if !managedArray.isEmpty {
//*****************************************************************
for comic in managedArray {
var comicToCheck = Comic()
comicToCheck = comic as! Comic
if comicToCheck.wholeSeriesNumber == newIssueNumber {
print("number \(newIssueNumber) is alredy present")
return
} else {
isPresent = false
print("number not present, keep on!")
}
}
guard isPresent == false else {return}
saveSingleComicWithNumber(withIssueNumber: Int(newIssueNumber), theEntityName: theEntityName, theManagedContext: theManagedContext)
print("created Comic!")
try theManagedContext.save()
print("saved context!")
//*****************************************************************
} else {
saveSingleComicWithNumber(withIssueNumber: Int(newIssueNumber), theEntityName: theEntityName, theManagedContext: theManagedContext)
}
} catch let error as NSError {
print("Fetch error: \(error) description: \(error.userInfo)")
}
}
func saveSingleComicWithNumber(withIssueNumber: Int, theEntityName: String, theManagedContext: NSManagedObjectContext) {
let entity = NSEntityDescription.entity(forEntityName: theEntityName, in: theManagedContext)!
let comicToAdd = Comic(entity: entity, insertInto: theManagedContext)
comicToAdd.wholeSeriesNumber = Int16(withIssueNumber)
comicToAdd.issueInCollection = false
comicToAdd.titleOfItalianSerie = "title"
if comicToAdd.wholeSeriesNumber == 2 {
comicToAdd.issueInCollection = false
}
do {
try theManagedContext.save()
} catch let error as NSError {
print("could not save. \(error), \(error.userInfo)")
}
}
So I am really new to threading and I've been reading up on it all day. For some reason though the data isn't loading before other code executes
Basically I need all the values that have a key ["whatever"] to be filled into an array, which works in other places because I don't need to load it first. So i have checked and double checked the keys that I am updating do exist and the keys I am extracting do exist maybe not the values yet but the keys do.
The problem is the code goes to fast to through the method. How would I make the main thread wait untill my firebase has loaded the data I have tried it below but it does not seem to be working
here is my code
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let alertController = UIAlertController(title: "Accept Bet", message: "Match the bet of " + amountBets[indexPath.row], preferredStyle: .alert)
let okButton = UIAlertAction(title: "No", style: .default, handler: { (action) -> Void in
print("Ok button tapped")
})
let yesButton = UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
// let them know to wait a second or the bet won't go through
var waitController = UIAlertController(title: "Please Wait", message: "You must wait for the bet to go through", preferredStyle: .alert)
self.present(waitController, animated: true, completion: nil)
//take away that bitches money
self.takeAwayMoney(self.amountBets[indexPath.row], completion: { (result: Bool?) in
guard let boolResult = result else {
return
}
if boolResult == true {
self.updateBet(indexPath.row, completion: {(result: String?) in
guard let resultRecieved = result else {
return
}
print(self.opposingUserNames)
//let delayInSeconds = 7.0 // 1
//DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
self.dismiss(animated: true, completion: nil)
let successController = UIAlertController(title: "Success", message: "You have made a bet with " + self.opposingUserNames!, preferredStyle: .alert)
let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
successController.addAction(okButt)
self.present(successController, animated: true, completion: nil)
//lastly delete the opposing UserName
print(self.opposingUserNames)
self.amountBets.remove(at: indexPath.row)
self.tableView.reloadData()
print("Second")
print(self.opposingUserNames)
//}
})
} else {
return
}
})
//then delete that cell and do another pop up that says successful
// check if value is yes or no in the database
})
alertController.addAction(okButton)
alertController.addAction(yesButton)
present(alertController, animated: true, completion: nil)
}
The below function updates the values OpposingUsername and show
func updateBet(_ index: Int, completion: #escaping (_ something: String?) -> Void) {
let userID = FIRAuth.auth()?.currentUser?.uid
datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
// ...
self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
//
// this is the unique identifier of the bet. eg, -Kfx81GvUxoHpmmMwJ9P
guard let dict = snapshot.value as? [String: AnyHashable] else {
print("failed to get dictionary from Bets.\(self.userName)")
return
}
let values = ["OpposingUsername": self.userName,"Show": "no"]
self.datRef.child("Bets").child(self.tieBetToUser[index]).updateChildValues(values)
// now get the opposing username which is just the Username registered to that specific bet
self.datRef.child("Bets").child(self.tieBetToUser[index]).observe(.childAdded, with: { snapshot in
guard let dict2 = snapshot.value as? [String: AnyHashable] else {
return
}
let userNameOfOtherPlayer = dict2["Username"] as? String
self.opposingUserNames = userNameOfOtherPlayer!
completion(self.opposingUserNames)
})
})
}) { (error) in
print(error.localizedDescription)
}
}
ok so with this updated code it cuts out the logic errors I had earlier, but now the app hangs on my waitAlertViewController. Not sure why. it does updated the bet in the firebase database so I know its working and running that code but its like never completing it all. sorry bibscy I see what you mean now
completion handlers are pretty powerful once you understand them better
//Notice that I made `result: String?` optional, it may or may not have a value.
func getOpoosingUserNames(_ username: String,_ index: Int, completion: #escaping (_ result: String?) -> Void ) {
let userID = FIRAuth.auth()?.currentUser?.uid
datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let username = value?["username"] as? String ?? ""
self.userName = username
// ...
self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
//
// this is the unique identifier of the bet. eg, -Kfx81GvUxoHpmmMwJ9P
let betId = snapshot.key as String
guard let dict = snapshot.value as? [String: AnyHashable] else {
print("failed to get dictionary from Bets.\(self.userName)")
return
}
if let show = dict["Show"] as? String {
let opposingUser = dict["OpposingUsername"] as? String
self.opposingUserNames.append(opposingUser!)
}
completion(opposingUserNames)
})
}) { (error) in
print(error.localizedDescription)
}
}
//update the be
func updateBet(_ index: Int, completion: #escaping (_ something: [String]?) -> Void) {
let userID = FIRAuth.auth()?.currentUser?.uid
datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
// ...
self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
//
// this is the unique identifier of the bet. eg, -Kfx81GvUxoHpmmMwJ9P
guard let dict = snapshot.value as? [String: AnyHashable] else {
print("failed to get dictionary from Bets.\(self.userName)")
return
}
let values = ["OpposingUsername": self.userName,"Show": "no"]
//store the values received from Firebase in let valueOfUpdate and pass this
// constant to your completion handler completion(valueOfUpdate) so that you can use this value in func
//tableView(_ tableView:_, didSelectRowAt indexPath:_)
let valueOfUpdate = self.datRef.child("Bets").child(self.tieBetToUser[index]).updateChildValues(values)
completion(valueOfUpdate)
}) { (error) in
print(error.localizedDescription)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let alertController = UIAlertController(title: "Accept Bet", message: "Match the bet of " + amountBets[indexPath.row], preferredStyle: .alert)
let okButton = UIAlertAction(title: "No", style: .default, handler: { (action) -> Void in
print("Ok button tapped")
})
let yesButton = UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
//take away that bitches money
self.takeAwayMoney(self.amountBets[indexPath.row])
//then delete that cell and do another pop up that says successful
// check if value is yes or no in the database
self.updateBet(indexPath.row, completion: {(result: String) in
guard let resultReceivedInupdateBet = result, else {
print("result of updateBet() is \(result)")
}
print("If you see this print, database was updated")
//calling this method with the indexPath.row clicked by the user
self.getOpoosingUserNames(self.userName, indexPath.row, completion: { (result: [String]) in
guard let resultReceivedIngetOpoosingUserNames = result{
print("result of getOpoosingUserNames is \(result)")
}
print("If you see this print, you received a value from db after calling getOpoosingUserNames and that value is in \(result) ")
//result is not nil, resultReceivedIngetOpoosingUserNames has the same value as result.
}//end of self.getOpoosingUserNames
self.checkForNo(indexPath.row)
self.amountBets.remove(at: indexPath.row)
self.tableView.reloadData()
print(self.opposingUserNames)
let successController = UIAlertController(title: "Success", message: "You have made a bet with " + self.opposingUserNames[indexPath.row], preferredStyle: .alert)
let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
successController.addAction(okButt)
self.present(successController, animated: true, completion: nil)
//lastly delete the opposing UserName
self.opposingUserNames.remove(at: indexPath.row)
})
alertController.addAction(okButton)
alertController.addAction(yesButton)
present(alertController, animated: true, completion: nil)
}