How to URL encode a NSString

Chandler De Angelis picture Chandler De Angelis · Mar 15, 2013 · Viewed 12.7k times · Source

I am trying to url encode a string, but the NSURLConnection is failing because of a 'bad url'. Here is my URL:

    NSString *address = mp.streetAddress;
    NSString *encodedAddress = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *cityState= mp.cityState;
    NSString *encodedCityState = [cityState stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *fullAddressURL = [NSString stringWithFormat:@"http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<X1-ZWz1bivd5de5mz_8xo7s>&address=%@&citystatezip=%@", encodedAddress, encodedCityState];
    NSURL *url = [NSURL URLWithString:fullAddressURL];

Here is the API's example of calling the URL:

Below is an example of calling the API for the address for the exact address match "2114 Bigelow Ave", "Seattle, WA":

http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<ZWSID>&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA

For some reason this URL is failing to connect. Can someone help me out?

Answer

βhargavḯ picture βhargavḯ · Mar 16, 2013

You have to encode your fullAddressURL before sending that to NSURL instead of encoding address & cityState individually.

NSString *address = @"2114 Bigelow Ave";
//NSString *encodedAddress = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *cityState= @"Seattle, WA";
// NSString *encodedCityState = [cityState stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSString *fullAddressURL = [NSString stringWithFormat:@"http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<X1-ZWz1bivd5de5mz_8xo7s>&address=%@&citystatezip=%@", address, cityState];
fullAddressURL = [fullAddressURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"fullAddressURL: %@",fullAddressURL);

NSURL *url = [NSURL URLWithString:fullAddressURL];

I have tested above code and it is giving me same output as given link http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<ZWSID>&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA