如何从iOS应用程序执行URL请求?

use*_*339 2 iphone url cocoa-touch objective-c

我想将以下请求发送到服务器.服务器已经知道如何处理它,但我该如何发送它?

http://www.********.com/ajax.php?script=logoutUser&username=****
Run Code Online (Sandbox Code Playgroud)

Oma*_*ith 9

对于同步请求,您将执行以下操作:

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);
}
Run Code Online (Sandbox Code Playgroud)

更新:对于执行异步请求,请参考此示例

  • 我认为向初学者iOS开发人员推荐同步请求并不是一个好主意,他们可能不理解/欣赏阻止UI的含义.他们最终制作了无法响应的应用,可能会让他们从应用商店中被拒绝.eskimo1在开发论坛上写了一篇文章,概述了你所有的其他选择.实现异步网络的最简单方法是使用新的`NSURLConnection`异步完成块方法:`[NSURLConnection sendAsynchronousRequest:queue:completionHandler]`. (2认同)