检查另一个ViewController的按钮

时间:2017-05-09 08:41:02

标签: ios firebase swift3 firebase-realtime-database

我正在尝试一个事件应用程序。我可以将事件添加到Firebase数据库并检索它们。当我从viewController中单击添加按钮时,事件的信息将添加到Firebase数据库中。但是在我退出并再次登录之前,它无法在我的tableViewController上显示。

这里是我的检索代码:

private func loadPlaces() {


        let ref = FIRDatabase.database().reference()

        ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in

            let images = snapshot.value as! [String : AnyObject]
            // self.places.removeAll()
            for (_, value) in images {
                  let userToShow = events()
                if let img = value["pathToImage"] as? String,
                    let eventDate = value["event date"] as? String,
                    let name = value["event name"] as? String
                    //let information = value["information"] as? String
                {


                  //  self.places.append(historicalPlaces(img: img , name: name2, inf:information))

                     userToShow.eventImages = img
                    userToShow.eventDates = eventDate
                    userToShow.eventnames = name
                   // userToShow.information = information
                    self.event.append(userToShow)

                }


            }
            self.tableView.reloadData()
        })
        //  ref.removeAllObservers()

    }

这是我的uploadPost代码:

import UIKit
import os.log
import Firebase
class UploadPost: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var eventImage: UIImageView!
    @IBOutlet weak var selectImageBtn: UIButton!

    @IBOutlet weak var eventName: UITextField!
    @IBOutlet weak var eventInf: UITextView!

    @IBOutlet weak var addBtn: UIButton!

    @IBOutlet weak var eventDate: UITextField!
    @IBOutlet weak var addEvent: UIBarButtonItem!

    var picker = UIImagePickerController()

    let datePicker = UIDatePicker()

    override func viewDidLoad() {
        super.viewDidLoad()


        picker.delegate = self
        createDatePicker()
    }

    func createDatePicker(){

        //format for picker

        datePicker.datePickerMode = .dateAndTime

        // toolbar

        let toolbar = UIToolbar()

        toolbar.sizeToFit()

        // bar button item

        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
        toolbar.setItems([doneButton], animated: false)

        eventDate.inputAccessoryView = toolbar

        //assigning date picker to text field

        eventDate.inputView = datePicker

    }
    func donePressed(){

        //format date

        let dateFormatter = DateFormatter()

        dateFormatter.dateStyle = .short
        dateFormatter.timeStyle = .short

        eventDate.text = dateFormatter.string(from: datePicker.date)
        self.view.endEditing(true)

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
            self.eventImage.image = image
            selectImageBtn.isHidden = true
            addBtn.isHidden = false
        }

        self.dismiss(animated: true, completion: nil)
    }

    @IBAction func selectImage(_ sender: Any) {

        picker.allowsEditing = true
        picker.sourceType = .photoLibrary

        self.present(picker, animated: true, completion: nil)
    }

    @IBAction func addEventPressed(_ sender: Any) {


    }



    @IBAction func addPressed(_ sender: Any) {

        AppDelegate.instance().showActivityIndicator()

        let uid = FIRAuth.auth()!.currentUser!.uid
        let ref = FIRDatabase.database().reference()
        let storage = FIRStorage.storage().reference(forURL: "gs://bauventdemo.appspot.com")

        let key = ref.child("events").childByAutoId().key
        let imageRef = storage.child("events").child(uid).child("\(key).jpg")

        let data = UIImageJPEGRepresentation(self.eventImage.image!, 0.6)

        let uploadTask = imageRef.put(data!, metadata: nil) { (metadata, error) in
            if error != nil {
                print(error!.localizedDescription)
                AppDelegate.instance().dismissActivityIndicatos()
                return
            }

            imageRef.downloadURL(completion: { (url, error) in
                if let url = url {
                    let feed = ["userID" : uid,
                                "pathToImage" : url.absoluteString,
                                "event name" : self.eventName.text!,
                                "event date" : self.eventDate.text!,
                                "author" : FIRAuth.auth()!.currentUser!.displayName!,
                                "event information" : self.eventInf.text!,
                                "postID" : key] as [String : Any]

                    let postFeed = ["\(key)" : feed]

                    ref.child("posts").updateChildValues(postFeed)
                    AppDelegate.instance().dismissActivityIndicatos()

                    self.dismiss(animated: true, completion: nil)
                }
            })

        }

        uploadTask.resume()



    }




    }

我的代码仅在我登录时检查数据库,如何在添加新事件时检查firebase数据库并检索它们?

2 个答案:

答案 0 :(得分:0)

不更新表的原因是因为您尝试在后台线程中重新加载表。 而是在主线程中重新加载它。像这样:

DispatchQueue.main.async {
        self.tableView.reloadData()
    }

更新了代码

private func loadPlaces() {


    let ref = FIRDatabase.database().reference()

    ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in

        let images = snapshot.value as! [String : AnyObject]
        // self.places.removeAll()
        for (_, value) in images {
              let userToShow = events()
            if let img = value["pathToImage"] as? String,
                let eventDate = value["event date"] as? String,
                let name = value["event name"] as? String
                //let information = value["information"] as? String
            {


              //  self.places.append(historicalPlaces(img: img , name: name2, inf:information))

                 userToShow.eventImages = img
                userToShow.eventDates = eventDate
                userToShow.eventnames = name
               // userToShow.information = information
                self.event.append(userToShow)

            }


        }

        DispatchQueue.main.async {
           self.tableView.reloadData()
        }
    })
    //  ref.removeAllObservers()

}

答案 1 :(得分:0)

我尝试添加刷新按钮,从数据库中检索数据作为解决方法。

 @IBAction func refresh(_ sender: Any) {

       loadPlaces()


    }

我将此代码用于防止重复事件。

self.event.removeAll()