NSURL file extension addition etc

Viewed 7924

I have received a URL from the savePanel sheet and I would like to do following:

  • Check to see if it has an extension
  • if it does, remove it
  • add a custom extension
  • if it does not, then add a custom extension

Any simple way to do this.. I tried something like following but it does not work

if ( [tmp pathExtension] != @"xxx" )
   path = [tmp stringByAppendingFormat:@"xxx"];

OK... A possible solution as follows

NSString *path;
NSURL *filepath;
fileurl = [sheet URL];
fileurl = [fileurl URLByDeletingPathExtension];
fileurl = [fileurl URLByAppendingPathExtension:@"yyy"];
path = [fileurl path];
3 Answers

Here is an update for Swift 4.1 using URL

// assuming you are building an URL from string
let url = URL(string: "file.abc")!
let finalUrl = url.deletingPathExtension().appendingPathExtension("mp3")
let finalString = finalUrl.path // output "file.mp3"
Related