通过重试将NSOperation子类化为互联网操作

Ida*_*she 4 multithreading objective-c nsoperation ios

我在后台线程中将NSOperation子类化为http post.那些特定的http帖子不需要返回任何值.

我想要做的是当我出现错误或超时时我希望它在增加延迟后发送(斐波那契).

到目前为止我已经这样做了:

NSInternetOperation.h:

#import <Foundation/Foundation.h>

@interface NSInternetOperation : NSOperation
@property (nonatomic) BOOL executing;
@property (nonatomic) BOOL finished;
@property (nonatomic) BOOL completed;
@property (nonatomic) BOOL cancelled;
- (id)initWebServiceName:(NSString*)webServiceName andPerameters:(NSString*)parameters;
- (void)start;
@end
Run Code Online (Sandbox Code Playgroud)

NSInternetOperation.m:

#import "NSInternetOperation.h"

static NSString * const kFinishedKey = @"isFinished";
static NSString * const kExecutingKey = @"isExecuting";

@interface NSInternetOperation ()
@property (strong, nonatomic) NSString *serviceName;
@property (strong, nonatomic) NSString *params;
- (void)completeOperation;
@end

@implementation NSInternetOperation

- (id)initWebServiceName:(NSString*)webServiceName andPerameters:(NSString*)parameters
{
    self = [super init];
    if (self) {
        _serviceName = webServiceName;
        _params = parameters;
        _executing = NO;
        _finished = NO;
        _completed = NO;
    }
    return self;
}

- (BOOL)isExecuting { return self.executing; }
- (BOOL)isFinished { return self.finished; }
- (BOOL)isCompleted { return self.completed; }
- (BOOL)isCancelled { return self.cancelled; }
- (BOOL)isConcurrent { return YES; }

- (void)start
{
    if ([self isCancelled]) {
        [self willChangeValueForKey:kFinishedKey];
        self.finished = YES;
        [self didChangeValueForKey:kFinishedKey];
        return;
    }

    // If the operation is not cancelled, begin executing the task
    [self willChangeValueForKey:kExecutingKey];
    self.executing = YES;
    [self didChangeValueForKey:kExecutingKey];

    [self main];
}

- (void)main
{
    @try {
        //
        // Here we add our asynchronized code
        //
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSURL *completeURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kWEB_SERVICE_URL, self.serviceName]];
            NSData *body = [self.params dataUsingEncoding:NSUTF8StringEncoding];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:completeURL];
            [request setHTTPMethod:@"POST"];
            [request setValue:kAPP_PASSWORD_VALUE forHTTPHeaderField:kAPP_PASSWORD_HEADER];
            [request setHTTPBody:body];
            [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)body.length] forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];


            if (__iOS_7_AND_HIGHER)
            {
                NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
                NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:[Netroads sharedInstance] delegateQueue:[NSOperationQueue new]];
                NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                    if (error)
                    {
                        NSLog(@"%@ Error: %@", self.serviceName, error.localizedDescription);
                    }
                    else
                    {
                        //NSString *responseXML = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                        //NSLog(@"\n\nResponseXML(%@):\n%@", webServiceName, responseXML);
                    }
                }];
                [dataTask resume];
            }
            else
            {
                [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                    if (connectionError)
                    {
                        NSLog(@"%@ Error: %@", self.serviceName, connectionError.localizedDescription);
                    }
                    else
                    {
                        //NSString *responseXML = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                        //NSLog(@"\n\nResponseXML(%@):\n%@", webServiceName, responseXML);
                    }
                }];
            }
        });

        [self completeOperation];
    }
    @catch (NSException *exception) {
        NSLog(@"%s exception.reason: %@", __PRETTY_FUNCTION__, exception.reason);
        [self completeOperation];
    }
}

- (void)completeOperation
{
    [self willChangeValueForKey:kFinishedKey];
    [self willChangeValueForKey:kExecutingKey];

    self.executing = NO;
    self.finished = YES;

    [self didChangeValueForKey:kExecutingKey];
    [self didChangeValueForKey:kFinishedKey];
}

@end
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 6

