美文网首页
NSURLConnection小文件下载写入沙盒

NSURLConnection小文件下载写入沙盒

作者: solozyx | 来源:发表于2016-08-07 14:08 被阅读14次

    使用delegate的方式:

    @interface ViewController () <NSURLConnectionDataDelegate>
    /** 文件数据 */
    @property (nonatomic, strong) NSMutableData *fileData;
    /** 文件的总长度 */
    @property (nonatomic, assign) NSInteger contentLength;
    @end
    

    <NSURLConnectionDataDelegate>相关代理方法实现:

    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/resources/videos/minion_15.mp4"];
        [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
    }
    
    #pragma mark - <NSURLConnectionDataDelegate>
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{
        self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
        self.fileData = [NSMutableData data];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
        [self.fileData appendData:data];
        CGFloat progress = 1.0 * self.fileData.length / self.contentLength;
        NSLog(@"已下载:%.2f%%", (progress) * 100);
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
        NSLog(@"下载完毕");
        // 将文件写入沙盒中
        // 缓存文件夹
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 文件路径
        NSString *file = [caches stringByAppendingPathComponent:@"box_minion_15.mp4"];
        NSLog(@"%@",file);
        // 写入数据
        [self.fileData writeToFile:file atomically:YES];
        self.fileData = nil;
    }
    

    如果要下载的文件足够小:

    - (void)dataDownlaod{
        NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/resources/images/minion_15.png"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *file = [caches stringByAppendingPathComponent:@"box_minion_15.png"];
        [data writeToFile:file atomically:YES];
    }
    

    相关文章

      网友评论

          本文标题:NSURLConnection小文件下载写入沙盒

          本文链接:https://www.haomeiwen.com/subject/tejlsttx.html