在iPhone開發中實現解壓縮gzip

來源:互聯網
上載者:User

iPhone開發中實現解壓gzip是本文要介紹的內容,最近做的一個東西中,需要從網路擷取xml檔案,但是該檔案用了gzip壓縮的。搜尋一 下有人說gzip壓縮的用urlrequest可以自己解壓,但是這必須從伺服器返回的header中有accept-Encoding說明是gzip 的。也就是用這句就可以實現自解壓

 
  1. [urlRequest addValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];  

這個在我的項目中沒有作用,因為伺服器返回的header中沒有Accept-Encoding的說明。這就需要手動解壓了!解壓需要匯入libz.1.2.3.dylib庫,匯入#import "zlib.h"

下面是解壓的代碼:

 
  1. -(NSData *)uncompressZippedData:(NSData *)compressedData    
  2. {    
  3.  
  4.     if ([compressedData length] == 0) return compressedData;    
  5.  
  6.     unsigned full_length = [compressedData length];    
  7.  
  8.     unsigned half_length = [compressedData length] / 2;    
  9.     NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];    
  10.     BOOL done = NO;    
  11.     int status;    
  12.     z_stream strm;    
  13.     strm.next_in = (Bytef *)[compressedData bytes];    
  14.     strm.avail_in = [compressedData length];    
  15.     strm.total_out = 0;    
  16.     strm.zalloc = Z_NULL;    
  17.     strm.zfree = Z_NULL;    
  18.     if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;    
  19.     while (!done) {    
  20.         // Make sure we have enough room and reset the lengths.    
  21.         if (strm.total_out >= [decompressed length]) {    
  22.             [decompressed increaseLengthBy: half_length];    
  23.         }    
  24.         strm.next_out = [decompressed mutableBytes] + strm.total_out;    
  25.         strm.avail_out = [decompressed length] - strm.total_out;    
  26.         // Inflate another chunk.    
  27.         status = inflate (&strm, Z_SYNC_FLUSH);    
  28.         if (status == Z_STREAM_END) {    
  29.             done = YES;    
  30.         } else if (status != Z_OK) {    
  31.             break;    
  32.         }    
  33.  
  34.     }    
  35.     if (inflateEnd (&strm) != Z_OK) return nil;    
  36.     // Set real length.    
  37.     if (done) {    
  38.         [decompressed setLength: strm.total_out];    
  39.         return [NSData dataWithData: decompressed];    
  40.     } else {    
  41.         return nil;    
  42.     }    
  43. }  

小結:在iPhone開發中實現解壓縮gzip的內容介紹完了,希望本文對你有所協助!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.