gpt4 book ai didi

ios - NSOperationQueue 在响应 iOS 上再次运行相同的任务

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:15:51 26 4
gpt4 key购买 nike

在我的项目中,我需要将数据发送到服务器,为此我使用了以下代码来完成任务:

- (void)sendJSONToServer:(NSString *) jsonString
{
// Create a new NSOperationQueue instance.
operationQueue = [NSOperationQueue new];
//

// Create a new NSOperation object using the NSInvocationOperation subclass to run the operationQueueTask method
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(operationQueueTask:)
object:jsonString];
// Add the operation to the queue and let it to be executed.
[operationQueue addOperation:operation];
}//End of sendJSONToServer method

-(void) operationQueueTask:(NSString *) jsonString
{
//NSOperationQueue *remoteResultQueue = [[NSOperationQueue alloc] init];
dispatch_queue_t myQueue = dispatch_queue_create("SERVER_QUEUE",NULL);
dispatch_async(myQueue, ^{
// Performing long running process
// Sending json data to server asynchronously
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[jsonString length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_URL_eg_http://www.example.com"]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(@"Response is:%@",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];

dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
NSLog(@"Thread Process Finished");
});
});
}//End of operationQueueTask method

通过上面的代码,我可以发送数据并获得响应。

但是当没有互联网时,数据不会发送到服务器。如何根据我们得到的回应处理这种情况。

假设我们得到响应 success在公平条件下 an false在最坏的情况下。

重试更新代码
-(id)init
{
self = [super init];
if (self != nil)
{
//initialize stuffs here
pendingOperationQueue = [[NSMutableArray alloc] init];
operationQueue = [NSOperationQueue new];
}
return self;
}//End of init method

- (void)sendJSONToServer:(NSString *) jsonString
{
NSOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationQueueTask:) object:[NSString stringWithString:[pendingOperationQueue objectAtIndex:0]]];
[operation start];
}//End of sendJSONToServer method

-(void) operationQueueTask:(NSString *) jsonString
{
//NSOperationQueue *remoteResultQueue = [[NSOperationQueue alloc] init];
dispatch_queue_t myQueue = dispatch_queue_create("SERVER_QUEUE",NULL);
dispatch_async(myQueue, ^{
// Performing long running process
// Sending json data to server asynchronously
NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[jsonString length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_URL_http://www/example.com"]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(@"Response is:%@",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);

if([[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] rangeOfString:@"true"].location == NSNotFound)
{
// Add the operation to the queue and let it to be executed.
NSLog(@"Failed To Add To Server, Rerunning the task");
}
else
{
NSLog(@"Successfully Added To Server");
NSLog(@"ADDED_DATA_TO_SERVER: %@", jsonString);
if([pendingOperationQueue count] > 0)
{
[pendingOperationQueue removeObjectAtIndex:0];

if([pendingOperationQueue count] > 0)
{
NSOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationQueueTask:) object:[NSString stringWithString:[pendingOperationQueue objectAtIndex:0]]];
[operation start];
}
}
}
}];
});
}//End of operationQueueTask method

最佳答案

当心!这是一个很长的答案。 TL;DR:您不能重新运行 NSOperation ,但您可以设计您的类和方法,以便轻松重试请求。

首先快速回答您的标题问题:您不能重新运行 NSOperation ,它们的设计初衷并非如此。来自 docs :

An operation object is a single-shot object — that is, it executes its task once and cannot be used to execute it again.



顺便说一下,让我们看一下您当前正在做的事情并稍微清理一下,以便更轻松地重新使用它。那里有大量您不需要的异步内容;我会一点一点地经历它。

让我们从您的 operationQueueTask: 开始方法。您在该方法中做的第一件事是:
dispatch_queue_t myQueue = dispatch_queue_create("SERVER_QUEUE",NULL);

这意味着每次调用该方法时,您都在创建一个新的调度队列。如果您真的愿意,您可以这样做,但这并不是调度队列的真正设计目的。一个更好的主意是使用已经可用的后台队列之一:
dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

