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

来源:互联网 发布:caffe slice层 编辑:程序博客网 时间:2024/05/12 02:09

新建继承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
0 0
原创粉丝点击