【问题标题】:How to get firebase data as a array如何将firebase数据作为数组获取
【发布时间】:2020-11-20 12:59:35
【问题描述】:

public func getAllItems(completion: @escaping (Result<[Item], Error>) -> Void) 
{
    database.child("Items").observe(.value, with: {snapshot in
        guard (snapshot.value as? [[String: Any]]) == nil else{
            completion(.failure(DatabaseError.failedToFetch))
            return
        }
        
        var newUrlArray: [Item]  = []
        var newItemArray: [Item]  = []
        for child in snapshot.children{
            if let childSnapshots = child as? DataSnapshot,
                let dict = childSnapshots.value as? [String:Any],
                let title = dict["title"] as? String,
                let content = dict["content"] as? String,
                let itemId = dict["itemid"] as? String,
                let price = dict["price"] as? Int{
                let item = Item(title: title, content: content, itemId:  itemId, price: price, urs: newUrlArray)
                newItemArray.append(item)
            }
        }
        completion(.success(newDataArray))
    })
}

我的问题是如何获得 urls 在图片中显示为数组或者是否有可能。

【问题讨论】:

    标签: arrays swift firebase-realtime-database


    【解决方案1】:

    您需要更深入地了解 JSON/快照层次结构以获取 URL。

    如果我为了可读性而暂时删除非 URL 代码,它会是这样的:

    for child in snapshot.children{
        if let childSnapshots = child as? DataSnapshot,
            let dict = childSnapshots.value as? [String:Any],
            let urls = childSnapshots.childSnapshot(atPath: "urls").value as? [String:Any],
            ...
        }
    }
    

    所以上面的urls 是另一个字典,您可以在其中循环其键以获取 URL 值。

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多