美文网首页codeER.tec
【code_小马】SDWebImage加载url图片不显示

【code_小马】SDWebImage加载url图片不显示

作者: 曾经像素有点低 | 来源:发表于2018-08-25 14:50 被阅读0次
    我们是工程师 ——加油 !

    1问题描述

    使用SDwebImage去加载含有逗号的url 时候会无法加载,但是在浏览器上显示正常。

    报错:Error Domain=NSURLErrorDomain Code=-1100 "(null)"

    接口例如:

    代码.png
    输出台
    报错.png

    我知道遇到问题都急于解决,所以先写解决方案,后写分析

    2 解决方法:

     找到UIImageView+WebCache.m文件,
     在统一下载图片入口前面添加如下代码(当然,
     用户代理的value也可以是其他格式,下面代码只做为参考)
    
    
    
    - (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"];
        }
    
    
     ...... /*这里省略SD源码*/ 
    }
    
    

    3.问题分析

    这是因为缺少 User-Agent 用户代理。
    看到别人的博文上面解释的用户代理是这么解释的:用户代理 User Agent,是指浏览器,它的信息包括硬件平台、系统软件、应用软件和用户个人偏好。

    设置用户代理格式例如:

    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
    

    个人的理解是 : 设置了用户代理,才能访问到这张图片。至于这个用户代理的格式,只要有值或者约定的特定格式字符串都可以。

    相关文章

      网友评论

        本文标题:【code_小马】SDWebImage加载url图片不显示

        本文链接:https://www.haomeiwen.com/subject/jvhgiftx.html