NSURL返回Nil Value

时间:2011-08-31 14:58:00

标签: objective-c nsurl

以下是我的代码

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];

这里的字符串有值,但url返回nil。 任何人都可以说出为什么会这样。

谢谢....

“这不起作用,所以这就是我所做的”

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];

2 个答案:

答案 0 :(得分:27)

对于包含非法字符的网址,NSURL将返回nil,如空格。

在将字符串与[NSURL URLWithString:]一起使用之前,请确保使用[NSString stringByAddingPercentEscapesUsingEncoding:]转义所有不允许的字符。

这是the class reference for NSString

答案 1 :(得分:-1)

大家好我现在的问题在这里解决了我在“http”之前留下了一个空白。

正确的代码是

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

NSURL *url          = [[NSURL alloc] initWithString:string];
相关问题