相关疑难解决方法(0)

AFNetworking可以同步返回数据(在块内)吗?

我有一个使用AFJSONRequestOperation的函数,我希望仅在成功后返回结果.你能指出我正确的方向吗?对于块和AFNetworking,我仍然有点无能为力.

-(id)someFunction{
    __block id data;

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
        success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json){
            data = json;
            return data; // won't work
        }
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){

        }];



    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation: operation];

    return data; // will return nil since the block doesn't "lock" the app.
}
Run Code Online (Sandbox Code Playgroud)

synchronous ios objective-c-blocks afnetworking

46
推荐指数
4
解决办法
4万
查看次数

等待完成块在AFNetworking请求中完成

我正在使用AFNetworking发出JSON请求,然后调用[operation 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");
Run Code Online (Sandbox Code Playgroud)

objective-c synchronous nsoperation afnetworking

7
推荐指数
1
解决办法
2万
查看次数