0

I am trying to accomplish a very simple task of loading a WebView that has a variable. I am hoping to pass the variable from objective-c to a remote PHP file. The code I am using does not seem to work. The variable is valid, but I cannot get it to pass to the PHP file to be read by the WebView. Any help would be great!

    NSString *userId = [[NSUserDefaults standardUserDefaults]
                        stringForKey:@"userId"];

[webViewFirst loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.website.com/page.php?userId=%@",userId]]];

Thank you very much!

djromero
  • 19,551
  • 4
  • 71
  • 68
Brandon
  • 2,163
  • 6
  • 40
  • 64

2 Answers2

0

Try +[NSString stringWithFormat] to build the URL string:

NSString *userId = <#whatever#>;
NSString *link = [NSString stringWithFormat:@"http://www.website.com/page.php?userId=%@", userId]
[webViewFirst loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:link]];
djromero
  • 19,551
  • 4
  • 71
  • 68
0

NSURL URLWithString does not support string formatting, so you cannot use it like you are trying to do.

What happens, instead, is that the C , operator is used, which just sequences the two expressions: @"http://www.website.com/page.php?userId=%@" and userId, and evaluates to the last one.

Use stringWithFormat to get it right:

[webViewFirst loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.website.com/page.php?userId=%@",userId]]]];
sergio
  • 68,819
  • 11
  • 102
  • 123