When your app suddenly crashes with the cryptic errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 error, you’re facing a classic file reference problem in Apple’s Cocoa framework. This error typically occurs when your application attempts to access a file or resource through an alias that has no longer existed or moved.
The Ukrainian error message translates to “could not find the specified shortcut command,” pointing directly to the core issue: a broken file reference. This article will explain why this happens and provide concrete, tested solutions to fix it permanently.
Understanding the errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 Error
The errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 error belongs to the NSCocoaErrorDomain family with error code 4. This specific error code maps to NSFileNoSuchFileError in Apple’s framework documentation. When you encounter this error, your system tells you it tried to access a file or directory through a reference (often an alias or bookmark). Still, that target doesn’t exist at the expected location.
Here’s how the error typically appears in console logs:
Error Domain=NSCocoaErrorDomain Code=4 “не вдалося знайти вказану швидку команду.”
UserInfo={NSFilePath=/Users/username/Documents/Project/missingfile.swift,
NSUnderlyingError=0x600003d70fe0 {Error Domain=NSPOSIXErrorDomain Code=2 “No such file or directory”}}
Breaking this down:
- Domain: NSCocoaErrorDomain (Apple’s Cocoa framework)
- Code: 4 (Corresponds to NSFileNoSuchFileError)
- Message: “не вдалося знайти вказану швидку команду.” (Ukrainian for “could not find the specified shortcut command”)
- File Path: The path where the system expected to find the file
- Underlying Error: POSIX error 2 (ENOENT – No such file or directory)

