I would take a different approach. Here's how I'd do it:
NSString * q = [NSString stringWithFormat:@"%@ %@, %@", self.address, self.city, self.state];
NSDictionary * queryDictionary = [NSDictionary dictionaryWithObjectsAndKeys:q, @"q", @"h", @"t", nil];
NSMutableArray * fields = [NSMutableArray array];
for (NSString * key in queryDictionary) {
NSString * value = [queryDictionary objectForKey:key];
NSString * encoded = [NSString stringWithFormat:@"%@=%@", [key URLEncodedString_ch], [value URLEncodedString_ch]];
[fields addObject:encoded];
}
NSString * queryString = [fields componentsJoinedByString:@"&"];
NSString * googleString = [NSString stringWithFormat:@"http://maps.google.com?%@", queryString];
NSURL * googleURL = [NSURL URLWithString:googleString];
[[UIApplication sharedApplication] openURL:googleURL];
-URLEncodedString_ch
can be found here
Why is this better? There are several reasons:
- The keys in a query string should be URL encoded. Granted that right now they're just one letter that's in the ASCII set, but can you guarantee that they'll always be?
- The values in a query string should be URL encoded. Right now you're only trying to plus-encode the spaces. What if your address contains an
&
or =
? It would be unusual for an address, but not impossible (especially the &
in a street name).
- This is highly extensible. If you decide to add support for foreign address and need more than a simple ASCII address, it's rather trivial to add the
@"UTF-8"
and @"oe"
object and key to the dictionary for inclusion in the query string.
- The percent encoding (if you use the category method linked to above) is more accurate than
stringByAddingPercentEscapesUsingEncoding: