gpt4 book ai didi

objective-c - 等待完成 block 在 AFNetworking 请求中完成

转载 作者:太空狗 更新时间:2023-10-30 03:35:50 25 4
gpt4 key购买 nike

我正在使用 AFNetworking 发出 JSON 请求,然后调用 [operation waitUntilFinished] 以等待操作和成功或失败 block 。但是,它似乎是正确的 - 就日志消息而言,我得到“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");

最佳答案

这是通过使用 AFNetworking 设置请求,但进行同步调用然后手动处理完成 block 来实现的。很简单的。 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

关于objective-c - 等待完成 block 在 AFNetworking 请求中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10670892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com