NSURL and URL Validity
I'm using a URL from an API where a search term is surrounded by quotation marks. For example:
http://www.example.com/searchterm="search"
.
However, because of the quotation marks, my NSURL (generated by URLWithString) is nil due to an invalid URL. Is there a way around this? Thanks!
You can place a backslash before the quotation mark, or the URL encoded value %22
:
http://www.example.com/searchterm=\"search\"
http://www.example.com/searchterm=%22search%22
or you can remove the quotations before using it as an NSURL.
NSString * searchUrl = @"http://www.example.com/searchterm=\"search\"";
searchUrl =
[searchUrl stringByReplacingOccurrencesOfString:@"\"" withString:@""]; // something to this effect, not tested.
Then you can go about your normal NSURL call:
[NSURL URLWithString: searchUrl];
Try the following:
#define SAFARI_SEARCH_URL_FORMAT @"http://search/search?q=\"%@\""
mySearchBar.text =@"hello";
NSString * tempstr = [NSString stringWithFormat:SAFARI_SEARCH_URL_FORMAT, mySearchBar.text];
NSURL *an1Url = [[[NSURL alloc] initWithString:[tempstr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
] autorelease];
NSLog(@"--(%@)--",an1Url);
an1Url
will not be nil
精彩评论