如何使用sendAsynchronousRequest:queue:completionHandler: [英] how to use sendAsynchronousRequest:queue:completionHandler:
问题描述
两部分问题
第一部分:
我正在尝试为我的数据库创建一个ASynchronous请求。我目前正在同步这样做但是我想学习两种方法来更好地理解发生的事情。
Part one: I am trying to create an ASynchronous request to my database. I am currently doing it Synchronously however I want to learn both ways to better my understanding of whats going on.
目前我已经设置了这样的同步调用。
Currently I have set up my Synchronous call like this.
- (IBAction)setRequestString:(NSString *)string
{
//Set database address
NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:@"http://127.0.0.1:8778/instacodeData/"]; // imac development
//PHP file name is being set from the parent view
[databaseURL appendString:string];
//call ASIHTTP delegates (Used to connect to database)
NSURL *url = [NSURL URLWithString:databaseURL];
//SynchronousRequest to grab the data
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error;
NSURLResponse *response;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (!result) {
//Display error message here
NSLog(@"Error");
} else {
//TODO: set up stuff that needs to work on the data here.
NSString* newStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(@"%@", newStr);
}
}
我认为我需要做的就是更换电话
I think what I need to do is replace the call
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
与ASynchronous版本
with the ASynchronous version
sendAsynchronousRequest:queue:completionHandler:
但是我不知道该怎么做传递给queue或completionHandler ...非常感谢任何示例/解决方案。
however I'm not sure what to pass to queue or completionHandler... Any examples/solutions would be greatly appreciated.
第二部分:
我一直在阅读关于多任务,我想通过确保我的连接请求完成,如果有中断,支持它。我一直关注这个示例
在其中它解释了如何在发生中断时获得更多时间,我明白它在做什么......但不知道如何将它应用于此连接? !如果您有任何例子/教程,帮助我弄清楚如何运用它,这将是真棒
In it it explains how to gain more time if an interrupt occurs, I understand what its doing.. but not how to apply it to this connection? if you have any examples/tutorials to help me figure out how to apply it that would be awesome!
推荐答案
第1部分:
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
[delegate receivedData:data];
else if ([data length] == 0 && error == nil)
[delegate emptyReply];
else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
[delegate timedOut];
else if (error != nil)
[delegate downloadError:error];
}];
这篇关于如何使用sendAsynchronousRequest:queue:completionHandler:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!