Using Swift to handle GZipped (containing JSON) HT

2019-02-18 10:23发布

问题:

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.

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

回答1:

On swift side:

  • 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.

On php side:

  • 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);
    
  • 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');
    


标签: json swift http