2017-04-19 28 views
1

我打電話給youtube API以獲得視頻的標題。然後我想在屏幕上的表格中顯示視頻的標題。塊在完成執行後如何訪問titleios - 更新區塊內的用戶界面

下面的代碼拿到冠軍

-(void)getVideoTitle:(NSString *)urlStr success:(void (^)(NSDictionary *responseDict))success{ 

urlStr = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%%2C+snippet%%2C+statistics&id=%@&key={API_KEY}",urlStr]; 

NSURL *url = [[NSURL alloc] initWithString:urlStr]; 
// Create your request 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

// Send the request asynchronously 
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) { 

    // Callback, parse the data and check for errors 
    if (data && !connectionError) { 
     NSError *jsonError; 
     NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError]; 

     if (!jsonError) { 
      success(jsonResult); 
      // NSLog(@"Response from YouTube: %@", jsonResult); 
     } 
    } 
}] resume]; 

}

下面是如何調用上面的函數:

[self getVideoTitle:@"zB4I68XVPzQ" success:^(NSDictionary *responseDict){ 
    NSArray *itemsArray = [responseDict valueForKey:@"items"]; 
    NSDictionary *item = itemsArray[0]; 
    NSDictionary* snippet = [item valueForKey:@"snippet"]; 
    NSString *title = [snippet valueForKey:@"title"]; 
}]; 

如何獲得訪問該塊之外title變量之後該塊已完成執行?

我都試過,沒有運氣

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self updateMyUserInterfaceOrSomething]; 
}); 

回答

1

在您的代碼如下:

NSString* recievedTitle __block = nil; //title is here, after block below run 

    [self getVideoTitle:@"zB4I68XVPzQ" success:^(NSDictionary *responseDict){ 
     NSArray *itemsArray = [responseDict valueForKey:@"items"]; 
     NSDictionary *item = itemsArray[0]; 
     NSDictionary* snippet = [item valueForKey:@"snippet"]; 
     recievedTitle = [snippet valueForKey:@"title"]; //here you write it 
     // or 
     NSString *title = [snippet valueForKey:@"title"]; 
     [self updateInterfaceWithTitle: title] 
    }]; 

/// 

- (void)updateInterfaceWithTitle:(NSString*)title{ 
    //use title here 
}