![](/img/trans.png)
[英]How do i retrieve data from firebase store by document in flutter?
[英]How do I create an Object from a firebase document that also has a collection?
有没有办法使 Object 符合具有其他对象数组的 Codable?
我得到了关注 Object:
struct Album: Identifiable, Codable {
let id = UUID()
let name: String
let artist: String
let songs: [AlbumSong]
let releaseDate: Date
let price: Int
let albumImageUrl: String
var unlocked: Bool
}
我尝试从 firebase 数据库中获取我的数据并创建一个相册,但它需要符合 Codable。 我想问题是 AlbumSong 的数组
@State var albums: [Album] = []
FirebaseManager.shared.firestore.collection("songs").getDocuments { querySnapshot, error in
if let error = error {
print(error)
return
}
guard let documents = querySnapshot?.documents else {
return
}
self.albums = documents.compactMap { document -> Album? in
do {
return try document.data(as: Album.self)
} catch {
return nil
}
}
这是专辑歌曲的样子:
struct AlbumSong: Identifiable {
let id = UUID()
let title: String
let duration: TimeInterval
var image: String
let artist: String
let track: String
}
要使用Codable
类型的所有属性也必须是可编码的。 大多数 Swift 原始类型( String
, Int
,....)都可以。 为了使您的Album
符合要求,您必须使Codable
符合AlbumSong
struct AlbumSong: Identifiable, Codable {
let id = UUID()
let title: String
let duration: TimeInterval
var image: String
let artist: String
let track: String
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.