Have you ever found yourself staring at an error message that looks like a mess of characters? The errordomain=nscocoaerrordomain&errormessage=kunde inte hitta den angivna genvägen.&errorcode=4 error is precisely that kind of headache-inducing problem. This Swedish error message translates to “Unable to find the specified shortcut” and primarily signals that your app can’t locate a file it desperately needs.
When this error crashes your application or halts your development process, it doesn’t just waste time—it creates a puzzling roadblock that can seem impossible to overcome. This error typically materializes during file operations, resource loading, or when working with document-based applications on macOS or iOS platforms.
I’ve tackled this error numerous times, and I’ll walk you through everything you need to know to diagnose and fix it permanently. Let’s transform this cryptic message into a solved problem with practical, code-focused solutions.

Decoding errordomain=nscocoaerrordomain&errormessage=kunde inte hitta den angivna genvägen.&errorcode=4
What This Error Means
The errordomain=nscocoaerrordomain&errormessage=kunde inte hitta den angivna genvägen.&errorcode=4 error breaks down into three critical components:
- errordomain=nscocoaerrordomain: Identifies that the error originates within Apple’s Cocoa framework, which handles core application functionality for macOS and iOS.
- errormessage=kunde inte hitta den angivna genvägen: Swedish error message meaning “Could not find the specified shortcut” (this language variation often appears based on system language settings).
- errorcode=4: The specific error code (4) corresponds to NSFileNoSuchFileError, indicating a file or resource couldn’t be found at an expected location.
Here’s how this error typically appears in console output:
Error Domain=NSCocoaErrorDomain Code=4 “kunde inte hitta den angivna genvägen.”
UserInfo={NSFilePath=/Users/developer/Documents/ProjectFiles/config.json,
NSUnderlyingError=0x600002b90940 {Error Domain=NSPOSIXErrorDomain Code=2 “No such file or directory”}}
The exact numerical mapping in the Cocoa framework:
- Error 4 = NSFileNoSuchFileError = File not found
- Error 2 in the underlying POSIX error = ENOENT = No such file or directory
This combination confirms that your application attempted to access a file that doesn’t exist where you expected it to be.

Common Causes of errordomain=nscocoaerrordomain&errormessage=kunde inte hitta den angivna genvägen.&errorcode=4
1. Hardcoded Path Problems
One of the most frequent triggers for this error is using absolute, hardcoded file paths that don’t account for environment changes:
// Problematic code with hardcoded path
let configPath = “/Users/developer/Documents/MyApp/config.json”
let configData = try Data(contentsOf: URL(fileURLWithPath: configPath))
When your application runs on a different machine or user account, this path becomes invalid instantly. Here’s how to fix it:
// Fixed code using bundle resources
guard let configPath = Bundle.main.path(forResource: “config”, ofType: “json”) else {
print(“Config file not found in bundle”)
return
}
let configData = try Data(contentsOf: URL(fileURLWithPath: configPath))
2. Missing Files During Deployment
Your development environment might contain files that don’t get included in the final build:
// Problematic assumption about file inclusion
func loadAssets() {
let assetURL = Bundle.main.url(forResource: “specialGraphics”, ofType: “png”)!
// Error occurs if file wasn’t included in the bundle
let assetData = try! Data(contentsOf: assetURL)
}
The solution is to verify bundle contents and use proper error handling:
// Fixed version with proper error handling
func loadAssets() -> Data? {
guard let assetURL = Bundle.main.url(forResource: “specialGraphics”, ofType: “png”) else {
print(“Asset file missing from bundle”)
return nil
}
do {
return try Data(contentsOf: assetURL)
} catch {
print(“Failed to load asset: \(error.localizedDescription)”)
return nil
}
}
3. Sandbox Restrictions
macOS and iOS sandbox restrictions often prevent access to files outside approved paths:
// Code attempting to access restricted location
let documentsPath = “/Library/Application Support/SharedData/config.json”
let configData = try Data(contentsOf: URL(fileURLWithPath: documentsPath))
The fix requires using proper sanctioned directories:
// Fixed code using sanctioned directories
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
let configURL = appSupportURL.appendingPathComponent(“config.json”)
do {
if fileManager.fileExists(atPath: configURL.path) {
let configData = try Data(contentsOf: configURL)
// Process data
} else {
print(“Config file doesn’t exist at expected location”)
}
} catch {
print(“Error accessing config: \(error)”)
}
4. File Permission Issues
Sometimes the file exists, but your app lacks permission to access it:
// Problematic direct file access without permission checks
let fileURL = URL(fileURLWithPath: “/Users/Shared/CompanyData/settings.json”)
let settingsData = try String(contentsOf: fileURL)
The solution involves proper permission handling and user consent:
// Fixed code with security-scoped bookmark for persistent access
import Cocoa
func accessProtectedFile() {
let openPanel = NSOpenPanel()
openPanel.canChooseFiles = true
openPanel.canChooseDirectories = false
openPanel.allowsMultipleSelection = false
openPanel.begin { result in
if result == .OK, let fileURL = openPanel.url {
// Start security-scoped resource access
guard fileURL.startAccessingSecurityScopedResource() else {
print(“Permission denied”)
return
}
defer {
fileURL.stopAccessingSecurityScopedResource()
}
do {
let fileData = try Data(contentsOf: fileURL)
// Process file data
print(“Successfully read file of size: \(fileData.count) bytes”)
} catch {
print(“Error reading file: \(error.localizedDescription)”)
}
}
}
}

