1 飞机航班查询软件

1.1 问题

NSURLConnection是IOS提供的用于处理Http协议的网络请求的类,可以实现同步请求也可以实现异步请求,本案例使用NSURLConnection类实现一个飞机航班查询的工具软件,采用GET的同步请求方式访问网络数据,如图-1所示:

图-1

1.2 方案

首先创建一个SingleViewApplication应用,在Storyboard文件中搭建查询界面,上方的三个Textfield控件分别用于接受用户输入的出发城市、到达城市和触发日期,界面中间有一个查询按钮,当用户点击该按钮则发送网络请求,根据用户输入的信息获取飞机航班信息。将三个Textfield控件分别关联成ViewController的输出口属性departCity、arriveCity、departDate。

界面的下半部分是一个TableView控件,用于展示网络返回的数据结果,将TableView控件的dataSource和delegate设置为ViewController,并关联成ViewController的输出口属性resultTV。

其次需要确定一个能够提供数据的公共网络平台,本案例使用http://webservice.webxml.com.cn网络平台,该平台能够提供多种类型的服务例如火车时刻查询、天气预报查询等。

本案例使用飞机航班查询,该服务的名称是getDomesticAirlinesTime,进入该服务界面可以看到除了提供参数使用说明还有测试窗口,如图-2所示:

图-2

这里可以使用测试功能进行测试,查看返回的XML文件的内容,出发城市输入上海,到达城市输入北京,日期输出2015-3-8,这里输入的信息必须符合参数要求不可以随意修改,如图-3所示:

图-3

点击调用按钮发出请求,可以在弹出的新页面中查看返回的XML文件的内容,如图-4所示:

图-4

然后根据应用的需要在返回的XML文件中获取需要的信息,将相关的航班信息保存在ScheduledFlight类中,该类继承至NSObject,根据所需定义如下属性:

NSString类型的属性company,记录航空公司名称;

NSString类型的属性airlineCode,记录航班号;

NSString类型的属性startDrome,记录起飞机场;

NSString类型的属性arriveDrome,记录到达机场;

NSString类型的属性startTime,记录起飞时间;

NSString类型的属性arriveTime,记录到达时间;

NSString类型的属性mode,记录飞机机型。

接下来需要创建一个Parse类型用于解析XML文件,从中获取需要的航班信息,并将信息存入ScheduledFlight类型的实例中。Parse类有一个公开的静态方法getFlightsByData:,该方法返回一个NSMutableArray类型的数组,该数组的每一个元素都是一个ScheduledFlight类型的实例,即航班信息。

然后将查询按钮关联成ViewController的动作方法search:,该方法中根据用户输入的查询条件得到NSString类型的路径path,由于含有中文因此需要进行编码,然后通过path创建NSURL对象和NSMutableURLRequest对象,最后通过NSURLConnection类的工厂方法sendSynchronousRequest:returningResponse:发送同步请求,得到返回的NSData类型的数据。

最后通过Parse类的getFlightsByData:方法解析数据得到一组航班信息,将其存放在ViewController的NSMutableArray类型的属性flights中,根据flights存放的航班数据更新表视图resultTV的显示内容。

1.3 步骤

实现此案例需要按照如下步骤进行。

步骤一:搭建查询界面

首先创建一个SingleViewApplication应用,在Storyboard文件中搭建查询界面,上方的三个Textfield控件分别用于接受用户输入的出发城市、到达城市和触发日期,界面中间有一个查询按钮,当用户点击该按钮则发送网络请求,根据用户输入的信息获取飞机航班信息。将三个Textfield控件分别关联成ViewController的输出口属性departCity、arriveCity、departDate。

界面的下半部分是一个TableView控件,用于展示网络返回的数据结果,将TableView控件的dataSource和delegate设置为ViewController,并关联成ViewController的输出口属性resultTV,代码如下所示:

 
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *departCity;
@property (weak, nonatomic) IBOutlet UITextField *arriveCity;
@property (weak, nonatomic) IBOutlet UITextField *departDate;
@property (weak, nonatomic) IBOutlet UITableView *resultTV;
@end

 

在Storyboard中完成的界面如图-5所示:

图-5

步骤二:创建航班类ScheduledFlight

