aboutsummaryrefslogtreecommitdiff
path: root/Hotline/Utility/TextDocument.swift
blob: 82727defccc1ca2d47ea25a649c7d7cdc42f5d18 (plain)
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
import Foundation
import UniformTypeIdentifiers
import SwiftUI

struct TextFile: FileDocument {
  // tell the system we support only plain text
  static var readableContentTypes = [UTType.plainText, UTType.utf8PlainText]
  
  // by default our document is empty
  var text = ""
  
  // a simple initializer that creates new, empty documents
  init(initialText: String = "") {
    text = initialText
  }
  
  // this initializer loads data that has been saved previously
  init(configuration: ReadConfiguration) throws {
    
    if let data = configuration.file.regularFileContents {
      if let str = String(data: data, encoding: .utf8) {
        self.text = str
      }
    }
  }
  
  // this will be called when the system wants to write our data to disk
  func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
    return FileWrapper(regularFileWithContents: self.text.data(using: .utf8)!)
  }
}