【发布时间】:2014-01-16 17:33:00
【问题描述】:
我必须为 iOS 设备开发一个简单的聊天应用程序。 我试图这样做:
当我运行我的应用程序时,我会调用这个方法:
-(void) NewChatMessages{
// Create the asynchronous request.
NSString *chatURL = [NSString stringWithFormat: @"http://www.example.com/chat.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:chatURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------234213413243214124321456566";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"myTel\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",myTel] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
[request setHTTPBody:body];
// Create url connection and fire request
chatConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
这个请求,调用一个 php 脚本来检查是否有新消息给我:
$myTel = $_POST['myTel'];
$exist=mysql_query("SELECT * from chat WHERE tel = '$myTel'");
$num_rows = mysql_num_rows($esiste);
if($num_rows > 0){
//there is a new chat message for me! (maybe it's not only one)
echo "1";
}
else{
//there aren't new chat messages for me
echo "0";
}
当我收到响应(使用 URLRequest 委托)时,如果我收到 1,我下载新消息,否则什么也没有。 然后我再次调用这个方法(每次我收到响应)来创建一个新的 URL 连接并检查是否有新的聊天消息给我。 这个解决方案很好用,但我的问题是,这是开发聊天应用程序的正确方法吗? 这种方法是不是太递归了,是不是内存和数据占用过多?
【问题讨论】: