Home > Back-end >  Get an [String] link from a json file
Get an [String] link from a json file

Time:02-05

Here is my structure for the json file

    struct DataRespons: Codable {
        
        let data: [String]
        let status: String
    }

JSON file url

    {
        "status": "success",
        "data": [
            "f7c75c1f-10ab-4298-9dc9-e80b7bd07dfd",
            "6f5f6eeb-191d-4ad9-b5ef-6f61fd5fcefc",
            "8008800880088008",
            "64a3f5d0-37c7-4c30-8d0f-3b67fb5c8fde"
        ]
    }

This is my class for JSON requests and decoding I use these functions to get an array of links

I hope I wrote correctly what I want to receive, and if there are any questions, please contact me


    @MainActor
    class NetworkModel: ObservableObject {
        
        @Published var listId: [String] = []
        var statusList = ""
        var statusUser = ""
        @Published var userData = UserRespons(status: "??", data: UserData(id: "???", firstName: "???", lastName: "??", age: 4, gender: "???", country: "???"))
                
        func getList() {
            guard let url = URL(string: "some URL") else { fatalError("Missing URL") }
            var request = URLRequest(url: url)
            request.addValue("bearer \(token)", forHTTPHeaderField: "Authorization")
            let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
                if let error = error {
                    print("Requst error",error)
                    return
                }
                guard let response = response as? HTTPURLResponse else { return }
                if response.statusCode == 200 {
                    guard let data = data else { return }
                    DispatchQueue.main.async {
                        do {
                            let decoded = try JSONDecoder().decode(DataRespons.self, from: data)
                            self.listId = decoded.data
                            self.statusList = decoded.status
                        } catch let error{
                            print("Error decode",error)
                        }
                    }
                }
            }
            dataTask.resume()
        }
   

I can't through index [String] to get each element

CodePudding user response:

use this code to access the data elements of an array:

 // ....
 self.listId = decoded.data 

 for i in listId.indices {
     print("--> listId[\(i)] = \(listId[i]) ")
 }
 
 print("--> listId[0] = \(listId[0]) ")
 print("--> listId[1] = \(listId[1]) ")

 // ....
 

Read the very basics of Swift, specially regarding arrays here:

https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html

  • Related