NSURLConnection

    _musicData = [NSMutableData data];
    UIImageView *imageView = [UIImageView new];
    imageView.frame = CGRectMake(0, 0, 200, 200);
    imageView.center = self.view.center;
    [self.view addSubview:imageView];
    
    
    
    
    NSString *path  = @"http://www.3337973.cc/imgall/mjuxu2djfy2diojtfzrw63i/uploads/allimg/140828/3-140RQ34K1.jpg";
    
    NSLog(@"-----out");
    
    __block NSData *imageData;
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        UIImage *image = [UIImage imageWithData:data];
       
        imageData = data;
        imageView.image= [UIImage imageWithData:data];
        NSLog(@"err:%@",connectionError);
    }];
    
    NSLog(@"---->%@",imageData);
    
@interface ViewController ()
{
    NSMutableData *_musicData;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *path2 = @"http://link.hhtjim.com/163/145662.mp3";
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path2]] delegate:self startImmediately:NO];
    
    [connection start];   
}
//找到歌曲的总大小
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    NSLog(@"response:%@",response);
    NSLog(@"--fileSize:%lld",response.expectedContentLength);
}
//每次下载数据的大小
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    NSLog(@"data-->%ld",data.length);
    [_musicData appendData:data];
}

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

    NSLog(@"error");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    NSLog(@"done finish");
    [_musicData writeToFile:@"/Users/frankfan/desktop/留什么给你.mp3" atomically:YES];
}
@end

你可能感兴趣的:(NSURLConnection)