本案例使用http://webservice.webxml.com.cn公共网络平台获取飞机航班信息,然后通过XML解析将信息展示在界面上。

首先创建一个航班类ScheduledFlight,该类继承至NSObject,根据所需定义如下公开属性:

NSString类型的属性company,记录航空公司名称;

NSString类型的属性airlineCode,记录航班号;

NSString类型的属性startDrome,记录起飞机场;

NSString类型的属性arriveDrome,记录到达机场;

NSString类型的属性startTime,记录起飞时间;

NSString类型的属性arriveTime,记录到达时间;

NSString类型的属性mode,记录飞机机型,代码如下所示:

 
@interface ScheduledFlight : NSObject
@property (nonatomic,copy) NSString *company;
@property (nonatomic,copy) NSString *airlineCode;
@property (nonatomic,copy) NSString *startDrome;
@property (nonatomic,copy) NSString *arriveDrome;
@property (nonatomic,copy) NSString *startTime;
@property (nonatomic,copy) NSString *arriveTime;
@property (nonatomic,copy) NSString *mode;
@end
步骤三:创建XML解析类Parse

接下来需要创建一个Parse类型用于解析XML文件,从中获取需要的航班信息,并将信息存入ScheduledFlight类型的实例中。首先在该类中定义三个私有属性NSMutableArray类型的flights用于记录最终获得的一组航班信息,ScheduledFlight类型的currentFlight用于记录当前正在解析的航班,NSString类型的currentString用于记录当前正在读取的字符串,代码如下所示:

 
@interface Parser ()<NSXMLParserDelegate>
@property (nonatomic,strong) NSMutableArray *flights;
@property (nonatomic,strong) ScheduledFlight *currentFlight;
@property (nonatomic,copy) NSString *currentString;
@end
Parse类有一个公开的静态方法getFlightsByData:,该方法返回一个NSMutableArray类型的数组,记录着最终解析出来的所有航班信息,即self.flights,代码如下所示:

-(NSMutableArray *)getFlightsByData:(NSData *)data{
self.flights = [NSMutableArray array];
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
parser.delegate = self;
[parser parse];
return self.flights;
}
然后通过实现NSXMLParserDelegate协议中的相关方法进行XML数据解析,得到所有的航班信息,代码如下所示:

 
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"AirlinesTime"]) {
//创建ScheduledFlight实例
self.currentFlight = [[ScheduledFlight alloc]init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
self.currentString = string;
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"Company"]) {
self.currentFlight.company = self.currentString;
}else if ([elementName isEqualToString:@"AirlineCode"]) {
self.currentFlight.airlineCode = self.currentString;
}else if ([elementName isEqualToString:@"StartDrome"]) {
self.currentFlight.startDrome = self.currentString;
}else if ([elementName isEqualToString:@"ArriveDrome"]) {
self.currentFlight.arriveDrome = self.currentString;
}else if ([elementName isEqualToString:@"StartTime"]) {
self.currentFlight.startTime = self.currentString;
}else if ([elementName isEqualToString:@"ArriveTime"]) {
self.currentFlight.arriveTime = self.currentString;
}else if ([elementName isEqualToString:@"Mode"]) {
self.currentFlight.mode = self.currentString;
}else if ([elementName isEqualToString:@"AirlinesTime"]){
//解析完成将当前的航班放入self.flights数组中保存
[self.flights addObject:self.currentFlight];
}
}
步骤四:发送网络请求,展示航班信息

首先在ViewController类中定义一个NSMutableArray类型的属性flights,用于记录需要展示的航班信息,然后实现表视图的协议方法展示数据,代码如下所示:

 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.flights.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
