Search code examples
objective-ccocoansurlnsfilemanagernsworkspace

URL Containing forward slash doesn't work with NSWorkSpace


There exists a file name with forward slash(/) in the system.

For example: URL -> ~/Documents/FolderName/TestFilename/myFile.dmg.

Last Path Component is -> "TestFilename/myFile.dmg"

File Name is -> "TestFilename/myFile.dmg"

Now when i use the below code in my application to reveal in finder kind of stuff with the following one. It fails to does revealing in finder.

NSURL *fileURL = [NSURL URLWithString:@"/Documents/FolderName/TestFilename/myFile.dmg"];
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[fileURL]];

Now how do get this resolved for such case and make it revealing in finder for such files. I do have tried with "CFURLCreateStringByAddingPercentEscapes", it doesn't seems to be work. .


Solution

  • This can be achieved if you can segregate file name and file location in your code.

    Below is the sample code:

    NSString *location = @"Users/Desktop";
    NSString *fileName = @"TestFilename/myFile.dmg";
    if ([fileName rangeOfString:@"/"].location != NSNotFound)
    {
           fileName = [fileName stringByReplacingOccurrencesOfString:@"/" withString:@":"];
    }
    
    [[NSWorkspace sharedWorkspace] selectFile:[location stringByAppendingPathComponent:fileName] inFileViewerRootedAtPath:location];