ImportService.swift (1277B)
1 import Foundation 2 3 @MainActor 4 final class ImportService { 5 private let store: GameStore 6 private let driveMonitor: DriveMonitor 7 8 init(store: GameStore, driveMonitor: DriveMonitor) { 9 self.store = store 10 self.driveMonitor = driveMonitor 11 } 12 13 func importGame(from url: URL) -> UUID? { 14 guard ["xd", "puz"].contains(url.pathExtension.lowercased()) else { return nil } 15 16 let needsAccess = url.startAccessingSecurityScopedResource() 17 defer { 18 if needsAccess { 19 url.stopAccessingSecurityScopedResource() 20 } 21 } 22 23 let source: String 24 do { 25 switch url.pathExtension.lowercased() { 26 case "xd": 27 source = try String(contentsOf: url, encoding: .utf8) 28 case "puz": 29 source = try PUZToXDConverter.convert(puzData: Data(contentsOf: url)) 30 default: 31 return nil 32 } 33 } catch { 34 return nil 35 } 36 37 if driveMonitor.containerAvailable { 38 try? driveMonitor.importFile(from: url) 39 } 40 41 if let existing = store.findGameID(matching: source) { 42 return existing 43 } 44 return try? store.createGame(from: source) 45 } 46 }