iOS 文件下載並保存到沙盒中

同步下載,若是內容過大時,不推薦,會阻塞UIapp

- (void)syncDownload異步

{async

    NSString *path = @"http://lx.cdn.baidupcs.com/file/test.mp4"; //下載文件地址url

    NSURL *url = [NSURL URLWithString:path];spa

    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];代理

    NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];orm

    [self save:data];cdn

}ci

- (void)save:(NSData *)data同步

{

    NSString *temp = NSTemporaryDirectory();

    

    NSFileManager *fm = [NSFileManager defaultManager];

 

    _path = [temp stringByAppendingPathComponent:@"test.mp4"];

 

    BOOL b = [fm createFileAtPath:_path contents:_data attributes:nil];

}

//異步下載

- (void)asyncDownload

{

    NSString *path = @"http://lx.cdn.baidupcs.com/file/test.mp4"; //下載文件地址

    NSURL *url = [NSURL URLWithString:path];

    NSURLRequest *req = [[NSURLRequest allocinitWithURL:url];

 

    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:selfstartImmediately:YES];

}

//實現異步下載代理

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"error");

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"response");

    recLenth = 0;//初始化接收到的長度

    _data = [[NSMutableData alloc] initWithCapacity:0];

    lenth = [response expectedContentLength];//獲取下載內容總長度

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [_data appendData:data];//接收到數據

    recLenth += [data length];

    float pro = (float)recLenth/(float)lenth;//計算下載進度0-1

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"finish");

    [self save:_data];

 

}

相關文章
相關標籤/搜索