iOS开发(OC)——iOS原生API实现文件下载
2016-06-04 21:17
357 查看
新建继承NSObject类Downloader
Downloader.h代码
Downloader.m代码
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
相关文章推荐
- OBlog任意文件下载漏洞
- php隐藏实际地址的文件下载方法
- java实现适用于安卓的文件下载线程类
- php利用header函数实现文件下载时直接提示保存
- asp.net 文件下载的通用方法
- JSP文件下载功能的4种方法
- JSP隐含对象response实现文件下载
- JSP response对象实现文件下载的两种方式
- php实现文件下载功能的几个代码分享
- php实现文件下载实例分享
- PHP实现文件下载详解
- PHP实现文件下载断点续传详解
- PHP+Mysql+jQuery文件下载次数统计实例讲解
- php实现文件下载代码分享
- IIS支持exe文件下载配置方法附图
- VBS下载者(通过vbscript实现文件下载)
- php限制文件下载速度的代码
- JavaEE实现文件下载
- Android通过startService实现文件批量下载
- PHP 下载文件时自动添加bom头的方法实例