Diagnostic Steps for Resolving errordomain=nscocoaerrordomain&errormessage=kunde inte hitta den angivna genvägen.&errorcode=4
Step-by-Step Diagnosis Process
Follow this systematic approach to pinpoint the exact cause of your error:
- Verify the exact path being used when the error occurs:
// Add diagnostic logging
func accessFile(at path: String) {
let fileURL = URL(fileURLWithPath: path)
print(“Attempting to access file at: \(fileURL.path)”)
print(“File exists check: \(FileManager.default.fileExists(atPath: fileURL.path))”)
// Additional path inspection
let components = fileURL.pathComponents
print(“Path components: \(components)”)
// Try accessing anyway to see specific error
do {
let data = try Data(contentsOf: fileURL)
print(“Successfully read \(data.count) bytes”)
} catch {
print(“Access error details: \(error)”)
if let nsError = error as NSError {
print(“Domain: \(nsError.domain), Code: \(nsError.code)”)
print(“User info: \(nsError.userInfo)”)
}
}
}
- Check file existence with FileManager:
// Create a testing function
func testFilePath(_ path: String) -> Bool {
let expandedPath = NSString(string: path).expandingTildeInPath
let exists = FileManager.default.fileExists(atPath: expandedPath)
if !exists {
// Check parent directory existence
let directoryURL = URL(fileURLWithPath: expandedPath).deletingLastPathComponent()
let directoryExists = FileManager.default.fileExists(atPath: directoryURL.path)
print(“Parent directory exists: \(directoryExists)”)
if directoryExists {
// List contents of parent directory
do {
let contents = try FileManager.default.contentsOfDirectory(atPath: directoryURL.path)
print(“Directory contents: \(contents)”)
} catch {
print(“Error listing directory: \(error)”)
}
}
}
return exists
}
- Create a sandbox test to check permissions:
func testSandboxPermissions(for url: URL) {
// Check read permissions
let readableAttr = [FileAttributeKey.readable]
do {
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
let readable = attributes[.posixPermissions] as? Int ?? 0
print(“Posix permissions: \(String(format: “%o”, readable))”)
// Try minimal access
let handle = try FileHandle(forReadingFrom: url)
print(“File opened successfully”)
handle.closeFile()
} catch {
print(“Permission diagnostic error: \(error)”)
}
}
- Debug bundle resource loading:
func debugBundleResource(named resourceName: String, extension ext: String) {
let bundle = Bundle.main
// Log bundle path
print(“Bundle path: \(bundle.bundlePath)”)
// Check resource exists
if let path = bundle.path(forResource: resourceName, ofType: ext) {
print(“Resource found at path: \(path)”)
} else {
print(“Resource NOT found in bundle”)
// List all bundle resources with same extension
let resourceURLs = bundle.urls(forResourcesWithExtension: ext, subdirectory: nil)
print(“Available resources with extension .\(ext): \(resourceURLs ?? [])”)
// List all resources in main bundle
if let bundleURL = Bundle.main.resourceURL {
do {
let resources = try FileManager.default.contentsOfDirectory(at: bundleURL, includingPropertiesForKeys: nil)
print(“All bundle resources: \(resources)”)
} catch {
print(“Error listing bundle resources: \(error)”)
}
}
}
}
Prevention Strategies vs. Recovery Approaches
| Prevention Technique | Recovery Strategy |
| Use relative paths based on well-known directories | Implement fallback resource loading from alternate locations |
| Add file existence checks before every file operation | Create missing directories and default configuration files on-demand |
| Keep sensitive files within app sandbox boundaries | Guide users through file access permissions with NSOpenPanel |
| Store persistent bookmarks for user-selected files | Implement robust error recovery to handle missing files gracefully |
| Include resource verification in the app launch sequence | Cache critical data to prevent repeated file access failures |

