Files
praca_inzynierska/Peered/NotesList/NotesStorage.swift
T
2025-09-25 19:36:21 +02:00

52 lines
1.1 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.init) {
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)
}
}