IOS 图片下载
最近做一个ios程序的功能,要求图片在本地的话直接显示,不在本地则去网上下载,然后存储。到网上找完资料之后根据自己的理解实现了功能,下面说说思路。
实现一个继承imageview的类,这个类主要功能就是根据传来的图片名字判断本地是否存在该图片,不存在则下载,存在就直接显示。
- (void)drawrect:(cgrect)rect {
nsstring *docdir = [nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) objectatindex:0];
nsstring *picpath = [docdir stringbyappendingpathcomponent:self.picname]; //获取路径
if ([[nsfilemanager defaultmanager] fileexistsatpath:picpath]) {
//存在图片的时候直接读取
nsdata *data = [nsdata datawithcontentsoffile:picpath];
self.thumbnail.image = [uiimage imagewithdata:data];
}
else{//开线程去下载并存储
[nsthread detachnewthreadselector:@selector(loadimage) totarget:self withobject:nil];
}
}
- (void)loadimage {
//下载图片
nsurl *url=[nsurl urlwithstring:@"https://www.baidu.com/img/baidu_sylogo1.gif"];
uiimage *img = [[uiimage alloc] initwithdata:[nsdata datawithcontentsofurl:url]];
self.thumbnail.image = img;
//存储图片
nsstring *docdir = [nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) objectatindex:0];
nsstring *picpath=[docdir stringbyappendingpathcomponent:self.picname];
//将图片写到documents文件中
[uiimagepngrepresentation(self.thumbnail.image) writetofile: picpath atomically:yes];
//线程退出
[nsthread exit];
}
下一篇: php5中类的学习
推荐阅读
-
[PHP]利用XAMPP搭建本地服务器, 然后利用iOS客户端上传数据到本地服务器中(三. PHP端代码实现) - M_Lee
-
iOS 14.3/iPadOS 14.3开发者预览版 Beta 2(18C5054c)怎么升级?
-
iOS15.4支持戴口罩解锁了!网友实测:支付也能用、无需Apple Watch
-
iOS 15.4支持戴口罩解锁 实测仅支持iPhone 12/13!速度超快 支付也能用
-
iOS应用突然无法从App Store获取到内购(IAP)产品列表的解决
-
Android自定义控件仿ios下拉回弹效果
-
iOS与unity交互、opencv开发教程
-
讲述Sagit.Framework解决:双向引用导致的IOS内存泄漏(下)- block中任性用self
-
ios开发之UITextField、UITextView限制最大输入数
-
IOS键盘弹出、隐藏