Implementing a Robust Solution for errordomain=nscocoaerrordomain&errormessage=kunde inte hitta den angivna genvägen.&errorcode=4
Let’s build a comprehensive file access manager that prevents this error through careful path management, proper error handling, and recovery strategies:
import Foundation
/// Robust file manager that handles NSCocoaErrorDomain Code 4 errors
class SafeFileManager {
static let shared = SafeFileManager()
private let fileManager = FileManager.default
// MARK: – Secure Path Resolution
/// Returns a secure path for app-specific data files
func secureDataPath(filename: String) -> URL {
let directories = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)
let appSupport = directories[0].appendingPathComponent(Bundle.main.bundleIdentifier ?? “com.app.default”)
// Create directory if needed
if !fileManager.fileExists(atPath: appSupport.path) {
try? fileManager.createDirectory(at: appSupport, withIntermediateDirectories: true)
}
return appSupport.appendingPathComponent(filename)
}
// MARK: – Safe File Operations
/// Safely reads data from a file with comprehensive error handling
func safelyReadFile(at path: String) -> Result<Data, FileError> {
// Expand any tildes in the path
let expandedPath = (path as NSString).expandingTildeInPath
// Check if file exists
guard fileManager.fileExists(atPath: expandedPath) else {
return .failure(.fileNotFound(path: expandedPath))
}
// Try to read the file
do {
let data = try Data(contentsOf: URL(fileURLWithPath: expandedPath))
return .success(data)
} catch {
// Convert NSError to our custom error type
if let nsError = error as NSError {
if nsError.domain == NSCocoaErrorDomain && nsError.code == 4 {
return .failure(.fileNotFound(path: expandedPath))
} else if nsError.domain == NSCocoaErrorDomain && nsError.code == 257 {
return .failure(.permissionDenied(path: expandedPath))
}
}
return .failure(.generalError(underlyingError: error))
}
}
/// Reads a resource from the app bundle with fallback options
func readBundleResource(named name: String, extension ext: String) -> Result<Data, FileError> {
// Try to get the resource URL
guard let resourceURL = Bundle.main.url(forResource: name, ofType: ext) else {
// Fallback: try searching case-insensitively
let resourceURLs = Bundle.main.urls(forResourcesWithExtension: ext, subdirectory: nil) ?? []
// Find resource with case-insensitive matching
if let matchedURL = resourceURLs.first(where: {
$0.deletingPathExtension().lastPathComponent.lowercased() == name.lowercased()
}) {
do {
let data = try Data(contentsOf: matchedURL)
return .success(data)
} catch {
return .failure(.generalError(underlyingError: error))
}
}
return .failure(.resourceNotFound(name: name, extension: ext))
}
// Resource URL found, try to read it
do {
let data = try Data(contentsOf: resourceURL)
return .success(data)
} catch {
return .failure(.generalError(underlyingError: error))
}
}
/// Creates a security-scoped bookmark for persistent file access
func createPersistentBookmark(for url: URL) -> Result<Data, FileError> {
do {
let bookmarkData = try url.bookmarkData(options: .withSecurityScope,
includingResourceValuesForKeys: nil,
relativeTo: nil)
return .success(bookmarkData)
} catch {
return .failure(.bookmarkCreationFailed(url: url, error: error))
}
}
/// Resolves a security-scoped bookmark to a URL with access
func resolveBookmark(_ bookmarkData: Data) -> Result<URL, FileError> {
do {
var isStale = false
let url = try URL(resolvingBookmarkData: bookmarkData,
options: .withSecurityScope,
relativeTo: nil,
bookmarkDataIsStale: &isStale)
if isStale {
return .failure(.staleBookmark)
}
if !url.startAccessingSecurityScopedResource() {
return .failure(.accessDenied(url: url))
}
// Note: You must call url.stopAccessingSecurityScopedResource() when done
return .success(url)
} catch {
return .failure(.bookmarkResolutionFailed(error: error))
}
}
// MARK: – Error Types
/// Custom error type for file operations
enum FileError: Error, LocalizedError {
case fileNotFound(path: String)
case permissionDenied(path: String)
case resourceNotFound(name: String, extension: String)
case bookmarkCreationFailed(url: URL, error: Error)
case bookmarkResolutionFailed(error: Error)
case staleBookmark
case accessDenied(url: URL)
case generalError(underlyingError: Error)
var errorDescription: String? {
switch self {
case .fileNotFound(let path):
return “Could not find file at path: \(path)”
case .permissionDenied(let path):
return “Permission denied for file at path: \(path)”
case .resourceNotFound(let name, let ext):
return “Could not find resource named ‘\(name)’ with extension ‘.\(ext)'”
case .bookmarkCreationFailed(let url, _):
return “Failed to create security-scoped bookmark for \(url.path)”
case .bookmarkResolutionFailed:
return “Failed to resolve security-scoped bookmark”
case .staleBookmark:
return “Bookmark is stale and needs to be recreated”
case .accessDenied(let url):
return “Security-scoped resource access denied for \(url.path)”
case .generalError(let error):
return “File operation error: \(error.localizedDescription)”
}
}
}
}
Example Usage of the SafeFileManager Class
// Application code using the safe file manager
func loadConfiguration() {
let configManager = SafeFileManager.shared
// Try reading from app support directory first
let configPath = configManager.secureDataPath(filename: “config.json”).path
let configResult = configManager.safelyReadFile(at: configPath)
switch configResult {
case .success(let configData):
print(“Config loaded successfully, \(configData.count) bytes”)
processConfiguration(configData)
case .failure(let error):
print(“Could not load config: \(error.localizedDescription)”)
// Fall back to bundle resource
let bundleResult = configManager.readBundleResource(named: “default_config”, extension: “json”)
switch bundleResult {
case .success(let defaultConfig):
print(“Loaded default configuration from bundle”)
processConfiguration(defaultConfig)
// Save to app support for next time
try? defaultConfig.write(to: URL(fileURLWithPath: configPath))
case .failure:
print(“Critical error: Could not load default configuration”)
loadEmergencyDefaults()
}
}
}
// Test suite for the SafeFileManager
func testSafeFileManager() {
let manager = SafeFileManager.shared
// Test 1: Try reading non-existent file
let badPath = “/tmp/definitely_does_not_exist.txt”
let badResult = manager.safelyReadFile(at: badPath)
if case .failure(let error) = badResult {
print(“Test 1 passed: \(error.localizedDescription)”)
}
// Test 2: Create and read a temporary file
let tempDir = NSTemporaryDirectory()
let tempPath = tempDir + “test_file.txt”
let testString = “This is test content”
try? testString.data(using: .utf8)?.write(to: URL(fileURLWithPath: tempPath))
let goodResult = manager.safelyReadFile(at: tempPath)
if case .success(let data) = goodResult,
let content = String(data: data, encoding: .utf8),
content == testString {
print(“Test 2 passed: Successfully read test file”)
}
// Clean up
try? FileManager.default.removeItem(atPath: tempPath)
}
Conclusion: Banishing the errordomain=nscocoaerrordomain&errormessage=kunde inte hitta den angivna genvägen.&errorcode=4 Error
The errordomain=nscocoaerrordomain&errormessage=kunde inte hitta den angivna genvägen.&errorcode=4 error boils down to one critical issue: your app can’t find a file where it is expected to be. You can effectively eliminate this error from your applications by implementing proper path resolution, defensive file access checks, and robust error handling.
The most vital implementation advice is never to assume file existence or accessibility. Always verify paths before access, provide fallback mechanisms, and gracefully handle edge cases. The SafeFileManager class provided in this guide offers a comprehensive approach that you can adapt to your specific needs.
Remember: All file operations should be wrapped in appropriate error handling that anticipates NSCocoaErrorDomain errors.