2011-07-13 23 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(); 
} 
?> 

我建立了一個模型類(Question)在目標c中具有每行元素在行關聯數組中具有的確切屬性。

我的問題是:

1)我如何可以讀取目標C中的回顯的JSON數組元素和它們的相對屬性?

2)如何創建一個Question對象數組並將其映射到rows數組中的元素?我需要在我的方法「+(NSMutableArray *)getQuestions:(NSString *)部分:(NSString *)url」中寫入以捕獲來自PHP(回聲)的回覆?

編輯:

這裏是PHP的輸出:

http://dev.speechlink.co.uk/David/get_questionstest.php

UPDATE

使用ASIHTTPRequest更改方法 - 不能deserialise JSON字符串:

//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

好吧,讓我們一次一步地完成這一步。

通過使用幾種不同的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]; 

現在你擁有一個充滿在你的榜樣問題的數組。現在你可以遍歷這個數組,並用數據中的數據填充你的數據。現在讓我們切實可行。如果你只需要爲每個問題管理一個對象而不是四個,那會更容易,不是嗎?讓我們做一個包含每個實例一個問題的類。


接口:

@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 

現在這只是一個簡單的例子。沒有什麼花哨。現在,您可以循環訪問之前的數組,並創建包含每個問題數據的「問題」對象。出於我的目的,假設你有一個名爲questionsArrayNSMutableArray包含你想要使用的問題。我們將遍歷字典並將字典中的問題添加到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];')。看看是否包含數據。 –

+0

嗨,那也返回null。我不知道我在哪裏;錯誤地獲取數據。當在瀏覽器中查看鏈接到HTML(刪除發佈數據的所有集)時,JSON字符串會正確顯示。 – user559142

1

看看Stig Brautaset的感覺ellent JSON解析器,地址爲GitHub

甚至還有一些示例項目。

從您的PHP,人們會希望解析器產生和NSDictionary對象的數組。我不確定問題2中的含義,但可以遍歷數組並使用NSDictionary值創建自定義的「問題」對象。

希望這會有所幫助。

沒有看到您添加了第三個問題。這在上面的「TweetStream」示例中得到了回答。我建議您使用Apple所述的NSURLConnectionDelegate方法。