我开发了一个名为 File Downloader 的类,如下所示:
第 1 步:创建一个“FileDownloader.h”并将其添加到其中。
#import <Foundation/Foundation.h>
@protocol fileDownloaderDelegate <NSObject>
@optional
- (void)downloadProgres:(NSNumber*)percent forObject:(id)object;
@required
- (void)downloadingStarted;
- (void)downloadingFinishedFor:(NSURL *)url andData:(NSData *)data;
- (void)downloadingFailed:(NSURL *)url;
@end
@interface FileDownloader : NSObject
{
@private
NSMutableURLRequest *_request;
NSMutableData *downloadedData;
NSURL *fileUrl;
id <fileDownloaderDelegate> delegate;
double totalFileSize;
}
@property (nonatomic, strong) NSMutableURLRequest *_request;
@property (nonatomic, strong) NSMutableData *downloadedData;
@property (nonatomic, strong) NSURL *fileUrl;
@property (nonatomic, strong) id <fileDownloaderDelegate> delegate;
- (void)downloadFromURL:(NSString *)urlString;
@end
第 2 步:创建一个“FileDownloader.m”并编写以下内容
#import "FileDownloader.h"
@implementation FileDownloader
@synthesize _request, downloadedData, fileUrl;
@synthesize delegate;
- (void)downloadFromURL:(NSString *)urlString
{
[self setFileUrl:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
self._request = [NSMutableURLRequest requestWithURL:self.fileUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0f];
NSURLConnection *cn = [NSURLConnection connectionWithRequest:self._request delegate:self];
[cn start];
}
#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if([delegate respondsToSelector:@selector(downloadingStarted)])
{
[delegate performSelector:@selector(downloadingStarted)];
}
totalFileSize = [response expectedContentLength];
downloadedData = [NSMutableData dataWithCapacity:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[downloadedData appendData:data];
if([delegate respondsToSelector:@selector(downloadProgres:forObject:)])
{
[delegate performSelector:@selector(downloadProgres:forObject:) withObject:[NSNumber numberWithFloat:([downloadedData length]/totalFileSize)] withObject:self];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if([delegate respondsToSelector:@selector(downloadingFailed:)])
{
[delegate performSelector:@selector(downloadingFailed:) withObject:self.fileUrl];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if([delegate respondsToSelector:@selector(downloadingFinishedFor:andData:)])
{
[delegate performSelector:@selector(downloadingFinishedFor:andData:) withObject:self.fileUrl withObject:self.downloadedData];
}
}
@end
第 3 步:现在在您的视图控制器中导入“#import "FileDownloader.h"" 并在 .h 文件中导入 "fileDownloaderDelegate" 委托
第 4 步:创建对象,设置委托和 URL 以下载文件。
FileDownloader *objDownloader = [[FileDownloader alloc] init];
[objDownloader setDelegate:self];
[objDownloader downloadFromURL:@"yourURL"];
第 5 步:不要忘记在视图控制器中实现 Delegate 方法以获取有关下载进度的通知。请享用..