IOS網絡編程---(數據請求+slider)將網絡上的大文件下載到本地,并打印其進度
網絡編程---將網絡上的大文件下載到本地,并打印其進度。
點擊“開始傳輸”按鈕,將網絡上的大文件先下載下來,下載完成后,保存到本地。
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