几个反应:

  1. 在您解决重试逻辑,你应该将你的调用[self completeOperation]到内部的完成块NSURLSessionDataTask或sendAsynchronousRequest.您当前的操作类过早地完成(因此不会遵循依赖关系和您的网络操作队列的意图maxConcurrentOperationCount).

  2. 重试逻辑似乎不起眼.也许是这样的:

    - (void)main
    {
        NSURLRequest *request = [self createRequest]; // maybe move the request creation stuff into its own method
    
        [self tryRequest:request currentDelay:1.0];
    }
    
    - (void)tryRequest:(NSURLRequest *)request currentDelay:(NSTimeInterval)delay
    {
        [NSURLConnection sendAsynchronousRequest:request queue:[self networkOperationCompletionQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    
            BOOL success = NO;
    
            if (connectionError) {
                NSLog(@"%@ Error: %@", self.serviceName, connectionError.localizedDescription);
            } else {
                if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                    NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
                    if (statusCode == 200) {
                        // parse XML response here; if successful, set `success` to `YES`
                    }
                }
            }
    
            if (success) {
                [self completeOperation];
            } else {
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
                dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
                    NSTimeInterval nextDelay = [self nextDelayFromCurrentDelay:delay];
                    [self tryRequest:request currentDelay:nextDelay];
                });
            }
        }];
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 就个人而言,我对这整个努力都很谨慎.令我感到震惊的是你应该根据错误的类型使用逻辑.值得注意的是,如果错误是由于缺少互联网连接而导致的失败,您应该使用可达性来确定连接并响应通知,以便在恢复连接时自动重试,而不仅仅是在规定的重试间隔的数学级别重试.

    除了网络连接(使用Reachability可以更好地解决)之外,我还不清楚其他网络故障是否需要重试逻辑.

一些不相​​关的观察:

  1. 注意,我dispatch_async已经将请求发布main到后台队列中消除了,因为您已经使用了异步方法(即使您没有,也可能将此操作添加到后台队列中).

  2. 我还删除了try/ catchlogic,因为与其他语言/平台不同,异常处理不是处理运行时错误的首选方法.通常,Cocoa中的运行时错误通过NSError.在Cocoa中,异常通常仅用于处理程序员错误,但不用于处理用户将遇到的运行时错误.请参见Apple的处理错误的用Objective-C编程指南.

  3. 如果只是在各自的声明中为属性定义适当的getter方法,则可以删除手动实现isExecuting和isFinishedgetter方法:

    @property (nonatomic, readwrite, getter=isExecuting) BOOL executing;
    @property (nonatomic, readwrite, getter=isFinished)  BOOL finished;
    
    Run Code Online (Sandbox Code Playgroud)
  4. 但是,您可能希望编写自己的setExecuting和setFinishedsetter方法,如果需要,可以为您执行通知,例如:

    @synthesize finished  = _finished;
    @synthesize executing = _executing;
    
    - (void)setExecuting:(BOOL)executing
    {
        [self willChangeValueForKey:kExecutingKey];
        _executing = executing;
        [self didChangeValueForKey:kExecutingKey];
    }
    
    - (void)setFinished:(BOOL)finished
    {
        [self willChangeValueForKey:kFinishedKey];
        _finished = finished;
        [self didChangeValueForKey:kFinishedKey];
    }
    
    Run Code Online (Sandbox Code Playgroud)

    然后,当您使用的setter它会做的通知你,你可以删除willChangeValueForKey和didChangeValueForKey你已经散布你的代码.

  5. 另外,我认为你不需要实现isCancelled方法(因为已经为你实现了).但是你真的应该覆盖一个cancel调用它的super实现的方法,但也取消你的网络请求并完成你的操作.或者,cancel您可以转移到delegate网络请求的基础再现,而不是实现方法,但请确保检查方法[self isCancelled]内部didReceiveData.

    并且isCompleted让我感到多余isFinished.看起来你可以完全消除completed财产和isCompleted方法.

  6. 你可能会不必要地同时支持复制的网络代码量NSURLSession和NSURLConnection.如果你真的想要,你可以做到这一点,但他们向我们保证NSURLConnection仍然支持,所以它让我感到不必要(除非你想享受NSURLSessioniOS 7+设备的一些特定功能,你目前没有这些功能).做任何你想做的事,但就个人而言,我正在使用NSURLConnection我需要支持早期iOS版本的地方,而NSURLSession我不支持,但除非有一些令人信服的业务要求,否则我不会倾向于实现这两者.