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



我有一个像应用程序一样的聊天,为了接收定期聊天,我想定期轮询服务器,比如 5 分钟。并检查是否有任何新消息。

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

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

请帮忙。

谢谢

您可以在后台线程上启动 NSTimer 并定期调用主线程,这是我的做法:

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

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

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

继续帕特里克的回答:- 如果你可以在没有委托的情况下尝试 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);
}

使用以下方法解决此问题:

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

//call server task here

}

相关内容

  • 没有找到相关文章

最新更新