等待函数运行完成只获取数据

时间:2015-05-16 02:52:40

标签: ios dispatch

我有一个从服务器获取数据的函数,它将在其他函数运行时异步运行。

我的问题,我在viewdidload()调用函数[self getdata]。和NSLog在被调用函数下面,但数据是延迟。它变为null。我可能知道无论如何等待功能运行完成只为我打印出数据吗?

-(void)getdata
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *userID = [prefs objectForKey:@"userID"];

//get merged news
float latitude = [[prefs objectForKey:LAST_KNOWN_LATITUDE] floatValue];
float longitude = [[prefs objectForKey:LAST_KNOWN_LONGITUDE] floatValue];

NSInteger ref_id =[[[eventDict objectForKey:@"id"] substringFromIndex:2]integerValue];
NSInteger reference_EventType = [[eventDict objectForKey:@"type_id"]integerValue];
NSString *type =@"EVENT";

NSString *str = [NSString stringWithFormat:@"%@event.php", API_URL];
NSURL *URL = [NSURL URLWithString:str];

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:URL];
__unsafe_unretained ASIFormDataRequest *_request = request;

[request setRequestMethod:@"POST"];
[request setPostValue:@"get_event_notification" forKey:@"tag"];
[request setPostValue:[NSNumber numberWithInteger:ref_id] forKey:@"reference_id"];
[request setPostValue:[NSNumber numberWithInteger:reference_EventType] forKey:@"reference_eventType"];
[request setPostValue:type forKey:@"reference_type"];
[request setPostValue:[NSNumber numberWithFloat:latitude] forKey:@"latitude"];
[request setPostValue:[NSNumber numberWithFloat:longitude] forKey:@"longitude"];
[request setPostValue:userID forKey:@"user_id"];
[request setDelegate:self];
[request setTimeOutSeconds:30.0];
[request setShouldAttemptPersistentConnection:NO];
[request startAsynchronous];
[request setCompletionBlock:^(void){
    NSInteger responseCode = [_request responseStatusCode];

    if (responseCode == 200 || responseCode == 201 || responseCode == 202)
    {
        //NSLog(@"%@", [_request responseString]);
        NSMutableDictionary *response = (NSMutableDictionary *)[[_request responseString] JSONValue];

        NSInteger success = [[response objectForKey:@"success"] integerValue];
        if (success == 1)
        {

            if ([[response objectForKey:@"event"] isKindOfClass:[NSArray class]]) {
                event = [[response objectForKey:@"event"] objectAtIndex:0];
                dataArray=[event objectForKey:@"merged"];
                NSLog(@"dataArray %d",dataArray.count);

                mergedCount=[NSString stringWithFormat:@"%d",dataArray.count];

                NSArray *pathsMergedCount = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectoryMergedCount = [pathsMergedCount objectAtIndex:0];
                NSString *filePathMergedCount= [documentsDirectoryMergedCount stringByAppendingPathComponent:@"fileMergedCount.txt"];

                [mergedCount writeToFile:filePathMergedCount atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];



                for(i=0;i<[dataArray count];i++)
                {
                    feedDict=[dataArray objectAtIndex:i];


                    [eventIDMerged addObject:[feedDict objectForKey:@"event_id"]];
                    [eventDescMerged addObject:[feedDict objectForKey:@"description"]];



                             }
            }}}
}];
[request setFailedBlock:^(void){
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Failed" message:@"Internet connection too slow, please ensure you have a strong internet connection to have better user experience" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alert show];

}];




}
-(void)viewDidLoad
{
[self getdata];
 dispatch_async(dispatch_get_main_queue(), ^{
        NSArray *pathsMergedCount =    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,    YES);
        NSString *documentsDirectoryMergedCount = [pathsMergedCount objectAtIndex:0];
        NSString *filePathMergedCount= [documentsDirectoryMergedCount stringByAppendingPathComponent:@"fileMergedCount.txt"];
        NSString *strMergedCount = [NSString stringWithContentsOfFile:filePathMergedCount encoding:NSUTF8StringEncoding error:NULL];


        NSLog(@"Count3m  %@",strMergedCount);

    });
});

}

1 个答案:

答案 0 :(得分:0)

请参阅此主题中的答案:

Storing values in completionHandlers - Swift

它包含指向完整项目的链接(在Swift中),演示使用完成处理程序来管理异步任务。