Using RestKit to perform a synchronous request

雨燕双飞 提交于 2020-01-04 01:58:15

问题


- (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.


回答1:


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.



回答2:


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:).



来源:https://stackoverflow.com/questions/20589064/using-restkit-to-perform-a-synchronous-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!