NSURLConnection的使用

NSURLConnection用于网络连接,这个是对于异步连接的另外一种实现方法。这种方法能够在异步连接获取数据时进行若干次的进度获知。

NSURLConnection需遵循NSURLConnectionDataDelegate协议,协议必须得实现方法包括:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;



#import "ViewController.h"


#define URL02 @"http://ww3.sinaimg.cn/bmiddle/c8dc68bajw1eaw9bpj6kfj20by0bymyw.jpg"


@interface ViewController ()


@end


@implementation ViewController

- (void)sendAsyn1:(NSString *)urlStr

{

    NSString *path = URL02;

    NSURL *url = [NSURL URLWithString:path];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    [NSURLConnection connectionWithRequest:request delegate:self];

    NSLog(@"发起异步连接");

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    //创建一个UIImageView框架用于放图片

    self.imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];

    //测试是否创建成功 设置它的颜色为红色

    self.imgV.backgroundColor = [UIColor redColor];

    //将UIImageView加入到父视图

    [self.view addSubview:self.imgV];


    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn1.frame = CGRectMake(180, 320, 100, 44);

    [btn1 setTitle:@"异步下载" forState:UIControlStateNormal];

    [btn1 addTarget:self action:@selector(sendAsyn1:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn1];

    

}


double length = 0.00;//用于存放数据的总长度


//获得服务器响应后调用该方法,只调用一次,可以获取响应对象,而进一步通过响应对象得知响应的期望长度

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"建立数据连接");

    self.data = [[NSMutableData alloc] init];//为NSMutableData开辟空间

    length = response.expectedContentLength;//获取数据的总长度

}


//该方法是接受到响应后调用该方法,但是在整个请求过程中会调用多次,data参数就是每次获取的数据块

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    

    [self.data appendData:data];//反复执行该段语句 拼接数据块 直到完成接收

    double dataSource =(self.data.length/length)*100 ;//当前获得的数据/数据总长度   就是它的百分比

    NSLog(@"数据接收到%.2f%%", dataSource );

    self.imgV.image = [UIImage imageWithData:self.data];//显示已经载好的数据直到完成

    

   }

//整个连接请求完成,数据加载完毕之后调用方法

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"接收完成");

}

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值