简体   繁体   中英

NSFileManager - Working with spaces?

I am trying to copy a file to the temporary directory using:

NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:pathWithSpaces 
                                        toPath:fullPath 
                                         error:&error];
if(error) {
    NSLog(@"Error!!!");
}
else {
    NSLog(@"Saved to temp directory");
}

But when I try to copy a file whose path has spaces, it throws an error.

Anyone have experience with this?? Thanks

The log is as follows:

2014-09-25 10:36:47.798 MyApp[25463:1128329] /Users/USER/Pictures/Screenshots/Screen%20Shot%202014-09-25%20at%2010.07.49.png
2014-09-25 10:36:47.798 MyApp[25463:1128329] Error!!!

(I selected a file name with spaces)

First, do not examine error unless the method returned false . It is not an accurate way to determine if the method failed. Only the method's return value tells you that.

Second, if you're going to log when an error occurs, write out the error object to find out what happened.

Third, -copyItemAtPath:toPath:error: handles paths with spaces just fine. It is the shell (the command line in Terminal or whatever), which may treat spaces as separators and thus messes up. Anything which is not using the shell, that is any programmatic API, does not need spaces quoted or escaped or anything like that.

Lastly, your "path" does not look like it's really a path. You have /Users/USER/Pictures/Screenshots/Screen%20Shot%202014-09-25%20at%2010.07.49.png . That looks like you chopped up a URL string, what with the percent-escaped spaces. You can't simply strip off the leading "file://" (or "file//localhost/") to get a proper path from a file URL. If you have the URL in an NSURL , just access its path property.

You need to reconsider how you're computing the pathWithSpaces , because you're surely doing it wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM