2011-07-08 64 views
0

我有一個iPhone應用程序將數據發佈到一個php應用程序,後者又將這些數據存儲在遠程mysql數據庫中。PHP到目標C(iPhone應用程序)通信

我想讓php文件通知iphone應用程序存儲是否成功。這是我的PHP代碼:

<?php 

//connect to database 
function connect() { 
    $dbh = mysql_connect ("localhost", "123", "456789") or die ('I cannot connect to the database because: ' . mysql_error()); 
    mysql_select_db("PDS", $dbh); 
    return $dbh; 
} 

//store posted data 
if(isset($_POST['message'])){ 
    $message = $_POST['message']; 
    $dbh = connect(); 
    $query = "INSERT INTO messages (message) VALUES ('$message')"; 
    $result = mysql_query($query) or die ("didn't query");   
} 
?> 

1)我將如何修改上面的PHP文件呼應根據請求的SQL查詢的成功/失敗的東西嗎?

2)哪一部分的客觀C API的處理閱讀PHP變量

回答

1

有Objective-C和PHP之間沒有直接的溝通。您可以使用NSURLConnection或更好的方式在Objective-C中查詢Web-URL ASIHttp。被查詢的資源然後用你正在給它的參數(在你的情況下,通過發佈給它)做一些事情並返回一些東西。通常,您同意標準(例如JSON)事先進行通信,或者只是使用HTTP-Statuscodes來處理這類內容。比你可以exmaine由NSURLConnection給予的迴應(看文檔),並找出發生了什麼在服務器上

更新:ASI-Http的優點是更直接使用,它封裝了很多低爲你的級別的東西。否則,它執行與NSURLConnection相同的操作

下一次更新: 下面是ASIHTTP和正確的字符串解析的解決方案。這將使用HTTP GET,PUT後會不會更加困難

NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; 
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
[request startSynchronous]; 
NSError *error = [request error]; 
if (!error) { 
    NSString *response = [request responseString]; 
    NSArray *results = [response componentsSeparatedByString:@", "]; 
    for (NSString* result in results) { 
    NSString * trimmedResult = [result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
    if ([trimmedResult isEqualToString:@"failure"]) 
    NSLog(@"operation %i failed.", i + 1); 
    } 
} 
+0

爲什麼ASIHTTP比NSURLConnection更好? – user559142

+0

更新了答案 – LordT

1

就直接讓PHP的回聲到頁面上,有iPhone應用程序獲得頁面的內容,並分析它們。

例如如果php頁面回聲success, failure, success,您可以使用:

NSString *contents = readthepage (google how to do this) 
NSArray *results = [contents componentsSeparatedByString:@", "]; 
for (int i = 0; i < [results count]; i++) { 
    NSString *result = [results ObjectAtIndex:i]; 
    if ([result rangeOfString:@"failure"].length > 0) // this isn't the perfect test, it checks whether _result_ contains the string @"failure", not is equal to. If it matters to you, find a different method. 
     NSLog(@"operation %i failed.", i + 1); 
    } 
} 
+0

你不能測試NSString的平等。相反,您必須執行[result isEqualToString:@「failure」]例如。在這裏,你正在測試指針相等而不是值相等。 – Cyrille

+0

我意識到,正如我在寫它時,我只是忘了寫它的正確方法。根據我的經驗,'isEqualToString'並不總是正確地工作。我通常使用'rangeOfString'。 – Greg

+0

你應該在比較之前修剪你的結果字符串 – LordT

相關問題