#
import
"HMTRootViewController.h"
010.
#
import
"HMTAppDelegate.h"
011.
012.
013.
@interface
HMTRootViewController ()
014.
015.
@property
(nonatomic,strong)UIImageView *imageView;
016.
@property
(nonatomic,strong)UIProgressView *progressIndicator;
017.
018.
@property
(nonatomic,strong)NSURLSession *urlSession;
019.
020.
@property
(nonatomic,strong)NSURLSessionDownloadTask *sessionDownloadTask;
021.
@property
(nonatomic,strong)NSURLSessionDownloadTask *resumableTask;
022.
@property
(nonatomic,strong)NSURLSessionDownloadTask *backgroundTask;
023.
@property
(nonatomic,strong)NSData *partialData;
024.
025.
@end
026.
027.
@implementation
HMTRootViewController
028.
029.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
030.
{
031.
self = [
super
initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
032.
if
(self) {
033.
034.
}
035.
return
self;
036.
}
037.
038.
- (
void
)viewDidLoad{
039.
040.
[
super
viewDidLoad];
041.
042.
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(
0
,
64
,
320
,
300
)];
043.
[self.view addSubview:_imageView];
044.
045.
self.progressIndicator = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
046.
_progressIndicator.frame = CGRectMake(
50
,
500
,
220
,
50
);
047.
[self.view addSubview:_progressIndicator];
048.
049.
UIButton *cancleButton = [UIButton buttonWithType:UIButtonTypeSystem];
050.
cancleButton.frame = CGRectMake(
120
,
400
,
40
,
40
);
051.
[cancleButton setTitle:@
"取消"
forState:UIControlStateNormal];
052.
[cancleButton addTarget:self action:
@selector
(didClickCancleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
053.
[self.view addSubview:cancleButton];
054.
055.
UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeSystem];
056.
downloadButton.frame = CGRectMake(
20
,
400
,
40
,
40
);
057.
[downloadButton setTitle:@
"下载"
forState:UIControlStateNormal];
058.
[downloadButton addTarget:self action:
@selector
(didClickDownloadButtonAction:) forControlEvents:UIControlEventTouchUpInside];
059.
[self.view addSubview:downloadButton];
060.
061.
UIButton *uploadButton = [UIButton buttonWithType:UIButtonTypeSystem];
062.
uploadButton.frame = CGRectMake(
70
,
400
,
40
,
40
);
063.
[uploadButton setTitle:@
"上传"
forState:UIControlStateNormal];
064.
[uploadButton addTarget:self action:
@selector
(didClickUploadButtonAction:) forControlEvents:UIControlEventTouchUpInside];
065.
[self.view addSubview:uploadButton];
066.
067.
UIButton *resumableButton = [UIButton buttonWithType:UIButtonTypeSystem];
068.
resumableButton.frame = CGRectMake(
180
,
400
,
40
,
40
);
069.
[resumableButton setTitle:@
"恢复"
forState:UIControlStateNormal];
070.
[resumableButton addTarget:self action:
@selector
(didClickResuableButtonAction:) forControlEvents:UIControlEventTouchUpInside];
071.
[self.view addSubview:resumableButton];
072.
073.
UIButton *backgroundLoadButton = [UIButton buttonWithType:UIButtonTypeSystem];
074.
backgroundLoadButton.frame = CGRectMake(
220
,
400
,
80
,
40
);
075.
[backgroundLoadButton setTitle:@
"后台下载"
forState:UIControlStateNormal];
076.
[backgroundLoadButton addTarget:self action:
@selector
(didClickBackgroundButtonAction:) forControlEvents:UIControlEventTouchUpInside];
077.
[self.view addSubview:backgroundLoadButton];
078.
079.
080.
#pragma mark - 如果我们需要利用NSURLSession进行数据传输我们需要:
081.
082.
083.
084.
085.
086.
087.
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
088.
089.
090.
091.
092.
093.
094.
095.
096.
097.
self.urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];
099.
NSURLRequest *request = [NSURLRequest requestWithURL:url];
100.
101.
102.
103.
104.
105.
106.
self.sessionDownloadTask = [self.urlSession downloadTaskWithRequest:request];
107.
108.
109.
110.
111.
112.
}
113.
114.
#pragma mark 点击下载
115.
- (
void
)didClickDownloadButtonAction:(UIButton *)button{
116.
117.
118.
[_sessionDownloadTask resume];
119.
120.
}
121.
122.
#pragma mark 点击上传
123.
- (
void
)didClickUploadButtonAction:(UIButton *)button{
124.
125.
126.
if
(_imageView.image == nil) {
127.
128.
NSLog(@
"image view is empty"
);
129.
return
;
130.
131.
}
132.
133.
134.
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
135.
136.
CGSize size = _imageView.bounds.size;
137.
indicator.center = CGPointMake(size.width /
2.0
, size.height /
2.0
);
138.
[self.imageView addSubview:indicator];
139.
[indicator startAnimating];
140.
141.
143.
144.
145.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:
5
.0f];
146.
request.HTTPMethod = @
"PUT"
;
147.
148.
149.
150.
151.
152.
NSString *authStr = @
"admin:123456"
;
153.
154.
155.
156.
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
157.
NSString *encodeStr = [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
158.
NSString *authValue = [NSString stringWithFormat:@
"Basic %@"
, encodeStr];
159.
[request setValue:authValue forHTTPHeaderField:@
"Authorization"
];
160.
161.
162.
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
163.
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];
164.
165.
166.
NSData *imageData = UIImageJPEGRepresentation(_imageView.image,
0.75
);
167.
168.
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
169.
170.
171.
172.
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
173.
NSLog(@
"OK -> %@"
, str);
174.
175.
[NSThread sleepForTimeInterval:
5
.0f];
176.
177.
dispatch_async(dispatch_get_main_queue(), ^{
178.
179.
[indicator stopAnimating];
180.
[indicator removeFromSuperview];
181.
182.
});
183.
184.
}];
185.
186.
187.
[uploadTask resume];
188.
}
189.
190.
#pragma mark 点击取消
191.
192.
- (
void
)didClickCancleButtonAction:(UIButton *)button{
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
if
(!self.sessionDownloadTask) {
207.
208.
209.
[self.sessionDownloadTask cancelByProducingResumeData:^(NSData *resumeData) {
210.
211.
self.partialData = resumeData;
212.
self.sessionDownloadTask = nil;
213.
214.
}];
215.
}
216.
}
217.
218.
#pragma mark 恢复下载(断点续传)
219.
- (
void
)didClickResuableButtonAction:(UIButton *)button{
220.
221.
if
(self.partialData) {
222.
223.
self.sessionDownloadTask = [self.urlSession downloadTaskWithResumeData:self.partialData];
224.
self.partialData = nil;
225.
226.
}
else
{
227.
229.
self.resumableTask = [self.urlSession downloadTaskWithRequest:request];
230.
231.
}
232.
233.
[self.sessionDownloadTask resume];
234.
235.
}
236.
237.
#pragma mark 后台下载模式
238.
- (
void
)didClickBackgroundButtonAction:(UIButton *)button{
239.
241.
self.backgroundTask = [[self backgroundSession] downloadTaskWithRequest:request];
242.
243.
[self.backgroundTask resume];
244.
}
245.
246.
#pragma mark - NSURLSessionDownloadTaskDelegate
247.
248.
- (
void
)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
if
(session == [self backgroundSession]) {
263.
264.
self.backgroundTask = nil;
265.
HMTAppDelegate *appDelegate = (HMTAppDelegate *)[UIApplication sharedApplication].delegate;
266.
if
(appDelegate.backgroundURLSessionCompletionHandler) {
267.
268.
void
(^handler)() = appDelegate.backgroundURLSessionCompletionHandler;
269.
appDelegate.backgroundURLSessionCompletionHandler = nil;
270.
handler();
271.
}
272.
273.
}
274.
275.
276.
NSFileManager *fileManager = [NSFileManager defaultManager];
277.
NSURL *cachesURLPath = [[fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
278.
279.
NSURL *destinationPath = [cachesURLPath URLByAppendingPathComponent:[location lastPathComponent]];
280.
281.
NSError *error = nil;
282.
BOOL success = [fileManager moveItemAtURL:location toURL:destinationPath error:&error];
283.
[fileManager removeItemAtURL:location error:NULL];
284.
285.
286.
287.
if
(success) {
288.
289.
dispatch_async(dispatch_get_main_queue(), ^{
290.
291.
UIImage *image = [UIImage imageWithContentsOfFile:[destinationPath path]];
292.
self.imageView.image = image;
293.
294.
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
295.
296.
});
297.
}
298.
299.
}
300.
301.
302.
- (
void
)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
303.
304.
305.
if
(error == nil) {
306.
307.
dispatch_async(dispatch_get_main_queue(), ^{
308.
309.
self.progressIndicator.hidden = YES;
310.
});
311.
}
312.
313.
}
314.
315.
316.
- (
void
)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
317.
318.
double
currentValue = totalBytesWritten / (
double
)totalBytesExpectedToWrite;
319.
dispatch_async(dispatch_get_main_queue(), ^{
320.
NSLog(@
"%f"
,currentValue);
321.
self.progressIndicator.hidden = NO;
322.
self.progressIndicator.progress = currentValue;
323.
});
324.
}
325.
326.
327.
- (
void
)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
328.
329.
}
330.
331.
#pragma mark - NSURLSession另一个重要的特性:即使当应用不在前台时,你也可以继续传输任务。当然,我们的会话模式也要为后台模式
332.
- (NSURLSession *)backgroundSession{
333.
334.
335.
static
NSURLSession *backgroundSession = nil;
336.
static
dispatch_once_t onceToken;
337.
dispatch_once(&onceToken, ^{
338.
339.
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration:@
"com.shinobicontrols.BackgroundDownload.BackgroundSession"
];
340.
backgroundSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
341.
342.
});
343.
344.
return
backgroundSession;
345.
}
346.
347.
- (
void
)didReceiveMemoryWarning
348.
{
349.
[
super
didReceiveMemoryWarning];
350.
351.
}
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.