iOS网络 AFN简单的下载 与 session下载带进度数据
博客专区 > 沉恋 的博客 > 博客详情
iOS网络 AFN简单的下载 与 session下载带进度数据
沉恋 发表于3年前
iOS网络 AFN简单的下载 与 session下载带进度数据
  • 发表于 3年前
  • 阅读 111
  • 收藏 0
  • 点赞 0
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

//
//  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

http://pan.baidu.com/s/1eQiZSzg



共有 人打赏支持
粉丝 9
博文 55
码字总数 63031
×
沉恋
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: