过滤数据快照Swift Firebase

时间:2018-05-28 11:05:35

标签: swift firebase firebase-realtime-database

我正在尝试从数据库中返回我已成功完成的数据。问题是我不希望所有数据都被显示,而只是具有存储在JSON树中的当前UID的数据。

这是我的JSON树,只有一个当前的UID,但会有很多。

user_posts- 
  LDLc60j71FBvJGeYn5i 
     description: "Write here"
     photoUrl: "https://firebasestorage.googleapis.com/v0/b/blo..."
     uid: "zQRxvM3cwzQMewUtVamk8JQrEFJ3"

这是我当前的代码,它返回数据库文件夹中的所有数据:

var posts2 = [user_posts]()
func loadPosts(){
    Database.database().reference().child("user_posts").observe(.childAdded) {(snapshot: DataSnapshot) in
        if let dict = snapshot.value as? [String: Any] {
            let descriptionText = dict["description"] as! String
            let photoUrlString = dict["photoUrl"] as! String
            let post = user_posts(descriptionText: descriptionText, photoUrlString: photoUrlString)
            self.posts2.append(post)
            self.myPageTableView.reloadData()
        }
    }
}


override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()
    myPageTableView.dataSource = self
    myPageTableView.delegate = self
    loadPosts()

}



func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return posts2.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier:"myPageCell", for: indexPath)
        as! myPageTableViewCell
    cell.myPageDescription?.text = posts2[indexPath.row].description
    let photoUrl = posts2[indexPath.row].photoUrl
    let url = URL(string: photoUrl)
    cell.myPageImage.sd_setImage(with: url, placeholderImage: nil)
    return cell
    }
}

1 个答案:

答案 0 :(得分:1)

要仅加载特定用户的帖子,您需要使用Firebase查询:

from django.db import models
from django.contrib.gis.db import models
from django.forms import ModelForm
from django_google_maps import fields as map_fields
import shapely.geometry
import googlemaps
from googlemaps import Client

# Create your models here.

class Route(models.Model):
    startPoint_address = PointField()
    startPoint_geolocation = Pointfield()
    endPoint_address = PointField()
    endPoint_geolocation = Pointfield()
    # endPoint = models.PointField()
    # deviationDistance = models.IntegerField(default=20)
    # routeName = models.CharField(max_length=50)




# https://github.com/geodav-tech/decode-google-maps-polyline
def decode_polyline(polyline_str):
    '''Pass a Google Maps encoded polyline string; returns list of 
    lat/lon pairs'''
    index, lat, lng = 0, 0, 0
    coordinates = []
    changes = {'latitude': 0, 'longitude': 0}

    # Coordinates have variable length when encoded, so just keep
    # track of whether we've hit the end of the string. In each
    # while loop iteration, a single coordinate is decoded.
    while index < len(polyline_str):
        # Gather lat/lon changes, store them in a dictionary to apply them later
        for unit in ['latitude', 'longitude']:
            shift, result = 0, 0

            while True:
                byte = ord(polyline_str[index]) - 63
                index+=1
                result |= (byte &  0x1f) << shift
                shift += 5
                if not byte >= 0x20:
                    break

            if (result & 1):
                changes[unit] = ~(result >> 1)
            else:
                changes[unit] = (result >> 1)

        lat += changes['latitude']
        lng += changes['longitude']

        coordinates.append((lat / 100000.0, lng / 100000.0))

    return coordinates

gmaps = googlemaps.Client(key='AIzaSyCetShZ10WQVBVPaIu9pdPEktRVQq78TF4')

google_directions = gmaps.directions("Stellenbosch", "Cape Town")
encoded_polyline = google_directions[0]['overview_polyline']['points']
decoded_polyline = decode_polyline(encoded_polyline)
shapely_line = shapely.geometry.LineString(decoded_polyline)
buffered_line = shapely_line.buffer(0.00001)

另见Firebase documentation on ordering and filtering data