Skip to content

Instantly share code, notes, and snippets.

@akardas16
Created August 28, 2022 06:14
Show Gist options
  • Save akardas16/4aa48f68f8136aff9e5faf2c92284334 to your computer and use it in GitHub Desktop.
Save akardas16/4aa48f68f8136aff9e5faf2c92284334 to your computer and use it in GitHub Desktop.
Save, Check, Decode File
//
// ContentView.swift
// JSON
//
// Created by Jessica Linden on 8/27/22.
//
import SwiftUI
struct Person: Codable {
var name: String
}
struct ContentView: View {
@State private var person = Person(name: "Jessie")
@State private var result = ""
@State var decodeResult:String = ""
var body: some View {
VStack(spacing: 20) {
Text("Hit save then check for file")
TextField("Name", text: $person.name)
.padding()
Text("result: \(result)")
.padding().multilineTextAlignment(.center)
HStack{
Spacer()
Button("Save") {
save(encode())
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
Spacer()
Button(action: {
checkFileAvaliable()
}) {
Text("Check")
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
Spacer()
}
Text(decodeResult).multilineTextAlignment(.center)
Button(action: {
decode()
}) {
Text("Decode")
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
.padding()
}
func checkFileAvaliable(){
do {
let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileUrl = documentDirectory.appendingPathComponent("person")
.appendingPathExtension("txt") // you need spesify file extension
if FileManager.default.fileExists(atPath: fileUrl.path) {
result = "File available! You can decode File"
} else {
result = "File couldn' Found"
}
} catch {
print(error)
}
}
func encode(_ encoder: JSONEncoder = .init()) -> String {
guard let encodedData = try? encoder.encode(person) else {
fatalError("Failed to encode user data")
}
let jsonString = String(data: encodedData, encoding: .utf8)!
return jsonString
}
func save(_ jsonString: String) {
let url = getDocumentsDirectory()
.appendingPathComponent("person").appendingPathExtension("txt")// you need spesify file extension check person.txt avaliable or not
do {
try jsonString.write(to: url, atomically: true, encoding: String.Encoding.utf8)
print("jsonString \(jsonString)")
print("jsonString \(url.path)")
print("successfully wrote jsonString to url")
result = "saved succesfully check path is avaliable or not"
} catch {
print("Failed to save user data")
}
}
func decode() {
let url = getDocumentsDirectory().appendingPathComponent("person")
.appendingPathExtension("txt")
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load url")
}
guard let decoded = try? JSONDecoder().decode(Person.self, from: data) else {
fatalError("Failed to decode url")
}
person = decoded
decodeResult = "Decoded Succesfully: \(person.name)"
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment