2016-11-24 16:28:07 dkq972958298 阅读数 2743

在实际开发中,我们经常要对比较大的数据进行压缩后再上传服务器,下面是我在项目中压缩数据时所使用的压缩方法:


对数据进行压缩:

 zipAndUnzip *zipAnd = [[zipAndUnzip alloc] init];
    
    NSString *str = @"六六六六了还是德国大使馆和低俗化工及第三方换个撒点恢复健康的十分好的设计哈佛的号发的撒开了凤凰健康的十分健康的沙发";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSData *dataDeflate = [zipAnd gzipDeflate:data];



对数据进行解压:

NSData *dataInflate =  [zipAnd gzipInflate:dataDeflate];
    NSString *aString = [[NSString alloc] initWithData:dataInflate encoding:NSUTF8StringEncoding];



压缩的方法是:

//压缩
- (NSData *)gzipDeflate:(NSData*)data
{
    if ([data length] == 0) return data;
    
    z_stream strm;
    
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.total_out = 0;
    strm.next_in=(Bytef *)[data bytes];
    strm.avail_in = (uInt)[data length];
    
    // Compresssion Levels:
    //   Z_NO_COMPRESSION
    //   Z_BEST_SPEED
    //   Z_BEST_COMPRESSION
    //   Z_DEFAULT_COMPRESSION
    
    if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY) != Z_OK) return nil;
    
    NSMutableData *compressed = [NSMutableData dataWithLength:16384];  // 16K chunks for expansion
    
    do {
        
        if (strm.total_out >= [compressed length])
            [compressed increaseLengthBy: 16384];
        
        strm.next_out = [compressed mutableBytes] + strm.total_out;
        strm.avail_out = (uInt)([compressed length] - strm.total_out);
        
        deflate(&strm, Z_FINISH);
        
    } while (strm.avail_out == 0);
    
    deflateEnd(&strm);
    
    [compressed setLength: strm.total_out];
    return [NSData dataWithData:compressed];
}



解压缩的方法是:

