有很多方法可以做到這一點,一些「更正確」比別人:-)但你是正確的。 我解釋了我會在類似情況下做什麼:
1-對於PHP引擎,您應該創建一個API來訪問您的數據。哪些數據? 最簡單,也許你可以做的第一件事就是測試(僅用於測試目的!)是創建一個頁面,通過POST從您的ios APP接收查詢並用編碼的JSON字符串回答。使用JSON,您可以傳輸整個對象層次結構:變量,數組,字典......由您決定如何將對象鏈接在一起。 如果您想對數據進行編碼是一個表,你可以做一些與此類似:
// first connect to the database and execute the query, then...
$data = array();
while(!$RS->EOF){
for ($i = 0; $i < $cols; $i++){
$rowName = utf8_encode($RS->Fields[$i]->name);
$rowValue = utf8_encode($RS->Fields[$i]->value);
$rowData[$rowName] = $rowValue;
}
array_push($data, $rowData);
$RS->MoveNext();
}
$response['data'] = $data;
echo json_encode($response);
結果與第一字典,一個名爲「數據」鍵JSON對象。 在「數據」鍵裏面有一個字典數組。每個字典有關鍵的列名,併爲數據的列值:
data = (
{
attivita = "this is the first row in the table";
id = 2548;
},
{
attivita = "this is the second row in the table";
id = 2547;
};
}
您只需使用json_encode來創建JSON字符串。
在iPhone端,我建議你下載並使用AFNetworking。這是一個非常好的和開源框架,有很多內置的對象和方法對HTTP/HTTPS請求,XML,JSON ECC ... 使用AFNetworking你可以以類似的方式請求:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:@"http://url.for.the.php.page"];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:mainPath parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// your success code here
// remember, the first object is a dictionary with a key called data
NSArray *arrayOfData = [JSON objectForKey:@"data"];
NSMutableArray *arrayOfActivities = [NSMutableArray array];
for (NSDictionary *objectDictionary in arrayOfData) {
// objectDictionary is your dictionary containing
// a key with the column name and a value with the column content
// here you can init your custom objects
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// your failure code here
}];
[operation start];
正如你所看到的,JSONRequestOperationWithRequest:方法完成處理程序返回你解碼JSON,這樣你就可以訪問你的字典/陣列直接使用objectForKey或objectAtIndex ;-)
最後建議:在生產和安全的環境,你應該避免通過發佈請求發送查詢。我在這裏粘貼的代碼是用於私人應用程序(僅供我用於測試目的)。最好爲每種請求和安全的身份驗證方法使用不同的API(查看oAuth)。 我建議你看看Instagram或Twitter API(Instagram更簡單),試圖使用它。他們會給你一些關於如何創建你自己的API的想法。
祝你好運
在url 38917這是什麼?方法? –
這只是我編寫的一個數字,它是一個PHP模塊請求的示例URL結構。通常你會在URL請求中看到方法參數,所以我選擇的數字可以表示類似於數據庫中對象的唯一標識符。 –