您的位置:首页 > 移动开发 > IOS开发

iOS开发(OC)——iOS原生API实现文件下载

2016-06-04 21:17 357 查看
新建继承NSObject类Downloader

Downloader.h代码

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

//@class Downloader;

typedef void(^Success)(NSMutableData *data,NSString *name);
typedef void(^Failure)(NSError *error);

@protocol ProGress <NSObject>

-(void)postPro:(CGFloat)pro;//代理实现进度传递

@end

@interface Downloader : NSObject <NSURLConnectionDataDelegate>
{
long long _length;//文件大小
NSMutableData *_datas;
long long _currenLenght;//当前下载的文件大小

}

@property (nonatomic, assign) long long length;
@property (nonatomic, strong) NSMutableData *datas;
@property (nonatomic, copy) Success success;
@property (nonatomic, copy) Failure failure;

@property (nonatomic, strong) NSString *strURL;
@property (nonatomic,strong)NSString *fileName;

@property (nonatomic,assign)id<ProGress>proDelegate;

- (void)asynchronousDownload:(NSString *)url failure:(Failure)failure;

@end


Downloader.m代码

//
//  Downloader.m
//  QNNSEC
//
//  Created by chenp on 16/5/25.
//  Copyright © 2016年 chenp. All rights reserved.
//

#import "Downloader.h"

@implementation Downloader

- (void)asynchronousDownload:(NSString *)strURL
{
_currenLenght=0;
self.strURL = strURL;
NSURL *url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];

[NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)asynchronousDownload:(NSString *)url failure:(Failure)failure
{
self.failure = failure;

[self asynchronousDownload:url];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_length = response.expectedContentLength;
_datas = [NSMutableData dataWithCapacity:_length];
self.fileName= [response suggestedFilename];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
_currenLenght+=data.length;
[self.datas appendData:data];
if (self.proDelegate && [self.proDelegate conformsToProtocol:@protocol(ProGress)]) {
[self.proDelegate postPro:(CGFloat)_currenLenght/(CGFloat)_length];
}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"--->> Downloader 下载完成");
self.success(self.datas,self.fileName);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.failure(error);
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  文件下载