2012-04-01 82 views
0

我有一個計時器,它調用一個新的線程,這個線程調用一個正在pararelo上工作的函數,但是當應用程序在一段時間後在後臺凍結時。我的代碼如下NSThread在後臺IOS

在DidLoad:

timerMusica = [NSTimer scheduledTimerWithTimeInterval:(15) target:self selector:@selector(treadAtualizaMusica) userInfo:nil repeats:YES]; 

... 函數來調用新的線程:被執行

-(void)treadAtualizaMusica{ 
    [NSThread detachNewThreadSelector:@selector(atualizaMusica:) toTarget:self withObject:nil]; 
} 

行動:

- (void)atualizaMusica:(NSTimer *)aNotification{ 
    NSURL *dataUrl = [NSURL URLWithString:@"http://www.xxxxx.com.br/musica.php"]; 
    NSString *fileString = [NSString stringWithContentsOfURL:dataUrl encoding:NSASCIIStringEncoding error:nil]; 

    NSLog(@"buscando string"); 

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { 
     if (fileString == NULL) { 
      autoScrollLabel.text = [NSString stringWithFormat:@"xxxxx"]; 
      autoScrollLabel.textColor = [UIColor whiteColor]; 
      autoScrollLabel.font = [UIFont boldSystemFontOfSize:12 ]; 

     } 
     else{ 
      autoScrollLabel.text = [NSString stringWithFormat:@"%@",fileString]; 
      autoScrollLabel.textColor = [UIColor whiteColor]; 
      autoScrollLabel.font = [UIFont boldSystemFontOfSize:12 ]; 
     } 

    } 
    else{ 
     if (fileString == NULL) { 
      scrollMusica.text = [NSString stringWithFormat:@"xxxxx"]; 
      scrollMusica.textColor = [UIColor whiteColor]; 
      scrollMusica.font = [UIFont boldSystemFontOfSize:12 ]; 

     } 
     else{ 
      scrollMusica.text = [NSString stringWithFormat:@"%@",fileString]; 
      scrollMusica.textColor = [UIColor whiteColor]; 
      scrollMusica.font = [UIFont boldSystemFontOfSize:12 ]; 
     } 
    } 
} 

我不知道如果它是打開一個新線程的正確方法,但這是我發現的搜索。

我需要這個單獨的線程,因爲我的函數在服務器中查找字符串,並且用戶的連接速度很慢,應用程序在此下載過程中被鎖定。上面的代碼解決了這個問題,但創建了另一個我,正如我上面提到的,當應用程序在後臺停止一段時間後它會凍結。

回答

0

當您切換任務時,iOS中沒有運行後臺線程。
您需要獲得許可才能繼續運行更多。
使用

的UIApplication beginBackgroundTaskWithExpirationHandler

+0

說得對,現在我正在研究。 但你有任何如何實現的例子?到現在爲止我無法理解該方法... 謝謝! – jucajl 2012-04-01 02:26:47

+0

而不是分離你在這個方法塊中運行你的代碼的線程 – CiNN 2012-04-01 02:42:53

+0

@JoãoLuiz在'[UIApplication sharedApplication]'上調用該方法提供一個繼續代碼塊。如果這是造成混淆的原因,iOS明確允許您只需要少量額外時間來完成某些關鍵的附加任務。您無權繼續無限期地運行以達到任意目的。 – Tommy 2012-11-20 20:16:30