UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Decompress JSON File from URL

Forums > SwiftUI

I am trying to unzip a file from an URL via the zlib protocol. I wrote a function (loadData) that should first get the compressed Data, then decompress it, then decode it (JSON decoder) and finally put it into the variable "spotdata". However, nothing shows up on my simulator or preview. Does anyone know what I am doing wrong? Thank you in advance!

struct ContentView: View {   

    @State var spotData = WindAppSpot()

    var body: some View {
        ZStack {
            VStack {
                Text("Hello World")
                Text("\(spotData.spot)")
            }
        }.onAppear(perform: loadData)
    }
}

extension ContentView {

    func loadData() {

        guard let url = URL(string: "https://github.com/Bene2907/Bene2907.github.io/raw/main/outfile.dat") else {
            return
        }
        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { data, response, error in

            if let data = data {
                do {
                    let decompressedData = try (data as NSData).decompressed(using: .zlib)
                    if let response_obj = try? JSONDecoder().decode(WindAppSpot.self, from: decompressedData as Data) {

                        DispatchQueue.main.async {
                            self.spotData = response_obj
                        }
                    }
                } catch {
                    print(error.localizedDescription)
                }
            }
        }.resume()
    }
}

The structure looks something like this:

struct WindAppSpot: Decodable {
    var spot: String? = "no spot"
    //... 
}

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.