iOS 学习 - 10下载(1) NSURLConnection 篇
程序的实现需要借助几个对象:
NSURLRequest:建立了一个请求,可以指定缓存策略、超时时间。和NSURLRequest对应的还有一个NSMutableURLRequest,如果请求定义为NSMutableURLRequest则可以指定请求方法(GET或POST)等信息。
NSURLConnection:用于发送请求,可以指定请求和代理。当前调用NSURLConnection的start方法后开始发送异步请求。
当然了这种方法比较原始。。。
//
// ViewController.m
// xiazai
//
// Copyright © 2016年 asamu. All rights reserved.
// #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate>
{
NSMutableData *_data;//响应数据
UITextField *_textField;
UIButton *_button;
UIProgressView *_progressView;
UILabel *_label;
long long _totalLength;
NSDictionary *_musicDic;
}
@end @implementation ViewController
#pragma mark -- UI方法
- (void)viewDidLoad {
[super viewDidLoad];
[self analysisJson];
[self layoutUI]; }
#pragma mark -- 私有方法
#pragma mark 解析 JSON
-(void)analysisJson{
NSError *error;
NSString *str = @"http://douban.fm/j/mine/playlist?channel=3";
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *musicDic = [[NSDictionary alloc]init];
//遍历字典 取出 key - @"song"
for (musicDic in dic[@"song"]) {
_musicDic = musicDic;
}
} #pragma mark 界面布局
-(void)layoutUI{
//地址栏
_textField = [[UITextField alloc]initWithFrame:CGRectMake(, , , )];
//加圆角和边框
_textField.layer.cornerRadius = 3.0f;
_textField.layer.borderWidth = 0.5f;
_textField.textColor = [UIColor redColor];
/*
解析的 JOSN 中的 歌曲名加上 .mp3 的后缀
这个名字就是存储在沙盒中的名字,所以要加 .mp3
由于名称不一样,所以不会覆盖
*/
NSString *musicName = [_musicDic[@"title"] stringByAppendingString:@".mp3"];
_textField.text = musicName;
[_textField sizeToFit];
[self.view addSubview:_textField];
//进度条
_progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(, , , )];
[self.view addSubview:_progressView];
//状态显示
_label = [[UILabel alloc]initWithFrame:CGRectMake(, , , )];
_label.textColor = [UIColor colorWithRed: green:/255.0 blue:1.0 alpha:1.0];
[self.view addSubview:_label];
//下载按钮
_button = [[UIButton alloc]initWithFrame:CGRectMake(, , , )];
[_button setTitle:@"下载" forState:UIControlStateNormal];
[_button setTitleColor:[UIColor colorWithRed: green:/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
[_button addTarget:self action:@selector(sendRequest) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
}
#pragma mark -- 更新进度
-(void)updateProgress{
if (_data.length == _totalLength) {
_label.text = @"Finish downloaded";
}else{
_label.text = @"downing...";
[_progressView setProgress:(float)_data.length/_totalLength];
}
}
#pragma mark -- 发送请求
-(void)sendRequest{
NSLog(@"begin");
NSString *urlStr = [NSString stringWithFormat:_musicDic[@"url"],_textField.text];
//解码
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 创建 URL 链接
NSURL *url = [NSURL URLWithString:urlStr];
//创建请求
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0f];
//创建连接
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//启动连接
[connection start];
}
#pragma mark -- 连接代理方法
#pragma mark 开始响应
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"receive response");
_data = [[NSMutableData alloc]init];
_progressView.progress = ;
//通过响应头中的 Content-Length 取得整个响应的长度
NSHTTPURLResponse *httpRespose = (NSHTTPURLResponse *)response;
NSDictionary *httpResponseHeaderFields = [httpRespose allHeaderFields];
_totalLength = [[httpResponseHeaderFields objectForKey:@"Content-Length"]longLongValue];
}
#pragma mark 接收响应数据,(根据响应内容的大小此方法会被重复调用)
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"Receive data");
//连续接收数据
[_data appendData:data];
//更新进度
[self updateProgress];
}
#pragma mark 接收数据完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"loading finish");
//数据接收完保存文集(注意苹果官方要求:下载数据只能保存在缓存目录)
NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
savePath = [savePath stringByAppendingPathComponent:_textField.text];
[_data writeToFile:savePath atomically:YES];
NSLog(@"path:%@",savePath);
}
#pragma mark 请求失败
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"connection error,error detail is:%@",error.localizedDescription);
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end
随笔 10()部分,都来自 KenshinCui,后系列就不一一列出,估计大神的 url 没用了,所以我换了个音乐的 url,可以用。初学者,若有错误,敬请指出,不甚感激。
iOS 学习 - 10下载(1) NSURLConnection 篇的更多相关文章
- iOS 学习 - 10下载(4) NSURLSession 会话 篇
NSURLConnection通过全局状态来管理cookies.认证信息等公共资源,这样如果遇到两个连接需要使用不同的资源配置情况时就无法解决了,但是这个问题在NSURLSession中得到了解决.N ...
- iOS 学习 - 10下载(3) NSURLSession 音乐 篇
使用 NSURLSession 下载,需要注意的是文件下载文件之后会自动保存到一个临时目录,需要开发人员自己将此文件重新放到其他指定的目录中 // // ViewController.m // Web ...
- iOS 学习 - 10下载(2) NSURLSession 图片 篇
使用NSURLSessionDownloadTask下载文件的过程与前面差不多,需要注意的是文件下载文件之后会自动保存到一个临时目录,需要开发人员自己将此文件重新放到其他指定的目录中. // // V ...
- ios学习- 10大iOS开发者最喜爱的类库
该10大iOS开发者最喜爱的库由“iOS辅导团队”成员Marcelo Fabri组织投票选举而得,参与者包括开发者团队,iOS辅导团队以及行业嘉宾.每个团队都要根据以下规则选出五个最好的库: 1)不能 ...
- iOS学习10之OC类和对象
本次是OC的第一节课,主要是学习和理解类与对象 1.面向对象 1> OOP(Object Oriented Programming)面向对象编程. 面向对象以事物为中心,完成某件事情都需要哪些事 ...
- iOS学习笔记之异步图片下载
写在前面 在iOS开发中,无论是在UITableView还是在UICollectionView中,通过网络获取图片设置到cell上是较为常见的需求.尽管有很多现存的第三方库可以将下载和缓存功能都封装好 ...
- [转帖]nginx学习,看这一篇就够了:下载、安装。使用:正向代理、反向代理、负载均衡。常用命令和配置文件
nginx学习,看这一篇就够了:下载.安装.使用:正向代理.反向代理.负载均衡.常用命令和配置文件 2019-10-09 15:53:47 冯insist 阅读数 7285 文章标签: nginx学习 ...
- iOS学习路线图
一.iOS学习路线图 二.iOS学习路线图--视频篇 阶 段 学完后目标 知识点 配套学习资源(笔记+源码+PPT) 密码 基础阶段 学习周期:24天 学习后目标: ...
- iOS学习资料整理
视频教程(英文) 视频 简介 Developing iOS 7 Apps for iPhone and iPad 斯坦福开放教程之一, 课程主要讲解了一些 iOS 开发工具和 API 以及 iOS S ...
随机推荐
- 前端自动化开发之grunt
上篇文章介绍了前端模块化开发工具seaJs,利用seaJs我们可以轻松实现前端的模块化编程,参见http://www.cnblogs.com/luozhihao/p/4818782.html 那么今天 ...
- 【UWP】UI适配整理
做UWP有几个月了,期间发布了几个应用,在这里整理一下适配相关的一些东西,UWP关于UI的适配主要有两种方式: 1.VisualState+Trigger:通过触发器出发界面更变,通常在Desktop ...
- CodeSnippet.info 开源说明 和 环境搭建 (第一版)
Github开源声明 本网站的代码开源,开源的目的如下 技术分享 希望业内同行贡献代码 希望能够让网站更加安全 开源地址: CodeSnippet开源地址 关于代码贡献 任何人都可以贡献代码,一般在 ...
- 从NavigationController 下的UITableView中移除 header
this.AutomaticallyAdjustsScrollViewInsets = false; 解析:AutomaticallyAdjustsScrollViewInsets为系统自动为适应na ...
- Java---Java的面试题(一)
1.什么是Java虚拟机?为什么Java被称作是"平台无关的编程语言"? Java虚拟机是一个可以执行Java字节码的虚拟机进程.Java源文件被编译成能被Java虚拟机执行的字节 ...
- web工程依赖的问题
http://blog.csdn.net/testcs_dn/article/details/43764497 做个记录
- 第 25 章 CSS3 过渡效果
学习要点: 1.过渡简介 2.transition-property 3.transition-duration 4.transition-timing-function 5.transition-d ...
- Java集合源码分析(五)HashSet<E>
HashSet简介 HashSet实现Set接口,由哈希表(实际上是一个HashMap实例)支持.它不保证set 的迭代顺序:特别是它不保证该顺序恒久不变.此类允许使用null元素. HashSet源 ...
- python tornado websocket 多聊天室(返回消息给部分连接者)
python tornado 构建多个聊天室, 多个聊天室之间相互独立, 实现服务器端将消息返回给相应的部分客户端! chatHome.py // 服务器端, 渲染主页 --> 聊天室建立web ...
- CentOS minimal网络设置
CentOS minimal版本默认不启动网络,所以要自己配置. 配置过程: 编辑配置文件: vi /etc/sysconfig/network-script/ifcfg-eth0 需要更改两项 NM ...