How to URL encode NSString

I am trying to encode a string, but NSURLConnection does not work due to 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 an example API for calling a URL:

The following is an example of an API call for an address to match exactly the addresses "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 not connecting. Can someone help me?

+6
source share
1 answer

You must encode your fullAddressURL before sending to NSURL instead of the encoding address and cityState separately.

 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 tested the code above and it gives me the same result as the specified link http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<ZWSID>&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA

+16
source

All Articles