Я работаю над приложением, которое хранит данные в файлах JSON. В настоящее время FileUtils имеет все функции, которые работают с файлами. ContentView содержит основной контент приложения, а AddEggView добавляет контент в основной ContentView. Моя проблема заключается в том, что при тестировании на iPhone мой основной контент не перерисовывается повторно при отправке новой привычки в AddEggView, но, похоже, он работает на Mac.
FileUtils:
import Foundation
func addJsonToFile(jsonString: String) {
// Get the URL of the documents directory
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
print("Documents directory not found")
return
}
// Append the file name "habitData.json" to the documents directory URL
let fileURL = documentsDirectory.appendingPathComponent("habitData.json")
do {
if FileManager.default.fileExists(atPath: fileURL.path) {
// File exists, append to existing content
var existingData = try Data(contentsOf: fileURL)
// Remove trailing ']' if it exists
if let lastChar = existingData.last, lastChar == UInt8(ascii: "]") {
existingData.removeLast()
}
// If there's existing data, add a comma to separate objects
if !isEmptyFile(fileURL: fileURL) {
print("has content")
existingData.append(contentsOf: ", ".data(using: .utf8)!)
} else {
print("empty")
existingData.append(contentsOf: "[ ".data(using: .utf8)!)
}
// Convert the new JSON string to data and append to existing data
if let jsonData = jsonString.data(using: .utf8) {
existingData.append(jsonData)
// Append ']' to complete the array
existingData.append(UInt8(ascii: "]"))
// Write the updated data back to the file
try existingData.write(to: fileURL, options: .atomic)
} else {
print("Failed to convert JSON string to data")
}
print("Json data appended successfully to: \(fileURL)")
} else {
// File doesn't exist, create a new file with the JSON data wrapped in an array
let wrappedJsonString = "[\(jsonString)]"
try wrappedJsonString.write(to: fileURL, atomically: true, encoding: .utf8)
print("Json data saved successfully to a new file: \(fileURL)")
}
} catch {
print("Error appending json data: \(error)")
}
}
func getJsonData() -> Data? {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
print("Documents directory not found")
return nil
}
let fileURL = documentsDirectory.appendingPathComponent("habitData.json")
do {
// Read data from the file
let data = try Data(contentsOf: fileURL)
return data
} catch {
print("Error reading JSON data: \(error)")
return nil
}
}
func isEmptyFile(fileURL: URL) -> Bool {
do {
let fileContents = try String(contentsOf: fileURL, encoding: .utf8)
print("File contains: " + fileContents)
return fileContents.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
} catch {
print("Error reading file: \(error)")
return true // If there's an error reading the file, we can assume it's empty or inaccessible
}
}
Я считаю, что с рендерингом что-то не так, поскольку терминал сообщил мне, что:
Данные Json успешно добавлены в: file:///var /mobile/Containers/Data/Application/D5AEAD8C-23FB-45B1-A65C-C0DF3A520047/Documents/habitData.json
Я впервые работаю с постоянными данными, и я не слишком уверен, как исправить эту ошибку. Любая помощь будет полезна, спасибо!
Я работаю над приложением, которое хранит данные в файлах JSON. В настоящее время FileUtils имеет все функции, которые работают с файлами. ContentView содержит основной контент приложения, а AddEggView добавляет контент в основной ContentView. Моя проблема заключается в том, что при тестировании на iPhone мой основной контент не перерисовывается повторно при отправке новой привычки в AddEggView, но, похоже, он работает на Mac. FileUtils: [code]import Foundation
func addJsonToFile(jsonString: String) { // Get the URL of the documents directory guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { print("Documents directory not found") return }
// Append the file name "habitData.json" to the documents directory URL let fileURL = documentsDirectory.appendingPathComponent("habitData.json")
do { if FileManager.default.fileExists(atPath: fileURL.path) { // File exists, append to existing content var existingData = try Data(contentsOf: fileURL)
// Remove trailing ']' if it exists if let lastChar = existingData.last, lastChar == UInt8(ascii: "]") { existingData.removeLast() }
// If there's existing data, add a comma to separate objects if !isEmptyFile(fileURL: fileURL) { print("has content") existingData.append(contentsOf: ", ".data(using: .utf8)!) } else { print("empty") existingData.append(contentsOf: "[ ".data(using: .utf8)!) }
// Convert the new JSON string to data and append to existing data if let jsonData = jsonString.data(using: .utf8) { existingData.append(jsonData)
// Append ']' to complete the array existingData.append(UInt8(ascii: "]"))
// Write the updated data back to the file try existingData.write(to: fileURL, options: .atomic) } else { print("Failed to convert JSON string to data") }
print("Json data appended successfully to: \(fileURL)") } else { // File doesn't exist, create a new file with the JSON data wrapped in an array let wrappedJsonString = "[\(jsonString)]" try wrappedJsonString.write(to: fileURL, atomically: true, encoding: .utf8) print("Json data saved successfully to a new file: \(fileURL)") } } catch { print("Error appending json data: \(error)") } }
let fileURL = documentsDirectory.appendingPathComponent("habitData.json") do { // Read data from the file let data = try Data(contentsOf: fileURL) return data } catch { print("Error reading JSON data: \(error)") return nil } }
func isEmptyFile(fileURL: URL) -> Bool { do { let fileContents = try String(contentsOf: fileURL, encoding: .utf8) print("File contains: " + fileContents) return fileContents.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } catch { print("Error reading file: \(error)") return true // If there's an error reading the file, we can assume it's empty or inaccessible } }
[/code] Просмотр содержимого: [code]import SwiftUI import UIKit extension UIScrollView { open override var clipsToBounds: Bool { get { false } set { } } }
struct ContentView: View { // State Variables @State private var fulfilled = 0 @State private var numOfEggs = 3 @State private var displayState = true @State private var displayHabit = " " @State private var showAddEggView = false @State private var loadJsonData = true
// For Array of Habit Structs (loaded on initalization) @ObservedObject var viewModel = HabitViewModel()
// ContentView var body: some View { NavigationView { // Main Chicken let chickenImageName = fulfilled == numOfEggs ? "chicken_in_egg" : "chicken_in_egg_sad"
if inputHabit != "" { do { let habit = Habit(habitName: inputHabit) let jsonData = try JSONEncoder().encode(habit) let jsonString = String(data: jsonData, encoding: .utf8)!
#Preview { AddEggView(viewModel: HabitViewModel()) } [/code] Я считаю, что с рендерингом что-то не так, поскольку терминал сообщил мне, что: Данные Json успешно добавлены в: file:///var /mobile/Containers/Data/Application/D5AEAD8C-23FB-45B1-A65C-C0DF3A520047/Documents/habitData.json Я впервые работаю с постоянными данными, и я не слишком уверен, как исправить эту ошибку. Любая помощь будет полезна, спасибо!