2015-09-30 129 views
1

所以我要在我的應用這個方法返回BOOL如果和更新適用於我的應用程序內容設置的NSData dataWithContentsOfURL超時

- (BOOL)isUpdateAvailable{ 
    NSData *dataResponse=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"url that returns json object"] ]; 
    if(dataResponse!=nil){ 
     NSError *error; 
     dicUpdates = [NSJSONSerialization JSONObjectWithData:dataResponse options:NSJSONReadingMutableContainers error:&error]; 
    } 
    if(dicUpdates.count > 0) isUpdateAvailable = YES; 
    else isUpdateAvailable = NO; 
    return isUpdateAvailable; 
} 

我需要爲這個同步請求,使下一個視圖控制器將取決於在服務器響應。然而,有時服務器需要很長時間來響應或者互聯網真的很慢,我需要設置一個時間來防止應用程序「被凍結」。

我以前使用NSUrlconnection來完成這項任務,但它已被棄用。另外,我嘗試使用NSURLSession,(一直使用它也下載更新後臺線程),但我只是可以弄清楚它是否可以用於同步請求。

任何想法如何處理這個?我只需要一個返回BOOL的同步方法。最好的祝福。

回答

0

我們必須在NSURLSession中使用NSURLRequest來設置超時間隔。 檢查下面的代碼:

- (BOOL)isUpdateAvailable{ 
NSURLSession *session = [NSURLSession sharedSession]; 
[[session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"url that returns json object"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:4]//timeout 
     completionHandler:^(NSData *dataResponse, 
          NSURLResponse *response, 
          NSError *error) { 
      // handle response 
      if(dataResponse!=nil){ 
       NSError *error; 
       dicUpdates = [NSJSONSerialization JSONObjectWithData:dataResponse options:NSJSONReadingMutableContainers error:&error]; 
      } 
      if(dicUpdates.count > 0) isUpdateAvailable = YES; 
      else isUpdateAvailable = NO; 
      return isUpdateAvailable; 


     }] resume]; 
} 
+0

我有錯誤,因爲返回'返回isUpdateAvailable;'是完成處理程序中,香港專業教育學院搬到它的會話任務之外。我馬上試試這個代碼,謝謝! –

+0

這不起作用,因爲該方法返回isUpdateAvailable var,甚至沒有等待requestwithURL方法, –