本文共 2208 字,大约阅读时间需要 7 分钟。
图片加载失败的问题,很可能是由于用户未设置User-Agent导致的。以下是详细的解决方法:
当你在网页开发过程中使用SDWebImage库加载图片时,如果发现图片无法正确显示并提示错误信息Error Domain=NSURLErrorDomain Code=403
,很有可能是由于图片加载的URL协议不兼容或者缺少必要的User-Agent信息引起的。图片链接如果仅使用HTTP协议而非HTTPS协议,可能会导致部分网站服务器拒绝请求。
HTTP与HTTPS协议不兼容:部分网站服务器为了防止未授权的爬虫抓取,会限制仅允许HTTPS协议的外部请求。如果你的图片链接使用HTTP协议访问,这些服务器会返回403错误。
缺少User-Agent信息:大多数现代网站都会检测请求的来源(User-Agent),以识别爬虫或非法抓取行为。如果你的请求没有User-Agent头信息,服务器可能会拒绝响应。
要解决这个问题,可以按照以下步骤进行:
设置User-Agent头信息
在使用SDWebImageDownloader
加载图片之前,需要先设置User-Agent。可以通过使用sharedDownloader
单例来设置User-Agent信息:NSString *userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][__bridge NSString *kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][__bridge NSString *kCFBundleIdentifierKey],[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][__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"];}
处理字符编码问题
如果User-Agent字符串中包含非ASCII字符,可以尝试使用CFStringTransform
进行转换: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; }}
设置请求头
确保User-Agent信息已经正确设置到请求头中:[[SDWebImageDownloader sharedDownloader] setValue:userAgent forHTTPHeaderField:@"User-Agent"];
sharedDownloader
是单例,设置User-Agent只需执行一次即可保存。通过以上方法,可以有效解决图片加载失败的问题,确保图片能够正常显示。
转载地址:http://cfhg.baihongyu.com/