forked from tanhaogg/THWebService
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTHDownloadWebService.m
More file actions
212 lines (182 loc) · 5.44 KB
/
THDownloadWebService.m
File metadata and controls
212 lines (182 loc) · 5.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
//
// THDownloadWebService.m
// UserSystem
//
// Created by Hao Tan on 12-3-21.
// Copyright (c) 2012年 http://www.tanhao.me All rights reserved.
//
#import "THDownloadWebService.h"
#import "THWebDefine.h"
@implementation THDownloadWebService
@synthesize overwrite;
@synthesize fileName=_fileName;
@synthesize filePath=_filePath;
@synthesize fileSize;
@synthesize peakSpeed;
@synthesize averageSpeed;
@synthesize downloadBlock;
+ (void)serviceWithUrl:(NSURL *)url handler:(THDownloadWebServiceBlock)block
{
THDownloadWebService *service = [[[self class] alloc] init];
service.url = url;
[service startWithHandler:block];
}
- (void)setDelegate:(id)anObject
{
_delegate = anObject;
}
- (id)delegate
{
return _delegate;
}
- (void)stop
{
[super stop];
[_fileHandle closeFile];
_fileHandle = nil;
[_timer invalidate];
_timer = nil;
_startDate = nil;
totalDownSize = 0;
onceDownSize = 0;
peakSpeed =0;
averageSpeed = 0;
fileSize = 0;
}
- (NSURLRequest *)setUpRequest:(NSError **)error
{
//当url为空的时间,返回失败
if (!_url)
{
if (error) *error = THErrorURLFail;
return nil;
}
//未指定文件名
if (!_fileName)
{
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:_url MIMEType:NULL expectedContentLength:0 textEncodingName:NULL];
_fileName = [response suggestedFilename];
/*
NSString *urlStr = [_url absoluteString];
_fileName = [urlStr lastPathComponent];
if ([_fileName length] > 32) _fileName = [_fileName substringFromIndex:[_fileName length]-32];
*/
}
//未指定路径
if (!_filePath)
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
_filePath = documentsDir;
}
//目标地址与缓存地址
_destinationPath=[_filePath stringByAppendingPathComponent:_fileName];
_temporaryPath=[_destinationPath stringByAppendingFormat:kTHDownLoadTask_TempSuffix];
//处理如果文件已经存在的情况
if ([[NSFileManager defaultManager] fileExistsAtPath:_destinationPath])
{
if (overwrite)
{
[[NSFileManager defaultManager] removeItemAtPath:_destinationPath error:nil];
}else
{
if (error) *error = THErrorFileExist;
return nil;
}
}
//缓存文件不存在,则创建缓存文件
if (![[NSFileManager defaultManager] fileExistsAtPath:_temporaryPath])
{
BOOL createSucces = [[NSFileManager defaultManager] createFileAtPath:_temporaryPath contents:nil attributes:nil];
if (!createSucces)
{
if (error) *error = THErrorCreateFail;
return nil;
}
}
//设置fileHandle
_fileHandle = [NSFileHandle fileHandleForWritingAtPath:_temporaryPath];
offset = [_fileHandle seekToEndOfFile];
NSString *range = [NSString stringWithFormat:@"bytes=%llu-",offset];
//设置下载的一些属性
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:_url];
[request addValue:range forHTTPHeaderField:@"Range"];
if (error) *error = NULL;
return request;
}
- (void)startWithHandler:(THDownloadWebServiceBlock)block;
{
self.downloadBlock = block;
[self startAsynchronous];
}
- (BOOL)startAsynchronous
{
BOOL sucess = [super startAsynchronous];
if (sucess)
{
_timer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:kTHDownLoadTimerInterval target:self selector:@selector(lisenProgressAndSpeed) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
_startDate = [[NSDate alloc] init];
}
return sucess;
}
- (void)lisenProgressAndSpeed
{
offset = [_fileHandle offsetInFile];
double totalTimeGap = fabs([_startDate timeIntervalSinceNow]);
double onceTimeGap = [_timer timeInterval];
averageSpeed = totalDownSize/totalTimeGap;
peakSpeed = onceDownSize/onceTimeGap;
onceDownSize = 0;
double progress = 0;
if (fileSize > 0)
{
progress = offset*1.0/fileSize;
}
if ([_delegate respondsToSelector:@selector(downloadProgressChange:progress:)])
{
[[self delegate] downloadProgressChange:self progress:progress];
}
if (self.downloadBlock)
{
self.downloadBlock(NULL,NULL,progress,NO);
}
}
#pragma mark -
#pragma mark NSURLConnectionDelegate
- (void)didReceiveResponse:(NSURLResponse *)response
{
if ([response expectedContentLength] != NSURLResponseUnknownLength)
{
fileSize = [response expectedContentLength] + offset;
}
[super didReceiveResponse:response];
if (self.downloadBlock)
{
self.downloadBlock(response,NULL,0,NO);
}
}
- (void)didReceiveData:(NSData *)aData
{
totalDownSize += aData.length;
onceDownSize += aData.length;
[_fileHandle writeData:aData];
}
- (void)didFailWithError:(NSError *)error
{
[super didFailWithError:error];
if (self.downloadBlock)
{
self.downloadBlock(NULL,error,0,NO);
}
}
- (void)didFinishLoading
{
[[NSFileManager defaultManager] moveItemAtPath:_temporaryPath toPath:_destinationPath error:nil];
[super didFinishLoading];
if (self.downloadBlock)
{
self.downloadBlock(NULL,NULL,0,YES);
}
}
@end