iOS开发技巧iOS点点滴滴iOS Developer

简单封装一个下载单例类

2016-01-13  本文已影响483人  静花寒

在简友的建议下,我今天试着重新写了一个下载单例类,实际用下来,可以说省去了很多麻烦事,果然单例还是很有必要的,废话不多说,下面上干货
@Realank

我写的尽量详细些,这样大家也好理解

#import <Foundation/Foundation.h>
#import "DailySelected.h"
@interface DownloadHandle : NSObject<NSURLConnectionDelegate>

+ (DownloadHandle *)shareDownloadHandle;
//传递的是model,因为等会model里面其他一些东西有用。
- (void)createDownloadWithDailySelected:(DailySelected *)dailySelected;
//第一个参数我声明是为了做进度条的接口数据,外界通过接收这个数据,可以做可视的运动的进度条
@property (nonatomic,strong) NSString *percent;
@property (nonatomic,strong) DailySelected *dailySelected;
@property (nonatomic,assign) CGFloat currentLength;
@property (nonatomic,assign) CGFloat totalLength;
@property (nonatomic,retain) NSMutableData *recvivedData;
@property (nonatomic,retain) NSString *fileName;

@end
#import "DownloadHandle.h"
static DownloadHandle *downloadHandle;
@implementation DownloadHandle

+ (DownloadHandle *)shareDownloadHandle
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        downloadHandle = [[DownloadHandle alloc] init];
    });
    return downloadHandle;
}

- (void)createDownloadWithDailySelected:(DailySelected *)dailySelected
{
    self.recvivedData = [[NSMutableData alloc] initWithLength:0];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:dailySelected.playUrl] cachePolicy:(NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:5.0];
    self.dailySelected = dailySelected;
    self.fileName = [[[[NSURL URLWithString:dailySelected.playUrl] absoluteString]lastPathComponent]copy];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    if (connection == nil) {
        
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.recvivedData appendData:data];
    self.currentLength += data.length;
    //MB
    //百分比
    self.percent = [NSString stringWithFormat:@"%.02f%%",(self.currentLength / self.totalLength) * 100];
    //NSLog(@"%@",self.percent);
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.totalLength = [response expectedContentLength];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *filePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0]stringByAppendingPathComponent:self.fileName];
    NSData *data = self.recvivedData;
    [data writeToFile:filePath atomically:NO];//将数据写入Documents目录。
    //NSLog(@"%@",filePath);
    self.fileName = filePath;
    //NSLog(@"%@",self.fileName);
    [[OpenEyeDataBase shareSqliteManager] insertDownloadWithModel:self.dailySelected];
    [[OpenEyeDataBase shareSqliteManager] insertDownloadWithModel:self.dailySelected fileName:self.fileName];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"fileName" object:nil];
}

这样,一个简单的单例类就可以使用了。

上一篇 下一篇

猜你喜欢

热点阅读