How to URL encode a NSString

我是研究僧i 提交于 2019-12-23 08:56:41

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/15443040/how-to-url-encode-a-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!