Solution - Adding leading slash with new URL API:
func getFileName(from fileNameWithExtension: String) -> String {
let url = URL(
filePath: "/" + fileNameWithExtension,
directoryHint: .notDirectory,
relativeTo: nil
)
// Debug logging
print("Input: \(fileNameWithExtension)")
print("URL created: \(url)")
print("URL.path: \(url.path)")
print("URL.lastPathComponent: \(url.lastPathComponent)")
return url.lastPathComponent
}
// Usage
let result = getFileName(from: "~TestFile.irfd")
Debug Output (iOS 26):
Input: ~TestFile.irfd
URL created: file:///~TestFile.irfd
URL.path: /~TestFile.irfd
URL.lastPathComponent: ~TestFile.irfd
By prefixing with /, the filename becomes an absolute path, preventing the ~ from being interpreted as the home directory symbol.
This approach:
Uses the modern URL(filePath:directoryHint:relativeTo:) API (not deprecated)
Works correctly on both iOS 18 and iOS 26
Follows the "valid pathname" rule you mentioned
Btw, i could not find the official Apple documentation that explains this path resolution behavior for ~ and the new URL API. @DTS Engineer Thanks for suggestion. if you know about any link about functions above please, share it Thanks.
Topic:
App & System Services
SubTopic:
General
Tags: