http异步请求

#import "TRViewController.h"


@interface TRViewController ()

@property (nonatomic, strong)NSMutableData *allData;

@property (nonatomic)int fileLength;

@end


@implementation TRViewController

- (IBAction)clicked:(id)sender {

    

 

    

    NSString *path = @"http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/57899053/39500263198000128.mp3?xcode=f4db023f0362b5b1d65e437b93846cee45b7764643675ea8&song_id=39500263";


    NSURL *url = [NSURL URLWithString:path];

    

    //创建http请求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    

    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

    if (conn) {

        NSLog(@"连接成功!!!");

    }

}



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    self.allData = [NSMutableData data];

    

    NSHTTPURLResponse *hr = (NSHTTPURLResponse*)response;

    // 字典,通过Content-Length取得文件长度

    NSLog(@"%@",hr.allHeaderFields);

    self.fileLength = [[hr.allHeaderFields objectForKey:@"Content-Length"] intValue];

}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [self.allData appendData:data];

    

    self.myPV.progress = self.allData.length*1.0/self.fileLength;

}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    // 完成后将数据保存

    [self.allData writeToFile:@"/Users/tangqinglong/Desktop/bbbb.mp3" atomically:YES];

    

}

//网络出错的话会进到此方法

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值