UIApplication openUrl not working with formatted NSString

agentfll picture agentfll · Mar 29, 2010 · Viewed 12.8k times · Source

I have the following code to open google maps:

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@, Anchorage, AK",addressString];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

But it doesn't work and there is no error. It just doesn't open.

Answer

user121301 picture user121301 · Mar 29, 2010

URLWithString requires a percent-escaped string. Your sample url contains spaces which results in a nil NSURL being created. Additionally, the addressString may also contain characters that need to be escaped. Try percent-escaping the url string first:

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@, Anchorage, AK",addressString];
NSString *escaped = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:escaped]];