iOS SDWebImage載入url圖片不顯示
阿新 • • 發佈:2019-02-08
文章目錄
1、問題描述
2、問題的原因
3、如何解決問題
一、問題描述
使用SDwebImage去載入含有逗號的url 時候會無法載入,但是在瀏覽器上顯示正常。
我們先看錯誤碼是多少?
[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原始碼*/
}
.
.