NSOpenPanel not correctly accessing NSUrl from filename with Whitespace
-
21-06-2021 - |
Question
Did a search, didn't find any issues on this.
My application takes .csv files, switches the data around and spits it out in a way my company finds useful. The issue is that the program seems to require filenames without whitespace. For instance "My data.csv" will not work, but "My_data.csv" will work. Here is what I believe to be the relevant code
NSArray *allowedTypes = [NSArray arrayWithObjects:@"CSV",@"csv",nil];
openDLG = [NSOpenPanel openPanel];
[openDLG setDelegate:self];
[openDLG setCanChooseFiles:YES];
[openDLG setAllowedFileTypes:allowedTypes];
NSInteger openReturn = [openDLG runModal];
if (openReturn == NSFileHandlingPanelOKButton) {
NSArray *rawCSVs = [openDLG URLs];
NSEnumerator *enumerator = [rawCSVs objectEnumerator];
id object;
while ((object = [enumerator nextObject])) {
NSString *tempDump = [NSString stringWithContentsOfURL:object encoding:NSUTF8StringEncoding error:NULL];
NSArray *bigArray = [tempDump csvRows];
int total = [bigArray count];
....do other things
In debug mode, the "object" comes up as nil for filenames with whitespace and "tempdump" string comes up as @"nil" for filenames with whitespace, but comes up wonderfully for names_with_underscores
Solution
An URL does not permit every character, so you will need to do some conversion.
NSString *rawString = [NSString stringWithString:@"/Users/myusername/test 1.txt"];
NSString *escapedString = [rawString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:escapedString];
NSLog(@"url: %@", url);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow