How to set timeout interval for RESTKIT Object Man

2019-05-06 16:03发布

问题:

I am using the RESTKIT Object Manager to get information from my server. The snippet of my implementation code is as follows:

-(void)getObjects
{
    //Instantiate the RestKit Object Manager
    RKObjectManager *sharedManager = [RKObjectManager sharedManager];

    //show the spinner
    [self showLoading];

    //call server with the resourcepath
    [sharedManager loadObjectsAtResourcePath:self.resourcePath delegate:self];
}

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects 
{

    // handling in scenarios of empty arrays
    if ( [objects count]==0 ){
        [self hideLoading];
        if (emptyHandler){
            emptyHandler();
        }else{
            [self standardEmptyHandling];            
        }
        return;
    }

    // planned failure
    if ( [[objects objectAtIndex:0] isKindOfClass:[Failure class]]){
        NSAssert([objects count]==1,@"object returned is type failure, but there are more than one object in it");
        failureObject=[objects objectAtIndex:0];
        [self hideLoading];
        [self standardErrorHandling];
        return;
    }

    //return completion block to caller
    completionHandler(objects);

}

However there might be cases whereby there is a server error or reachability error this causing the process to continue trying for a long duration before terminating (spinner will be displayed for an extended amount of time_.

Is there a way to set a timeout duration in my implementation so that I can prompt the user an alert to try again if the server does not respond in 20 secs for example?

回答1:

This has now been resolved by RestKit contributors in this pull request https://github.com/RestKit/RestKit/pull/491 and can be set easily as follows:

RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:@"http://..."];
objectManager.client.timeoutInterval = 30.0; // 30 seconds


回答2:

Apple's default timeout for URL requests is 60 secs.

Here is a discussion about the pending issue in RestKit:

http://groups.google.com/group/restkit/browse_thread/thread/8672eba8b1901f5d

A NSTimer could be an easy way around.

#pragma mark - RKRequestDelegate
- (void)requestDidStartLoad:(RKRequest *)request {
   [NSTimer scheduledTimerWithTimeInterval:20.0
       target:self
       selector:@selector(handleRequestTimeout)
       userInfo:nil
       repeats:NO];
}