码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发 - NSURLConnection实现断点续传下载

时间:2015-05-13 12:56:19      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:nsurlconnection   下载   请求   ios   开发   

常用类

NSURL//请求地址
NSURLRequest//一个NSURLRequest对象就代表一个请求,它包含的信息有:
一个NSURL对象
请求方法、请求头、请求体
请求超时
… …

NSMutableURLRequest://NSURLRequest的子类
NSURLConnection      //负责发送请求,建立客户端和服务器的连接
发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据

NSURLConnection的使用步骤

使用NSURLConnection发送请求的步骤很简单
创建一个NSURL对象,设置请求路径
传入NSURL创建一个NSURLRequest对象,设置请求头和请求体
使用NSURLConnection发送NSURLRequest

技术分享

NSURLConnection发送请求

NSURLConnection常见的发送请求方法有以下几种
同步请求


+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;

异步请求:根据对服务器返回数据的处理方式的不同,又可以分为2种
block回调


+ (void)sendAsynchronousRequest:(NSURLRequest*) request                          queue:(NSOperationQueue*) queue                                                  completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
代理
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;

在startImmediately = NO的情况下,需要调用start方法开始发送请求
- (void)start;

成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate协议

NSURLConnectionDataDelegate代理方法

//开始接收到服务器的响应时调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

//接收到服务器返回的数据时调用(服务器返回的数据比较大时会调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

//服务器返回的数据完全接收完毕后调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

//请求出错时调用(比如请求超时)
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

NSMutableURLRequest可变URL请求

NSMutableURLRequest是NSURLRequest的子类,常用方法有

//设置请求超时等待时间(超过这个时间就算超时,请求失败)
- (void)setTimeoutInterval:(NSTimeInterval)seconds;

//设置请求方法(比如GET和POST)
- (void)setHTTPMethod:(NSString *)method;

//设置请求体
- (void)setHTTPBody:(NSData *)data;

//设置请求头
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

创建GET和POST请求

//创建GET请求
NSString *urlStr = [@"http://192.168.1.102:8080/Server/login?username=123&pwd=123" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//创建POST请求
NSString *urlStr = @"http://192.168.1.102:8080/Server/login";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 请求体
NSString *bodyStr = @"username=123&pwd=123";
request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

断点续传下载实例

#import "ViewController.h"
#import "DACircularProgressView.h"

@interface ViewController () <NSURLConnectionDataDelegate>
- (IBAction)download:(UIButton *)sender;

/**
 *  用来写数据的文件句柄对象
 */
@property (nonatomic, strong) NSFileHandle *writeHandle;
/**
 *  文件的总大小
 */
@property (nonatomic, assign) long long totalLength;
/**
 *  当前已经写入的文件大小
 */
@property (nonatomic, assign) long long currentLength;

/**
 *  连接对象
 */
@property (nonatomic, strong) NSURLConnection *conn;

@property (nonatomic, weak) DACircularProgressView *circleView;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    DACircularProgressView *circleView = [[DACircularProgressView alloc] init];
    circleView.frame = CGRectMake(100, 50, 100, 100);
    circleView.progressTintColor = [UIColor redColor];
    circleView.trackTintColor = [UIColor blueColor];
    circleView.progress = 0.0000001;
    [self.view addSubview:circleView];
    self.circleView = circleView;
}

#pragma mark - NSURLConnectionDataDelegate代理方法
/**
 *  请求失败时调用(请求超时、网络异常)
 *
 *  @param error      错误原因
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError");
}

/**
 *  1.接收到服务器的响应就会调用
 *
 *  @param response   响应
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (self.currentLength) return;

    // 文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"];

    // 创建一个空的文件 到 沙盒中
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr createFileAtPath:filepath contents:nil attributes:nil];

    // 创建一个用来写数据的文件句柄
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];

    // 获得文件的总大小
    self.totalLength = response.expectedContentLength;
}

/**
 *  2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)
 *
 *  @param data       这次返回的数据
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 移动到文件的最后面
    [self.writeHandle seekToEndOfFile];

    // 将数据写入沙盒
    [self.writeHandle writeData:data];

    // 累计文件的长度
    self.currentLength += data.length;

    self.circleView.progress = (double)self.currentLength/ self.totalLength;
}

/**
 *  3.加载完毕后调用(服务器的数据已经完全返回后)
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.currentLength = 0;
    self.totalLength = 0;

    // 关闭文件
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}

- (IBAction)download:(UIButton *)sender {
    // 状态取反
    sender.selected = !sender.isSelected;

    // 断点续传
    // 断点下载

    if (sender.selected) { // 继续(开始)下载
        // 1.URL
        NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos.zip"];

        // 2.请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

        // 设置请求头
        NSString *range = [NSString stringWithFormat:@"bytes=%lld-", self.currentLength];
        [request setValue:range forHTTPHeaderField:@"Range"];

        // 3.下载(创建完conn对象后,会自动发起一个异步请求)
        self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
    } else { // 暂停
        [self.conn cancel];
        self.conn = nil;
    }
}
@end

NSURLConnection小结

1.发布异步请求01--block回调
+ (void)sendAsynchronousRequest:(NSURLRequest*) request
    queue:(NSOperationQueue*) queue
    completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler

//request : 需要发送的请求
//queue : 一般用主队列,存放handler这个任务
//handler : 当请求完毕后,会自动调用这个block

2.利用NSURLConnection发送请求的基本步骤
1> 创建URL
NSURL *url = [NSURL URLWithString:@"http://4234324/5345345"];

2> 创建request
NSURLRequest *request = [NSURLRequest requestWithURL:url];

3> 发送请求
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
 ^(NSURLResponse *response, NSData *data, NSError *connectionError) {
     4> 处理服务器返回的数据
 }];

iOS开发 - NSURLConnection实现断点续传下载

标签:nsurlconnection   下载   请求   ios   开发   

原文地址:http://blog.csdn.net/wangzi11322/article/details/45690749

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!