如何定期从后台线程上的服务器轮询数据?

时间:2012-05-15 23:09:28

标签: iphone ios multithreading ipad polling

我有一个类似app的聊天,为了接收定期聊天,我想定期轮询服务器,比如5分钟......并检查是否有新消息。

作为初学者,我尝试过简单的NSURLConnection并发送和接收数据,但在轮询时卡住了。 什么是正确的民意调查方式?我应该使用NSTimer定期投票吗? 有没有可以帮助我的示例代码?

我有一个在主线程上运行的计时器,它每5秒调用一个后台线程并向服务器发送请求。现在发生了什么,NSURLConnection的代表没有被调用。可以做些什么?

请帮忙。

由于

3 个答案:

答案 0 :(得分:1)

你可以在后台线程上启动NSTimer并定期调用主线程,这就是我的工作方式:

[self performSelectorOnMainThread:@selector(LaunchTimer) withObject:nil waitUntilDone:NO];

只需创建一个“LaunchTimer”函数,以一定的间隔调用更新函数,调用NSURLConnection,当您收到新消息时,通过调用主线程来更新聊天窗口,如下所示:

[self performSelectorOnMainThread:@selector(update:) withObject:newMessages waitUntilDone:NO];

答案 1 :(得分:1)

继续Patrick的回答: - 如果你可以在没有代表的情况下尝试NSURLConnection,

    -(void)update:(id)objmessage
{
    NSString *post =[NSString stringWithFormat:@"timestamp=%@&user_id=%@",DatetimeString,UID];

    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:@"Your server URL"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSError *error;
    NSURLResponse *response;
    NSData *returnData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    returnString=[[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
    if(!returnString)
    {
        UIAlertView *erroralert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There is an error getting response" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [erroralert show];
        [erroralert release];
    }
    else 
    {
        NSLog(@"%@",returnString);
    }
    SBJSON *json = [[SBJSON new] autorelease];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:[json objectWithString:returnString error:nil]];
    //NSLog(@"%@",dic);
}

答案 2 :(得分:-1)

用以下方法解决这个问题:

[self performSelectorOnMainThread:@selector(performPollinginBackground) withObject:nil   waitUntilDone:NO];

-(void)performPollinginBackground{


//call server task here


}