zoukankan      html  css  js  c++  java
  • IOS 图片下载

            最近做一个IOS程序的功能,要求图片在本地的话直接显示,不在本地则去网上下载,然后存储。到网上找完资料之后根据自己的理解实现了功能,下面说说思路。

            实现一个继承imageView的类,这个类主要功能就是根据传来的图片名字判断本地是否存在该图片,不存在则下载,存在就直接显示。

    - (void)drawRect:(CGRect)rect {

        NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

        NSString *picPath = [docDir stringByAppendingPathComponent:self.picName]; //获取路径

        if ([[NSFileManagerdefaultManager] fileExistsAtPath:picPath]) {

            //存在图片的时候直接读取

           NSData *data = [NSDatadataWithContentsOfFile:picPath];

            self.thumbnail.image = [UIImageimageWithData:data];

        }

        else{//开线程去下载并存储

            [NSThreaddetachNewThreadSelector:@selector(loadImage) toTarget:selfwithObject:nil];

        }

    }


    - (void)loadImage {

        //下载图片

        NSURL *url=[NSURLURLWithString:@"http://www.baidu.com/img/baidu_sylogo1.gif"];

        UIImage *img = [[UIImagealloc] initWithData:[NSDatadataWithContentsOfURL: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];

    }

               因为这是个view,因此我在- (void)drawRect:(CGRect)rect  写判断。



  • 相关阅读:
    2050编程赛 冰水挑战 HDU 6495
    Codeforces Round #565 (Div. 3) F.Destroy it!
    ADO 查询
    Default parameters (Function) – JavaScript 中文开发手册
    Errors: Deprecated expression closures (Errors) – JavaScript 中文开发手册
    JavaScript RegExp 对象
    在Java中为静态最终变量赋值
    FE_INVALID (Numerics) – C 中文开发手册
    getter-return (Rules) – Eslint 中文开发手册
    no-irregular-whitespace (Rules) – Eslint 中文开发手册
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3127476.html
Copyright © 2011-2022 走看看