博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Objective-c 网络编程3 NSURLSession
阅读量:6496 次
发布时间:2019-06-24

本文共 6150 字,大约阅读时间需要 20 分钟。

hot3.png

////  ViewController.m//  网络编程3////  Created by DC017 on 15/12/10.//  Copyright © 2015年 DC017. All rights reserved.//#pragma mark NSURLSession 学习#import "ViewController.h"@interface ViewController ()
{    UITextField * textfield;    UIButton * xiazai;    UIButton * quxiao;    UIButton * zanting;    UIButton * huifu;    UILabel * label;    UIProgressView * progress;        NSURLSessionDownloadTask *downloadTask;    }@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    [self layout];    // Do any additional setup after loading the view, typically from a nib.}//layout布局-(void)layout{    textfield=[[UITextField alloc]initWithFrame:CGRectMake(20, 60, 300, 20)];    textfield.layer.borderWidth=1;    textfield.layer.borderColor=[UIColor redColor].CGColor;    textfield.text=@"http://b.zol-img.com.cn/desk/bizhi/image/5/2560x1600/1414029841427.jpg";    //设置圆角    textfield.layer.cornerRadius=4;    [self.view addSubview:textfield];            label=[[UILabel alloc]initWithFrame:CGRectMake(60, 200, 80, 20)];    label.textColor=[UIColor redColor];    [self.view addSubview:label];        progress =[[UIProgressView alloc]initWithFrame:CGRectMake(20, 100,300 ,5)];        [self.view addSubview:progress];        xiazai=[[UIButton alloc]initWithFrame:CGRectMake(20, 400, 60, 20)];    zanting=[[UIButton alloc]initWithFrame:CGRectMake(100, 400, 60, 20)];    huifu=[[UIButton alloc]initWithFrame:CGRectMake(180, 400, 60, 20)];    quxiao=[[UIButton alloc]initWithFrame:CGRectMake(260, 400, 60, 20)];            [xiazai  setTitle:@"下载" forState:UIControlStateNormal];    [zanting setTitle:@"暂停" forState:UIControlStateNormal];    [huifu setTitle:@"恢复" forState:UIControlStateNormal];    [quxiao setTitle:@"取消" forState:UIControlStateNormal];                [xiazai setTitleColor:[UIColor redColor] forState:UIControlStateNormal];    [zanting setTitleColor:[UIColor redColor] forState:UIControlStateNormal];    [huifu setTitleColor:[UIColor redColor] forState:UIControlStateNormal];    [quxiao setTitleColor:[UIColor redColor] forState:UIControlStateNormal];        [xiazai addTarget:self action:@selector(xiazai) forControlEvents:UIControlEventTouchUpInside];    [zanting addTarget:self action:@selector(zanting) forControlEvents:UIControlEventTouchUpInside];    [huifu addTarget:self action:@selector(huifu) forControlEvents:UIControlEventTouchUpInside];    [quxiao addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchUpInside];                         [self.view addSubview:xiazai];    [self.view addSubview:zanting];    [self.view addSubview:huifu];    [self.view addSubview:quxiao];    }-(void)xiazai{    NSLog(@"下载");    //创建url    NSString * strurl=textfield.text;        strurl =[strurl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];        NSURL *url=[NSURL URLWithString:strurl];        //创建请求    NSURLRequest * request=[NSURLRequest requestWithURL:url];        //创建session 会话        //配置session(默认--单例)    NSURLSessionConfiguration * sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];        sessionConfig.timeoutIntervalForRequest=10.0f;//请求时间    sessionConfig.allowsCellularAccess=YES;//是否允许蜂窝网络下载(2g,3g,4g)        //创建会话    NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];//指定配置和代理    downloadTask =[session downloadTaskWithRequest:request];        [downloadTask resume];    }-(void)zanting{    NSLog(@"暂停");    [downloadTask suspend];    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;    }-(void)huifu{    NSLog(@"恢复");    [downloadTask resume];    if ([label.text isEqualToString:@""]) {        [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;    }else{    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;    }}-(void)quxiao{    NSLog(@"取消");    progress.progress=0;    [downloadTask cancel];    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;    label.text=nil;}-(void)setjindutiaozhuangtai:(int64_t)zongliang setjindutiao:(int64_t)dangqianxiazailiang{        //异步    dispatch_async(dispatch_get_main_queue(), ^{        progress.progress=(float)dangqianxiazailiang/zongliang;        if (dangqianxiazailiang==zongliang) {            label.text=@"下载完成";            [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;        }        else{            label.text=@"正在下载";                        [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;        }    });       }#pragma mark 下载任务代理#pragma mark 下载中()- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask      didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{                [self setjindutiaozhuangtai:totalBytesExpectedToWrite setjindutiao:totalBytesWritten];        NSLog(@"bytesWritten: %lld  totalBytesWritten:%lld   totalBytesExpectedToWrite:%lld ",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);            }- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}#pragma mark 下载完成- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL *)location{        NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];        path=[path stringByAppendingPathComponent:@"图片01.jpg"];        NSLog(@" 缓存路径  %@",path);        NSURL * saveUrl=[NSURL fileURLWithPath:path];        NSLog(@"    %@",saveUrl);        //关键:复制文件,从location——》saveUrl        NSError * error;        [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&error];          if (error) {        NSLog(@"错误:%@",error);    }    }-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{    if (error) {        NSLog(@"%@",error);    }}@end

转载于:https://my.oschina.net/u/2483781/blog/542238

你可能感兴趣的文章
VS2013 编译&使用 stlport
查看>>
几种更新(Update语句)查询的方法
查看>>
20步打造最安全的Nginx Web服务器
查看>>
WP8:Unity3D之间的值传递
查看>>
string与数值之间的转换
查看>>
Windows系统安装Oracle 11g客户端
查看>>
怎样写出一个较好的高速排序程序
查看>>
【动态规划】最长公共子序列与最长公共子串
查看>>
要立刷金组flag了T_T
查看>>
Swift常量和变量
查看>>
GNU Make chapter 2 —— Makefile 介绍
查看>>
[转]在Eclipse中使用JUnit4进行单元测试(中级篇)
查看>>
gdb图形化调试工具总结
查看>>
白话经典算法系列之七 堆与堆排序
查看>>
微软职位内部推荐-SDEII
查看>>
Windows下FFmpeg高速入门
查看>>
【分享】 IT囧事
查看>>
Android安卓开发中图片缩放讲解
查看>>
【Java】Lucene检索引擎详解
查看>>
Cts框架解析(7)-任务运行的调度室
查看>>