ios – dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: “The given information used to be now not legitimate JSON.”


Ran into this problem, the same plot on my macbook doesn’t run and gives an error, but when I looked with my friend and he too compiled this project to dance the same thing on macOs, it runs and works fine as it should. Has anyone run into this problem? The thing is, I have an api, I make a request, and when I click on the button that makes my api request:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: “The given data was not valid JSON.”, underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 “Unexpected character ‘S’ around line 1, column 1.” UserInfo={NSJSONSerializationErrorIndex=0, NSDebugDescription=Unexpected character ‘S’ around line 1, column 1.})))

Here is my code for your documentation

import SwiftUI import Combine import Foundation

struct ContentView: View {
    @State private var selectedTab = 0
    @State private var searchText = ""
    @State private var selectedOption = "Selectează opțiunea"
    @State private var dynamicOptions: [String] = []

        
    let dayOfTheWeek = ["Luni", "Marti", "Miecuri", "Joi", "Vineri", "Sambata", "Duminica"]
    let weeks = [
        "1 (28.8.2023 - 3.9.2023)",
        "2 (4.9.2023 - 10.9.2023)",
        "3 (11.9.2023 - 17.9.2023)",
        "4 (18.9.2023 - 24.9.2023)",
        "5 (25.9.2023 - 1.10.2023)",
        "6 (2.10.2023 - 8.10.2023)",
        "7 (9.10.2023 - 15.10.2023)",
        "8 (16.10.2023 - 22.10.2023)",
        "9 (23.10.2023 - 29.10.2023)",
        "10 (30.10.2023 - 5.11.2023)",
        "11 (6.11.2023 - 12.11.2023)",
        "12 (13.11.2023 - 19.11.2023)",
        "13 (20.11.2023 - 26.11.2023)",
        "14 (27.11.2023 - 3.12.2023)",
        "15 (4.12.2023 - 10.12.2023)",
        "16 (11.12.2023 - 17.12.2023)",
        "17 (18.12.2023 - 24.12.2023)"
    ]
    
    let timeSlots = [
        "8:00 9:30",
        "9:45 11:15",
        "11:30 13:00",
        "13:15 14:45",
        "15:00 16:30",
        "16:45 18:15",
        "18:30 20:00"
    ]
    let staticOptions = ["Nu exista optiuni"]
    let searchOptions = ["Opțiune 1", "Opțiune 2", "Opțiune 3"]

    struct OfficesResponse: Decodable {
        let results: [[String: String]]
    }
    
    struct Offices: Decodable {
           let Id: String
           let Denumire: String
       }
    

    private func fetchOfficesFromAPI() async throws -> [Offices] {
        let url = URL(string: "http://orar.usarb.md/api/access/getOffices")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        
        let (data, _) = try await URLSession.shared.data(for: request)

        let offices = try JSONDecoder().decode([Offices].self, from: data)
        
        return offices
    }

    var body: some View {
        ScrollView {
            VStack {
                headerImage
                
                VStack(spacing: 20) {
                    titleText
                    
                    HStack(spacing: 20) {
                        TabButton(title: "Grupuri", isSelected: selectedTab == 1) {
                            selectedTab = 1
                        }
                        
                        TabButton(title: "Profesori", isSelected: selectedTab == 2) {
                            selectedTab = 2
                        }
                        
                        TabButton(title: "Aule", isSelected: selectedTab == 3) {
                            Task {
                                do {
                                    let offices = try await fetchOfficesFromAPI()
                                    DispatchQueue.main.async {
                                        dynamicOptions = offices.map { $0.Denumire }
                                        print("Opțiunile dinamice au fost actualizate.")
                                    }
                                } catch {
                                    print("A apărut o eroare la preluarea oficiilor: \(error)")
                                }
                            }
                            selectedTab = 3
                        }


                    }
                    .padding(.horizontal)
                    
                    AutocompleteTextField(title: "Introducere text", options: selectedTab == 3 ? dynamicOptions : staticOptions, text: $searchText)
                        .padding(.horizontal)
                        .cornerRadius(10)

                    
                    menuPicker(title: "Alege ziua", options: dayOfTheWeek, selectedOption: $selectedOption)
                        .padding(.horizontal)
                    
                    menuPicker(title: "Alege săptămâna", options: weeks, selectedOption: $selectedOption)
                        .padding(.horizontal)
                    
                    timeSlotRows
                        .padding(.horizontal)
                }
                buttonsRow
                    .padding(.horizontal)
                    .padding(.vertical, 10)

                infoText
            }
        }
    }
    
    private var headerImage: some View {
        Image("logo-orar")
            .resizable()
            .scaledToFit()
            .frame(height: 150)
    }
    
    private var titleText: some View {
        Text("Orarul Cursurilor")
            .font(.title)
            .fontWeight(.bold)
            .frame(maxWidth: .infinity)
            .padding()
            .background(
                RoundedRectangle(cornerRadius: 80)
                    .fill(LinearGradient(gradient: Gradient(colors: [Color.green.opacity(0.6), Color.green.opacity(0.4)]), startPoint: .leading, endPoint: .trailing))
                    .shadow(radius: 5)
            ) .padding(.horizontal, 10)
    }
    
