小文件下载(三种方式)


第一种:直接赋值

-(void)post
{
    NSURL *url = [NSURL URLWithString:@"http://......."];

    NSData *data = [NSData dataWithContentsOfURL:url];

    self.imageView.image = [UIImage imageWithData:data];
}

第二种:发送异步请求

-(void)second
{
    NSURL *url = [NSURL URLWithString:@"http://......."];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

        self.imageView.image = [UIImage imageWithData:data];

    }];
}

第三种:NSURLConnection代理

-(void)viewDidLoad
{
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:@"http://......."];

    //包装请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //发送请求
    [NSURLConnection connectionWithRequest:request delegate:self];

}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.dataM = [NSMutableData data];

    self.totoleLength = response.expectedContentLength;

    NSLog(@"%s",__func__);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.dataM appendData:data];

    self.currentLength = self.dataM.length;

    CGFloat progress = 1.0 * self.currentLength / self.totoleLength;

    NSLog(@"%f",progress);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%s",__func__);

    //沙盒路径
    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    //拼接文件
    NSString *fullPath = [cache stringByAppendingPathComponent:@"abc.png"];

    [self.dataM writeToFile:fullPath atomically:YES];
}

你可能感兴趣的:(IOS开发)