0

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

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

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

请帮忙。

谢谢

4

3 回答 3

1

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

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

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

[self performSelectorOnMainThread:@selector(update:) withObject:newMessages waitUntilDone:NO];
于 2012-05-15T23:54:00.270 回答
1

继续帕特里克的回答:-如果您可以在没有委托的情况下尝试 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);
}
于 2012-05-16T04:10:19.243 回答
-1

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

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

-(void)performPollinginBackground{


//call server task here


}
于 2012-05-16T23:55:31.340 回答