Common Causes of the errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 Error
1. Broken File Aliases or Bookmarks
When your application stores file references using NSURL bookmarks or NSFileManager aliases, these can break if the target file moves or is deleted.
// Problematic code creating a bookmark that might break later
let fileURL = URL(fileURLWithPath: “/Users/developer/Documents/ImportantFile.swift”)
do {
let bookmarkData = try fileURL.bookmarkData()
UserDefaults.standard.set(bookmarkData, forKey: “SavedFileReference”)
} catch {
print(“Failed to create bookmark: \(error)”)
}
// Later, when trying to access:
if let bookmarkData = UserDefaults.standard.data(forKey: “SavedFileReference”) {
var isStale = false
do {
// This will fail with errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 if file moved
let url = try URL(resolvingBookmarkData: bookmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: &isStale)
// Use the file
} catch {
// Error occurs here
print(“Failed to resolve bookmark: \(error)”)
}
}
Solution:
// Improved code with stale bookmark handling
if let bookmarkData = UserDefaults.standard.data(forKey: “SavedFileReference”) {
var isStale = false
do {
let url = try URL(resolvingBookmarkData: bookmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: &isStale)
if isStale {
// Bookmark is stale, update it
let newBookmarkData = try url.bookmarkData()
UserDefaults.standard.set(newBookmarkData, forKey: “SavedFileReference”)
print(“Updated stale bookmark”)
}
// Verify file exists before using
var isDirectory: ObjCBool = false
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) {
// Safe to use the file
} else {
// File doesn’t exist despite bookmark resolving
print(“File referenced by bookmark no longer exists”)
// Prompt user for new file location
}
} catch {
print(“Failed to resolve bookmark: \(error)”)
// Recovery strategy – ask user to locate file again
}
}
2. Incorrect Security Scoped Resource Access
Failing to start/stop security-scoped resource access properly when working with sandboxed applications can lead to this error.
// Problematic code not managing security scope correctly
if let bookmarkData = UserDefaults.standard.data(forKey: “SecurityScopedBookmark”) {
var isStale = false
do {
let url = try URL(resolvingBookmarkData: bookmarkData,
options: .withSecurityScope,
relativeTo: nil,
bookmarkDataIsStale: &isStale)
// Missing: url.startAccessingSecurityScopedResource()
let data = try Data(contentsOf: url) // Will fail with errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4
// Process data
} catch {
print(“Error: \(error)”)
}
}
Solution:
// Proper security-scoped resource handling
if let bookmarkData = UserDefaults.standard.data(forKey: “SecurityScopedBookmark”) {
var isStale = false
do {
let url = try URL(resolvingBookmarkData: bookmarkData,
options: .withSecurityScope,
relativeTo: nil,
bookmarkDataIsStale: &isStale)
// Start accessing the resource
let didStartAccessing = url.startAccessingSecurityScopedResource()
defer {
// Always release the security-scoped resource
if didStartAccessing {
url.stopAccessingSecurityScopedResource()
}
}
// Now safe to access the file
if FileManager.default.fileExists(atPath: url.path) {
let data = try Data(contentsOf: url)
// Process data
} else {
throw NSError(domain: NSCocoaErrorDomain, code: 4, userInfo: [
NSLocalizedDescriptionKey: “The referenced file no longer exists.”
])
}
// If bookmark was stale, update it
if isStale {
let newBookmarkData = try url.bookmarkData(options: .withSecurityScope)
UserDefaults.standard.set(newBookmarkData, forKey: “SecurityScopedBookmark”)
}
} catch {
print(“Error accessing security-scoped resource: \(error)”)
// Implement recovery strategy
}
}
3. Resource Bundle Issues in Distributed Apps
When your app uses resource bundles, the paths to these resources can break, especially when distributed or archived.
// Problematic code with hard-coded paths
let resourcePath = “/Users/developer/Library/Developer/Xcode/DerivedData/MyApp-abc123/Build/Products/Debug/Resources.bundle/config.json”
let url = URL(fileURLWithPath: resourcePath)
do {
let data = try Data(contentsOf: url) // Will fail with errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 in distribution
// Process data
} catch {
print(“Failed to load resource: \(error)”)
}
Solution:
// Proper bundle resource access
func loadResource(named fileName: String, extension ext: String) -> Data? {
// Look in main bundle first
if let mainBundleURL = Bundle.main.url(forResource: fileName, withExtension: ext) {
do {
return try Data(contentsOf: mainBundleURL)
} catch {
print(“Error loading from main bundle: \(error)”)
}
}
// Check for resource in a nested bundle
if let resourceBundleURL = Bundle.main.url(forResource: “Resources”, withExtension: “bundle”),
let resourceBundle = Bundle(url: resourceBundleURL),
let resourceURL = resourceBundle.url(forResource: fileName, withExtension: ext) {
do {
return try Data(contentsOf: resourceURL)
} catch {
print(“Error loading from resource bundle: \(error)”)
}
}
return nil
}
// Usage
if let configData = loadResource(named: “config”, extension: “json”) {
// Process the data
} else {
// Handle missing resource gracefully
print(“Could not locate the required resource”)
}
4. File System Changes During Runtime
File system monitoring can fail if proper techniques aren’t used to handle file system changes.
// Problematic code not handling file system changes
class DocumentMonitor {
let documentURL: URL
init(documentURL: URL) {
self.documentURL = documentURL
}
func readDocument() throws -> String {
// This will fail with errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 if file is moved
return try String(contentsOf: documentURL, encoding: .utf8)
}
}
Solution:
// Robust file system monitoring with FSEvents
import Foundation
class DocumentMonitor {
private var documentURL: URL
private var eventStream: FSEventStreamRef?
private var callback: (URL?) -> Void
init(documentURL: URL, onChange: @escaping (URL?) -> Void) {
self.documentURL = documentURL
self.callback = onChange
startMonitoring()
}
deinit {
stopMonitoring()
}
func readDocument() throws -> String {
// Check file exists before attempting to read
guard FileManager.default.fileExists(atPath: documentURL.path) else {
throw NSError(domain: NSCocoaErrorDomain, code: 4, userInfo: [
NSLocalizedDescriptionKey: “Document no longer exists at expected location”
])
}
return try String(contentsOf: documentURL, encoding: .utf8)
}
private func startMonitoring() {
// Directory to monitor (parent directory of the file)
let pathsToWatch = [documentURL.deletingLastPathComponent().path]
var context = FSEventStreamContext()
context.info = Unmanaged.passUnretained(self).toOpaque()
// Create and start the event stream
eventStream = FSEventStreamCreate(
kCFAllocatorDefault,
{ (streamRef, clientCallBackInfo, numEvents, eventPaths, eventFlags, eventIds) in
let monitor = Unmanaged<DocumentMonitor>.fromOpaque(clientCallBackInfo!).takeUnretainedValue()
monitor.handleFSEvent(numEvents: numEvents, eventPaths: eventPaths, eventFlags: eventFlags)
},
&context,
pathsToWatch as CFArray,
FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
1.0, // 1 second latency
FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents)
)
if let eventStream = eventStream {
FSEventStreamScheduleWithRunLoop(eventStream, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue)
FSEventStreamStart(eventStream)
}
}
private func stopMonitoring() {
if let eventStream = eventStream {
FSEventStreamStop(eventStream)
FSEventStreamInvalidate(eventStream)
FSEventStreamRelease(eventStream)
self.eventStream = nil
}
}
private func handleFSEvent(numEvents: Int, eventPaths: UnsafeMutableRawPointer, eventFlags: UnsafePointer<FSEventStreamEventFlags>) {
let paths = Unmanaged<CFArray>.fromOpaque(eventPaths).takeUnretainedValue() as! [String]
for i in 0..<numEvents {
let flags = eventFlags[i]
let path = paths[i]
// Check if our specific file was affected
if path == documentURL.path {
if flags & FSEventStreamEventFlags(kFSEventStreamEventFlagItemRenamed) != 0 ||
flags & FSEventStreamEventFlags(kFSEventStreamEventFlagItemRemoved) != 0 {
// File was moved or deleted
DispatchQueue.main.async {
self.callback(nil)
}
} else if flags & FSEventStreamEventFlags(kFSEventStreamEventFlagItemModified) != 0 {
// File was modified
DispatchQueue.main.async {
self.callback(self.documentURL)
}
}
}
}
}
// Use this if file moves to try to locate it again
func locateMovedFile() -> URL? {
// Try to locate file with the same name in nearby directories
let fileName = documentURL.lastPathComponent
let searchDirectories = [
documentURL.deletingLastPathComponent().path,
NSHomeDirectory()
]
for directory in searchDirectories {
let potentialPath = (directory as NSString).appendingPathComponent(fileName)
if FileManager.default.fileExists(atPath: potentialPath) {
let newURL = URL(fileURLWithPath: potentialPath)
documentURL = newURL // Update reference
return newURL
}
}
return nil
}
}
// Usage example:
let documentURL = URL(fileURLWithPath: “/Users/username/Documents/important.txt”)
let monitor = DocumentMonitor(documentURL: documentURL) { updatedURL in
if let url = updatedURL {
print(“Document was updated at: \(url)”)
// Handle update
} else {
print(“Document was moved or deleted”)
if let newLocation = monitor.locateMovedFile() {
print(“Found document at new location: \(newLocation)”)
} else {
print(“Document could not be located”)
// Prompt user for new location
}
}
}
Solutions Comparison Table
| Prevention Techniques | Recovery Strategies |
| Use resource-loading APIs with bundle-relative paths | Implement automatic file search in standard directories |
| Check file existence before each access operation | Prompt users to reselect files when references break |
| Create and use security-scoped bookmarks properly | Store multiple reference types (path, bookmark, UUID) |
| Implement proper file system monitoring | Use content-based file identification as the fallback |
| Store content hashes along with references | Maintain a backup copy of critical resources |

