سؤال

I am using RestKit in my Objective-C project and need to specify a timeout for a call to my service of around 10 seconds.

After reading around, it doesn't look like RestKit supports this, so my plan is to:

  • Start a timer when my request is sent
  • When the data is loaded, disable the timer

Here's my problem...

If the timer method fires, I need to cancel the request and invoke the method below manually. I'm not 100% sure how to achieve this.

There's some context in my other question, showing how RestKit is implemented in my project and what it's doing in this case.

Many thanks in advance for any help you can give me on this one.

- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error { 
     NSLog(@"Hit error: %@", error); 
}
هل كانت مفيدة؟

المحلول

You can use cancelRequestsWithDelegate: selector in order to achieve the described workflow.

- (void)cancelAfterTimeout {
    [[[[RKObjectManager sharedManager] client] requestQueue] cancelRequestsWithDelegate:self];
    NSError *myError = [[[NSError alloc] initWithDomain:NSPOSIXErrorDomain
            code:12345 userInfo:nil] autorelease];
    //feel free to customize the error code, domain and add userInfo when needed.
    [self handleRestKitError:myError];
}

However, it might be tricky to invoke that delegate error handler, but you can work around it by creating new, separate error handler like this:

- (void)handleRestKitError:(NSError*)error {
    //do something with the error
}

and modify the body of your didFailWithError: method:

- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error { 
     [self handleRestKitError:error] 
}

نصائح أخرى

In RestKit version 0.20.x you can cancel scheduled requests using

[[RKObjectManager sharedManager]
    cancelAllObjectRequestOperationsWithMethod:RKRequestMethodAny
                           matchingPathPattern:YOUR_PATTERN];

You can always end up with: [[RKObjectManager sharedManager].operationQueue cancelAllOperations]; Each of your requests will finish with error -999 (operation cancelled). You can check the error.code and perform appropriate action.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top