Столкнулся с этой проблемой, тот же сюжет на моем макбуке не запускается и выдает ошибку, но когда я посмотрел с другом, и он тоже скомпилировал этот проект, чтобы танцевать то же самое на macOs, он запускается и работает нормально, как должно. Кто-нибудь сталкивался с этой проблемой? Дело в том, что у меня есть API, я делаю запрос, и когда я нажимаю кнопку, которая делает мой запрос API:
dataCorrupted(Swift.DecodingError .Context(codingPath: [], debugDescription: «Данные данные недействительны в формате JSON.», базовая ошибка: Необязательно (Error Domain=NSCocoaErrorDomain Code=3840 «Неожиданный символ 'S' в строке 1, столбце 1». UserInfo={NSJSONSerializationErrorIndex) =0, NSDebugDescription=Неожиданный символ 'S' в строке 1, столбце 1.})))
Вот мой код для вашей документации
импорт SwiftUI import Объединение импорта
Код: Выделить всё
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 -> [Офисы] {
let url = URL(строка: «http://orar.usarb.md/api/access/getOffices»)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let (data, _) = попробуйте дождаться URLSession.shared.data(for: request)
let office = попробуйте JSONDecoder() .decode([Офисы].self, from: data)
возврат офисов
var body: some View {
ScrollView {
VStack {
headerImage
VStack(интервал: 20) {
titleText
HStack(интервал: 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 = Office.map { $0.Denumire print("Динамическая настройка для актуализации.")< br /> } catch {
print("A apărut o eroare la preluarea oficiilor: \(error)")
selectedTab = 3< br />
.padding(.horizontal)
AutocompleteTextField(title: «Ввести текст», параметры: 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: недели, selectedOption: $selectedOption)
.padding (.horizontal)
timeSlotRows
.padding(.horizontal)
buttonRow
.padding(.horizontal)
.padding( .vertical, 10)
infoText
Private var headerImage: some View {
Image( "logo-orar")
.resizable()
.scaledToFit()
.frame(height: 150)
частная переменная titleText: некоторый вид {
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)
приватная переменная buttonRow: some View {
HStack(spacing: 15) {
button("Descarca orar", цвет: .green)
button("Examene", color : .red)
button("Planificare", color: .purple)
частная переменная infoText: some View {
Text( «Очередь с 23:00 до 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 : Строка, параметры: [Строка], selectedOption: Binding) -> some View {
MenuPicker(title: title, options: options, selectedOption: selectedOption)
.padding(.horizontal)
Private var timeSlotRows: some View {
VStack(spacing: 0) {
ForEach(0.. some View {
Button(action: {
Task {
do {
let office = попробуйте await fetchOfficesFromAPI( )
print(offices)
} catch {
print(error)
}) {
Текст (title)
.frame(height: 40)
.frame(maxWidth: .infinity)
.background(color.opacity(0.5))
.foregroundColor(.black)
}
struct ContentView_Previews: PreviewProvider {
статические переменные предварительные просмотры: некоторые представления {
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 (высота: 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
})< br /> .textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.horizontal)
.cornerRadius(10)
if isDropdownVisible {
VStack(alignment: .leading , интервал: 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 {< br /> Picker(title, choice: $selectedOption) {
ForEach(options, id: \.self) { option in
Text(option)
/> .pickerStyle(MenuPickerStyle())
.frame(ширина: 340, высота: 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 {< br /> var timeSlot: String
var HistoryText: String
var SeminarText: String
var ProfessorText: String
var AuditoriumText: String
var body: некоторый вид {
HStack {
Text(timeSlot)
.frame(maxWidth: 50)
.padding(.horizontal, 10)
.padding(.vertical, 4)
.background(Color.green)
.foregroundColor(.white)
Spacer().frame(ширина: 20)
VStack(выравнивание: .center, интервал: 4) {
Текст(historyText)
.font(.system(size: 14))
.fontWeight(.black)
Текст(seminarText)
.font(.system(size: 14))
.fontWeight(.bold)
Text(professorText)
.font(.system(size: 13))
.fontWeight(.bold)
Text(auditoriumText)
.font(.system(size: 14))
.padding()
Spacer()
} }
Источник: https://stackoverflow.com/questions/781 ... iption-the