On the server side, I have code like this to provide JSON to my iOS application:
$val = array("a", "b", "c","d");
return json_encode($val);
Within that application, I try to communicate with the server using the following code:
NSError *error = nil;
NSString *szURL =@"http://192.168.1.159/return.php";
NSURL *url = [NSURL URLWithString:szURL];
NSString *strData = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
NSArray *appLists = (NSArray *)[strData JSONValue];
However, strData is always nil. Why is this happening, and what can I do to prevent it?
I would recommend, unless you want your requests to occur synchronously and block up the UI, to perform an asynchronous request using
NSURLConnectionor a third party solution. I likeTTURLRequestfrom http://three20.info because it makes it very easy to specify headers, gets the JSON value from the data, etc. An example call would look like this:Then your delegate must implement these methods: