等待完成块在AFNetworking要求完成(Waiting for completion bloc

2019-06-24 14:35发布

我正在与AFNetworking JSON请求,然后调用[操作waitUntilFinished]于操作和成败块等待。 但是,它似乎正确的,虽然下降 - 在日志消息方面,我得到“0”,“3”,“1”,而不是“0”,“1”,“3”

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://google.com"]];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFFormURLParameterEncoding;
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:@"query", @"q", nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:[url path] parameters:params];
NSLog(@"0");
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *innerRequest, NSHTTPURLResponse *response, id JSON) {
 NSLog(@"1");
 gotResponse = YES;
} failure:^(NSURLRequest *innerRequest, NSHTTPURLResponse *response, NSError *error, id JSON) {
  NSLog(@"2");
  gotResponse = YES;
}];
NSLog(@"Starting request");
[operation start];
[operation waitUntilFinished];
NSLog(@"3");

Answer 1:

这是通过使用AFNetworking设立的请求,但是进行同步调用,然后手动操作完成块。 非常简单。 AFNetworking似乎并不支持这一https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ ,虽然周围的工作是很简单的。

#import "SimpleClient.h"

#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
#import "AFJSONUtilities.h"

@implementation SimpleClient

+ (void) makeRequestTo:(NSString *) urlStr
        parameters:(NSDictionary *) params
        successCallback:(void (^)(id jsonResponse)) successCallback 
        errorCallback:(void (^)(NSError * error, NSString *errorMsg)) errorCallback {

   NSURLResponse *response = nil;
   NSError *error = nil;

   NSURL *url = [NSURL URLWithString:urlStr];

   AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

   httpClient.parameterEncoding = AFFormURLParameterEncoding;

   NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:[url path] parameters:params];
   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

   if(error) {
      errorCallback(error, nil);
   } else {
      id JSON = AFJSONDecode(data, &error);
      successCallback(JSON);
   }
}

@end


Answer 2:

这应该(几乎)工作。 您对通话

NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:[url path] parameters:params];

或许不应当通过[url path]path:参数。 在AFNetworking土地,这条道路是基础URL后一切(例如基础URL可以是“http://google.com”和路径“/ Gmail的”或其他)。

话虽这么说,它可能不是一个好主意,使异步操作与waitUntilFinished线程阻塞同步操作,但我敢肯定,你有你的理由...;)



Answer 3:

我有同样的问题,发现了不同的解决方案。 我有一种互相依赖的两个操作,但是可以并行加载。 然而,第一个完成块完成之前不能执行所述第二操作的完成块。

科林指出,这可能是一个不错的选择使Web请求块。 这对我来说是必不可少的,所以我做到了异步。

这是我的解决方案:

// This is our lock
@interface SomeController () {
    NSLock *_dataLock;
}
@end

@implementation

// This is just an example, you might as well trigger both operations in separate
// places if you get the locking right
// This might be called e.g. in awakeFromNib
- (void)someStartpoint {
    AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:[NSURLRequest requestWithURL:url1]
                                                                                         success:^(NSURLRequest *request, NSHTTPURLResponse *response, id data) {
        // We're done, we unlock so the next operation can continue its
        // completion block
        [_dataLock unlock];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) {
        // The request has failed, so we need to unlock for the next try
        [_dataLock unlock];
    }];

    AFJSONRequestOperation *operation2 = [AFJSONRequestOperation JSONRequestOperationWithRequest:[NSURLRequest requestWithURL:url2]
                                                                                         success:^(NSURLRequest *request, NSHTTPURLResponse *response, id data) {
        // The completion block (or at least the blocking part must be run in a
        // separate thread
        [NSThread detachNewThreadSelector:@selector(completionBlockOfOperation2:) toTarget:self withObject:data];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) {
        // This second operation may fail without affecting the lock
    }];

    // We need to lock before both operations are started
    [_dataLock lock];

    // Order does not really matter here
    [operation2 start];
    [operation1 start];
}

- (void)completionBlockOfOperation2:(id)data {
    // We wait for the first operation to finish its completion block
    [_dataLock lock];

    // It's done, so we can continue

    // We need to unlock afterwards, so a next call to one of the operations
    // wouldn't deadlock
    [_dataLock unlock];
}

@end


Answer 4:

使用委托方法调用

里面放块的方法下载/上传完成时将调用本身。



文章来源: Waiting for completion block to complete in an AFNetworking request