How to Diagnose the errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 Error
When you encounter this error, follow these steps to diagnose the issue properly:
Step 1: Examine the Full Error Information
Use this logging enhancement to capture complete error details:
extension Error {
var detailedDescription: String {
let nsError = self as NSError
var description = “Error Domain: \(nsError.domain), Code: \(nsError.code)\n”
description += “Description: \(nsError.localizedDescription)\n”
if let failingURL = nsError.userInfo[NSURLErrorKey] as? URL {
description += “URL: \(failingURL)\n”
}
if let filePath = nsError.userInfo[NSFilePathErrorKey] as? String {
description += “File Path: \(filePath)\n”
}
if let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError {
description += “Underlying Error: Domain=\(underlyingError.domain), Code=\(underlyingError.code), \(underlyingError.localizedDescription)\n”
}
description += “User Info: \(nsError.userInfo)”
return description
}
}
// When catching an error:
do {
let data = try Data(contentsOf: fileURL)
} catch {
print(“Detailed error information:\n\(error.detailedDescription)”)
// Log or display this information
}
Example output:
Detailed error information:
Error Domain: NSCocoaErrorDomain, Code: 4
Description: не вдалося знайти вказану швидку команду.
File Path: /Users/developer/Documents/Project/missingfile.swift
Underlying Error: Domain=NSPOSIXErrorDomain, Code=2, No such file or directory
User Info: [NSFilePath: /Users/developer/Documents/Project/missingfile.swift, NSUnderlyingError: Error Domain=NSPOSIXErrorDomain Code=2 “No such file or directory”]
Step 2: Verify File Existence Systematically
class FileDiagnostics {
static func checkFilePath(_ path: String) -> [String: Any] {
var results: [String: Any] = [:]
let fileManager = FileManager.default
// Check basic existence
var isDirectory: ObjCBool = false
let exists = fileManager.fileExists(atPath: path, isDirectory: &isDirectory)
results[“exists”] = exists
results[“isDirectory”] = isDirectory.boolValue
if exists {
// Check permissions
results[“readable”] = fileManager.isReadableFile(atPath: path)
results[“writable”] = fileManager.isWritableFile(atPath: path)
results[“executable”] = fileManager.isExecutableFile(atPath: path)
results[“deletable”] = fileManager.isDeletableFile(atPath: path)
// Get attributes
do {
let attributes = try fileManager.attributesOfItem(atPath: path)
results[“size”] = attributes[.size] as? UInt64
results[“creationDate”] = attributes[.creationDate] as? Date
results[“modificationDate”] = attributes[.modificationDate] as? Date
results[“posixPermissions”] = attributes[.posixPermissions] as? Int
results[“ownerID”] = attributes[.ownerAccountID] as? Int
results[“groupID”] = attributes[.groupOwnerAccountID] as? Int
} catch {
results[“attributesError”] = error.localizedDescription
}
// Check if it’s a symbolic link
do {
let destPath = try fileManager.destinationOfSymbolicLink(atPath: path)
results[“isSymlink”] = true
results[“symlinkDestination”] = destPath
results[“symlinkDestinationExists”] = fileManager.fileExists(atPath: destPath)
} catch {
results[“isSymlink”] = false
}
} else {
// Check parent directory
let parentDir = (path as NSString).deletingLastPathComponent
results[“parentDirectoryExists”] = fileManager.fileExists(atPath: parentDir)
// Check for similarly named files
if fileManager.fileExists(atPath: parentDir) {
do {
let filename = (path as NSString).lastPathComponent
let contents = try fileManager.contentsOfDirectory(atPath: parentDir)
let similar = contents.filter { $0.lowercased().contains(filename.lowercased()) }
results[“similarFiles”] = similar
} catch {
results[“directoryListingError”] = error.localizedDescription
}
}
}
return results
}
static func diagnoseFileError(at path: String) {
let diagnostics = checkFilePath(path)
print(“File Diagnostics for \(path):”)
for (key, value) in diagnostics.sorted(by: { $0.key < $1.key }) {
print(” \(key): \(value)”)
}
// Provide advice based on results
if diagnostics[“exists”] as? Bool == true {
if diagnostics[“readable”] as? Bool == false {
print(“\nDiagnosis: File exists but is not readable. Check permissions.”)
} else if diagnostics[“isSymlink”] as? Bool == true && diagnostics[“symlinkDestinationExists”] as? Bool == false {
print(“\nDiagnosis: Broken symbolic link. The destination file doesn’t exist.”)
}
} else {
print(“\nDiagnosis: File doesn’t exist at the specified path.”)
if let similar = diagnostics[“similarFiles”] as? [String], !similar.isEmpty {
print(“Found similar files that might be what you’re looking for:”)
for file in similar {
print(” – \(file)”)
}
}
if diagnostics[“parentDirectoryExists”] as? Bool == false {
print(“The parent directory doesn’t exist either. The structure might have changed.”)
}
}
}
}
// Usage
FileDiagnostics.diagnoseFileError(at: “/Users/developer/Documents/Project/missingfile.swift”)
Step 3: Test Bookmark Resolvability
func testBookmarkResolvability(bookmarkData: Data) {
print(“Testing bookmark resolvability…”)
do {
var isStale = false
let url = try URL(resolvingBookmarkData: bookmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: &isStale)
print(“Bookmark resolves to: \(url.path)”)
print(“Is bookmark stale? \(isStale)”)
// Check if the resolved path exists
let exists = FileManager.default.fileExists(atPath: url.path)
print(“Does the resolved file exist? \(exists)”)
if isStale {
print(“Bookmark is stale, which indicates the file moved but is still accessible.”)
print(“Recommended action: Update the bookmark”)
} else if !exists {
print(“Bookmark resolved but the file doesn’t exist. This suggests recent deletion.”)
print(“Recommended action: Check if file was moved to Trash or renamed”)
} else {
print(“Bookmark is valid and file exists.”)
}
} catch {
print(“Failed to resolve bookmark: \(error)”)
print(“This indicates the bookmark is completely broken or the file is gone.”)
print(“Recommended action: Create a new bookmark after finding the file”)
}
}
// Usage
if let savedBookmarkData = UserDefaults.standard.data(forKey: “SavedFileReference”) {
testBookmarkResolvability(bookmarkData: savedBookmarkData)
} else {
print(“No bookmark data found in UserDefaults”)
}

