iOS网络 使用NSURLConnect下载--进度+无内存峰值

ViewController.h里的代码

//
//  ViewController.m
//  使用NSURLConnect下载-进度+无内存峰值
//
//  Created by chen on 15/2/17.
//  Copyright (c) 2015年 lanrw. All rights reserved.
//

#import "ViewController.h"
#import "FileDownload.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    FileDownload *download = [[FileDownload alloc]init];
    NSString *path = @"http://localhost/14-KVO实战演练.mp4";
    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:path];
    [download fileDownloadWithUrl:url];
}


@end



FileDownload.h里的代码

- (void)fileDownloadWithUrl:(NSURL *)url;



FileDownload.m里的代码
//
//  FileDownload.m
//  使用NSURLConnect下载-进度+无内存峰值
//
//  Created by chen on 15/2/17.
//  Copyright (c) 2015年 lanrw. All rights reserved.
//

#import "FileDownload.h"


@interface FileDownload () <NSURLConnectionDataDelegate>
// 目标路径
@property (nonatomic,copy) NSString *targetPath;
// 文件总大小
@property (nonatomic,assign) long long expectedContentLength;
// 已下载文件的大小
@property (nonatomic,assign) long long fileSize;
@end
@implementation FileDownload

- (void)fileDownloadWithUrl:(NSURL *)url
{
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];
}

#pragma mark - 代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 存放下载文件的目标路径
    self.targetPath = [@"/Users/chen/Desktop" stringByAppendingPathComponent:response.suggestedFilename];
    self.expectedContentLength = response.expectedContentLength;
    self.fileSize = 0;
    [[NSFileManager defaultManager]removeItemAtPath:self.targetPath error:NULL];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    self.fileSize += data.length;
    float progress = (float)self.fileSize / self.expectedContentLength;
    NSLog(@"%f",progress);
    [self appendData:data];
}
// 拼接下载的数据块
- (void)appendData:(NSData *)data
{
    NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:self.targetPath];
    if(fp == nil){
        [data writeToFile:self.targetPath atomically:YES];
    }else{
        [fp seekToEndOfFile];
        [fp writeData:data];
        [fp closeFile];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"下载完成");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"错误");
}


@end   

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



你可能感兴趣的:(iOS网络 使用NSURLConnect下载--进度+无内存峰值)