一、具体问题  

  开发的过程中,发现某个界面部分图片的显示出现了问题只显示占位图片,取出图片的url在浏览器却是能打开的,各种尝试甚至找同行的朋友帮忙在他们项目里展示都会存在问题,最终发现通过第三方框架SDWebImage或者YYWebImage下载带有逗号的url图片链接都会下载失败,在下载方法完成的回调block里面打印信息如下:

Error Domain=NSURLErrorDomain Code= "(null)"

  现列举两个不能正常展示的图片url:

http://img1.imgtn.bdimg.com/it/u=3044191397,2911599132&fm=27&gp=0.jpg

http://img2.imgtn.bdimg.com/it/u=3509004173,840437551&fm=27&gp=0.jpg

  有兴趣的小伙伴可以拿到自己的项目里试试

二、问题原因

  网上有小伙伴提出是因为缺少User-Agent用户代理导致的。只有设置了用户代理,才能访问到这张带有逗号的url图片。至于这个用户代理的格式,只要有值或者约定的特定格式字符串都可以。

三、具体解决

1.第三方框架YYWebImage

  找到YYWebImageManager.m文件,定位到设置http请求头的属性即_headers的地方,加入一个User-Agent的键值对,具体改动可以看下面的方法

- (instancetype)initWithCache:(YYImageCache *)cache queue:(NSOperationQueue *)queue{
self = [super init];
if (!self) return nil;
_cache = cache;
_queue = queue;
_timeout = 15.0; NSString *userAgent = @"";
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; if (userAgent) {
if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
NSMutableString *mutableUserAgent = [userAgent mutableCopy];
if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
userAgent = mutableUserAgent;
}
}
} //带有逗号的图片url不显示的问题,重要的是设置代理才能解决
if (YYImageWebPAvailable()) {
_headers = @{ @"Accept" : @"image/webp,image/*;q=0.8", @"User-Agent" : userAgent};
} else {
_headers = @{ @"Accept" : @"image/*;q=0.8", @"User-Agent" : userAgent};
}
return self;
}

2.第三方框架SDWebImage

  找到SDWebImageDownloader.m文件,也是定位到设置http请求头的属性即_HTTPHeaders的地方,加入一个User-Agent的键值对,具体改动可以看下面的方法

- (id)init {
if ((self = [super init])) {
_operationClass = [SDWebImageDownloaderOperation class];
_shouldDecompressImages = YES;
_executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
_downloadQueue = [NSOperationQueue new];
_downloadQueue.maxConcurrentOperationCount = ;
_URLCallbacks = [NSMutableDictionary new];
/***********************/
NSString *userAgent = @"";
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; if (userAgent) {
if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
NSMutableString *mutableUserAgent = [userAgent mutableCopy];
if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
userAgent = mutableUserAgent;
}
}
}
/***********************/
#ifdef SD_WEBP
_HTTPHeaders = [@{@"Accept": @"image/webp,image/*;q=0.8", userAgent : @"User-Agent"} mutableCopy];
#else
_HTTPHeaders = [@{@"Accept": @"image/*;q=0.8", userAgent : @"User-Agent"} mutableCopy];
#endif
_barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
_downloadTimeout = 15.0;
}
return self;
}

或者是直接在UIImageView+WebCache.m文件中,在统一下载图片入口最前面添加如下代码

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
/***********************/
NSString *userAgent = @"";
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; if (userAgent) {
if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
NSMutableString *mutableUserAgent = [userAgent mutableCopy];
if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
userAgent = mutableUserAgent;
}
} [[SDWebImageDownloader sharedDownloader] setValue:userAgent forHTTPHeaderField:@"User-Agent"];
}
/***********************/
[self sd_cancelCurrentImageLoad]; ........省略原源码
}

3.其他第三方下载图片的框架

  直接全局搜索字符串"Accept",因为虽然缺少设置User-Agent用户代理,但是http请求头一般都会有设置"Accept",所以定位后,直接再加一个User-Agent的键值对就可以了

