私が提出するという変数を投稿したURLへのリクエストを送信するiPhoneアプリを持っている:PHP - > JSON - > iPhone
+(NSMutableArray*)getQuestions:(NSString*)section from: (NSString*) url{
NSMutableArray *questions = [[NSMutableArray alloc] init];
//connect to database given by url
//NSError *error = nil;
//NSURLResponse *response = nil;
NSMutableString* myRequestString = [[NSMutableString string]initWithFormat:@"section=%@", section];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPMethod: @"POST"];
//post section
[request setHTTPBody: myRequestData];
//store them in the array;
return [questions autorelease];
}
私のPHPファイル:
<?php
//connect to database
function connect() {
$dbh = mysql_connect ("localhost", "abc1", "12345") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
//store posted data
if(isset($_POST['section'])){
$dbh = connect();
$section = $_POST['section'];
$query = mysql_query("SELECT * FROM QUESTIONS WHERE sectionId = $section;") or die("Error: " . mysql_error());;
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
echo '{"questions":'.json_encode($rows).'}';
mysql_close();
}
?>
私が構築しています各行要素が行連想配列内に有する正確な特性を有する目的関数cのモデルクラス(質問)。
私の質問は以下のとおりです。
1)私は客観Cでecho'd JSONの配列要素とそれらの相対的な属性を読み取ることができますどのように?
2)Questionオブジェクトの配列を作成し、各オブジェクトを行配列の要素にマップするにはどうすればよいですか?
3)私のメソッド "+(NSMutableArray *)getQuestions:(NSString *)section from:(NSString *)url"でPHPからの返信をキャプチャするにはどうすればよいですか?
編集:ここでは
は、PHPの出力です:
http://dev.speechlink.co.uk/David/get_questionstest.php
UPDATE
ASIHTTPRequestを使用するように変更する方法 - JSON文字列をdeserialiseできません:
//method to
+(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 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(@"Data: %@", questions); //outputs Data: (null)
[json release];
[request release];
}else{
//UIAlertView to warn users there was an error
}
return questions;
}
こんにちは、返信ありがとうございます。質問でNSLogを実行すると、私はnullを返します、なぜこれが可能でしょうか? – user559142
あなたのデータが正しく取得されていません。 ( 'NSDictionary * questions = [json objectFromJSONString];')この行から作成された 'questions'を記録してみてください。それにデータが含まれているかどうかを確認する –
こんにちは、それもnullを返します。私はどこにいるのか分かりません;データを間違って取得しています。ブラウザのリンクをHTMLに表示すると(JSON文字列が正しく表示されます)、 – user559142