码迷,mamicode.com
首页 > 其他好文 > 详细

文件下载与NSOutputStream

时间:2016-12-10 22:27:47      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:pat   direct   关闭   com   arc   ros   style   mil   文件名   

代码:

#import "ViewController.h"

@interface ViewController () <NSURLConnectionDataDelegate>

@property (nonatomic, strong) NSOutputStream *outputStream;

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSString *urlString = @"http://127.0.0.1/file";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // caches目录路径
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    // 文件名
    NSString *fileName = response.suggestedFilename;
    // 文件完整路径
    NSString *fileFullPath = [cachesPath stringByAppendingPathComponent:fileName];
    NSLog(@"%@", fileFullPath);
    
    // 创建流
    NSOutputStream *outputStream = [[NSOutputStream alloc] initToFileAtPath:fileFullPath append:YES];
    self.outputStream = outputStream;
    
    // 打开流
    [outputStream open];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.outputStream write:data.bytes maxLength:data.length];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // 关闭流
    [self.outputStream close];
}

 

文件下载与NSOutputStream

标签:pat   direct   关闭   com   arc   ros   style   mil   文件名   

原文地址:http://www.cnblogs.com/loftyspirit/p/6158280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!