前段时间做了一个项目,要实现空中升级(就是从服务器下载更新包,然后写入到硬件里面),刚好用到网络编程
使用场景进行小文件传输:
方案一
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;
}