ios - dataWithContentsOfURL 取有些图片返回空?

 金瑞期货秦臻 发布于 2022-10-26 07:17

使用dataWithContentsOfURL方法取图片文件,有些返回nil,例如:

NSURL *url=[NSURL URLWithString:@"http://wx2.sinaimg.cn/mw690/6f250299gy1fefknh4ml6j21kw163gyj.jpg"];
NSData *data=[NSData dataWithContentsOfURL:url options:nil error:&error];

图是微博里随便找的,直接在浏览器可以打开;执行后data为nil,Error如下:

Error Domain=NSCocoaErrorDomain Code=256 "The file “6f250299gy1fefknh4ml6j21kw163gyj.jpg” couldn’t be opened." UserInfo={NSURL=http://wx2.sinaimg.cn/mw690/6...}

同样的使用方法,换成其他比如百度Logo图片:

NSURL *url=[NSURL URLWithString:@"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"];
NSData *data=[NSData dataWithContentsOfURL:url options:nil error:&error];

结果正常。求问怎么回事?

1 个回答
  • EDIT:
    你在info.plist 里面设置一下这个。
    有可能是http的原因,百度那个是https。
    我不设置这个访问http那张图片会报App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
    How do I load an HTTP URL with App Transport Security enabled in iOS 9?
    Transport security has blocked a cleartext HTTP

    我试了一下,并没有出现你说的错误,能够正常得到图片。

        NSError *error;
        NSURL *url=[NSURL URLWithString:@"http://wx2.sinaimg.cn/mw690/6f250299gy1fefknh4ml6j21kw163gyj.jpg"];
        NSData *data=[NSData dataWithContentsOfURL:url options:0 error:&error];
        
        UIImage *image = [UIImage imageWithData:data];

    2022-10-27 00:43 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有