【发布时间】:2012-07-04 15:14:41
【问题描述】:
我已经学习了一些教程,但我一直坚持执行 Post 请求。我只想将 3 个参数发送到 URL 和响应。而且它必须是异步的,因为它会给我一些图像,我想在视图上一张一张地显示。
你们能帮帮我吗?
【问题讨论】:
标签: ios cocoa request http-post
我已经学习了一些教程,但我一直坚持执行 Post 请求。我只想将 3 个参数发送到 URL 和响应。而且它必须是异步的,因为它会给我一些图像,我想在视图上一张一张地显示。
你们能帮帮我吗?
【问题讨论】:
标签: ios cocoa request http-post
这很好here。
但我发现这样做的方式更简单,我将向您展示。关于 SO 和其他提供此知识的地方仍然存在许多问题。
首先我们使用参数设置我们的请求:
- (NSData *)executePostCall {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", YOUR_URL]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *requestFields = [NSString stringWithString:@""];
requestFields = [requestFields stringByAppendingFormat:@"parameter1=%@&", parameter1];
requestFields = [requestFields stringByAppendingFormat:@"parameter2=%@&", parameter2];
requestFields = [requestFields stringByAppendingFormat:@"parameter3=%@", parameter3];
requestFields = [requestFields stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *requestData = [requestFields dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestData;
request.HTTPMethod = @"POST";
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error == nil && response.statusCode == 200) {
NSLog(@"%i", response.statusCode);
} else {
//Error handling
}
return responseData;
}
这必须包装在一个块中,因为我们不能在主线程上执行它,因为它会锁定我们的应用程序,这是不受欢迎的,所以我们执行以下操作来包装这个请求,我会其余细节由您决定:
dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *result = [self executePostCall];
dispatch_async(dispatch_get_main_queue(), ^{
// Handle your resulting data
});
});
dispatch_release(downloadQueue);
【讨论】:
NSURLConnection 文档是最好的资源 :) 来吧,真的很简单。
使用NSURLRequest。您可以在后台下载文件并在收到委托通知后显示:Downloading to a Predetermined Destination
【讨论】: