iOS的Bencode编解码应用(pod 'GEBEncoding')

Bencode是BitTorrent用在传输数据结构的编码方式。

Bencode(发音为 Bee-Encode)这种编码方式支持四种数据型态:
• 字元串
• 整数
• 串列
• 字典表
Bencode 最常被用在.torrent文档中,文件里的元数据都是 Bencode 过的字典表。其也被用在tracker返回响应时使用。

虽然比用纯二进制编码效率低,但由于结构简单而且不受字节存储顺序影响(所有数字以十进制编码)——这对于跨平台性非常重要。而且具有较好的灵活性,即使存在故障的字典键,只要将其忽略并更换新的就能兼容补充。

使用GEBEncoding完成Bencode

GEBEncoding

GEBEncoding:An Objective-C BEncoding Library

屏幕快照 2018-06-07 下午4.46.50.png

代码结构:

屏幕快照 2018-06-07 下午4.56.45.png

GEBEncoding使用方法:

引入pod库

这个pod库是我根据上面的代码,建立的pod库。方便iOS项目集成。

    pod 'GEBEncoding'

编码encode

//  +(NSData *)encodeDataFromObject:(id)object
//
//  This method to returns an NSData object that contains the bencoded
//  representation of the object that you send. You can send complex structures
//  such as an NSDictionary that contains NSArrays, NSNumbers and NSStrings, and
//  the encoder will correctly serialise the data in the expected way.
//
//  Supports NSData, NSString, NSNumber, NSArray and NSDictionary objects.
//
//  NSStrings are encoded as NSData objects as there is no way to differentiate
//  between the two when decoding.
//
//  NSNumbers are encoded and decoded with their longLongValue.
//
//  NSDictionary keys must be NSStrings.

+(NSData *)encodedDataFromObject:(id)object;

反编码

//  +(id)objectFromEncodedData:(NSData *)sourceData;
//
//  This method returns an NSObject of the type that is serialised in the bencoded
//  sourceData.
//
//  Bad data should not cause any problems, however if it is unable to deserialise
//  anything from the source, it may return a nil, which you need to check for.

+(id)objectFromEncodedData:(NSData *)sourceData;

+(id)objectFromEncodedData:(NSData *)sourceData withTypeAdvisor:(GEBEncodedTypeAdvisor)typeAdvisor;

使用效果:

    #import <GEBEncoding.h>
  
    NSDictionary * dict = @{@"inputs.sourceType":@"faceID",@"inputs.data":@"qwer"};
    NSData * data = [GEBEncoding encodedDataFromObject:dict];
    
    $ po data
    "d11:inputs.data4:qwer17:inputs.sourceType6:faceIDe"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容