文件下载(NSURLConnection/NSURLSession)

最基本的网络文件下载(使用原生的网络请求)

 

#pragma mark - 小文件下载

 

// 方法一: NSData dataWithContentsOfURL
- (void)downloadFile1
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 其实这就是一个GET请求
        NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/images/minion_01.png"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        NSLog(@"%lu", data.length);
    });
}

 

// 方法二: NSURLConnection
- (void)downloadFile2
{
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/images/minion_01.png"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%lu", data.length);
    }];
}

 

//方法三:NSURLSession iOS7开始出现的 为取代NSURLConnection
- (void)downloadFile3
{
    // 1.得到session对象
    NSURLSession *session = [NSURLSession sharedSession];

    // 2.创建一个下载task
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/test.mp4"];
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {// location : 临时文件的路径(下载好的文件)

        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
        NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];

        // 将临时文件剪切或者复制Caches文件夹
        NSFileManager *mgr = [NSFileManager defaultManager];

        // AtPath : 剪切前的文件路径
        // ToPath : 剪切后的文件路径
        [mgr moveItemAtPath:location.path toPath:file error:nil];
    }];
    
    // 3.开始任务
    [task resume];
}

 

 

#pragma mark - 大文件下载

 

//方法一: NSURLConnection (合理:单个线程 下载一点就写入一点)使用NSFileHandle
//句柄对象
@property (nonatomic, strong) NSFileHandle * writeHandle;

- (void)downloadFile4
{
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/videos.zip"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 下载(创建完conn对象后,会自动发起一个异步请求,通过delegate回调下载信息)
    [NSURLConnection connectionWithRequest:request delegate:self];
}

#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{//请求失败

}

// 1.接收到服务器的响应就会调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"];

    // 创建一个空的文件 到 沙盒中
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr createFileAtPath:filepath contents:nil attributes:nil];

    // 创建一个用来写数据的文件句柄
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];
}

// 2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 移动到文件的最后面
    [self.writeHandle seekToEndOfFile];

    // 将数据写入沙盒
    [self.writeHandle writeData:data];
}

// 3.加载完毕后调用(服务器的数据已经接收完毕)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
    // 关闭文件 设置为空
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}

 

 

//方法二: NSURLConnection 使用NSOutputStream

//文件流
@property (nonatomic, strong) NSOutputStream * fileStream;

- (void)downloadFile6
{
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/videos.zip"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 下载(创建完conn对象后,会自动发起一个异步请求,通过delegate回调下载信息)
    [NSURLConnection connectionWithRequest:request delegate:self];
}

#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{//请求失败

}

// 1.接收到服务器的响应就会调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"];

    // 创建一个空的文件 到 沙盒中
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr createFileAtPath:filepath contents:nil attributes:nil];

    // 创建一个用来写数据的文件句柄
    self.fileStream = [NSOutputStream outputStreamToFileAtPath:filepath append:YES];
}

// 2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //将数据追加到文件流中
    [self.fileStream write:data.bytes maxLength:data.length];
}

// 3.加载完毕后调用(服务器的数据已经接收完毕)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
    // 关闭文件流
    [self.fileStream close];
}

 

 

 

 

更多内容--> 博客导航 每周一篇哟!!!

 

 

有任何关于iOS开发的问题!欢迎下方留言!!!或者邮件lieryangios@126.com 虽然我不一定能够解答出来,但是我会请教iOS开发高手!!!解答您的问题!!!

 

posted on 2017-07-31 12:35  人生为代码而活  阅读(503)  评论(0编辑  收藏  举报

导航