下载的几种方式-将使用协议下载的方法封装成类

一、同步下载

》第一种方式:将URL转化为字符串打印

    NSString *str1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com/"] encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"str1 : %@", str1);


》第二种方式:将URL转化为Data数据打印

    NSData *data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com/"] options:NSDataReadingMappedAlways error:nil];
    NSString *str2 = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
    NSLog(@"str2 : %@", str2);


》第三种方式:使用 sendSynchronousRequest:returningResponse:error: 方法

    NSURLResponse *response1 = [[NSURLResponse alloc] init];
    NSData *data2 = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com/"]] returningResponse:&response1 error:nil];
    NSString *str3 = [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];
    NSLog(@"str3: %@", str3);


二、异步下载

》第一种方式:使用sendAsynchronousRequest:queue:completionHandler: 方法

    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com/"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"下载完成。。。");
    }];
    NSLog(@"程序结束");

》第二种方式:使用NSURLConnectionDataDelegate 

第一步:创建资源路径

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];


第二步:创建请求对象

    NSURLRequest *request = [NSURLRequestrequestWithURL:url];

第三步:建立请求,开始连接

    NSURLConnection *connection = [[NSURLConnectionalloc] initWithRequest:request delegate:self];

    [connection start];

看如下图:


下面使用协议来把这些步骤封装起来:

//  Download.h
//  download封装
#import <Foundation/Foundation.h>
@class Download;

// 1、定义协议
@protocol DownloadDataDelegate <NSObject>

@optional
- (void)downloadDidFinishLoading:(Download *)download;
@end


@interface Download : NSObject <NSURLConnectionDataDelegate>

@property (nonatomic, copy)NSString *path;
@property (nonatomic, strong)NSData *data;

// 2、创建一个指针,用来指向实现该协议的对象
@property (nonatomic, weak) id<DownloadDataDelegate> delegate;

- (void)start;
- (void)cancel;

@end
Download.h 头文件中定义了一个DownloadDataDelegate 协议,并写了一个协议方法,用来作为下载完成后的处理。

//  Download.m
//  download封装
#import "Download.h"
@implementation Download {
    NSURLConnection *_connection;
    NSMutableData *_data1;
}

- (void)start {
    // 资源路径
    NSURL *url = [NSURL URLWithString:_path];
    // 创建一个请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 创建连接对象,并设置代理
    _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    // 连接开始
    [_connection start];
}

- (void)cancel {
    // 关闭连接
    [_connection cancel];
}

#pragma mark - NSURLConnectDataDelegate 方法
// 请求连接出错的处理方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}

// 请求连接返回的响应头的处理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // 我们使用的是HTTP协议,所以可以作出判断
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    if (httpResponse.statusCode == 200) {
        _data1 = [[NSMutableData alloc] init];

    }
}
// 请求连接收到数据的处理方法,数据量大就可能会不断调用许多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_data1 appendData:data];
}
// 下载完成后的处理方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // 总计,方便外部使用
    _data = _data1;
    //3. 使用指针调用协议方法 , 下载完成后之后会调用downloadDidFinishLoading:方法,以便在外部使用
    [_delegate downloadDidFinishLoading:self];
    
}

@end

这里只是简单的封装,还可以根据具体情况,进一步封装。下面是如何在外部使用:

//  ViewController.m

#import "ViewController.h"
#import "Download.h"

@interface ViewController () <DownloadDataDelegate>
{
    NSMutableData *_resData;
}

@end

@implementation ViewController
            
- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建NSMutableData类对象,接受总共的数据
    _resData = [[NSMutableData alloc] init];
    
    // 创建download 对象,给出资源路径,下载东西
    Download *download = [[Download alloc] init];
    download.path = @"http://www.baidu.com";
    // 这里和其它协议一样,设置代理
    download.delegate = self;
    [download start];
    
}
#pragma mark - DownloadDataDelegate 方法
// 做一些下载后的处理,这里简单的打印了一下
- (void)downloadDidFinishLoading:(Download *)download {
    NSLog(@"下载完成");
    [_resData appendData:download.data];
    NSString *dataStr = [[NSString alloc] initWithData:_resData encoding:NSUTF8StringEncoding];
    NSLog(@"dataStr %@", dataStr);
}

@end





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值