网络编程—将网络上的大文件下载到本地,并打印其进度。
点击“开始传输”按钮,将网络上的大文件先下载下来,下载完成后,保存到本地。
UI效果图如下:
具体代码如下:
// ViewController.m
// 0611—数据请求+滚动条
#import “ViewController.h”
unsigned long tempLength;
@interface ViewController () <NSURLConnectionDataDelegate>
{
NSMutableData * resultData;
UISlider * _slider;
}
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self _loadView];
}
– (void) _loadView
{
self.view.backgroundColor=[UIColor colorWithRed: green:1 blue:1 alpha:0.7];
UISlider * slider=[[UISlider alloc]initWithFrame:CGRectMake(, 200, self.view.frame.size.width, 40)];
slider.backgroundColor=[UIColor colorWithRed:0.1 green:0.1 blue:0.7 alpha:0.2];
slider.minimumValue=; //设置最小值
slider.maximumValue=1; //设置最大值
slider.value=; //设置起始值
slider.enabled=YES;
_slider=slider;
[self.view addSubview:slider];
// NSLog(@”%f”,self.view.frame.size.width); 375
// NSLog(@”%f”,self.view.frame.size.height); 667
UIButton * button=[[UIButton alloc]initWithFrame:CGRectMake(, , 120, 50)];
button.center=self.view.center;
[button setTitle:@”开始传输” forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
button.backgroundColor=[UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.4];
[button addTarget:self action:@selector(startTransition) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: button];
}
– (void)startTransition
{
NSLog(@”点击了按钮~”);
//通过URL建立请求对象
NSURL * url=[NSURL URLWithString:@”http://192.168.2.106/hahaha.zip”];
NSURLRequest * request=[NSURLRequest requestWithURL:url];
//创建NSURLConnection 对象用来连接服务器并且发送请求
NSURLConnection * conn=[[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
}
#pragma mark – 代理方法
//接受到响应
– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@”——-%lu”,(unsigned long)response.expectedContentLength);
tempLength=(unsigned long)response.expectedContentLength;
resultData =[NSMutableData data];
}
//接收到数据
– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[resultData appendData:data];
_slider.value=(float)resultData.length/(float)tempLength;
NSLog(@”%lu ***** %f”,(unsigned long)resultData.length,_slider.value);
}
//结束下载
– (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@”下载结束,保存到本地文件”);
//创建一个文件
NSFileManager * manager=[NSFileManager defaultManager];
//用path保存路径
NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
path=[path stringByAppendingPathComponent:@”hahaha1.zip”];
NSLog(@”%@”, path);
//在路径下创建文档并将数据写入文档
[manager createFileAtPath:path contents:resultData attributes:nil];
}
//请求失败
– (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@”didFailWithError”);
}
@end
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/3368.html