2
我想發送以下請求到服務器。服務器已經知道如何處理它,但我該如何發送它?如何從iOS應用程序執行URL請求?
http://www.********.com/ajax.php?script=logoutUser&username=****
我想發送以下請求到服務器。服務器已經知道如何處理它,但我該如何發送它?如何從iOS應用程序執行URL請求?
http://www.********.com/ajax.php?script=logoutUser&username=****
爲你會做以下同步請求:
NSURL *url = [NSURL URLWithString:@"http://www.********.com/ajax.php?script=logoutUser&username=****"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//send it synchronous
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// check for an error. If there is a network error, you should handle it here.
if(!error)
{
//log response
NSLog(@"Response from server = %@", responseString);
}
更新:做一個異步請求,請參考,本example
你可以這樣做:
NSString *resp = [NSString stringWithContentsOfURL:url usedEncoding:enc error: &error];
我不認爲這是一個好主意,推薦向初學者的iOS開發人員發送同步請求,這些開發人員可能不瞭解/理解阻止UI的含義。他們最終只能製作出沒有響應的應用程序,可能會讓他們從應用程序商店中被拒絕。在開發論壇上有一篇由eskimo1撰寫的文章,概述了所有其他選項。實現異步網絡的最簡單方法是使用新的'NSURLConnection'異步完成塊方法:'[NSURLConnection sendAsynchronousRequest:queue:completionHandler]'。 –
@JackLawrence你的意見,我會建議最簡單的解決方案,如果他然後覺得他需要一個更具響應性的解決方案,他會搜索或稍後請求它,反正這不是一個很好的理由, ,答案是正確的,雖然它不適用於你的意見:) –
完美的作品,謝謝 – user1447339