iOS网络 NSURLConnect下载 使用文件流的方式

与前一篇一样 都是写了下载分类 这个是使用了文件流的方式进行下载,代码相对少了点

下面就只贴上重要代码

//
//  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,assign) long long expectedContentLength;
@property (nonatomic,assign) long long fileSize;
@property (nonatomic,copy) NSString *targetPath;
@property (nonatomic,strong) NSOutputStream *fileStream;
@end

@implementation FileDownload

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

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.expectedContentLength = response.expectedContentLength;
    self.fileSize = 0;
    self.targetPath = [@"/Users/chen/Desktop" stringByAppendingPathComponent:response.suggestedFilename];
    [[NSFileManager defaultManager]removeItemAtPath:self.targetPath error:NULL];
    self.fileStream = [[NSOutputStream alloc]initToFileAtPath:self.targetPath append:YES];
    [self.fileStream open];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    self.fileSize += data.length;
    float progress = (float)self.fileSize / self.expectedContentLength;
    NSLog(@"%f",progress);
    [self.fileStream write:data.bytes maxLength:data.length];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"下载完成");
    [self.fileStream close];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"下载出错");
    [self.fileStream close];
}

@end



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

你可能感兴趣的:(iOS网络 NSURLConnect下载 使用文件流的方式)