接下来,您将异步分派(dispatch)一个块到该队列。那个块:
  • 设置您的 NSMutableURLRequest .
  • 电话 [NSURLConnection sendAsynchronousRequest:...] .
  • 将另一个块(其中有关于更新 UI 的注释)分派(dispatch)到主队列。

  • 1 和 2 很好,我看不到您需要更改的任何内容。然而,3 是有问题的,因为调度被调用的位置。您现在的设置方式, NSURLConnection将触发其异步请求,然后,在有机会运行之前,您将块触发到主队列以更新 UI。您需要做的是在传递给 [NSURLConnection sendAsynchronousRequest:...] 的完成处理程序中触发该块。 .像这样:
    [NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
    NSLog(@"Response is:%@",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
    dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI
    NSLog(@"Thread Process Finished");
    });
    }];

    现在,注意您正在调用的方法的名称 NSURLConnection ? send Asynchronous Request: .它实际上为您处理在后台队列上排队的请求。这意味着,您实际上并不需要(或想要)所有 dispatch_*这个方法开头的东西。考虑到这一点,我们可以将其简化为:
    -(void) operationQueueTask:(NSString *) jsonString
    {
    NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[jsonString length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_URL_eg_http://www.example.com"]];

    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    [NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
    NSLog(@"Response is:%@",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
    dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI
    NSLog(@"Thread Process Finished");
    });
    }];
    } //End of operationQueueTask method

    现在,转到您的 sendJSONToServer:方法。您在这里做的事情与您在 operationQueueTask: 开始时所做的相似。 :您正在创建一个新的 NSOperationQueue每次运行时;这也不需要(通常也不需要)。您可能应该做的是创建 operationQueue当您的类初始化时(看起来它已经是您类上的实例变量,所以您在那里很好):
    // NOTE: I'm just using a default initializer here; if you already have an initializer, use that instead
    - (instancetype)init {
    if (self = [super init]) {
    operationQueue = [NSOperationQueue new];
    }
    return self;
    }

    这摆脱了你的第一行。接下来,您将创建一个 NSInvocationOperation其中调用 operationQueueTask:然后将其添加到您的 operationQueue .由于您一直在重新创建您的 operationQueue每次,我都会假设它不用于这些服务器请求以外的任何其他事情。在这种情况下,您实际上不需要在 operationQueue 上执行此操作。完全是因为,正如我们在之前的方法中发现的, NSURLConnection已经为您处理所有后台线程。在这种情况下,我们实际上可以从 operationQueueTask: 复制代码。至 sendJSONToServer:并摆脱 operationQueueTask:共。这使它看起来像:
    - (void)sendJSONToServer:(NSString*)jsonString {
    NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[jsonString length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_URL_eg_http://www.example.com"]];

    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    [NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
    NSLog(@"Response is:%@",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
    dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI
    NSLog(@"Thread Process Finished");
    });
    }];
    }

    注:我们还需要保留 operationQueue因为我们将它传递给 [NSURLConnection sendAsynchronousRequest:...作为它应该运行的队列。

    那么,当请求失败时,我们如何重试请求呢?最简单的方法是添加一个递归函数,在请求失败时调用自身。您将通过此方法 jsonString您想发送以及在它永远放弃之前应该尝试发送的最大次数。

    为了方便起见,让我们对现有函数再做一个更改:不要在函数内部处理完成块,而是让完成块成为您传递给函数的参数,以便它可以在其他地方进行处理。
    - (void)sendJSONToServer:(NSString*)jsonString withCompletionHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError))completionHandler {
    NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[jsonString length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"MY_URL_eg_http://www.example.com"]];

    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    [NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:completionHandler];
    }

    现在,让我们构建递归函数。我会称之为:
    - (void)sendJSONToServer:(NSString*)jsonString withRetryAttempts:(NSUInteger)retryTimes;

    基本流程将是:
  • 检查是否 retryTimes大于 0
  • 如果是,尝试将请求发送到服务器
  • 请求完成后,检查响应是否成功
  • 如果成功,更新主队列上的 UI
  • 如果不成功,从retryTimes减一并再次调用此函数

  • 这看起来像:
    - (void)sendJSONToServer:(NSString*)jsonString withRetryAttempts:(NSUInteger)retryTimes {
    if (retryTimes > 0) {
    [self sendJSONToServer:jsonString withCompletionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSLog(@"Response is:%@",[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
    if (/* check response to make sure it succeeded */) {
    dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI
    NSLog(@"Thread Process Finished");
    });
    } else {
    // Note: you can add a dispatch_after here (or something similar) to wait before the next attempt
    // You could also add exponential backoff here, which is usually good when retrying network stuff
    [self sendJSONToServer:jsonString withRetryAttempts:(retryTimes - 1)];
    }
    }];
    } else {
    // We're out of retries; handle appropriately
    }
    }

    注:其中有一些只是注释,因为它们是特定于应用程序的;它们需要在代码编译/运行之前实现。

    现在,而不是拨打 [yourClass sendJSONToServer:jsonString] ,电话: [yourClass sendJSONToServer:jsonString withRetryTimes:maxRetries]并且,如果请求失败,它应该重试到 maxRetries次。

    最后一点:正如@Deftsoft 提到的,Apple 的 Reachability 类是了解您是否与网络建立事件连接的好方法。在尝试调用 sendJSONToServer:withRetryTimes: 之前先检查一下是个好主意.这样,您就不会在最初甚至无法连接时尝试发出请求。

    关于ios - NSOperationQueue 在响应 iOS 上再次运行相同的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25525212/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com