如何使用sendAsynchronousRequest:queue:completionHandler:

时间:2012-02-14 01:17:06

标签: iphone ios nsurlconnection

两部分问题

第一部分: 我正在尝试为我的数据库创建一个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:

但是我不确定要传递给queue或completionHandler的内容......我们非常感谢任何示例/解决方案。

第二部分: 我一直在阅读有关多任务的内容,我想通过确保在有中断的情况下完成连接请求来支持它。我一直关注这个example

其中解释了如何在发生中断时获得更多时间,我明白它在做什么......但不知道如何将其应用于此连接?如果您有任何示例/教程来帮助我弄清楚如何应用它将会很棒!

6 个答案:

答案 0 :(得分:114)

第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];
}];

答案 1 :(得分:38)

以下是一个示例:

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);
         }

     }];

答案 2 :(得分:26)

对于队列参数,请试试这个魔术:

[NSOperationQueue mainQueue]

如果您在请求完成时更新UI,那么这很有用,因为主队列是主线程。它基本上为您提供NSURLConnection的先前行为。但是,如果您计划写入文件或解压缩,则可以在后台队列上完成,然后将异步调度回主队列以进行UI更新。

答案 3 :(得分:9)

我一直在研究类似的问题,我发布了这个问题并得到了明确的答案here,我希望这对第2部分有帮助。

对于第1部分,其他人在这里提到的是好的,但你需要添加另一张支票(我在下面修改了答案)。您的请求可能会返回说404错误(找不到页面),在这种情况下您将无法获取并且错误和数据将是> 0. 200是一个很好的响应,你也可以检查StatusCode 404或其他什么。

     [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[[NSOperationQueue alloc] init]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error) 
    {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
     if ([data length] >0 && error == nil && [httpResponse statusCode] == 200)
     {

                    // DO YOUR WORK HERE

     }

答案 4 :(得分:3)

由于iOS 9中已弃用sendAsynchronousRequest:urlRequest queue:queue completionHandler:,因此建议使用NSURLSession's -dataTaskWithRequest:completionHandler:。自iOS 7 and later以来可以使用。

原件:

 NSURL *URL = [NSURL URLWithString:@"http://example.com"];
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];

 [NSURLConnection sendAsynchronousRequest:request
                                    queue:[NSOperationQueue mainQueue]
                        completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
     // ...
 }];

通过NSURLSession:

 NSURL *URL = [NSURL URLWithString:@"http://example.com"];
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];

 NSURLSession *session = [NSURLSession sharedSession];
 NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                         completionHandler:
     ^(NSData *data, NSURLResponse *response, NSError *error) {
         // ...
     }];

 [task resume];

答案 5 :(得分:2)

sendAsynchronousRequest已在Swift中弃用。转到dataTaskWithRequest,幸运的是,它的使用方式几乎相同。

if let url = NSURL(string:"http://your_url") {

    let request:NSURLRequest = NSURLRequest(URL: url)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)

    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

    });

    task.resume()
}