您好我想从类DataViewController
获取异步块的结果,以便在课程MagazineViewController
中使用它,但我不会获得returnedData
的值,除非{第一次调用{1}}方法,因为操作是异步的,我知道我必须实现一个完成块并调用它,但我不知道该怎么做,这是我的代码,我如何编辑它以给我ViewDidLoad
块中返回的值并在其他类中使用它
DataViewController.m
setCompletionBlockWithSuccess
}
MagazineViewController类(我想在哪里使用- (void)getDataFromServer:(NSString *)urlString completion:(void (^)(AFHTTPRequestOperation *operation, id responseObject))completion {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSURLCredential *credential = [NSURLCredential credentialWithUser:userName password:Password persistence:NSURLCredentialPersistenceNone];
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:urlString parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCredential:credential];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:completion failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
} ];
[manager.operationQueue addOperation:operation];
)
returnedData
答案 0 :(得分:0)
您应该内联completion
。在调用NSLog
之前调用了您的第一个completion
语句,因此尚未设置returnedData
变量。
@implementation MagazineViewController
- (void)viewDidLoad {
[super viewDidLoad];
DataViewController *dataViewController = [[DataViewController alloc] init];
[dataViewController getDataFromServer:@"http://firstluxe.com/api/search/search?query=vogue&language=1&output_format=JSON"
completion:^ (AFHTTPRequestOperation *operation, id responseObject) {
returnedData = responseObject;
NSLog(@"returned %@ ", returnedData);
}];
}
@end
答案 1 :(得分:-1)
[self getDataFromServer:@"API URL" completion:^(int *operation, id responseObject) {
// Result from async method here.
}];