ageorgios
ageorgios

Reputation: 323

Using RestKit to perform a synchronous request

- (BOOL)do_a_Restkit_request_and_return_a_boolean
{
     [manager postObject:nil path:@"/mypath" parameters:@{@"password":password} success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
          myResult = [mappingResult firstObject] == 5;
      } failure:^(RKObjectRequestOperation *operation, NSError *error) {
      }];

      return myResult;

}

Hello I would like to make a RestKit call like the above Synchronous so as to return myResult after the call of the Success block.

Upvotes: 3

Views: 2140

Answers (2)

Aaron Brager
Aaron Brager

Reputation: 66242

You can use an approach like this:

NSMutableURLRequest *request = // create a request…
RKObjectRequestOperation *operation = [manager objectRequestOperationWithRequest:request success:nil failure:nil];
[operation start];
[operation waitUntilFinished];

BOOL myResult = NO;

if (!operation.error) {
      myResult = [operation.mappingResult firstObject] == 5;
}

return myResult;

Notes:

  • The completion blocks are called after the operation is finished, so if you provide success/failure blocks, they won't be called until after the method returns
    • (This is why I suggest you pass nil into the completion blocks.)
  • waitUntilFinished will block whatever thread you're on, so make sure it's not the main thread.
  • If you need help creating request, see Creating Request Objects in the RKObjectManager Class Reference.
  • Again, if you can rewrite your code to work asynchronously, that will probably be better than this solution.

Upvotes: 4

Wain
Wain

Reputation: 119031

You need to either embrace the asynchronous nature of network communication and background processing of the response, or use a different API / technology specifically for making synchronous requests. RestKit and AFNetworking are based more around the former.

Embracing asynchronous is the best option...

That said, you could use RestKit to create the NSURLRequest, then use NSURLConnection to synchronously download the response, then use RKMapperOperation to perform the mapping (and wait for completion with addOperations:waitUntilFinished:).

Upvotes: 2

Related Questions