Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to URL encode a NSString

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?

like image 402
Chandler De Angelis Avatar asked Mar 15 '13 22:03

Chandler De Angelis


Video Answer


1 Answers

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

like image 94
βhargavḯ Avatar answered Feb 09 '23 11:02

βhargavḯ