如何在Firebase中存储和检索Swift中的数据

时间:2016-06-24 00:54:14

标签: swift firebase firebase-realtime-database jsqmessagesviewcontroller

我有一个我构建的消息传递应用程序,我想显示用户正在使用我的应用程序的城市。该应用程序可以很好地收集和显示位置数据,但它一次只存储一个位置数据实例。例如,如果我从西雅图发布到应用程序,该应用程序将说我将从西雅图发布。但是,如果其他人从纽约发布到应用程序,西雅图的位置数据将被覆盖,就好像每个用户都在纽约。这显然是一个重大问题。

我以为我可以使用Firebase数据库(我已经用它来处理消息传递)来存储每个唯一用户的位置数据,然后在我发布时从数据库中检索它但我一直试图找到一个解决我的问题没有成功。

再一次,我收集位置数据没有问题,我只想为每个唯一用户存储一个唯一的位置。

以下是我的一些代码(注意:很抱歉它太长了,但我没有想要省略任何可能有助于回答我问题的代码):

class ChatViewController: JSQMessagesViewController, CLLocationManagerDelegate {

    // MARK: Properties


    //Location
    var city: String = ""
    var state: String = ""
    var country: String = ""
    var locationManager = CLLocationManager()

     func getLocation() -> String {
     if country == ("United States") {
     return (self.city + ", " + self.state)
     }
     else {
     return (self.city + ", " + self.state + ", " + self.country)
     }
     }

    //Firebase
    var rootRef = FIRDatabase.database().reference()
    var messageRef: FIRDatabaseReference!
    var userLocation: FIRDatabaseReference!

    //JSQMessages
    var messages = [JSQMessage]()

    var outgoingBubbleImageView: JSQMessagesBubbleImage!
    var incomingBubbleImageView: JSQMessagesBubbleImage!



    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            //collect user's location
            locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
            locationManager.requestLocation()
            locationManager.startUpdatingLocation()
        }

        title = "Group Chat"
        setupBubbles()
        // No avatars
        collectionView!.collectionViewLayout.incomingAvatarViewSize = CGSizeZero
        collectionView!.collectionViewLayout.outgoingAvatarViewSize = CGSizeZero

        // Remove file upload icon
        self.inputToolbar.contentView.leftBarButtonItem = nil;

        messageRef = rootRef.child("messages")
        userLocation = rootRef.child("locations")
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        observeMessages()
    }

  override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
  }


    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //--- CLGeocode to get address of current location ---//
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in

            if let pm = placemarks?.first
            {
                self.displayLocationInfo(pm)
            }

        })

    }


    func displayLocationInfo(placemark: CLPlacemark?)
    {
        if let containsPlacemark = placemark
        {

            self.city = (containsPlacemark.locality != nil) ? containsPlacemark.locality! : ""
            self.state = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea! : ""
            self.country = (containsPlacemark.country != nil) ? containsPlacemark.country! : ""

            print(getLocation())

        }

    }


    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("Error while updating location " + error.localizedDescription)
    }


    override func collectionView(collectionView: JSQMessagesCollectionView!,
                                 messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
        return messages[indexPath.item]
    }

    override func collectionView(collectionView: JSQMessagesCollectionView!,
                                 messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! {
        let message = messages[indexPath.item] // 1
        if message.senderId == senderId { // 2
            return outgoingBubbleImageView
        } else { // 3
            return incomingBubbleImageView
        }
    }

    override func collectionView(collectionView: UICollectionView,
                                 numberOfItemsInSection section: Int) -> Int {
        return messages.count
    }

    override func collectionView(collectionView: JSQMessagesCollectionView!,
                                 avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! {
        return nil
    }

    private func setupBubbles() {
        let factory = JSQMessagesBubbleImageFactory()
        outgoingBubbleImageView = factory.outgoingMessagesBubbleImageWithColor(
            UIColor.jsq_messageBubbleBlueColor())
        incomingBubbleImageView = factory.incomingMessagesBubbleImageWithColor(
            UIColor.jsq_messageBubbleLightGrayColor())
    }

    func addMessage(id: String, text: String) {
        let message = JSQMessage(senderId: id, displayName: "", text: text)
        messages.append(message)
    }

    override func collectionView(collectionView: UICollectionView,
                                 cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath)
            as! JSQMessagesCollectionViewCell

        let message = messages[indexPath.item]

        if message.senderId == senderId {
            cell.textView!.textColor = UIColor.whiteColor()
        } else {
            cell.textView!.textColor = UIColor.blackColor()
        }

        return cell
    }

    override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!,
                                     senderDisplayName: String!, date: NSDate!) {

        let itemRef = messageRef.childByAutoId() // 1
        let messageItem = [ // 2
            "text": text,
            "senderId": senderId
        ]
        itemRef.setValue(messageItem) // 3

        // Start storing location data
        let locRef = userLocation.childByAutoId()
        let locItem = [
            "location": getLocation()
        ]
        // Set location data in Firebase
        locRef.setValue(locItem)

        // 4
        JSQSystemSoundPlayer.jsq_playMessageSentSound()

        // 5
        finishSendingMessage()

    }

    private func observeMessages() {
        // 1
        let messagesQuery = messageRef.queryLimitedToLast(25)
        // 2
        messagesQuery.observeEventType(.ChildAdded) { (snapshot: FIRDataSnapshot!) in
            // 3
            let id = snapshot.value!["senderId"] as! String
            let text = snapshot.value!["text"] as! String


            // 4
            self.addMessage(id, text: text)

            // 5
            self.finishReceivingMessage()
        }

    }

    override func textViewDidChange(textView: UITextView) {
        super.textViewDidChange(textView)
    }


    override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {

        let message = messages[indexPath.item] // 1

        // This is where I need help retrieving the data from firebase
        let text = "From: " + getLocation()

        if message.senderId == senderId { // 2
            return nil
        } else { // 3
            return NSAttributedString(string: text)
        }

    }

    override func collectionView(collectionView: JSQMessagesCollectionView, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout, heightForCellBottomLabelAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return kJSQMessagesCollectionViewCellLabelHeightDefault
    }

}

1 个答案:

答案 0 :(得分:2)

在Firebase中,分别存储每个用户的位置:这样他们就不会被其他用户覆盖。

将新分支添加到数据库结构中,例如地点

接下来,添加一个名为

  

最后,为每个用户添加另一个具有 location 属性的子项。

接下来,只需查询此分支即可获取用户信息。当您更新用户的位置时,它只会覆盖他们的以前的位置。

请阅读与查询Firebase相关的文档: https://firebase.google.com/docs/database/ios/retrieve-data#read_data_once
和更新数据的文档:
https://firebase.google.com/docs/database/ios/save-data#basic_write

了解有关Firebase的更多信息。