//解压缩
- (NSData *)gzipInflate:(NSData*)data
{
    if ([data length] == 0) return data;
    
    unsigned long full_length = [data length];
    unsigned long  half_length = [data length] / 2;
    
    NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
    BOOL done = NO;
    int status;
    
    z_stream strm;
    strm.next_in = (Bytef *)[data bytes];
    strm.avail_in = (uInt)[data length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    
    if (inflateInit2(&strm, (15+32)) != Z_OK)
        return nil;
    
    while (!done)
    {
        // Make sure we have enough room and reset the lengths.
        if (strm.total_out >= [decompressed length])
            [decompressed increaseLengthBy: half_length];
        strm.next_out = [decompressed mutableBytes] + strm.total_out;
        strm.avail_out = (uInt)([decompressed length] - strm.total_out);
        
        // Inflate another chunk.
        status = inflate (&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END)
            done = YES;
        else if (status != Z_OK)
            break;
    }
    if (inflateEnd (&strm) != Z_OK)
        return nil;
    
    // Set real length.
    if (done)
    {
        [decompressed setLength: strm.total_out];
        return [NSData dataWithData: decompressed];
    }
    else return nil;
}



这个压缩实质上是二进制压缩的文件,可以对任何二进制文件进行压缩
2016-08-10 12:25:23 u011583971 阅读数 2632

最近需要压缩解压问题,查找了一些资料

  1. ZipArchive库,实现对文件的压缩解压缩,网上有资源,可以下载研究一下,对于一些冗余代码可以修改一下。资源链接http://download.csdn.net/detail/deskisme/4440505
  2. iOS zlib文件主要有deflate算法压缩

3.在我所需要的项目中需要解压缩从服务器中请求到的NSData数据(根据自己的情况选择),所有创建了一个NSData类extension 实现对请求到的data的解压缩,此demo代码中有压缩和解压缩两种方法。
可以比较一下zlib 和gzip的区别,压缩率等。(PS在我们查询资源的时候,对于一些东西,更重要的要自己验证一下。fighting^_^)


#import <Foundation/Foundation.h>

@interface NSData (STUnzipArchive)
// ZLIB
- (NSData *) zlibInflate;
- (NSData *) zlibDeflate;

// GZIP
- (NSData *) gzipInflate;
- (NSData *) gzipDeflate;

@end

#import "NSData+STUnzipArchive.h"
#include <zlib.h>
@implementation NSData (STUnzipArchive)

- (NSData *)zlibInflate
{
    if ([self length] == 0) return self;

    NSUInteger full_length = [self length];
    NSUInteger half_length = [self length] / 2;

    NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
    BOOL done = NO;
    int status;

    z_stream strm;
    strm.next_in = (Bytef *)[self bytes];
    strm.avail_in = (unsigned)[self length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;

    if (inflateInit (&strm) != Z_OK) return nil;

    while (!done)
    {
        // Make sure we have enough room and reset the lengths.
        if (strm.total_out >= [decompressed length])
            [decompressed increaseLengthBy: half_length];
        strm.next_out = [decompressed mutableBytes] + strm.total_out;
        strm.avail_out = (uint)([decompressed length] - strm.total_out);

        // Inflate another chunk.
        status = inflate (&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END) done = YES;
        else if (status != Z_OK) break;
    }
    if (inflateEnd (&strm) != Z_OK) return nil;

    // Set real length.
    if (done)
    {
        [decompressed setLength: strm.total_out];
        return [NSData dataWithData: decompressed];
    }
    else return nil;
}

- (NSData *)zlibDeflate
{
    if ([self length] == 0) return self;

    z_stream strm;

    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.total_out = 0;
    strm.next_in=(Bytef *)[self bytes];
    strm.avail_in = (uint)[self length];

    // Compresssion Levels:
    //   Z_NO_COMPRESSION
    //   Z_BEST_SPEED
    //   Z_BEST_COMPRESSION
    //   Z_DEFAULT_COMPRESSION

    if (deflateInit(&strm, Z_DEFAULT_COMPRESSION) != Z_OK) return nil;

    NSMutableData *compressed = [NSMutableData dataWithLength:16384];  // 16K chuncks for expansion

    do {

        if (strm.total_out >= [compressed length])
            [compressed increaseLengthBy: 16384];

        strm.next_out = [compressed mutableBytes] + strm.total_out;
        strm.avail_out = (uint)([compressed length] - strm.total_out);

        deflate(&strm, Z_FINISH);

    } while (strm.avail_out == 0);

    deflateEnd(&strm);

    [compressed setLength: strm.total_out];
    return [NSData dataWithData: compressed];
}

- (NSData *)gzipInflate
{
    if ([self length] == 0) return self;

    NSInteger full_length = [self length];
    NSInteger half_length = [self length] / 2;

    NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
    BOOL done = NO;
    int status;

    z_stream strm;
    strm.next_in = (Bytef *)[self bytes];
    strm.avail_in = (uint)[self length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;

    if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;
    while (!done)
    {
        // Make sure we have enough room and reset the lengths.
        if (strm.total_out >= [decompressed length])
            [decompressed increaseLengthBy: half_length];
        strm.next_out = [decompressed mutableBytes] + strm.total_out;
        strm.avail_out = (uint)([decompressed length] - strm.total_out);

        // Inflate another chunk.
        status = inflate (&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END) done = YES;
        else if (status != Z_OK) break;
    }
    if (inflateEnd (&strm) != Z_OK) return nil;

    // Set real length.
    if (done)
    {
        [decompressed setLength: strm.total_out];
        return [NSData dataWithData: decompressed];
    }
    else return nil;
}

- (NSData *)gzipDeflate
{
    if ([self length] == 0) return self;

    z_stream strm;

    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.total_out = 0;
    strm.next_in=(Bytef *)[self bytes];
    strm.avail_in = (uint)[self length];

    // Compresssion Levels:
    //   Z_NO_COMPRESSION
    //   Z_BEST_SPEED
    //   Z_BEST_COMPRESSION
    //   Z_DEFAULT_COMPRESSION

    if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY) != Z_OK) return nil;

    NSMutableData *compressed = [NSMutableData dataWithLength:16384];  // 16K chunks for expansion

    do {

        if (strm.total_out >= [compressed length])
            [compressed increaseLengthBy: 16384];

        strm.next_out = [compressed mutableBytes] + strm.total_out;
        strm.avail_out = (uint)([compressed length] - strm.total_out);

        deflate(&strm, Z_FINISH);

    } while (strm.avail_out == 0);

    deflateEnd(&strm);

    [compressed setLength: strm.total_out];
    return [NSData dataWithData:compressed];
}

@end
2018-10-24 11:17:41 u011018979 阅读数 191

layout: post
title: gzip_compressed_data_for_iOS
date: 2018-10-24
tag: objc
site: https://zhangkn.github.io
catalog: true
author: kunnan
subtitle: Gzip压缩数据

Gzip.h

#import <zlib.h>
@interface DDGzip : NSObject
/**
 *  Gzip压缩数据
 *
 *  @param data 需要压缩的数据
 *
 *  @return 压缩后的结果
 */
+(NSData *)compress:(NSData * )data;
/**
 *  Gzip解压数据
 *
 *  @param data 需要解压的数据
 *
 *  @return 解压后的结果
 */
+(NSData *)decompress:(NSData *)data;
@end

Gzip.m

#import "DDGzip.h"

@implementation DDGzip
+(NSData *)compress:(NSData *)data{
    if(!data||[data length]==0){
        NSLog(@"%s:Error:Can't compress an empty or null NSData object.",__func__);
        return nil;
    }
    z_stream zlibStreamStruct;
    zlibStreamStruct.zalloc=Z_NULL;
    zlibStreamStruct.zfree=Z_NULL;
    zlibStreamStruct.opaque=Z_NULL;
    zlibStreamStruct.total_out=0;
    zlibStreamStruct.next_in=(Bytef*)[data bytes];
    zlibStreamStruct.avail_in=(int)[data length];
    int initError=deflateInit2(&zlibStreamStruct,
                               Z_DEFAULT_COMPRESSION,
                               Z_DEFLATED,
                               (15+16),
                               8,
                               Z_DEFAULT_STRATEGY);
    if(initError!=Z_OK){
        NSString * errMsg=nil;
        switch (initError) {
            case Z_STREAM_ERROR:
                errMsg=@"Invalid parameter passed in to function." ;
                break;
            case Z_MEM_ERROR:
                errMsg=@"Insufficient memory." ;
                break;
            case Z_VERSION_ERROR:
                errMsg=@"The version of zlib.h and the version of the library linked do not match." ;
                break;
            default:
                errMsg= @"Unknown error code." ;
                break;
        }
        NSLog(@"%s:deflateInit2()Error:[%@] Message:[%s]",__func__,errMsg,zlibStreamStruct.msg);
        return nil;
    }
    NSMutableData * compressedData=[NSMutableData dataWithLength:[data length]*1.01+12];
    int deflateStatus;
    do{
        zlibStreamStruct.next_out=[compressedData mutableBytes]+zlibStreamStruct.total_out;
        zlibStreamStruct. avail_out = (unsigned int)[compressedData length ] - (unsigned int)zlibStreamStruct. total_out ;
        deflateStatus = deflate (&zlibStreamStruct, Z_FINISH );
    }while ( deflateStatus == Z_OK );
    if (deflateStatus != Z_STREAM_END )
    {
        NSString *errorMsg = nil ;
        switch (deflateStatus)
        {
            case Z_ERRNO :
                errorMsg = @"Error occured while reading file." ;
                break ;
            case Z_STREAM_ERROR :
                errorMsg = @"The stream state was inconsistent (e.g., next_in or next_out was NULL)." ;
                break ;
            case Z_DATA_ERROR :
                errorMsg = @"The deflate data was invalid or incomplete." ;
                break ;
            case Z_MEM_ERROR :
                errorMsg = @"Memory could not be allocated for processing." ;
                break ;
            case Z_BUF_ERROR :
                errorMsg = @"Ran out of output buffer for writing compressed bytes." ;
                break ;
            case Z_VERSION_ERROR :
                errorMsg = @"The version of zlib.h and the version of the library linked do not match." ;
                break ;
            default :
                errorMsg = @"Unknown error code." ;
                break ;
        }
        NSLog ( @"%s: zlib error while attempting compression:[%@] Message:[%s]" , __func__, errorMsg, zlibStreamStruct. msg );
        deflateEnd(&zlibStreamStruct);
        return nil;
    }
    deflateEnd(&zlibStreamStruct);
    [compressedData setLength:zlibStreamStruct.total_out];
    return compressedData;
}
+(NSData *)decompress:(NSData *)data{
    z_stream zStream;
    zStream. zalloc = Z_NULL ;
    zStream. zfree = Z_NULL ;
    zStream. opaque = Z_NULL ;
    zStream. avail_in = 0 ;
    zStream. next_in = 0 ;
    int status = inflateInit2 (&zStream, ( 15 + 32 ));
    if (status != Z_OK ) {
        return nil ;
    }
    
    Bytef *bytes = ( Bytef *)[data bytes ];
    NSUInteger length = [data length ];
    NSUInteger halfLength = length/ 2 ;
    NSMutableData *uncompressedData = [ NSMutableData dataWithLength :length+halfLength];
    zStream. next_in = bytes;
    zStream. avail_in = ( unsigned int )length;
    zStream. avail_out = 0 ;
    
    NSInteger bytesProcessedAlready = zStream. total_out ;
    while (zStream. avail_in != 0 ) {
        if (zStream. total_out - bytesProcessedAlready >= [uncompressedData length ]) {
            [uncompressedData increaseLengthBy :halfLength];
        }
        
        zStream. next_out = ( Bytef *)[uncompressedData mutableBytes ] + zStream. total_out -bytesProcessedAlready;
        zStream. avail_out = ( unsigned int )([uncompressedData length ] - (zStream. total_out -bytesProcessedAlready));
        status = inflate (&zStream, Z_NO_FLUSH );
        if (status == Z_STREAM_END ) {
            break ;
        } else if (status != Z_OK ) {
            return nil ;
            
        }
    }
    status = inflateEnd (&zStream);
    if (status != Z_OK ) {
        return nil ;
    }
    [uncompressedData setLength : zStream. total_out -bytesProcessedAlready];  // Set real length
    return uncompressedData;
}
@end

用法

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.timeoutInterval = 30.0;


    request.HTTPMethod = @"POST";

    
    

    NSData * dataUsingEncoding =  [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"dataUsingEncoding  length %ld",dataUsingEncoding.length);
    
    dataUsingEncoding =  [DDGzip compress:dataUsingEncoding];
    
    NSLog(@"dataUsingEncoding  compress  length %ld",dataUsingEncoding.length);

    
    request.HTTPBody = dataUsingEncoding ;
    
    // 设置gzip
    
    [request setValue:@"true" forHTTPHeaderField:@"IsGzip"];//IsGzip: true

See Also

  • OwenWangBroadthinking/MIFI-APP-IOS – DDGzip.h

  • newpost

    /Users/devzkn/bin//newpost gzip_compressed_data_for_iOS Gzip压缩数据 -t objc

    #原来"“的参数,需要自己加上”"

2015-11-20 09:47:31 february29 阅读数 474

概念

首先简单介绍下类的归档与zip压缩概念:

类的归档:将我们用到object-c对象以文件的形式存储下来,是数据持久化的一种方案。(其他还有 coredata ,sqlite , NSUserDefult) 。

zip压缩:将已存在的文件(图片,语音或者我们归档的文件。。)压缩为zip文件的过程。


归档

这里分为两大类:

1.单个类归档到单个文件,即一个类对应一个文件。

2.多个类归档到一个文件,即多个类对应一个文件。

1.单个类归档到单个文件  

    object-c中有四类对象是可以直接使用NSKeyedArchiverarchivedDataWithRootObject方法将内容写入磁盘的,分别是NSString,NSArray,NSDictionary,NSData

    非以上四种类型的,需要将自定义类实现NSCoding协议并重写encodeWithCoderinitWithCoder两个方法,分别用以编码和反编码。然后在编码时会用NSCoder的子类NSKeyedArchiverNSKeyedUnarchiver分别调用archivedDataWithRootObjectunarchiveObjectWithFile来启动自定义类中重写的那两个方法,类似于回调.

   要将一个自定义的类进行归档,那么类里面的每个属性都必须是可以被归档的,如果是不能归档的类型,我们可以把他转化为NSValue进行归档,然后在读出来的时候转化为响应的类型。


下面看代码:


 // NSString归档
    NSString *tranmitStr = [NSString stringWithFormat:@"我是归档的NSStirng对象"];
    NSString *StringPath = [documentpath stringByAppendingPathComponent:@"string.txt"];
    
    
    if([NSKeyedArchiver archiveRootObject:tranmitStr toFile:StringPath]){
        NSLog(@"归档成功");
    }else{
        NSLog(@"归档失败");
    }

    //NSString 中[tranmitStr writeToFile:@"" atomically:YES]; 这个方法已过期用下面的方法
    //[tranmitStr writeToFile:StringPath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil];//writeToFile方法不管用,它能够写一个文件,但是不知道怎么去解档读取里面的文件。<span style="color: rgb(0, 132, 0); font-family: 'Heiti SC Light'; font-size: 11px;">如果用这个方法在接档时候会出现</span><span style="color: rgb(0, 132, 0); font-size: 11px; line-height: normal; font-family: Menlo;">(null)</span><span style="color: rgb(0, 132, 0); font-family: 'Heiti SC Light'; font-size: 11px;">,应该会有里另一种解挡方案与之对应,感兴趣的可以去测试。</span>

   
    // NSData归档
    NSData *tranmitData=[[NSData alloc]init];
    NSString *DataPath = [documentpath stringByAppendingPathComponent:@"data.txt"];
    if([NSKeyedArchiver archiveRootObject:tranmitData toFile:DataPath]){
        NSLog(@"归档成功");
    }else{
        NSLog(@"归档失败");
    }
    
    // NSArray归档
    NSArray *tranmitArray=[[NSArray alloc]initWithObjects:@"a",@"e", nil];
    NSString *ArrayPath = [documentpath stringByAppendingPathComponent:@"array.txt"];
    if([NSKeyedArchiver archiveRootObject:tranmitArray toFile:ArrayPath]){
        NSLog(@"归档成功");
    }else{
        NSLog(@"归档失败");
    }
    // NSDictionary归档
    NSDictionary *tranmitDictionary=[[NSDictionary alloc]initWithObjectsAndKeys:
                                      @"这是NSDictionary当中的内容",@"content",
                                      @"value2",@"key2",
                                      @"value3",@"key3",
                                     nil];
    NSString *DictionaryPath = [documentpath stringByAppendingPathComponent:@"dictionary.txt"];
    if([NSKeyedArchiver archiveRootObject:tranmitDictionary toFile:DictionaryPath]){
        NSLog(@"归档成功");
    }else{
        NSLog(@"归档失败");
    }
    //[tranmitDictionary writeToFile:DictionaryPath atomically:YES];不管用
    
    //自定义类型归档
    CustomBean *bean= [[CustomBean alloc ]init];
    bean.customstr = @"hellow world";
    bean.customint = 12;
   
   // NSData *customBeanData = [NSKeyedArchiver archivedDataWithRootObject:bean];//转化成NSData对象
    NSString *customBeanPath =  [documentpath stringByAppendingPathComponent:@"customBeanPath.txt"];
    if([NSKeyedArchiver archiveRootObject:bean toFile:customBeanPath]){
        NSLog(@"归档成功");
    }else{
        NSLog(@"归档失败");
    }
    
   // [customBeanData writeToFile:customBeanPath atomically:YES];//不能用
    
   //-----------------------单个类解档----------------------------
    
    
    
    NSString *str2 =  [NSKeyedUnarchiver unarchiveObjectWithFile:StringPath];
    NSLog(@"str2 %@:",str2);
    NSArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:ArrayPath];
    NSLog(@" array2 %@:",array2);
    NSDictionary *dic2 =  [NSKeyedUnarchiver unarchiveObjectWithFile:DictionaryPath];
    NSLog(@"dic2 %@:",dic2);
    NSData *data2 = [NSKeyedUnarchiver unarchiveObjectWithFile:DataPath];
    NSLog(@"data2 %@:",data2);
    CustomBean *bean2 = [NSKeyedUnarchiver unarchiveObjectWithFile:customBeanPath];
    NSLog(@"CustomBean  %@:",bean2);
    

