【发布时间】:2011-07-14 19:26:45
【问题描述】:
您好,我有一个使用 ASIFormDataRequest 将变量发布到 php 文件的 iPhone 应用程序。然后,php 文件以关联数组的形式从我的远程数据库返回一组元组。
我使用 objectFromJSONString 反序列化 json 数据(使用 JSONKit 框架),但是打印出数据后,我得到 null。这是我的代码:
+(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
}
@结束
@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
我尝试过使用 ASIHTTPRequest 回调委托 (didFinishSelector)
更新:
这里是 php.ini 的链接。当您单击它时,您可以看到它正在正确输出 JSON:
http://dev.speechlink.co.uk/David/get_questionstest.php
这里是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_error());;
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
//echo '{"questions":'.json_encode($rows).'}';
echo json_encode($rows);
mysql_close();
?>
【问题讨论】:
标签: php iphone xcode asihttprequest