Objective-c 網絡編程1 Web請求和響應

//
//  ViewController.m
//  網絡編程
//
//  Created by DC017 on 15/12/9.
//  Copyright © 2015年 DC017. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
{
    UITextField *textfield;
    UILabel* label;
    UIButton *button;
    UIProgressView *progress;
    NSMutableData * mudata;
    long long totalLength;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
   

    [self buju];
    
}
-(void)buju{
    
    
    textfield =[[UITextField alloc]initWithFrame:CGRectMake(10, 60, 300, 30)];
    textfield.layer.borderWidth=2;
    textfield.layer.cornerRadius=7;
    textfield.text=@"http://b.zol-img.com.cn/desk/bizhi/image/7/1920x1080/1449126103556.jpg";
    textfield.layer.borderColor=[UIColor blackColor].CGColor;
    [self.view addSubview:textfield];
    
   progress=[[UIProgressView alloc]initWithFrame:CGRectMake(10, 100, 300,2 )];
   progress.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:progress];
    
    label =[[UILabel alloc]initWithFrame:CGRectMake(10, 130, 100, 20)];
    label.textColor=[UIColor blackColor];
    label.text=@"請下載";
    
    [self.view addSubview:label];
    
     button=[[UIButton alloc]initWithFrame:
    CGRectMake(40, 400, 50, 20)];
    
    [button setTitle:@"下載" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    button.layer.borderWidth=1;
    button.layer.borderColor=[UIColor redColor].CGColor;
    button.layer.cornerRadius=8;
    [self.view addSubview:button];
    
    [button addTarget:self action:@selector(xiazai) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}

-(void)xiazai{
    NSLog(@"下載");
    NSString * tri=textfield.text;
    //新版
    //tri=[tri stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    //舊版
    tri=[tri stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url=[NSURL URLWithString:tri];
    
    //建立請求
    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url cachePolicy:0 timeoutInterval:15.0f];
    
    //建立鏈接
    NSURLConnection * Connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    //啓動鏈接
    [Connection start];

}
#pragma mark -開始代理 的四種方法

#pragma mark 開始接收響應
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"接收響應");
    mudata=[[NSMutableData alloc]init];
    //初始化進度條
    progress.progress=0;
    NSLog(@"%@",response);
    
    //處理響應;
    //經過響應頭中
    
    NSHTTPURLResponse * httpurl=(NSHTTPURLResponse *)response;
    NSDictionary * head=[httpurl allHeaderFields];
    NSLog(@"%@",head);
    
    totalLength =[head [@"Content-Length"]longLongValue];
    
    NSLog(@"%lld",totalLength);
    
    
}
#pragma mark 接收數據
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"接收數據");
    
    [mudata appendData:data];
    //更新進度條
    
    [self gengxinjindutiao];
    
    
}
#pragma mark 數據接收完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"數據接收完成");
    //數據保存蘋果官方要求只能保存到緩存裏
    NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    NSLog(@"%@",path);
    path=[path stringByAppendingPathComponent:@"下載圖片01.jpg"];
    //保存下載內容
    [mudata writeToFile:path atomically:YES];
    
}

#pragma mark 請求數據失敗
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"請求失敗 緣由是:%@",error);
}

-(void)gengxinjindutiao{
    if (mudata.length==totalLength) {
        label.text=@"下載完成";
    }
    else{
        label.text=@"正在下載";
        
    }
    progress.progress=(float)mudata.length/totalLength;
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
相關文章
相關標籤/搜索