Hi I have an iPhone app that uses ASIFormDataRequest to post a variable to a php file. The php file then returns a set of tuples from my remote database in the form of an associative array.
I use objectFromJSONString to deserialise the json data (using the JSONKit framework), but pon printing out the data, I get null. Here is my code:
+(NSDictionary*)getQuestions:(NSString*)sectionId from: (NSString*) url{
NSDictionary *questions;
NSURL *link = [NSURL URLWithString:url];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request setPostValue:sectionId forKey:@"section"];
NSError *error = [request error];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestFinished:)];
[request startAsynchronous];
if (!error) {
//NSString *response = [request responseString];
//store them in the dictionary
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
questions = [json objectFromJSONString];
NSLog(@"%@",questions); //prints null
[json release];
[request release];
}else{
//UIAlertView to warn users there was an error
}
return questions;
}
//doesn't work
- (void)requestFinished:(ASIHTTPRequest *)request
{
//NSString *response = [request responseString];
NSLog(@"hello"); //never prints
}
@end
@implementation dbQuestionGetterViewController
@synthesize questions;
-(void)viewDidLoad{
//code to initialise view
NSDictionary* arr = [dbConnector getQuestions:@"2" from:@"http://dev.speechlink.co.uk/David/get_questions.php"];
self.questions = arr;
[super viewDidLoad];
}
@end
I have tried using an ASIHTTPRequest calback delegate (didFinishSelector)
UPDATE:
Here is the link to the php. When you click it you can see it's outputting JSON properly:
http://dev.speechlink.co.uk/David/get_questionstest.php
Here is the php:
<?php
//connect to database
$dbh = mysql_connect ("localhost", "abc", "123") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
$query = mysql_query("SELECT * FROM Questions WHERE sectionId = 1") or die("Error: " . mysql_erro开发者_StackOverflow中文版r());;
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
//echo '{"questions":'.json_encode($rows).'}';
echo json_encode($rows);
mysql_close();
?>
It will return nil if the string you're passing in isn't valid JSON.
There's two things that might be happening :
(1) You're not parsing the server's response properly - try outputting the json string to see what you think it is i.e.
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", json);
(2) The server is not sending correct JSON - try opening the URL in a browser and making sure that it's correctly formed.
精彩评论