Real-World Test Cases for errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 Error
To thoroughly verify your file reference system, implement these test cases:
class FileReferenceTests {
let fileManager = FileManager.default
let referenceManager = RobustFileReferenceManager()
func runAllTests() {
testBasicFileReference()
testMovedFile()
testDeletedFile()
testRenamedFile()
testRestoredFromTrash()
testExternalDriveDisconnect()
}
func testBasicFileReference() {
print(“Running test: Basic File Reference”)
// Create a test file
let tempDir = NSTemporaryDirectory()
let testFilePath = (tempDir as NSString).appendingPathComponent(“test_file.txt”)
let testContent = “Test content for basic file reference”
do {
try testContent.write(toFile: testFilePath, atomically: true, encoding: .utf8)
let fileURL = URL(fileURLWithPath: testFilePath)
// Save reference
try referenceManager.saveReference(to: fileURL)
// Resolve and verify
if let resolvedURL = referenceManager.resolveFile(path: testFilePath) {
let resolvedContent = try String(contentsOf: resolvedURL, encoding: .utf8)
assert(resolvedContent == testContent, “Content mismatch in basic reference test”)
print(“✅ Basic file reference test passed”)
} else {
print(“❌ Error in trash restore test: \(error)”)
}
}
func testExternalDriveDisconnect() {
print(“Running test: External Drive Disconnect Simulation”)
// This test simulates external drive behavior by using a special directory
let tempDir = NSTemporaryDirectory()
let externalDriveDir = (tempDir as NSString).appendingPathComponent(“ExternalDrive”)
let filePath = (externalDriveDir as NSString).appendingPathComponent(“external_file.txt”)
let testContent = “Test content for external drive file reference”
do {
// Create fake external drive directory
try fileManager.createDirectory(atPath: externalDriveDir, withIntermediateDirectories: true, attributes: nil)
// Create test file
try testContent.write(toFile: filePath, atomically: true, encoding: .utf8)
let fileURL = URL(fileURLWithPath: filePath)
// Save reference
try referenceManager.saveReference(to: fileURL)
// “Disconnect drive” by removing the directory
try fileManager.removeItem(atPath: externalDriveDir)
// Try to resolve (should fail gracefully)
if let resolvedURL = referenceManager.resolveFile(path: filePath) {
print(“⚠️ Unexpected: External file was resolved to \(resolvedURL.path)”)
} else {
print(“✅ External drive disconnect test passed (as expected, no resolution)”)
}
// “Reconnect drive”
try fileManager.createDirectory(atPath: externalDriveDir, withIntermediateDirectories: true, attributes: nil)
try testContent.write(toFile: filePath, atomically: true, encoding: .utf8)
// Try to resolve again
if let resolvedURL = referenceManager.resolveFile(path: filePath) {
let resolvedContent = try String(contentsOf: resolvedURL, encoding: .utf8)
assert(resolvedContent == testContent, “Content mismatch in external drive test”)
print(“✅ External drive reconnect test passed”)
} else {
print(“❌ Failed to resolve after drive reconnect”)
}
// Clean up
try fileManager.removeItem(atPath: externalDriveDir)
} catch {
print(“❌ Error in external drive simulation: \(error)”)
}
}
}
// Usage
let tests = FileReferenceTests()
tests.runAllTests()

Conclusion
The errordomain=nscocoaerrordomain&errormessage=не вдалося знайти вказану швидку команду.&errorcode=4 error occurs when your app tries to access a file through a reference that no longer resolves. By implementing robust file reference handling with security-scoped bookmarks, content hashing, and proper error recovery, you can eliminate this error in your applications. The most crucial technique is verifying file existence before access and implementing multiple fallback strategies rather than relying on a single file reference method. Failed to resolve basic file reference”) }
// Clean up
try fileManager.removeItem(atPath: testFilePath)
} catch {
print(“❌ Error in basic reference test: \(error)”)
}
}
func testMovedFile() {
print(“Running test: Moved File”)
// Create a test file
let tempDir = NSTemporaryDirectory()
let originalPath = (tempDir as NSString).appendingPathComponent(“original_location.txt”)
let newPath = (tempDir as NSString).appendingPathComponent(“new_location.txt”)
let testContent = “Test content for moved file reference”
do {
try testContent.write(toFile: originalPath, atomically: true, encoding: .utf8)
let originalURL = URL(fileURLWithPath: originalPath)
// Save reference
try referenceManager.saveReference(to: originalURL)
// Move the file
try fileManager.moveItem(atPath: originalPath, toPath: newPath)
// Try to resolve the original path
if let resolvedURL = referenceManager.resolveFile(path: originalPath) {
let resolvedContent = try String(contentsOf: resolvedURL, encoding: .utf8)
assert(resolvedContent == testContent, “Content mismatch in moved file test”)
print(“✅ Moved file test passed”)
} else {
print(“❌ Failed to resolve moved file”)
}
// Clean up
try fileManager.removeItem(atPath: newPath)
} catch {
print(“❌ Error in moved file test: \(error)”)
}
}
func testDeletedFile() {
print(“Running test: Deleted File”)
// Create and then delete a test file
let tempDir = NSTemporaryDirectory()
let testFilePath = (tempDir as NSString).appendingPathComponent(“file_to_delete.txt”)
let testContent = “Test content for deleted file reference”
do {
try testContent.write(toFile: testFilePath, atomically: true, encoding: .utf8)
let fileURL = URL(fileURLWithPath: testFilePath)
// Save reference
try referenceManager.saveReference(to: fileURL)
// Delete the file
try fileManager.removeItem(atPath: testFilePath)
// Try to resolve (should fail gracefully)
if let resolvedURL = referenceManager.resolveFile(path: testFilePath) {
print(“⚠️ Unexpected: Deleted file was resolved to \(resolvedURL.path)”)
} else {
print(“✅ Deleted file test passed (as expected, no resolution)”)
}
} catch {
print(“❌ Error in deleted file test: \(error)”)
}
}
func testRenamedFile() {
print(“Running test: Renamed File”)
// Create a test file that will be renamed
let tempDir = NSTemporaryDirectory()
let originalPath = (tempDir as NSString).appendingPathComponent(“original_name.txt”)
let newPath = (tempDir as NSString).appendingPathComponent(“renamed_file.txt”)
let testContent = “Test content for renamed file reference”
do {
try testContent.write(toFile: originalPath, atomically: true, encoding: .utf8)
let originalURL = URL(fileURLWithPath: originalPath)
// Save reference
try referenceManager.saveReference(to: originalURL)
// Rename the file
try fileManager.moveItem(atPath: originalPath, toPath: newPath)
// Try to resolve the original path
if let resolvedURL = referenceManager.resolveFile(path: originalPath) {
let resolvedContent = try String(contentsOf: resolvedURL, encoding: .utf8)
assert(resolvedContent == testContent, “Content mismatch in renamed file test”)
print(“✅ Renamed file test passed”)
} else {
print(“❌ Failed to resolve renamed file”)
}
// Clean up
try fileManager.removeItem(atPath: newPath)
} catch {
print(“❌ Error in renamed file test: \(error)”)
}
}
func testRestoredFromTrash() {
print(“Running test: Restored From Trash”)
// This test is macOS specific and simulates trash behavior
let tempDir = NSTemporaryDirectory()
let originalPath = (tempDir as NSString).appendingPathComponent(“file_to_trash.txt”)
let trashPath = (tempDir as NSString).appendingPathComponent(“.Trash/file_to_trash.txt”)
let testContent = “Test content for trashed file reference”
do {
// Create test directories including fake trash
let trashDir = (tempDir as NSString).appendingPathComponent(“.Trash”)
try fileManager.createDirectory(atPath: trashDir, withIntermediateDirectories: true, attributes: nil)
// Create test file
try testContent.write(toFile: originalPath, atomically: true, encoding: .utf8)
let originalURL = URL(fileURLWithPath: originalPath)
// Save reference
try referenceManager.saveReference(to: originalURL)
// “Trash” the file
try fileManager.moveItem(atPath: originalPath, toPath: trashPath)
// Verify file appears missing
if fileManager.fileExists(atPath: originalPath) {
print(“❌ File still exists at original location”)
}
// “Restore” from trash
try fileManager.moveItem(atPath: trashPath, toPath: originalPath)
// Try to resolve
if let resolvedURL = referenceManager.resolveFile(path: originalPath) {
let resolvedContent = try String(contentsOf: resolvedURL, encoding: .utf8)
assert(resolvedContent == testContent, “Content mismatch in trash restore test”)
print(“✅ Restored from trash test passed”)
} else {
print(“❌ Failed to resolve restored file”)
}
// Clean up
try fileManager.removeItem(atPath: originalPath)
try fileManager.removeItem(atPath: trashDir)
} catch {
print(“❌