使用AFNetworking(AFHTTPClient子类)将JSON发送到服务器=>这是一个异步操作

时间:2013-01-27 18:14:25

标签: ios json asynchronous afnetworking

经过大量研究后,我想出了如何从我的iOS 6客户端向我的rails服务器发送NSDictionary。我用了AFNetworking。下面是发送JSON的客户端代码。但是,我不确定这是否是异步调用,因为我没有看到正在使用操作队列的位置。如果不是,那么如何将其变为异步调用?

  -(void)sendEntryToServerAsJSON:(EntryParent*)_entryToBeSaved
  {
     NSDictionary* dictToBeSerialized = [_entryToBeSaved convertEntryParentObjToDict];


     [[appAPIClient sharedClient]postPath:@"entries.json"
                          parameters:dictToBeSerialized
                             success:^(AFHTTPRequestOperation *operation, id responseObject) {
       NSLog(@"Successfully sent JSON %@", [responseObject description]);
      }
                             failure:^(AFHTTPRequestOperation *operation, NSError *error)    {
       NSLog(@"Could not send JSON %@", [error description]);
      }];
  }

这是我对AFHTTPClient的实现

 + (appAPIClient *)sharedClient
 {
   NSLog(@"Inside appAPIClient sharedclient ");
   static appAPIClient *_sharedClient = nil;
   static dispatch_once_t oncePredicate;
   dispatch_once(&oncePredicate, ^{
    _sharedClient = [[self alloc]
                     initWithBaseURL:[NSURL URLWithString:URL_STR]];
  });

   return _sharedClient;
 }
 //==============================================================================

 - (id)initWithBaseURL:(NSURL *)url
 {
   self = [super initWithBaseURL:url];
   if (!self)
  {
    return nil;
   }
   NSLog(@"init with base url - appAPIClient");
   [self registerHTTPOperationClass:[AFJSONRequestOperation class]];

   // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:@"Accept" value:@"application/json"];

   return self;
}

我希望得到任何反馈,以改进此代码并使其异步。

1 个答案:

答案 0 :(得分:0)

到a)

请求被添加到主线程runloop中,因此它们在没有线程或队列的情况下是异步的。 runloops有点像C的select方法

见:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html

到b)请另外提出问题:)