2016-11-11 62 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。它提供了異步下載/上傳的幾個選項,以及完成塊。