如何将 Optional Json 解析为 String 变量
How to parse Optional Json to String variables
我正在尝试使用 Firebase 从我的数据库中获取数据。我不确定如何解包和分配变量。我正在尝试根据导入的名称、点赞和播放视频在屏幕顶部显示标题。
当我打印变量 jdata 时,它从 firebase 打印可选 JSON。
import Foundation
import SwiftUI
import AVKit
import Firebase
struct PlayerView: View {
@State var likes: Int = 0
@State var name: String = ""
@State var url: String = ""
@State let player = AVPlayer(url: URL(string: url))
func liked() { likes += 1 }
func update() {
FirebaseApp.configure()
let root = Database.database().reference()
root.observeSingleEvent(of: .value, with: { (snapshot) in
if let data = snapshot.value as? [String: Any] {
let jdata = data["urls"] // Optional JSON
print(jdata)
}
})
}
var body: some View {
VStack{
Text(name)
VideoPlayer(player: player).padding()
HStack {
Button("Like", action: liked).padding()
Text(String(likes)).padding()
}
HStack {
Button("Prev"){}.padding()
Button("Next"){}.padding()
}
Button(action: update) {
Text("Update Database")
}.padding()
}
}
}
打印后我的变量
可选({“-N25GwfJ9Cj7IlfkFNpL”= {喜欢= 0;名称=“NameTest”;url=“测试”;};})
根据您显示的数据,您可以尝试这种(未经测试的)方法:
root.observeSingleEvent(of: .value, with: { snapshot in
if let data = snapshot.value as? [String: Any],
let jdata = data["urls"] as? [String: Any] {
if let key = jdata.keys.first,
let result = jdata[key] as? [String: Any] {
print("-----> result: \(result)")
if let likes = result["likes"] {
print("-----> likes: \(likes)")
}
}
}
})
我正在尝试使用 Firebase 从我的数据库中获取数据。我不确定如何解包和分配变量。我正在尝试根据导入的名称、点赞和播放视频在屏幕顶部显示标题。
当我打印变量 jdata 时,它从 firebase 打印可选 JSON。
import Foundation
import SwiftUI
import AVKit
import Firebase
struct PlayerView: View {
@State var likes: Int = 0
@State var name: String = ""
@State var url: String = ""
@State let player = AVPlayer(url: URL(string: url))
func liked() { likes += 1 }
func update() {
FirebaseApp.configure()
let root = Database.database().reference()
root.observeSingleEvent(of: .value, with: { (snapshot) in
if let data = snapshot.value as? [String: Any] {
let jdata = data["urls"] // Optional JSON
print(jdata)
}
})
}
var body: some View {
VStack{
Text(name)
VideoPlayer(player: player).padding()
HStack {
Button("Like", action: liked).padding()
Text(String(likes)).padding()
}
HStack {
Button("Prev"){}.padding()
Button("Next"){}.padding()
}
Button(action: update) {
Text("Update Database")
}.padding()
}
}
}
打印后我的变量 可选({“-N25GwfJ9Cj7IlfkFNpL”= {喜欢= 0;名称=“NameTest”;url=“测试”;};})
根据您显示的数据,您可以尝试这种(未经测试的)方法:
root.observeSingleEvent(of: .value, with: { snapshot in
if let data = snapshot.value as? [String: Any],
let jdata = data["urls"] as? [String: Any] {
if let key = jdata.keys.first,
let result = jdata[key] as? [String: Any] {
print("-----> result: \(result)")
if let likes = result["likes"] {
print("-----> likes: \(likes)")
}
}
}
})