2016 - 1 - 23 작은 파일 다운로드

1: NSData 를 사용 하여 직접 다운로드:
    //
    
    NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png" ];
    NSData *data =  [NSData dataWithContentsOfURL:url options:kNilOptions error:nil];
    
    UIImage *image = [UIImage imageWithData:data];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 0, 200, 200);
    [self.view addSubview:imageView];

 2: NSURLConnect 사용
    NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png" ];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            UIImage *image = [UIImage imageWithData:data];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            imageView.frame = CGRectMake(0, 0, 200, 200);
            [self.view addSubview:imageView];
    }];
}

 3: 맞 춤 형 에이전트 로 다운로드
  이 방법 은 위 와 마찬가지 로 작은 파일 의 다운로드 에 만 적용 된다.
#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSMutableData *fileData;

@property (nonatomic, assign) NSInteger contentLength;

//@property (nonatomic, strong) UIImage *image;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    
    NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4" ];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    //   connect   
    [NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark - NSURLConnect    

// connection     ,            data
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
    NSHTTPURLResponse *newResponse = response;
    //         
    self.contentLength = [newResponse.allHeaderFields[@"Content-Length"] integerValue];
    
    self.fileData = [NSMutableData data];
}

//       ,          ,         
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.fileData appendData:data];
    
    CGFloat per =   (1.0 * self.fileData.length / self.contentLength);
    NSLog(@"%f",per);
}

//     
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%zd",self.fileData.length);
}

좋은 웹페이지 즐겨찾기