18

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.

Petros Koutsolampros
  • 2,790
  • 1
  • 14
  • 20
agentfll
  • 858
  • 2
  • 10
  • 21

2 Answers2

44

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]];  
5

Need to escape the urlString , else [NSURL URLWithString:urlString] will return nill.

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@, Anchorage, AK",addressString];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ]];
Biranchi
  • 16,120
  • 23
  • 124
  • 161