使用异步操作iOS的结果

时间:2015-03-19 11:02:32

标签: ios web-services asynchronous

您好我想从类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

2 个答案:

答案 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.
}];