强制app等待方法完成(数据下载)

时间:2014-06-02 21:46:06

标签: ios objective-c download

我正在使用一个从受OAuth2.0保护的服务器请求数据的应用。当我使用GTM OAuth库检索数据时,程序将继续运行,同时在后台下载数据。我需要某种机制来强制我的应用程序等到调用didFinishWithData选择器,或者我需要一种方法来通知我的ViewController下载完成,这样我就可以立即使用这些数据。

我已经尝试了条件块,但那些不是为我做的。我也尝试轮询我感兴趣的数据对象,但如果我这样做,数据似乎永远不会下载。我听说我可以通过某种方式利用通知中心来完成这项任务,所以在我等待这里的回复时,我会更多地了解它。

基本上是这样:

-(void) getAlert{
// Define the URL of the API module we'd like to utilize.
NSURL *url = [[NSURL alloc] initWithString:@"https://access.active911.com/interface/open_api/api/alerts"];
// Constructs a an HTTP request object to send to the server in order to obtain data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:@"1" forHTTPHeaderField:@"alert_days"];
// This fetcher sends the request along with the authentication header in a recognizable manner.
GTMHTTPFetcher *fetcher = [[GTMHTTPFetcher alloc] initWithRequest:request];
// Attach the OAuth credentials for the fetcher's use.
[fetcher setAuthorizer:auth];
// Execute the operation.
[fetcher waitForCompletionWithTimeout:10];
NSLog(@"About to get alert");
[fetcher beginFetchWithDelegate:self didFinishSelector:@selector(responseHandler:finishedWithData:finishedWithError:)];
NSLog(@"got alert");
}

-(void)responseHandler:(id)valueNotUsed finishedWithData:(NSData *)data finishedWithError:(NSError *)error{
    // Retrieve the server data in a usable object
    // All that's being done here is conversion to an NSDictionary
    // followed by the creation of subdictionaries from that dictionary
    // until our final value can be picked directly out of the resulting dict
    NSData *jsonData = [[NSData alloc] initWithData:data];
    NSError *dictError;
    NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:jsonData //1

                      options:kNilOptions
                      error:&dictError];
    NSDictionary *token = [json objectForKeyedSubscript:@"message"];
    NSArray *alerts = [token objectForKeyedSubscript:@"alerts"];
    NSDictionary *alertData = alerts[0];
    mapCode = [alertData objectForKeyedSubscript:@"map_code"];
    NSString *city = [alertData objectForKeyedSubscript:@"city"];
    NSLog(@"Map code: '%@' with city '%@' and access token %@", mapCode, city, accessToken);   
}

我需要将mapCode传递给我的视图控制器。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

首先,请重新考虑在从服务器获取结果时暂停UI。这可能会为应用程序创建一个非常糟糕的用户体验,只有在绝对必要时才应该这样做。

其次,您的responseHandler方法有效吗?你只需要在responseHandler所在的VC中使用mapCode吗?

如果是这样,您甚至不需要使用通知。只需:

-(void)responseHandler:(id)valueNotUsed finishedWithData:(NSData *)data finishedWithError:(NSError *)error{
  ...
  ...
  mapCode = [alertData objectForKeyedSubscript:@"map_code"];
  [self updateVCWithMapCode:mapCode];
}

这将在收到响应后调用该方法。也明确地传递它,所以你也不需要将mapCode作为属性。

相关问题