CustomBean类是一个键值对的类 ,其实个人认为这个自定义的方式比较鸡肋,我们完全可以用NSDictionary去完成相同的功能。
下面是实现nscoding的方法。
#import <UIKit/UIKit.h>

@interface CustomBean : NSObject<NSCoding>

@property(nonatomic,copy,readwrite) NSString *customstr;
@property(nonatomic,readwrite) int  customint;

@end
#import "CustomBean.h"

@implementation CustomBean

-(void)encodeWithCoder:(NSCoder *)aCoder//要一一对应
{
    [aCoder encodeInt:self.customint forKey:@"customint"];
    [aCoder encodeObject:self.customstr forKey:@"customstr"];
    
}
-(id)initWithCoder:(NSCoder *)aDecoder//和上面对应
{
    if (self=[super init]) {
        self.customint=[aDecoder decodeIntForKey:@"customint"];
        self.customstr=[aDecoder decodeObjectForKey:@"customstr"];
       
    }
    return self;
}

- (NSString *)description{
    NSString *string = [NSString stringWithFormat:@"customstr=%@,customint=%d",self.customstr, self.customint];
    return string;
}
@end


2.多个类归档到一个文件

多个类归档到一个文件的时候需要借助nsmutabledata来完成。

 //-----------------------多个类归档----------------------------
    
    //多个类型归档到一个文件当中需要借助NSMutableData类
    
    NSArray *array = [NSArray arrayWithObjects:@"zhangsan",@"lisi", nil];
    
    NSMutableData *data = [NSMutableData data];//初始化NSMutableData
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];//用NSKeyedArchiver包装一下
    //编码
    [archiver encodeObject:array forKey:@"array"];
    [archiver encodeInt:100 forKey:@"scope"];
    [archiver encodeObject:@"jack" forKey:@"name"];
    
    //完成编码,将上面的归档数据填充到data中,此时data中已经存储了归档对象的数据
    [archiver finishEncoding];
    
    NSString *filePath = [documentpath stringByAppendingPathComponent:@"array.src"];
    //这里调用NSMutableData的writeToFile方法将data写入到本地路径当中。
    BOOL success = [data writeToFile:filePath atomically:YES];
    if(success){
        NSLog(@"多个类归档");
    }
     //-----------------------多个类解档----------------------------
    //读取归档数据
    NSData *data22 = [[NSData alloc] initWithContentsOfFile:filePath];
    //创建解归档对象,对data中的数据进行解归档
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data22];
    //解归档
    NSArray *array22 = [unarchiver decodeObjectForKey:@"array"];
    NSLog(@"多个类解档array22%@",array22);
    
    int value = [unarchiver decodeIntForKey:@"scope"];
    NSLog(@"多个类解档%d",value);
    

