파일 다운로드 및 NSOutputStream

3459 단어
코드:
#import "ViewController.h"

@interface ViewController () 

@property (nonatomic, strong) NSOutputStream *outputStream;

@end

@implementation ViewController

- (void)touchesBegan:(NSSet *)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];
}

@end

 
전재 대상:https://www.cnblogs.com/xwoder/p/6158280.html

좋은 웹페이지 즐겨찾기