使用Swift处理GZipped(包含JSON)HTTP响应 [英] Using Swift to handle GZipped (containing JSON) HTTP response

查看:127
本文介绍了使用Swift处理GZipped(包含JSON)HTTP响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一些Android应用,这些应用从HTTP响应中获取GZipped Json数据.现在,我想编写一些执行相同操作的iPhone应用程序.

I have written Android apps that take GZipped Json data from a HTTP response. Now I want to write some IPhone apps that do the same thing.

使用Swift处理GZipped Json数据需要什么类和方法?

What class and approaches are needed to handle GZipped Json data using Swift?

推荐答案

敏捷的方面:

  • 解码gzip -对于联网,您可以使用 Alamofire .这个很 众所周知,并且基于NSURLConnection/NSURLSession,因此 支持自动压缩的编码响应. (我尝试并测试了这一点,它无需任何额外的代码即可工作).要检查php响应是否真的被压缩,请打印响应变量(alamofire完成处理程序中的第二个变量) 到控制台.这将打印响应头...应该 包含以下内容:内容编码:gzip".
  • 编码为gzip -如果您还希望将请求压缩为 iOS App to PHP(要发布到php文件的参数) 在此处.
  • Decoding gzip - For networking you can use Alamofire. It is very well known and based on NSURLConnection / NSURLSession so also supports gzipped encoded responses automatically. (I tried and tested this and it works without any extra code). To check if the php response is really gzipped, print the response variable (2nd variable in alamofire completion handler) to the console. This will print the response header... it should contain following: "Content-encoding: gzip".
  • Encoding to gzip - If you also want to zip the request from your iOS App to PHP (the parameters you are posting to the php file) take a look here.

在php端:

  • 解码gzip -要(从iOS应用中)解压缩收到的(压缩的)帖子数据,请使用以下方法:

  • Decoding gzip - To unzip received (gzipped) post data (from your iOS App) use this:

// Read the post data
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
   $raw_post_data .= fread($handle, 8192);
}
fclose($handle);

// unzip the post data
$raw_post_data_unzipped = gzdecode($raw_post_data);

  • 编码为gzip -要发送压缩后的响应(到您的iOS应用),请在您的php文件开头的某处添加以下行.

  • Encoding to gzip - To send gzipped responses (to your iOS App) add below line somewhere at the beginning of your php file.

    ob_start('ob_gzhandler');
    

  • 这篇关于使用Swift处理GZipped(包含JSON)HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