压缩

这里需要用到一个第三方的库 ZipArchive 这个库在谷歌的 由于墙的原因我们无法去官网下载。壁纸当初也是从github上下载的。
关于这块可以参照笔者之前写的一个demo  里面有库文件可以拖到自己的工程中去使用 
demo地址:https://github.com/february29/ZIPDecoding

//1.导入 minizip文件夹 ZipArchive.h ZipArchive.mm

//2.导入  libz.tbd

//3.ZipArchive.mm编译选项中,增加-fno-objc-arc

//4.#import "ZipArchive.h"

//5.调用解压,压缩代码 如下所示


//6.time函数报错设置tager ->search path -> always search user path设置为no

// 解压压缩操纵在字线程中做增加用途体验


 ZipArchive* zip = [[ZipArchive alloc] init];
    //压缩后的文件完整路径
    NSString *zipPath;
    zipPath = [documentpath stringByAppendingString:@"/transmit.zip"] ;
    BOOL ret = [zip CreateZipFile2:zipPath];
    
    ret = [zip addFileToZip:StringPath newname:[StringPath lastPathComponent]];
    ret = [zip addFileToZip:DataPath newname:[DataPath lastPathComponent]];
    ret = [zip addFileToZip:ArrayPath newname:[ArrayPath lastPathComponent]];
    ret = [zip addFileToZip:DictionaryPath newname:[DictionaryPath lastPathComponent]];
    

    if( ![zip CloseZipFile2] )
    {
        zipPath = @"";
    }
    
    return zipPath;







2017-04-19 15:14:36 georgehenrywilliam 阅读数 1027

首先,苹果提供了两种压缩图片的方法

UIImageJPEGRepresentation以及UIImagePNGRepresentation

压缩图片的时候使用JPEG最易,相比于PNG压缩的data数据更小,从而服务器的响应时间就越快,PNG相当于是压缩的原图,清晰度虽然比较高,但是data数据相较于JPEG会更大,从而导致服务器响应时间变慢,造成了一定的卡顿,用户交互不够好。

http://blog.csdn.net/mideveloper/article/details/11473627

另外大量上传服务器图片的时候滑动tableview会出现卡顿的现象,其实苹果已经给我们预留了接口,姑且叫做图片的懒加载吧,

if(!tableView.dragging&&!tableView.decelerating){....}

https://yq.aliyun.com/articles/29937



没有更多推荐了,返回首页