网络文件下载

前段时间做了一个项目,要实现空中升级(就是从服务器下载更新包,然后写入到硬件里面),刚好用到网络编程

使用场景进行小文件传输:

方案一

NSURLConnection

1、获取需要下载文件URL

NSURL *url=[NSURL URLWithString:@"http://xxx.xxx.xxx.xxx:8086/files/d26a4302-17f3-461f-88e5-2e2cd25d00b9.jpeg"];

2、下载文件

[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)

 {

        self.imageView.image = [UIImage imageWithData:data];

 }];

方案二

NSData

NSURL *url = [NSURL URLWithString:@"http://xxx.xxx.xxx.xxx:8086/files/d26a4302-17f3-461f-88e5-2e2cd25d00b9.jpeg"];

NSData *data = [NSData dataWithContentsOfURL:url];

self.imageView.image = [UIImage imageWithData:data];

NSLog(@"data : %@",data);


使用场景进行大文件传输

demo

NSURLConnection

在ViewController.m实现NSURLConnectionDataDelegate代理

如下:

@interface ViewController ()<NSURLConnectionDataDelegate>

{

}

先了解NSURLConnectDataDelegate代理函数

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)response;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;


- (nullable NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request;

- (void)connection:(NSURLConnection *)connection   didSendBodyData:(NSInteger)bytesWritten

                                                 totalBytesWritten:(NSInteger)totalBytesWritten

                                         totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite;


- (NSCachedURLResponse*)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse;


- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

实现如下:

ViewController.m

@interface ViewController ()<NSURLConnectionDataDelegate>

{

    NSString *_address;


}


@property (nonatomic,strong) NSFileHandle *writeHandle;

@property (nonatomic, strong) NSURLConnection *conn;

@property (nonatomic, assign) long long currentindex;


@end

- (void)downloadFileFromServer{

    NSURL *url=[NSURL URLWithString:@"http://58.250.30.13:8086/files/d26a4302-17f3-461f-88e5-2e2cd25d00b9.jpeg"];

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];


    // 由于传送大文件,文件分成几部分传送,self.currentIndex记录当前要读取数据的位置

    NSString *range=[NSString stringWithFormat:@"currentIndex =%lld-",self.currentindex];

    [request setValue:range forHTTPHeaderField:@"Range"];

    // 发送一个下载任务

    self.conn=[NSURLConnection connectionWithRequest:request delegate:self];

}

//实现NSURLConnectDataDelegate代理函数

//接收到下载请求调用代理函数

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];

    NSString *filepath=[caches stringByAppendingPathComponent:response.suggestedFilename];

    _address = filepath;

    // 先创建一个0kb文件 到沙盒

    NSFileManager *mgr=[NSFileManager defaultManager];

    NSLog(@"%@",filepath);

    [mgr createFileAtPath:filepath contents:nil attributes:nil];

    // 创建写数据的文件句柄

    self.writeHandle=[NSFileHandle fileHandleForWritingAtPath:filepath];

}


//接收到数据调用代理函数

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    // 移动到文件的最后写入数据

    [self.writeHandle seekToEndOfFile];

    [self.writeHandle writeData:data];

    self.currentIndex+=data.length;

}

//下载完成调用代理函数

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    self.currentIndex = 0;

    // 关闭文件

    [self.writeHandle closeFile];

    self.writeHandle=nil;

}















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值