2016-11-11 19 views
0

我所有的工作都很顺利,但有一点问题。我在 - (void)viewDidLoad {}中有NSURLRequest,并且需要一些时间从服务器获取数据。我希望它以异步的方式完成。如何在Objective-C中异步获取API数据?

以下是我的代码,请告诉我该怎么实现。 在此向各位致谢。 :)

- (void)viewDidLoad { 
[super viewDidLoad]; 
[[self tableView2]setDelegate:self ]; 
[[self tableView2]setDataSource:self]; 
array=[[NSMutableArray alloc]init]; 

NSString *castString = [NSString stringWithFormat:@"https://api.themoviedb.org/3/movie/%@/credits?api_key=c4bd81709e87b12e6c74a08609433c49",movieIDinString]; 
NSURL *url=[NSURL URLWithString:castString]; 

NSURLRequest *request=[NSURLRequest requestWithURL:url]; 
connection=[NSURLConnection connectionWithRequest:request delegate:self]; 
if (connection) 
{ 
    webData= [[NSMutableData alloc]init]; 
} 
+0

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^(空隙){// 后台线程 dispatch_async(dispatch_get_main_queue(),^(无效){// 运行UI更新 [_activityIndi​​catorImageView stopAnimating]; }); }); –

+0

@SudheerKolasani请你解释一下,因为我是Objective-C –

+0

的新手,它很简单,只需在后台加载url并在主线程中重新加载tableview –

回答

1

试试这个..

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ 
     //Background Thread 

     NSString *castString = [NSString stringWithFormat:@"https://api.themoviedb.org/3/movie/%@/credits?api_key=c4bd81709e87b12e6c74a08609433c49",movieIDinString]; 
     NSURL *url=[NSURL URLWithString:castString]; 

     NSURLRequest *request=[NSURLRequest requestWithURL:url]; 
     connection=[NSURLConnection connectionWithRequest:request delegate:self]; 
     if (connection) 
     { 
      webData= [[NSMutableData alloc]init]; 
     } 

     dispatch_async(dispatch_get_main_queue(), ^(void){ 
      //Run UI Updates 

// reload table view here 
      [_activityIndicatorImageView stopAnimating]; 
     }); 
    }); 
+0

我应该在viewDidLoad中执行它吗? –

1

如果您使用的API,它需要一定的时间,从服务器上获取数据。此时,您必须在主线程中使用后台线程和显示活动指示符。从API获取数据后,您需要将线程更改为主线程。请检查我的下面的代码。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
    // background thread 
    // code for API call 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     // main thread 
    }); 
}); 

也可以使用回调方法。

[helperApi instaUserDetails:finderDetailsDataDict andCallback:^(id jsonResponse) { 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      if ([[jsonResponse objectForKey:@"code"] intValue] == 200) { 

       userDetailsDict = [jsonResponse objectForKey:@"data"]; 

       mediaArray = [[[[jsonResponse objectForKey:@"data"] objectForKey:@"user"] objectForKey:@"media"] objectForKey:@"nodes"]; 
      } 
      [activityIndicator stopAnimating]; 
      [self createUI]; 
     }); 
    }]; 

NSURLConnection现在已被弃用。尝试使用NSURLSession。

0

尝试AFNeworking。它提供了异步下载/上传的几个选项,以及完成块。

相关问题