您的位置:首页 > 其它

NSURLConnection的使用

2013-11-24 21:55 302 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: