程序的实现需要借助几个对象:

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 篇的更多相关文章

  1. iOS 学习 - 10下载(4) NSURLSession 会话 篇

    NSURLConnection通过全局状态来管理cookies.认证信息等公共资源,这样如果遇到两个连接需要使用不同的资源配置情况时就无法解决了,但是这个问题在NSURLSession中得到了解决.N ...

  2. iOS 学习 - 10下载(3) NSURLSession 音乐 篇

    使用 NSURLSession 下载,需要注意的是文件下载文件之后会自动保存到一个临时目录,需要开发人员自己将此文件重新放到其他指定的目录中 // // ViewController.m // Web ...

  3. iOS 学习 - 10下载(2) NSURLSession 图片 篇

    使用NSURLSessionDownloadTask下载文件的过程与前面差不多,需要注意的是文件下载文件之后会自动保存到一个临时目录,需要开发人员自己将此文件重新放到其他指定的目录中. // // V ...

  4. ios学习- 10大iOS开发者最喜爱的类库

    该10大iOS开发者最喜爱的库由“iOS辅导团队”成员Marcelo Fabri组织投票选举而得,参与者包括开发者团队,iOS辅导团队以及行业嘉宾.每个团队都要根据以下规则选出五个最好的库: 1)不能 ...

  5. iOS学习10之OC类和对象

    本次是OC的第一节课,主要是学习和理解类与对象 1.面向对象 1> OOP(Object Oriented Programming)面向对象编程. 面向对象以事物为中心,完成某件事情都需要哪些事 ...

  6. iOS学习笔记之异步图片下载

    写在前面 在iOS开发中,无论是在UITableView还是在UICollectionView中,通过网络获取图片设置到cell上是较为常见的需求.尽管有很多现存的第三方库可以将下载和缓存功能都封装好 ...

  7. [转帖]nginx学习,看这一篇就够了:下载、安装。使用:正向代理、反向代理、负载均衡。常用命令和配置文件

    nginx学习,看这一篇就够了:下载.安装.使用:正向代理.反向代理.负载均衡.常用命令和配置文件 2019-10-09 15:53:47 冯insist 阅读数 7285 文章标签: nginx学习 ...

  8. iOS学习路线图

    一.iOS学习路线图   二.iOS学习路线图--视频篇       阶 段 学完后目标 知识点 配套学习资源(笔记+源码+PPT) 密码 基础阶段 学习周期:24天       学习后目标:    ...

  9. iOS学习资料整理

    视频教程(英文) 视频 简介 Developing iOS 7 Apps for iPhone and iPad 斯坦福开放教程之一, 课程主要讲解了一些 iOS 开发工具和 API 以及 iOS S ...

随机推荐

  1. C语言学习020:可变参数函数

    顾名思义,可变参数函数就是参数数量可变的函数,即函数的参数数量是不确定的,比如方法getnumbertotal()我们即可以传递一个参数,也可以传递5个.6个参数 #include <stdio ...

  2. JavaScript星形评分

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  3. Handler "BlockViewHandler" has a bad module "ManagedPipelineHandler" in its module list

    当你的ASP.NET MVC项跑在IIS时,出现如标题Handler "BlockViewHandler" has a bad module "ManagedPipeli ...

  4. c# TCP Socket通讯基础

    在做网络通讯方面的程序时,必不可少的是Socket通讯. 那么我们需要有一套既定的,简易的通讯流程. 如下: <pre name="code" class="csh ...

  5. 基于.Net Framework 4.0 Web API开发(4):ASP.NET Web APIs 基于令牌TOKEN验证的实现

    概述:  ASP.NET Web API 的好用使用过的都知道,没有复杂的配置文件,一个简单的ApiController加上需要的Action就能工作.但是在使用API的时候总会遇到跨域请求的问题, ...

  6. 动易CMS之标签管理

    一.如何添加一个标签 1.系统设置->模板标签管理->添加标签 2.输入标签名称,根据需要选择数据设置: sql语句则选择[系统数据库SQL查询] 3.添加参数 4.系统可以根据设置的条件 ...

  7. 框架Hibernate笔记系列 基础Session

    标题:框架Hibernate笔记 资料地址: 1. www.icoolxue.com 孔浩 1.背景简介 Hibenate是JBoss公司的产品.它是数据持久化的框架.Usually,我们使用JDBC ...

  8. 信鸽推送.NET SDK 开源

    github 地址 https://github.com/yeanzhi/XinGePushSDK.NET 传送门如何安装    建议使用nuget安装包,搜索"信鸽"即可    ...

  9. php高版本不再使用mysql_connect()来连接数据库

    想用php生成一个mysql数据字典导出来,用到下面代码会 $mysql_conn = mysql_connect ( "$dbserver", "$dbusername ...

  10. JVM调优总结:调优方法

    JVM调优总结:调优方法 2012-01-10 14:35 和你在一起 和你在一起的博客 字号:T | T 下面文章将讲解JVM的调优工具以及如何去调优等等问题,还有一些异常问题的处理.详细请看下文. ...