当前知识库站点已不再维护。请移步新版知识库:https://help.rongcloud.cn/

iOS 自定义消息中@消息的编解码问题

自定义消息涉及到@消息的时候,可能遇到的编解码出错的问题
发布时间: 2017-03-27 18:51

回答:

自定义消息的@消息的编解码

编码参考:

- (NSData *)encode {

  NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];

  [dataDict setObject:self.content forKey:@"content"];

  if (self.extra) {

    [dataDict setObject:self.extra forKey:@"extra"];

  }

  if (self.mentionedInfo) {

    NSDictionary *mentionDic = [self encodeMentionedInfo:self.mentionedInfo];//此方法在父类RCMessageContent中已经实现,直接调用即可

    [dataDict setObject:mentionDic forKey:@"mentionedInfo"];

  }

  NSData *data = [NSJSONSerialization dataWithJSONObject:dataDict

                                                 options:kNilOptions

                                                   error:nil];

  return data;

}



解码参考:

- (void)decodeWithData:(NSData *)data {

  __autoreleasing NSError *__error = nil;

  if (!data) {

    return;

  }

  NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data

                                                             options:kNilOptions

                                                               error:&__error];

  RCDictionary *json = [[RCDictionary alloc] initWithDictionary:dictionary];


  if (json) {

    self.content = [json stringObjectForKey:@"content"];

    self.extra = [json stringObjectForKey:@"extra"];

    

    NSDictionary *mentionedInfoDic = [json objectForKey:@"mentionedInfo"];

    [self decodeMentionedInfo:mentionedInfoDic];//此方法在父类RCMessageContent中已经实现,直接调用即可

  }

}