NSOutputStream操作会在字符中的<br />后面添加/r/n
项目是这样的,详情界面需要显示一段html代码的介绍,自己又不想用webview,原因有两个,一个是webview消耗内存比较大,二个是我用的是tableview,cell要事先设定高度,而webview又必须在加载完毕后才能设置高度,所以果断放弃webview,直接把html代码里面的<br />换成了\n然后用UILabel来展示,这里介绍一个根据cell内容获取cell高度的方法:
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height+1;
但是执行之后发现换行文字之间的间距过大,像是换了两次行,然后经理就说你用webview,我就跟他解释我为什么不用webview,他说:“xxx就用的webview”。我就直接无视,继续研究为什么间距过大。吐槽完毕进入正题
1.首先怀疑的时UILabel size to fit 惹得祸,用过这个属性的都知道一般达不到我们想要的效果,在一番验证后,判定不是UILable 的责任。
2.然后又打印了request 的response(json解析过的),发现打印效果如下:
打印数据直接换行了,怎么回事,难道是json 解析搞得鬼?然后又找到数据请求的地方,在- (
void)connection:(
NSURLConnection
__unused *)connection didReceiveData:(
NSData *)data 打印data 转化后的结果,效果如下:
嗯?发现了吧,所有的<br />后面都有\r\n,难道是afnetwork搞得鬼?项目中用的afnetwork。
3.新建一个项目,然后启动一个请求,协议代码如下:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[outputStream open];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSUInteger length = [data length];
while (YES) {
NSInteger totalNumberOfBytesWritten = 0;
if ([outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = (uint8_t *)[data bytes];
NSInteger numberOfBytesWritten = 0;
while (totalNumberOfBytesWritten < (NSInteger)length) {
numberOfBytesWritten = [outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)];
if (numberOfBytesWritten == -1) {
break;
}
totalNumberOfBytesWritten += numberOfBytesWritten;
}
break;
}
if (outputStream.streamError) {
[connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:connection withObject:outputStream.streamError];
return;
}
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSData *responseData = [outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"respons ... %@",str);
}
输出结果如下:
和上图一样,都是在<br \>后面加上了 “\r\n”。 这样问题就定位出来了,是NSOutputStream数据操作在捣乱。
以上就是解决问题的整个过程,如果你觉得作者哪里可以做的更好就评论回复吧,先谢谢啦