Feature: Notes creation
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
//
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user