调用H5的方法需要给H5传一些参数,参数中包括图片的base64字符串。
错误一:
图片转base64,后面参数不能随便写,正确做法如下
NSData *imageData = UIImageJPEGRepresentation(img,0.1);
NSString *strImgBase64 = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
把NSDataBase64EncodingEndLineWithLineFeed换成枚举中的其他值转成的base64,然后拼到json字符串中时,校验根本不通过,所以调H5没反应。
错误二:
把参数拼成json字符串时,字典转json字符串作为参数调H5根本没反应
//第一层 NSMutableDictionary *mDicBack = [NSMutableDictionary new]; mDicBack[@"msg"] = @"success"; mDicBack[@"code"] = @"0"; //第二层 NSMutableDictionary *mDic2 = [NSMutableDictionary new]; mDic2[@"fromserver"] = dic; mDic2[@"base64"] = [NSString stringWithFormat:@"data:image/jpg;base64,%@",strImgBase64]; mDicBack[@"data"] = mDic2;
//字典转json字符串 if ([NSJSONSerialization isValidJSONObject:mDicBack]) { NSData * jsonData = [NSJSONSerialization dataWithJSONObject:mDicBack options:NSJSONWritingPrettyPrinted error:nil]; jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; } NSString *backJson = [NSString stringWithFormat:@"callBack('%@')", jsonStr]; [self.h5View stringByEvaluatingJavaScriptFromString:backJson];
只能换下面手工拼接方法才行。
jsonStr = [NSString stringWithFormat:@"{"msg":"success","code":"0","data":{"fromserver":{"result":%@,"message":"%@","path":"%@","serverpath":"\%@"},"base64":"data:image/png;base64,%@"}}",dic[@"result"],dic[@"message"],dic[@"path"],dic[@"serverpath"],strImgBase64];