0

I am playing with the Instagram API and I encounter the following issue: I managed to decode and access the JSON data but when I try to access a certain value inside a SwiftUI View I encounter the following error: Thread 1: Fatal error: Index out of range. I am totally aware that this is triggered by the fact that the API load is asynchronous but I can not find a fix for this.

I would greatly appreciate your help

Below you can find the API response

API RESPONSE

Here you can find my model and JSON Decoder

struct InstaAPI: Codable {

    var name: String
    var period: String
    var description: String
    var values: [ValueResponse]
}

struct ValueResponse: Codable {
    let value: String
}

struct Entry: Codable {
    let data: [InstaAPI]
}

class getData: ObservableObject {

@Published var response = [Entry]()

init() {

    downloadJSON(from: URL(string: "https://graph.facebook.com/v6.0/17841402116620153/insights?metric=impressions&period=day&access_token=accounttoken")!)
}

func downloadJSON(from url: URL) {

    URLSession.shared.dataTask(with: url) { data, response, error in

        if let data = data {

            let jsonDecoder = JSONDecoder()

            do {

                let parsedJson = try jsonDecoder.decode(Entry.self, from: data)

                DispatchQueue.main.async {

                    self.response.append(parsedJson)
                }

                for data in parsedJson.data {

                    print(data.values[0].value)
                }

            } catch {
                print(error)
            }
        }

    }.resume()
}
}

error

1 Answer 1

1

maybe the old fashioned if would do the trick:

struct ContentView: View {
@ObservedObject var response = getData()
@State var responseNdx = 0
@State var dataNdx = 0

var body: some View {
    VStack {
        if responseNdx < self.response.response.count {
            if dataNdx < self.response.response[responseNdx].data.count {
                Text(self.response.response[responseNdx].data[dataNdx].name)
            }
        }
    }
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked like a charm! Thank you very much! I really appreciate your time and help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.