图片连接存到了一个数组中,下载一张添加一张。但是发现有时候只显示占位图不显示图片,刚开始以为是网络慢,下载需要一段时间,但是等了好久仍然没有。打断点查看了一下,原来是因为图片链接包含中文,这样的话下载不成功了。于是用NSUTF8将字符串进行编辑,然后再去下载便可以了。
NSString * imageUrl = [imageUrl1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
全部代码如下:
- (void)addImage:(NSArray *)imageUrlArr{
for (NSString *imageUrl1 in imageUrlArr) {
NSString * imageUrl = [imageUrl1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
UIImage *newImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imageUrl];//用地址去本地找图片
if (newImage != nil) {
//如果本地有
// newImage就是图片
[_imageMuarr addObject:newImage];
[self raloadImage];
} else {
//如果本地没有
//下载图片
[[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imageUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//这里是处理下载进度的,好像没必要管他
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (image) {
//下载完成后
//同上处理
[_imageMuarr addObject:image];
[self raloadImage];
}
}];
}
}
}
- (void)raloadImage{
_myScrollView.backgroundColor = [UIColor clearColor];//去掉预设图片,也就是背景
UIImage *image = [_imageMuarr lastObject];//取数组的最后一个元素
CGFloat width = 110.0 /image.size.height *image.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((_imageMuarr.count -1) *10.0 +_imageTotalWidth, 0, width, 110)];
imageView.userInteractionEnabled = YES;
imageView.image = image;
[_myScrollView addSubview:imageView];
_imageTotalWidth += width;
_myScrollView.contentSize = CGSizeMake((_imageMuarr.count -1) *10.0 +_imageTotalWidth, 110);
imageView.tag = _imageMuarr.count-1;
UITapGestureRecognizer * singleRecognizerImageView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewSingleTapFrom:)];
[imageView addGestureRecognizer:singleRecognizerImageView];
}
网上查的还有一个方法是
NSString *encodedString = (NSString *)
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)urlString,
(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
NULL,kCFStringEncodingUTF8);