DanTdd DanTdd - 4 months ago 15
Swift Question

How can I remove parts of an NSURL and save the result to a NSString with format?

How can I format

file:///Applications/App%20Store.app
to be stored as a string "App Store"? I want to remove everything before "App%20Store.app" and make it automatically add a space for the %20 in the new stored string.

My code takes user input from an
NSOpenPanel()
and saves the result shown above to an NSURL variable.

EDIT Got it working with this! Thanks

var URLinString : String = selectedApp!.absoluteString!

let newString = URLinString.stringByReplacingOccurrencesOfString("file:///Applications/", withString: "")

let newerString = newString.stringByReplacingOccurrencesOfString("%20", withString: " ")

Answer

Objective-C

NSURL *url = [NSURL URLWithString:@"file:///Applications/App%20Store.app"];
NSString *lastComponent = [url lastPathComponent];
NSLog(@"Last path component:%@", lastComponent);

Swift

var url = NSURL(string:"file:///Applications/App%20Store.app")
var lastComponent = url?.lastPathComponent
println("\(lastComponent)")
if lastComponent == "App Store.app" {
  println("Yes")
}

Console

Optional("App Store.app")
Yes
Comments