ScheduledFlight *flight = [self.flights objectAtIndex:indexPath.row];
// NSLog(@"%@",flight.company);
cell.textLabel.numberOfLines = 0;
cell.textLabel.text = [NSString stringWithFormat:@"航空公司:%@\n航班号:%@\n起飞机场:%@\n到达机场:%@\n起飞时间:%@\n到达时间:%@\n机型:%@",flight.company,flight.airlineCode,flight.startDrome,flight.arriveDrome,flight.startTime,flight.arriveTime,flight.mode];
[cell.textLabel setFont:[UIFont systemFontOfSize:10]];
cell.backgroundColor = [UIColor clearColor];
return cell;
}
然后将查询按钮关联成ViewController的动作方法search:,该方法中根据用户输入的查询条件得到NSString类型的路径path,由于含有中文因此需要进行编码,然后通过path创建NSURL对象和NSMutableURLRequest对象,最后通过NSURLConnection类的工厂方法sendSynchronousRequest:returningResponse:发送同步请求,得到返回的NSData类型的数据,代码如下所示:

 
- (IBAction)search:(UIButton *)sender {
[self.departDate resignFirstResponder];
//根据用户输入的信息得到路径
NSString *path = [NSString stringWithFormat:@"http://webservice.webxml.com.cn/webservices/DomesticAirline.asmx/getDomesticAirlinesTime?startCity=%@&lastCity=%@&theDate=%@&userID=",self.departCity.text,self.arriveCity.text,self.departDate.text];
//由于含有中文需要进行编码
path = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)path, NULL, NULL, kCFStringEncodingUTF8));
//创建url路径
NSURL *url = [NSURL URLWithString:path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"GET"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}
最后在ViewController类中导入头文件"ScheduledFlight.h""Parser.h",在search:方法中通过Parse类的getFlightsByData:方法解析数据得到一组航班信息,将其存放在ViewController的NSMutableArray类型的属性flights中,根据flights存放的航班数据更新表视图resultTV的显示内容,代码如下所示:

 
- (IBAction)search:(UIButton *)sender {
[self.departDate resignFirstResponder];
//根据用户输入的信息得到路径
NSString *path = [NSString stringWithFormat:@"http://webservice.webxml.com.cn/webservices/DomesticAirline.asmx/getDomesticAirlinesTime?startCity=%@&lastCity=%@&theDate=%@&userID=",self.departCity.text,self.arriveCity.text,self.departDate.text];
//由于含有中文需要进行编码
path = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)path, NULL, NULL, kCFStringEncodingUTF8));
//创建url路径
NSURL *url = [NSURL URLWithString:path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"GET"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
Parser *parser = [[Parser alloc]init];
self.flights = [parser getFlightsByData:data];
[self.resultTV reloadData];
}
1.4 完整代码

本案例中,ViewController.m文件中的完整代码如下所示:

 
#import "ViewController.h"
#import "ScheduledFlight.h"
#import "Parser.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *departCity;
@property (weak, nonatomic) IBOutlet UITextField *arriveCity;
@property (weak, nonatomic) IBOutlet UITextField *departDate;
@property (weak, nonatomic) IBOutlet UITableView *resultTV;
@property (nonatomic,strong) NSMutableArray *flights;
@end
@implementation ViewController
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.flights.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
ScheduledFlight *flight = [self.flights objectAtIndex:indexPath.row];
// NSLog(@"%@",flight.company);
cell.textLabel.numberOfLines = 0;
cell.textLabel.text = [NSString stringWithFormat:@"航空公司:%@\n航班号:%@\n起飞机场:%@\n到达机场:%@\n起飞时间:%@\n到达时间:%@\n机型:%@",flight.company,flight.airlineCode,flight.startDrome,flight.arriveDrome,flight.startTime,flight.arriveTime,flight.mode];
[cell.textLabel setFont:[UIFont systemFontOfSize:10]];
cell.backgroundColor = [UIColor clearColor];
return cell;
}
- (IBAction)search:(UIButton *)sender {
[self.departDate resignFirstResponder];
//根据用户输入的信息得到路径
NSString *path = [NSString stringWithFormat:@"http://webservice.webxml.com.cn/webservices/DomesticAirline.asmx/getDomesticAirlinesTime?startCity=%@&lastCity=%@&theDate=%@&userID=",self.departCity.text,self.arriveCity.text,self.departDate.text];
//由于含有中文需要进行编码
path = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)path, NULL, NULL, kCFStringEncodingUTF8));
//创建url路径
NSURL *url = [NSURL URLWithString:path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"GET"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
Parser *parser = [[Parser alloc]init];
self.flights = [parser getFlightsByData:data];
[self.resultTV reloadData];
}
@end
 
