21

I am trying to access google maps' forward geocoding service from my iphone app. When i try to make an NSURL from a string with a pipe in it I just get a nil pointer.

NSURL *searchURL = [NSURL URLWithString:@"http://maps.google.com/maps/api/geocode/json?address=6th+and+pine&bounds=37.331689,-122.030731|37.331689,-122.030731&sensor=false"];

I dont see any other way in the google api to send bounds coordinates with out a pipe. Any ideas about how I can do this?

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
aks
  • 422
  • 4
  • 12

3 Answers3

35

Have you tried replacing the pipe with %7C (the URL encoded value for the char |)?

Ben S
  • 68,394
  • 30
  • 171
  • 212
  • 4
    Doesn't NSString have a – stringByAddingPercentEscapesUsingEncoding: method that does that for you? – Tom H Jun 14 '10 at 20:31
  • doh. that is exactly what i needed, just didnt know about percent escapes besides %20. Thanks guys – aks Jun 14 '10 at 20:34
20

As stringByAddingPercentEscapesUsingEncoding is deprecated, you should use stringByAddingPercentEncodingWithAllowedCharacters.

Swift answer:

let rawUrlStr = "http://maps.google.com/maps/api/geocode/json?address=6th+and+pine&bounds=37.331689,-122.030731|37.331689,-122.030731&sensor=false";
let urlEncoded = rawUrlStr.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
let url = NSURL(string: urlEncoded)

Edit: Swift 3 answer:

let rawUrlStr = "http://maps.google.com/maps/api/geocode/json?address=6th+and+pine&bounds=37.331689,-122.030731|37.331689,-122.030731&sensor=false";
if let urlEncoded = rawUrlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
    let url = NSURL(string: urlEncoded)
}
Floris M
  • 1,764
  • 19
  • 18
9

If you want to be safe for whatever weird characters you will put in the future, use stringByAddingPercentEscapesUsingEncoding method to make the string "URL-Friendly"...

NSString *rawUrlStr = @"http://maps.google.com/maps/api/geocode/json?address=6th+and+pine&bounds=37.331689,-122.030731|37.331689,-122.030731&sensor=false";
NSString *urlStr = [rawUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *searchURL = [NSURL URLWithString:urlStr];
Aviel Gross
  • 9,770
  • 3
  • 52
  • 62