我正在使用表格视图,用户可以在其中下载视频文件。当我下载文件时,除了progressView之外,其他一切都正常。但是最后,我仍然准备好播放文件。 我对目标C中的请求不是很熟悉,因此我可能在代码中的某个时候搞砸了。有人能看到其中的错误吗?
另一个奇怪的是,我没有得到最后的NSLog(在connectionDidFinishLoading方法内部)
以下是影响下载的代码部分:
NSURLSession *session;
UIProgressView *progressBar;
BOOL currentlyDownloading;
NSString *videoToPlay;
BOOL downloadFinished;
- (void)viewDidLoad {
[super viewDidLoad];
session = [NSURLSession sharedSession];
currentlyDownloading = false;
downloadFinished = false;
videoToPlay = @"";
}
-(NSArray *)findFiles:(NSString *)extension
{
NSMutableArray *matches = [[NSMutableArray alloc]init];
NSFileManager *manager = [NSFileManager defaultManager];
NSString *item;
NSArray *contents = [manager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] error:nil];
for (item in contents)
{
if ([[item pathExtension]isEqualToString:extension])
{
[matches addObject:item];
}
}
return matches;
}
- (VideoTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"videoTuto" forIndexPath:indexPath];
if(indexPath.row == 0){
//local stream
cell.videoName.text = @"test local";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *urlPathStr = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp4"];
NSLog(@"urlpathstr: %@",urlPathStr);
if ([fileManager fileExistsAtPath:urlPathStr]){
NSLog(@"file exists");
cell.downloadState.image = [UIImage imageNamed:@"downloaded"];
cell.downloaded = [NSNumber numberWithBool:YES];
}else{
NSLog(@"file doesn't exist need to dwl it...");
cell.downloadState.image = [UIImage imageNamed:@"download"];
cell.downloaded = [NSNumber numberWithBool:NO];
}
cell.video = urlPathStr;
}else{
//server stream
cell.videoName.text = @"test server";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *urlPathStr = [[NSBundle mainBundle] pathForResource:@"tastege" ofType:@"mp4"];
NSLog(@"urlPathStr: %@",urlPathStr);
BOOL asVideo = false;
NSArray *videosStored = [self findFiles:@"mp4"];
for (NSInteger i = 0; i<[videosStored count]; i++) {
NSLog(@"obj at idx %lu : %@",i,[videosStored objectAtIndex:i]);
if([[videosStored objectAtIndex:i] isEqualToString:@"tastege.mp4"]){
asVideo = true;
}
}
if ([fileManager fileExistsAtPath:urlPathStr] || asVideo){
NSLog(@"file exists");
cell.downloadState.image = [UIImage imageNamed:@"downloaded"];
cell.downloaded = [NSNumber numberWithBool:YES];
NSString *fileName = @"tastege.mp4";
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:fileName];
cell.video = filePath;
}else{
NSLog(@"file doesn't exist need to dwl it...");
cell.downloadState.image = [UIImage imageNamed:@"download"];
cell.downloaded = [NSNumber numberWithBool:NO];
}
}
// Configure the cell...
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
VideoTableViewCell *cell = [[tableView visibleCells] objectAtIndex:indexPath.row];
if(cell.downloaded == [NSNumber numberWithBool:YES]){
NSLog(@"show vid");
videoToPlay = cell.video;
NSLog(@"cell.video: %@",cell.video);
NSLog(@"videoToPlay: %@",videoToPlay);
[self performSegueWithIdentifier:@"showVid" sender:self];
}else if(!currentlyDownloading){
//start download
currentlyDownloading = true;
__block BOOL postRequestReturned = false;
progressBar = cell.progress;
progressBar.hidden = NO;
NSString *fileName = @"tastege.mp4";
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:fileName];
NSString *videoUrl = [NSString stringWithFormat:@"MYURL/%@",fileName];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:videoUrl]];
[request setHTTPMethod:@"GET"];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if(data == nil){
NSLog(@"ERROR: %@", error.description);
}else{
[data writeToFile:filePath atomically:YES];
NSLog(@"File is saved to %@",filePath);
currentlyDownloading = false;
}
postRequestReturned = true;
}];
[task resume];
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
completionHandler(NSURLSessionResponseAllow);
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
progressBar.hidden = NO;
progressBar.progress=0.0f;
_downloadSize=[response expectedContentLength];
_dataToDownload=[[NSMutableData alloc]init];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
[_dataToDownload appendData:data];
progressBar.progress=((float)[ _dataToDownload length ]/(float)_downloadSize);
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Succeeded! Received %lu bytes of data",(unsigned long). [_dataToDownload length]);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
progressBar.hidden = YES;
downloadFinished = true;
[self.tableView beginUpdates];
NSArray *indexs = self.tableView.indexPathsForVisibleRows;
[self.tableView reloadRowsAtIndexPaths:indexs withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
}
非常感谢。
PS:我的代表团如下:UITableViewController <NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate>
据我所知,已经正确实施了