本案例中,ScheduledFlight.h文件中的完整代码如下所示:

 
#import <Foundation/Foundation.h>
@interface ScheduledFlight : NSObject
@property (nonatomic,copy) NSString *company;
@property (nonatomic,copy) NSString *airlineCode;
@property (nonatomic,copy) NSString *startDrome;
@property (nonatomic,copy) NSString *arriveDrome;
@property (nonatomic,copy) NSString *startTime;
@property (nonatomic,copy) NSString *arriveTime;
@property (nonatomic,copy) NSString *mode;
@end
 
本案例中,Parser.h文件中的完整代码如下所示:

 
#import <Foundation/Foundation.h>
#import "ScheduledFlight.h"
@interface Parser : NSObject
-(NSMutableArray *)getFlightsByData:(NSData *)data;
@end
 
本案例中,Parser.m文件中的完整代码如下所示:

 
#import "Parser.h"
@interface Parser ()<NSXMLParserDelegate>
@property (nonatomic,strong) NSMutableArray *flights;
@property (nonatomic,strong) ScheduledFlight *currentFlight;
@property (nonatomic,copy) NSString *currentString;
@end
@implementation Parser
-(NSMutableArray *)getFlightsByData:(NSData *)data{
self.flights = [NSMutableArray array];
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
parser.delegate = self;
[parser parse];
return self.flights;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"AirlinesTime"]) {
//创建ScheduledFlight实例
self.currentFlight = [[ScheduledFlight alloc]init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
self.currentString = string;
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"Company"]) {
self.currentFlight.company = self.currentString;
}else if ([elementName isEqualToString:@"AirlineCode"]) {
self.currentFlight.airlineCode = self.currentString;
}else if ([elementName isEqualToString:@"StartDrome"]) {
self.currentFlight.startDrome = self.currentString;
}else if ([elementName isEqualToString:@"ArriveDrome"]) {
self.currentFlight.arriveDrome = self.currentString;
}else if ([elementName isEqualToString:@"StartTime"]) {
self.currentFlight.startTime = self.currentString;
}else if ([elementName isEqualToString:@"ArriveTime"]) {
self.currentFlight.arriveTime = self.currentString;
}else if ([elementName isEqualToString:@"Mode"]) {
self.currentFlight.mode = self.currentString;
}else if ([elementName isEqualToString:@"AirlinesTime"]){
//解析完成将当前的航班放入self.flights数组中保存
[self.flights addObject:self.currentFlight];
}
}
@end
 

2 歌曲下载

2.1 问题

通常同步请求的用户体验不是很好,因此很多情况下会采用异步请求,异步请求是使用NSURLConnection的委托协议NSURLConnectionDelegate来实现的,本案例使用NSURLConnection类的异步请求实现网路歌曲的下载。

2.2 方案

首先创建一个SingleViewApplication应用,在ViewDidLoad方法中定义三个私有属性,NSData类型的fileData,用于存储接受文件的数据,NSString类型的fileName用于记录接受文件的名称,NSUInteger类型的length用于记录接受文件的长度。

在viewDidLoad方法中通过歌曲的网路路径path创建NSURL对象url和NSMutableURLRequest对象request,通过request创建一个NSURLConnection类型的对象connection,将delegate设置为ViewController,如果connection创建成功则表示异步请求发送成功。

当连接成功则会接收到响应,是一个NSURLResponse类型的实例response,通过response的属性allHeaderFields获取到下载文件的头文件,头文件里面包含文件的类型、长度、名称等信息。

最后通过实现NSURLConnectionDelegate协议和NSURLConnectionDataDelegate协议的相关方法接受网路数据响应,接受网络数据,完成数据下载并存入本地。

2.3 步骤

实现此案例需要按照如下步骤进行。

步骤一:创建NSURLConnection连接

