// ViewController.m
// AFN下载
//
// Created by chen on 15/2/22.
// Copyright (c) 2015年 lanrw. All rights reserved.
//
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
@property (nonatomic,strong) NSURLSession *session;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
/**
* 简单的下载
*/
// [self downloadFile];
/**
* 有进度的下载
*/
[self downloadFile2];
}
/**
* 简单的下载
*/
- (void)downloadFile
{
AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/post/abc/07.mp4"] cachePolicy:1 timeoutInterval:6];
[[manger downloadTaskWithRequest:request progress:NULL destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:response.suggestedFilename];
NSURL *url = [NSURL fileURLWithPath:filePath];
return url;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"%@",error.localizedDescription);
}] resume];
}
/**
* 使用代理监控下载进度
*/
- (void)downloadFile2
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/post/abc/07.mp4"] cachePolicy:1 timeoutInterval:15];
[[self.session downloadTaskWithRequest:request]resume];
}
#pragma mark - 代理方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSString *pathFile = [NSTemporaryDirectory() stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *manger = [NSFileManager defaultManager];
[manger copyItemAtPath:location.path toPath:pathFile error:NULL];
}
// 进度数据
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@"%f",progress);
}
// 懒加载
- (NSURLSession *)session
{
if(_session == nil)
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
}
return _session;
}
@end
简单使用AFN实现下载和查看进度
最新推荐文章于 2022-03-21 22:01:29 发布