NSURL returns Nil Value

Vijay picture Vijay · Aug 31, 2011 · Viewed 9.3k times · Source

Here Below is my code

NSString *string    = [NSString stringWithFormat:@" http://abc.com  /Demo/View.php?drinkId=%@&name=%@&comment=%@&date=%@&rating=%@&    ReqestType=SubmitComment",DrinkId,Name,Comment,Date,Rating];

NSURL *url          = [[NSURL alloc] initWithString:string];

Here in string there is value but url returns nil. Can Anyone tell why this happened.

Thanks ....

"This won't work, so here's what I did instead"

NSString *string    = [NSString stringWithFormat:@"http://abc.com/Demo/View.php?drinkId=%@&name=%@&comment=%@&date=%@&rating=%@&ReqestType=SubmitComment",DrinkId,Name,Comment,Date,Rating];

NSURL *url          = [[NSURL alloc] initWithString:string];

Answer

Mike Hay picture Mike Hay · Aug 31, 2011

NSURL will return nil for URLs that contain illegal chars, like spaces.

Before using your string with [NSURL URLWithString:] make sure to escape all the disallowed chars by using [NSString stringByAddingPercentEscapesUsingEncoding:].

Here is the class reference for NSString.