iOS下载图片失败的更多相关文章

  1. SDWebImage下载图片有时候无法成功显示出来

    之前用下面的方法现在图片,有时候会出现图片没有下载成功显示: - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)p ...

  2. iOS多线程自定义operation加载图片 不重复下载图片

    摘要:1:ios通过抽象类NSOperation封装了gcd,让ios的多线程变得更为简单易用:   2:耗时的操作交给子线程来完成,主线程负责ui的处理,提示用户的体验   2:自定义operati ...

  3. iOS多图片下载

    iOS多图片下载.在cell里面下载图片.做了缓存优化. (app.icon是图片地址) // 先从内存缓存中取出图片 UIImage *image = self.images[app.icon]; ...

  4. 使用SDWebImage下载图片,sharedDownloader方法下载成功,new 方法下载失败

    一,经历 1.使用 new 方法创建下载对象时,下载图片总是失败,而且不会执行成功或失败后的回调. 2.参考别人的代码,用的是sharedDownloader来创建下载对象,可以顺利下载图片. 3.看 ...

  5. 李洪强iOS开发之 - 实现九宫格并使用SDWebImage下载图片

     李洪强iOS开发之 - 实现九宫格并使用SDWebImage下载图片  源码:  // //  ViewController.m //  08-九宫格扩展 // //  Created by 李洪强 ...

  6. IOS开发-UI学习-根据URL显示图片,下载图片的练习(button,textfield,image view,url,data)

    编写一个如下界面,实现: 1.在文本输入框中输入一个网址,然后点击显示图片,图片显示到UIImageView中. 2.点击下载,这张显示的图片被下载到手机的Documents文件夹下的Dowmload ...

  7. IOS GCD (事例下载图片)

    @interface HMViewController () @property (weak, nonatomic) IBOutlet UIImageView *imageView; @end @im ...

  8. [翻译] AsyncImageView 异步下载图片

    AsyncImageView  https://github.com/nicklockwood/AsyncImageView AsyncImageView is a simple extension ...

  9. iOS:图片相关(18-02-12更)

    1.图片显示相关 1).图片聊天背景拉伸不失真 2).捏合.双击.下拉缩放 3).Banner.相册 4).动画 2.图片操作相关 1).获取.下载图片(分享.传图片用) 2).保存UIImage到本 ...

随机推荐

  1. 提高搜狗SR值和关键词排名

    凭借“输入法-浏览器-搜索”三级火箭战略,搜狗搜狗使用率已超过10%,并成功挤掉谷歌成为国内第二大搜索引擎服务提供商.随着搜狗的快速发展,越来越多的站长将目光投向针对搜狗搜索的关键词优化. 大家都知道 ...

  2. 2018.09.25 bzoj1856: [Scoi2010]字符串(组合数学)

    传送门 如果有n==m的条件就是卡特兰数. 但现在n不一定等于m. 我们可以考虑用求卡特兰数一样的方法来求答案. 我们知道有一种求卡特兰数的方法是转到二维平面求答案. 这道题就可以这样做. 我们将这个 ...

  3. 2018.07.04 POJ 2398 Toy Storage(二分+简单计算几何)

    Toy Storage Time Limit: 1000MS Memory Limit: 65536K Description Mom and dad have a problem: their ch ...

  4. C++之类和对象的特性

    简介:C++并不是一个纯粹的面向对象的语言,而是一种基于过程和面向对象的混合型的语言. 凡是以类对象为基本构成单位的程序称为基于对象的程序,再加上抽象.封装.继承和多态就成为面向对象程序. 1.掌握类 ...

  5. gj4 深入类和对象

    4.1 鸭子类型和多态 当看到一只鸟走起来像鸭子.游永起来像鸭子.叫起来也像鸭子,那么这只鸟就可以被称为鸭子 只要利用Python的魔法函数,就能实现某些Python数据类型的类似的方法. class ...

  6. aused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method fai

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roleDaoImpl' ...

  7. day3之文件操作

    一,文件操作基本流程. # 1.打开文件,产生文件句柄 # 2.操作文件句柄 # 3.关闭文件句柄 # f1 = open('11.txt',encoding='utf-8', mode='r') # ...

  8. 记spring mvc传入List<Object>的一次尝试

    首先,看一段异常: org.springframework.http.converter.HttpMessageNotReadableException: Could not read documen ...

  9. Codeforces735B Urbanization 2016-12-13 11:58 114人阅读 评论(0) 收藏

    B. Urbanization time limit per test 2 seconds memory limit per test 256 megabytes input standard inp ...

  10. B样条参数曲线学习(1)

    B样条参数曲线学习 Bezier曲线有许多优越性,但有两点不足: (1) 特征多边形的顶点个数决定了Bezier曲线的阶次,并且在阶次较大时,特征多边形对曲线的控制将会减弱: (2) Bezier曲线 ...