    private var buttonsRow: some View {
        HStack(spacing: 15) {
            button("Descarca orar", color: .green)
            button("Examene", color: .red)
            button("Planificare", color: .purple)
        }
    }
    
    private var infoText: some View {
        Text("Orarul nu lucrează între 23:00 și 3:00")
            .font(.headline)
            .fontWeight(.bold)
            .padding()
            .frame(maxWidth: .infinity)
            .background(
                LinearGradient(gradient: Gradient(colors: [Color.green.opacity(0.2), Color.green.opacity(0.7)]), startPoint: .leading, endPoint: .trailing)
                    .shadow(radius: 10)
                    .padding(.horizontal, 15)
            )
    }
    
    private func menuPicker(title: String, options: [String], selectedOption: Binding<String>) -> some View {
        MenuPicker(title: title, options: options, selectedOption: selectedOption)
            .padding(.horizontal)
    }
    
    private var timeSlotRows: some View {
        VStack(spacing: 0) {
            ForEach(0..<7) { index in
                TimeSlotRow(timeSlot: timeSlots[index],
                            historyText: "Istoria românilor și universală",
                            seminarText: "Seminar",
                            professorText: "prof. Eremia Maria",
                            auditoriumText: "aud. 381")
                    .background(index % 2 == 0 ? Color(.systemGray6) : Color.clear)
            }
        }
    }
    
    private func button(_ title: String, color: Color) -> some View {
        Button(action: {
            Task {
                do {
                    let offices = try await fetchOfficesFromAPI()

                    print(offices)
                } catch {
                    print(error)
                }
            }
        }) {
            Text(title)
                .frame(height: 40)
                .frame(maxWidth: .infinity)
                .background(color.opacity(0.5))
                .foregroundColor(.black)
        }
    } }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    } }

struct TabButton: View {
    var title: String
    var isSelected: Bool
    var action: () -> Void
    
    var body: some View {
        Button(action: action) {
            Text(title)
                .font(.headline)
                .frame(height: 40)
                .frame(maxWidth: .infinity)
                .background(isSelected ? Color.green.opacity(0.4) : Color.gray.opacity(0.2))
                .foregroundColor(.black)
                .cornerRadius(50)
        }
    } } struct AutocompleteTextField: View {
    var title: String
    var options: [String]
    @Binding var text: String
    @State private var isDropdownVisible = false
    @State private var filteredOptions: [String] = []

    var body: some View {
        VStack {
            TextField(title, text: $text, onEditingChanged: { isEditing in
                if isEditing {
                    self.isDropdownVisible = true
                }
            })
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .padding(.horizontal)
            .cornerRadius(10)

            if isDropdownVisible {
                           VStack(alignment: .leading, spacing: 0) {
                               ScrollView {
                                   ForEach(filteredOptions, id: \.self) { option in
                                       Button(action: {
                                           self.text = option
                                           self.isDropdownVisible = false
                                       }) {
                                           Text(option)
                                               .foregroundColor(.black)
                                               .padding()
                                       }
                                   }
                               }
                               .frame(maxHeight: 150)
                           }
                           .background(Color.white)
                           .cornerRadius(5)
                           .shadow(radius: 5)
                           .padding(.horizontal)
                           .padding(.bottom, 4)
                       }
        }
        .onReceive(Just(text)) { searchText in
            filteredOptions = options.filter { $0.localizedCaseInsensitiveContains(searchText) }
            isDropdownVisible = !searchText.isEmpty
        }
    } }



struct MenuPicker: View {
    var title: String
    var options: [String]
    @Binding var selectedOption: String
    
    var body: some View {
        Picker(title, selection: $selectedOption) {
            ForEach(options, id: \.self) { option in
                Text(option)
            }
        }
        .pickerStyle(MenuPickerStyle())
        .frame(width: 340, height: 40)
        .background(LinearGradient(gradient: Gradient(colors: [Color.green.opacity(0.6), Color.green.opacity(0.4)]), startPoint: .leading, endPoint: .trailing))
        .cornerRadius(30)
    } }

struct TimeSlotRow: View {
    var timeSlot: String
    var historyText: String
    var seminarText: String
    var professorText: String
    var auditoriumText: String
    
    var body: some View {
        HStack {
            Text(timeSlot)
                .frame(maxWidth: 50)
                .padding(.horizontal, 10)
                .padding(.vertical, 4)
                .background(Color.green)
                .foregroundColor(.white)
            Spacer().frame(width: 20)
            VStack(alignment: .center, spacing: 4) {
                Text(historyText)
                    .font(.system(size: 14))
                    .fontWeight(.black)
                
                Text(seminarText)
                    .font(.system(size: 14))
                    .fontWeight(.bold)
                
                Text(professorText)
                    .font(.system(size: 13))
                    .fontWeight(.bold)
                
                Text(auditoriumText)
                    .font(.system(size: 14))
            }
            .padding()
            Spacer()
        }
    } }

Leave a Reply

Your email address will not be published. Required fields are marked *