NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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"
    //... 
}

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

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

Reply to this topic…

You need to create an account or log in to reply.

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.