两部分问题
第一部分:我正在尝试创建一个对我的数据库的ASynchronous请求。我目前正在同步进行,但我想同时学习这两种方法,以更好地理解正在发生的事情。
目前我已经像这样设置了我的同步调用。
- (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);
}
}我想我需要做的就是把电话
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];使用ASynchronous版本
sendAsynchronousRequest:queue:completionHandler:然而,我不确定要传递给队列或completionHandler的是什么……任何示例/解决方案都将不胜感激。
第二部分:我一直在读关于多任务处理的文章,我想通过确保我的连接请求在中断时完成来支持它。我一直在关注这个example
它解释了如果中断发生,如何获得更多的时间,我知道它在做什么。但不知道如何将其应用于此连接?如果您有任何示例/教程来帮助我弄清楚如何应用它,那将是非常棒的!
发布于 2012-02-14 09:58:24
PArt 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];
}];发布于 2012-05-02 23:45:07
下面是一个示例:
NSString *urlAsString = @"http://www.cnn.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error)
{
if ([data length] >0 && error == nil)
{
// DO YOUR WORK HERE
}
else if ([data length] == 0 && error == nil)
{
NSLog(@"Nothing was downloaded.");
}
else if (error != nil){
NSLog(@"Error = %@", error);
}
}];发布于 2013-06-26 05:42:36
对于队列参数,试试这个魔术:
[NSOperationQueue mainQueue]如果您要在请求完成时更新UI,这将非常有效,因为主队列是主线程。它本质上为您提供了NSURLConnection之前的行为。但是,如果您计划写入文件或解压缩,那么您可以在后台队列上完成,然后将异步调度回主队列以进行UI更新。
https://stackoverflow.com/questions/9270447
复制相似问题