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
  • 相关阅读:
    Linux修改主机名称
    Druid监控SQL语句
    CentOS7.5搭建Hadoop分布式集群
    CentOS7.5 解决ifconfig报错
    windows 用VMware创建linux虚拟机,安装操作系统CentOS7.2
    MySQL报错this is incompatible with sql_mode=only_full_group_by
    CentOS配置Redis环境变量
    CentOS7.4搭建GitLab
    修改服务器路由策略
    Centos7 安装python3
  • 原文地址:https://www.cnblogs.com/ldnh/p/5289716.html
Copyright © 2011-2022 走看看