2011-07-13 13 views
2

私が提出するという変数を投稿した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; 
} 

答えて

4

さて、一度に1ステップずつ進めてください。

いくつかのJSON解析ライブラリのいずれかを使用すると、JSONからNSDictionaryを簡単に作成できます。 JSONKitを使って本当に楽しんでいます。あなたのプロジェクトに、JSONKitをインポートしたら、あなたはこのような何かを行うことができます。

NSString *url = @"http://dev.speechlink.co.uk/David/get_questionstest.php"; 
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]]; 
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
NSDictionary *questions = [json objectFromJSONString]; 
[json release]; 

は今、あなたはあなたの例では質問でいっぱいの配列を持っています。これで、この配列をループし、配列内のデータでデータを埋め込むことができます。さあ、実用的にしましょう。それぞれの質問に対して4つではなく1つのオブジェクトを管理しなければならないのであれば、それは簡単でしょう。各インスタンスに1つの質問を含むクラスを作成します。


インタフェース:

@interface Question : NSObject { 
    NSString *questionId; 
    NSString *question; 
    NSString *questionNumber; 
    NSString *sectionId; 
} 
@property(copy)NSString *questionID; 
@property(copy)NSString *question; 
@property(copy)NSString *questionNumber; 
@property(copy)NSString *sectionId; 

@end 

と実装:

@implementation Question 
@synthesize questionId, question, questionNumber, sectionID; 

@end 

今ではちょうど基本的な例です。何もない。これで、以前に持っていた配列をループすることができ、各質問のデータを含む「質問」オブジェクトを作成できます。私の目的のために、にquestionsArrayという名前の質問が含まれているとします。辞書をループし、辞書の質問をquestionsArray配列に追加します。

for (NSDictionary *q in questions) { 
    /* Create our Question object and populate it */ 
    Question *question = [[Question alloc]init]; 
    question.questionId = [q objectForKey:@"questionId"]; 
    question.question = [q objectForKey:@"question"]; 
    question.questionNumber = [q objectForKey:@"questionNumber"]; 
    question.sectionId = [q objectForKey:@"sectionId"]; 

    /* Add it to our question (mutable) array */ 
    [questionsArray addObject:question]; 
    [question release]; 
} 

多田!今度はQuestionオブジェクトでいっぱいの配列があります。質問オブジェクトのいずれかのプロパティを表示する場合は、そのプロパティにアクセスするだけで済みます。例えば、最初の質問の数をつかむために、あなただけのこの操作を行うことができます:私は私と私のコンパイラを持っていないよう

NSString *q1Number = [questionsArray objectAtIndex:0].questionNumber; 

が、これはすべてのテストされていないのでご注意ください。しかし、それはあなたを始めるはずです。 =)


編集:あなたは、あなたの要求は完全に間違ってやっていました。これを試してみてください:

+(NSDictionary*)getQuestions:(NSString*)sectionId from: (NSString*) url{ 
    NSDictionary *questions = nil; 
    NSURL *link = [NSURL URLWithString:url]; 
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link]; 
    [request setPostValue:sectionId forKey:@"section"]; 
    NSError *error = [request error]; 
    [request startSynchronous]; 

    if (!error) { 
     NSData *response = [request responseData]; 
     NSString *json = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
     questions = [json objectFromJSONString]; 
     [json release]; 
    } else{ 
     //UIAlertView to warn users there was an error 
    }    
    [request release]; 
    return questions; 
+0

こんにちは、返信ありがとうございます。質問でNSLogを実行すると、私はnullを返します、なぜこれが可能でしょうか? – user559142

+0

あなたのデータが正しく取得されていません。 ( 'NSDictionary * questions = [json objectFromJSONString];')この行から作成された 'questions'を記録してみてください。それにデータが含まれているかどうかを確認する –

+0

こんにちは、それもnullを返します。私はどこにいるのか分かりません;データを間違って取得しています。ブラウザのリンクをHTMLに表示すると(JSON文字列が正しく表示されます)、 – user559142

1

Stig Brautasetのexcを見てみましょう妥当なJSONパーサGitHub

さらに、いくつかのサンプルプロジェクトが含まれています。

あなたのPHPから、パーサーはNSDictionaryオブジェクトの生成と配列を期待します。質問2で何を意味するのかよく分かりませんが、配列全体を繰り返し処理して、NSDictionaryの値を持つカスタムの「質問」オブジェクトを作成できます。

これが役に立ちます。

3番目の質問が追加されていません。これは上記の "TweetStream"の例で答えられます。 Appleで説明されているNSURLConnectionDelegateメソッドを使用することをお勧めします。

関連する問題