欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

IOS 图片下载

程序员文章站 2022-05-18 10:18:03
       最近做一个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];

}