//根据urlString 下载网络图片的方法
-(UIImage * )downloadWebImageWithUrlString:(NSString *)urlString{
//1.将urlString 转换为 URL
NSURL *url =[NSURL URLWithString:urlString];
//2.根据URL获取数据
NSData *data =[NSData dataWithContentsOfURL:url];
//3.根据数据获取图片
UIImage *image =[UIImage imageWithData:data];
//4.将图片返回
return image;
}
- (void)viewDidLoad {
[super viewDidLoad];
//urlString 也就是要下载的图片的网址
NSString *urlString =@"http://static.oschina.net/uploads/user/738/1476033_100.jpg?t=1395636442000";
//创建一个imageView用于展示下载的图片
UIImageView *imageView =[[UIImageView alloc]initWithFrame:CGRectMake(80, 80, 200, 200)];
//调用下载图片的方法 并设置为imageView的image
imageView.image =[self downloadWebImageWithUrlString:urlString];
//将imageView添加到view上
[self.view addSubview:imageView];
}
运行之后出现的第一个bug:
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.
这是因为xCode7之后,苹果为了网络访问的安全性,禁止了对http的网络访问,只允许访问https的网址,只是不太符合我们国内的网络访问需求,解决方法如下
- 找到项目中的Info.plist文件 右键--> Open As -->Source Code
- 在Info.plist文件中 找到第一个 按下回车
- 将下面这段代码粘贴上
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
这段代码的作用是 告诉xCode 允许访问http的网址,
第二个bug
NSURL *url =[NSURL URLWithString:urlString]; urlString 存在 url却为nil
解决方法
- 1.首先查看机器是否联网
- 2.将urlString复制到浏览器上,查看该资源对应的图片是否存在
-
3.查看urlString中是否含有特殊字符,比如 汉字 ‘&’等,如果有特殊字符 ,需要将urlString进行转义
- 9.0之前用下面这个方法转义
urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- 9.0之后用如下方法代替,不知道参数怎么使用,求大神指教
[urlString stringByAddingPercentEncodingWithAllowedCharacters:<#(nonnull NSCharacterSet *)#>]
-
4.查看urlString中是否不小心敲入了空格。
第三个 bug:
NSData *data =[NSData dataWithContentsOfURL:url]; url 存在 data为nil ,等模拟出来再补充。