-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTextFileView.swift
73 lines (67 loc) · 2.1 KB
/
TextFileView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// TextFileView.swift
//
// Created by Speedyfriend67 on 27.06.24
//
import SwiftUI
struct TextFileView: View {
@State private var fileContent: String = ""
@State private var isLoading: Bool = true
@State private var showError: Bool = false
let fileURL: URL
var body: some View {
VStack {
if isLoading {
ProgressView("Loading...")
.padding()
} else if showError {
Text("Failed to load file.")
.foregroundColor(.red)
} else {
TextEditor(text: $fileContent)
.padding()
.navigationBarItems(trailing: Button("Save") {
saveFile()
})
}
}
.onAppear(perform: loadFile)
.navigationTitle(fileURL.lastPathComponent)
.navigationBarTitleDisplayMode(.inline)
}
private func loadFile() {
DispatchQueue.global(qos: .userInitiated).async {
do {
let content = try String(contentsOf: fileURL, encoding: .utf8)
DispatchQueue.main.async {
self.fileContent = content
self.isLoading = false
}
} catch {
DispatchQueue.main.async {
self.isLoading = false
self.showError = true
}
}
}
}
private func saveFile() {
DispatchQueue.global(qos: .userInitiated).async {
do {
try self.fileContent.write(to: self.fileURL, atomically: true, encoding: .utf8)
DispatchQueue.main.async {
// You can show a success message or give feedback to the user if needed
}
} catch {
DispatchQueue.main.async {
self.showError = true
}
}
}
}
}
struct TextFileView_Previews: PreviewProvider {
static var previews: some View {
TextFileView(fileURL: URL(fileURLWithPath: "/var/tmp/sample.txt"))
}
}