首先创建一个SingleViewApplication应用,在ViewDidLoad方法中定义三个私有属性,NSData类型的fileData,用于存储接受文件的数据,NSString类型的fileName用于记录接受文件的名称,NSUInteger类型的length用于记录接受文件的长度,代码如下所示:

 
@interface ViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
@property (nonatomic, strong)NSMutableData *fileData;
@property (nonatomic,copy)NSString *fileName;
@property (nonatomic,assign) NSUInteger length;
@end
在viewDidLoad方法中通过歌曲的网路路径path创建NSURL对象url和NSMutableURLRequest对象request,通过request创建一个NSURLConnection类型的对象connection,将delegate设置为ViewController,如果connection创建成功则表示异步请求发送成功,代码如下所示:

 
- (void)viewDidLoad
{
self.fileData = [NSMutableData data];
[super viewDidLoad];
NSString *path = @"http://music.baidu.com/data/music/file?link=http://zhangmenshiting.baidu.com/data2/music/65371921/401533401375268461128.mp3?xcode=c318182b0f97938776659f1fd7cf3f72f84b7d701136b422";
NSURL *url = [NSURL URLWithString:path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(@"连接成功");
}
}
步骤二:实现协议方法,完成数据下载

当连接成功则会接收到响应,是一个NSURLResponse类型的实例response,通过response的属性allHeaderFields获取到下载文件的头文件,头文件里面包含文件的类型、长度、名称等信息。

最后通过实现NSURLConnectionDelegate协议和NSURLConnectionDataDelegate协议的相关方法接受网路数据响应,接受网络数据,完成数据下载并存入本地,代码如下所示:

 
//接受到相响应时调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"接收到响应!!");
NSHTTPURLResponse *resp = (NSHTTPURLResponse*)response;
//获取头文件,头文件里面包含文件的类型,长度,名称等信息
NSDictionary *dic = resp.allHeaderFields;
NSLog(@"%@",dic);
self.length = [[dic objectForKey:@"Content-Length"] intValue];
self.fileName = [dic objectForKey:@"Content-Disposition"];
NSLog(@"length:%lu,filename:%@",self.length,self.fileName);
}
//接受数据时调用
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//已经接受的数据长度
NSLog(@"data length = %lu",(unsigned long)data.length);
//将持续接受的数据存入self.fileData
[self.fileData appendData:data];
}
//下载完成时调用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//当接受完成将文件存入本地
NSFileManager *fm = [NSFileManager defaultManager];
NSString *filePath = @"/Users/Vivian/Desktop/songs";
[fm createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
[self.fileData writeToFile:[filePath stringByAppendingPathComponent:self.fileName] atomically:YES];
NSLog(@"完成");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"error");
}
2.4 完整代码

本案例中,ViewController.m文件中的完整代码如下所示:

 
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
@property (nonatomic, strong)NSMutableData *fileData;
@property (nonatomic,copy)NSString *fileName;
@property (nonatomic,assign) NSUInteger length;
@end
@implementation ViewController
- (void)viewDidLoad
{
self.fileData = [NSMutableData data];
[super viewDidLoad];
NSString *path = @"http://music.baidu.com/data/music/file?link=http://zhangmenshiting.baidu.com/data2/music/65371921/401533401375268461128.mp3?xcode=c318182b0f97938776659f1fd7cf3f72f84b7d701136b422";
NSURL *url = [NSURL URLWithString:path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(@"连接成功");
}
}
//接受到相响应时调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"接收到响应!!");
NSHTTPURLResponse *resp = (NSHTTPURLResponse*)response;
//获取头文件,头文件里面包含文件的类型,长度,名称等信息
NSDictionary *dic = resp.allHeaderFields;
NSLog(@"%@",dic);
self.length = [[dic objectForKey:@"Content-Length"] intValue];
self.fileName = [dic objectForKey:@"Content-Disposition"];
NSLog(@"length:%lu,filename:%@",self.length,self.fileName);
}
//接受数据时调用
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//已经接受的数据长度
NSLog(@"data length = %lu",(unsigned long)data.length);
//将持续接受的数据存入self.fileData
[self.fileData appendData:data];
}
//下载完成时调用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//当接受完成将文件存入本地
NSFileManager *fm = [NSFileManager defaultManager];
NSString *filePath = @"/Users/Vivian/Desktop/songs";
[fm createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
[self.fileData writeToFile:[filePath stringByAppendingPathComponent:self.fileName] atomically:YES];
NSLog(@"完成");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"error");
}
@end
 

 

posted on 2015-12-15 21:22  A蜗牛为梦想而生A  阅读(343)  评论(0编辑  收藏  举报