zoukankan      html  css  js  c++  java
  • ios 从网络上获取图片并在UIImageView中显示

    ios 从网络上获取图片

     

     -(UIImage *) getImageFromURL:(NSString *)fileURL {

    NSLog(@"执行图片下载函数");

    UIImage * result;

    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];

    result = [UIImage imageWithData:data];

    return result;

    }

    二:

    先解释下以下代码中的变量:

    picsURL是一个存储URL地址的数组

    choice是选择图片的索引数

    self.imageView是View中的UIImageView

    其实显示一幅网络上的图片十分简单,如下2行代码即可。

    UIImage *image=[UIImage imageWithData:[NSDatadataWithContentsOfURL:[NSURLURLWithString:[picsURL objectAtIndex:choice]]]];

    [self.imageView setImage:image];

    但是这种方法是同步获取的,如果图片十分大的话,界面就会卡死了,所以一般采取异步方式来获取,如下:

    _data是一个NSMutableData

    - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response{
    //可以在显示图片前先用本地的一个loading.gif来占位。
       UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"loading.gif"];
       [self.imageView setImage:img];
       _data = [[NSMutableDataalloc] init];
       //保存接收到的响应对象,以便响应完毕后的状态。
       _response = response;
    }
    - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
    //_data为NSMutableData类型的私有属性,用于保存从网络上接收到的数据。
    //也可以从此委托中获取到图片加载的进度。
       [_data appendData:data];
       NSLog(@"%lld%%", data.length/_response.expectedContentLength * 100);
    }
    - (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{
       //请求异常,在此可以进行出错后的操作,如给UIImageView设置一张默认的图片等。
    }
    - (void)connectionDidFinishLoading:(NSURLConnection*)connection{
       //加载成功,在此的加载成功并不代表图片加载成功,需要判断HTTP返回状态。
       NSHTTPURLResponse*response=(NSHTTPURLResponse*)_response;
       if(response.statusCode == 200){
            //请求成功
            UIImage *img=[UIImage imageWithData:_data];
            [self.imageView setImage:img];
       }
    }

    这样就可以异步来加载图片了,提升了用户体验。

     
  • 相关阅读:
    MAUI预览版发布 (.NET 6 Preview2)
    ASP.NET Core 基础系列(6)(中间件)
    ASP.NET Core 基础系列(5)(appSetting)
    ASP.NET Core 基础系列(4)(Startup)
    ASP.NET Core 基础系列(3)(启动设置)
    ASP.NET Core 基础系列(2)(托管模型)
    ASP.NET Core 基础系列(1)(Main方法)
    Android开发学习之路-PopupWindow和仿QQ左滑删除
    部分病毒进程任务管理器终止不怎么办
    intellij idea 历史版本下载地址
  • 原文地址:https://www.cnblogs.com/worldtraveler/p/4588139.html
Copyright © 2011-2022 走看看