zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    三大平衡树(Treap + Splay + SBT)总结+模板
    Nim游戏与SG函数 ——博弈论小结
    POJ2104 (平方分割)二分查找理解。
    POJ 1568 极大极小搜索 + alpha-beta剪枝
    数论基础算法总结(python版)
    极小极大搜索 的个人理解(alpha-beta剪枝)
    POJ 2891 中国剩余定理的非互质形式
    欧拉函数相关的题目
    数学专题(转)
    编码问题的觉悟
  • 原文地址:https://www.cnblogs.com/ldnh/p/5289716.html
Copyright © 2011-2022 走看看