美文网首页
SDWebimage Error Domain=NSURLErr

SDWebimage Error Domain=NSURLErr

作者: 阶梯 | 来源:发表于2017-09-05 11:40 被阅读60次

    对于iOS加载图片,大家应该都用的Sdwebimage这个第三方库,简单又好用。但是我今天遇到了一个奇葩的问题。 有个图片url是‘http://12.12.182.92:726/myapp/app/obtainImage?id=8a83a3c1bf215‘,在浏览器上是可以显示。但是用sdwebimage显示不了。
    后来我换了另一个图片url是可以显示的。
    最后,我直接下载这张图片,发现报错了:Error Domain=NSURLErrorDomain Code=406 “The operation couldn’t be completed. (NSURLErrorDomain error 406.)”从log来看,报错原因是 SDWebImage : NSURLErrorDomain - Code = 406,找到解决方案是:通过重写 SDWebImage 中的 request headers ,来使图片下载成功。通过查找 Wikipedia 中对 ‘HTTP status code 406‘的定义:406 Not Acceptable - The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request,可修改 SDWebImage 中的如下代码:

    _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"];
    

    不过贸然修改第三方库的源代码是不明智的,所以在异步加载图片之前添加如下代码来使图片显示成功:

    [SDWebImageDownloader.sharedDownloader setValue:@"text/html,
    application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
    

    [SDWebImageDownloader.sharedDownloader setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8"
    forHTTPHeaderField:@"Accept"];
    //中文转utf8,并显示
    [self.codeImageView sd_setImageWithURL:[NSURL URLWithString:[codeStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]] placeholderImage:[UIImage imageNamed:@""]];

    相关文章

      网友评论

          本文标题:SDWebimage Error Domain=NSURLErr

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