NSURLConnection获取一个MP3文件

NSURLConnection网络请求

  • 直接上代码-这个没什么说的,你们自己有兴趣可以自己试试

代码

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>

//一个可变的data,因为NSURLConnection代理方法下载数据是分段下的,不信大家可以试试
@property (nonatomic,strong) NSMutableData *data;

@end

@implementation ViewController



#pragma mark -getter and setter methods

- (NSMutableData *)data
{
    if (!_data) {
        
        _data = [NSMutableData data];
    }
    return _data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSString *urlString = @"http://192.168.1.68/丁香花.mp3";
    
    //如果url中有中文,需要把它转换成百分比占位符
    
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    //NSURLRequestUseProtocolCachePolicy 自动缓存策略
    
    // 超时时间 默认是60s 一般设置为10 - 30 秒之间
    NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    
    //建立连接 NSURLConnection需要手动开启
    
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:requst delegate:self];
    
    [connection start];
    
}


//服务器返回信息
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@",response);
}

// 客户端在服务器下载数据 - 数据一次只能下一点
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    [self.data appendData:data];
    
    NSLog(@"%@",data);
    
}


//完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.data writeToFile:@"/Users/mac/Desktop/丁香花.mp3" atomically:YES];
    
    NSLog(@"下载完成");
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
posted @ 2016-03-17 22:16  往事亦如风  阅读(161)  评论(0编辑  收藏  举报