Home > Enterprise >  How to parse Optional Json to String variables
How to parse Optional Json to String variables

Time:05-17

I am trying to get data from my database using Firebase. I am unsure how to unwrap and assign the variables. I am trying to have a title on the top of the screen based on the name imported, likes, and playing the video.

When I print the variable jdata it prints the Optional JSON from the firebase.

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()

        }
    }
}

My variable after it prints Optional({"-N25GwfJ9Cj7IlfkFNpL" = { likes = 0; name = "NameTest"; url = "Testing"; }; })

CodePudding user response:

based on the data you show, you could try this (untested) approach:

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)")
            }
        }
    }
  })
  • Related