Files
praca_inzynierska/Implementation/Peered/NotesList/NotesStorage.swift
T

59 lines
1.2 KiB
Swift

//
// NotesStorage.swift
// Peered
//
// Created by Oskar Chybowski on 25/09/2025.
//
import Foundation
struct NotesStorage {
let storageProvider: FileManager = FileManager.default
func loadNotes() -> [Note] {
let files = try! storageProvider
.contentsOfDirectory(atPath: URL.documentsDirectory.path)
var notes = [Note]()
for file in files.compactMap({
URL(
filePath: $0,
directoryHint: .notDirectory,
relativeTo: URL.documentsDirectory
)
}) {
let name = file.lastPathComponent
let note = Note(
name: name,
path: file
)
notes.append(note)
}
return notes
}
func createNote(name: String) {
let currentNotes = loadNotes()
var proposedName = name
var index: Int? = nil
while currentNotes.contains(where: { $0.name == proposedName }) {
if let _index = index {
index = _index + 1
} else {
index = 1
}
}
proposedName = if let index {
"\(proposedName) \(index)"
} else {
proposedName
}
let pathToWrite = URL.documentsDirectory.appendingPathComponent(proposedName).appendingPathExtension(for: .text)
try! String().write(to: pathToWrite, atomically: true, encoding: .utf8)
}
}