'CoreData .FileExporter creates endless local backup of sqlite file on MacOS

I want to create a local backup of the CoreData sqlite file, and then have the user choose the save location with a popup. I've attached the following fileExporter to my view. The effect is great, the user can save the file wherever they like. But, the temporary location is flooded with 10s of local backups. It's even called when the backup button isn't pressed, like at launch or view change. Any ideas?

Is this intended behavior because one is supposed to delete the temporary file? If so, how do I know what the names of the temporary files are? I cannot predict when the app decides to make a backup. Do I just purge the whole temp folder every once in a while?

  .fileExporter(
              isPresented: $isExportingDatabasePickerOpen,
              document: SqlDocument(url: makeBackup() ),
              contentType: sqliteFile,
              onCompletion: { result in
                  exportingDatabase(result: result)
              }
          )

  func makeBackup() -> URL {
    
    let dateFormatter = ISO8601DateFormatter()
    dateFormatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime]
    let dateString = dateFormatter.string(from: Date())
    let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("CoreDataBackup - " + dateString + ".sql")
    try? container.copyPersistentStores(to: fileURL)
    
    return fileURL
    
  }

  func exportingDatabase(result: Result<URL, Error>) {
      switch result {
          case .success(let url):
              print("Saved to \(url)")
          case .failure(let error):
        print(error)
      }
  }
 
  struct SqlDocument: FileDocument {
      
      static var readableContentTypes: [UTType] { [.database] }

      var url: URL

      init(url: URL) {
          self.url = url
      }

      init(configuration: ReadConfiguration) throws {
          self.url = URL(fileURLWithPath: "")
      }

      func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
          let file = try! FileWrapper(url: url, options: .immediate)
          return file
      }
  }

Many backups



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source