iOS SDWebImage加载url图片不显示

文章目录

   1、问题描述

   2、问题的原因

   3、如何解决问题

一、问题描述

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

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

我们先看错误码是多少?

[self.logo sd_setImageWithURL:[NSURL URLWithString:[defaults stringForKey:@"userPortraitUri"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

      NSLog(@"错误信息:%@",error);

}];

.

报错如下 :

误信息:Error Domain=NSURLErrorDomain Code=403

二、问题的原因

查阅了下材料,这是因为缺少 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

感觉还是一脸懵逼哇。我自己的理解是 : 设置了用户代理,才能访问到这张图片。至于这个用户代理的格式,只要有值或者约定的特定格式字符串都可以

三、如何解决问题

找到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源码*/ 
}

.
.

相关其他问题整理

你可能感兴趣的:(Objective-C)