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) {

    NSMutableDictionary *mentionedInfodic = [[NSMutableDictionary alloc] init];

    [mentionedInfodic setObject:@(self.mentionedInfo.type) forKeyedSubscript:@"type"];

    if (self.mentionedInfo.type == RC_Mentioned_Users) {

      [mentionedInfodic setObject:self.mentionedInfo.userIdList

          forKeyedSubscript:@"userIdList"];

    }

    [mentionedInfodic setObject:self.mentionedInfo.mentionedContent

        forKeyedSubscript:@"mentionedContent"];

    [dataDict setObject:mentionedInfodic 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];//调用下面方法进行解码

  }

}


- (void)decodeMentionedInfo:(NSDictionary *)dictionary {//此方法在RCMessageContent中已经实现,直接调用即可

  RCDictionary *mentionedInfoDic =

      [[RCDictionary alloc] initWithDictionary:dictionary];

  if (mentionedInfoDic) {

    RCMentionedInfo *mentionedInfo = [[RCMentionedInfo alloc] init];

    mentionedInfo.type =

        [[mentionedInfoDic numberObjectForKey:@"type"] intValue];

    if (mentionedInfo.type == RC_Mentioned_Users) {

      mentionedInfo.userIdList = [mentionedInfoDic objectForKey:@"userIdList"];

    }

    mentionedInfo.mentionedContent =

        [mentionedInfoDic objectForKey:@"mentionedContent"];

    self.mentionedInfo = mentionedInfo;

  }

}