【问题标题】:Which method to choose when developing a simple iOS Chat Application开发简单的 iOS 聊天应用程序时选择哪种方法
【发布时间】: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 连接并检查是否有新的聊天消息给我。 这个解决方案很好用,但我的问题是,这是开发聊天应用程序的正确方法吗? 这种方法是不是太递归了,是不是内存和数据占用过多?

【问题讨论】:

    标签: php ios chat


    【解决方案1】:

    让您的应用收到消息通知的最佳方式是让您的服务器在用户收到新消息时向您的应用发送推送通知。这可以防止您的应用不断地访问服务器,只是为了检查是否有东西。如果这超出了您的 php 或 iOS 技能,我会推荐 Parse。很难总结它们,但它是一个非常强大的平台,他们有一个 tutorial that demonstrating 确切地知道如何做你的要求。

    【讨论】:

    • 如果您想使用自己的服务器发送推送通知怎么办?我收到此错误 atm,请查看我的帖子:stackoverflow.com/questions/18754008/…
    • 我不擅长 PHP,所以我无法帮助你。我的回答只是针对您最初的问题。
    • '你的问题'?大声笑错误的用户伙伴,我不是OP。好的,没问题,谢谢;我想你可能已经回答了我几个月前在 SO 上发布的问题。
    • @Pavan 我很抱歉 :-P 我希望我能帮助你,我知道足够的 PHP 来识别 PHP 代码。除此之外,我一无是处。
    • 好的,我没有使用解析,但我了解推送通知的工作原理。我对服务器端(php)有一些问题,但这是我需要的解决方案,所以我的应用程序不必经常联系服务器。谢谢!
    【解决方案2】:

    尝试使用套接字编程,而不是基于 API 的聊天应用程序。 尝试使用本教程。 Networking Tutorial for iOS: How To Create A Socket Based iPhone App and Server

    虽然本教程基于 Python 作为服务器端脚本,但这只是一个想法,您也可以轻松地使用 PHP。

    【讨论】:

      猜你喜欢
      • 2013-06-05
      • 2011-01-25
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-31
      相关资源
      最近更新 更多