2012-03-24 17 views
1

我正在寫一個非常簡單的聊天應用程序,並想知道如何暫停應用程序進入後臺時長輪詢選擇器。長查詢和applicationDidEnterBground:

目前,我有一個聊天室類(一個UIView),可處理長輪詢像這樣:

-(void)startPolling 
{ 
    [self performSelectorInBackground:@selector(longPoll) withObject: nil]; 
} 

- (void) longPoll { 

    //Poll the Requested URL... 

    NSData* responseData = [NSURLConnection sendSynchronousRequest:request 
               returningResponse:&response error:&error]; 

    [self performSelectorOnMainThread:@selector(dataReceived:) 
          withObject:responseData waitUntilDone:YES]; 
    [self performSelectorInBackground:@selector(longPoll) withObject: nil]; 
} 

-(void) dataReceived: (NSData*) data 
{  
    //Reload my Tableview etc.. 
} 

如何使用applicationDidEnterBackground:直到應用程序又回到前臺暫停longPoll選擇?或者這是由應用程序委託自動完成的?

由於

回答

1

該請求將被自動中止。並不能保證在恢復後請求必須成功,所以你必須處理錯誤,但不應該中斷。

請注意,編寫此代碼的方法可能比使用performSelectorInBackground:更好,因爲它總是啓動一個新的硬件線程。對於初學者來說,最好簡單地在longPoll內循環,而不是爲新請求啓動一個新線程。

+0

感謝您的回覆。你如何建議我在longPoll中循環? – Moe 2012-03-24 01:57:16

+0

可能只是一個無限循環。如果你有一些條件允許你停止輪詢(除了現有的/暫停程序),你可以使用它作爲條件。但理想情況下,您應該使用'sendAsynchronousRequest:queue:completionHandler:'而不是後臺線程上的同步請求。 – 2012-03-24 01:59:09