//
// ViewControllerA.m
// 初级网络-test
//
// Created by bch on 15-3-26.
// Copyright (c) 2015年 白超华. All rights reserved.
//
#import "ViewControllerA.h"
#define MP3_URL @"http://ws.stream.qqmusic.qq.com/30948371.mp3?vkey=2F5AE9F5F9E45F3A8B0DADA484616378F53DBC234C739FD692940AD673BA36D0&fromtag=52&guid=AEDCF56DE3F91B6D30A57937733680D7"
@interface ViewControllerA ()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
{
NSMutableData * _dataSource;//用于接收服务器传来数据的变量
NSString * name; //用来接收文件名,以便存储
}
@end
@implementation ViewControllerA
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
if (self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
//初始化上面的data
_dataSource=[[NSMutableData alloc]init];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
/* 异步请求*/
//首先呢,封装一个URL
NSURL *mp3URL=[NSURL URLWithString:MP3_URL];
//然后呢,封装一个请求,包含请求头,请求主体,和请求尾
//作用呢,目前主要是封装一个包裹,包裹里是向服务器请求的具体信息
NSURLRequest * request =[NSURLRequest requestWithURL:mp3URL];
//签名两步异步和同步都有
//建立连接
//利用上面的请求来建立连接,也就是说在请求连接的同时,就携带了请求的信息(request)
NSURLConnection * connection =[NSURLConnection connectionWithRequest:request delegate:self];
}
//亲,这是服务器基于您的request(请求),而送来的response(响应),请注意查收
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"亲,这个服务器告知您的文件名哦 =%@",response.suggestedFilename);
NSLog(@"亲,服务器同样在这个给您的回应信息中携带了您要下载的文件的大小 =%lld",response.expectedContentLength);
//为了更好的接收数据,我们先将我们的容器清空
_dataSource.length=0;
//接收文件名,以方便下一步的存储
name=response.suggestedFilename;
//WIFI旁边那个转圈的玩意
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES];
}
//亲,这时服务器,给您传送的数据,格式为data,请注意查收
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//我们把每一次接收过来的数据(data),都一点点的往容器里加,也就是拼接数据。
[_dataSource appendData:data];
NSLog(@"亲,服务器正给您传输数据。");
}
//亲,服务器已经把数据传输完毕,不久将会断开连接,请不要伤心
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//既然数据已经传输完毕,那么我们把数据写入到本地吧
[_dataSource writeToFile:[NSString stringWithFormat:@"Users/qianfeng01/Desktop/%@",name] atomically:YES];
NSLog(@"基于异步传输的文件下载操作已经完成,您所下载的文件已经保存到指定的位置。");
}
@end