我希望用户能够在 MPMoviePlayerConntroller
中播放视频,方法是在我的 uitableview
中点击一个单元格来选择视频,所以我要列出这段代码文件进入每个单元格:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
cell.textLabel.text = [filePathsArray[indexPath.row] lastPathComponent];
return cell;
}
这段代码成功运行,但现在我需要检查用户选择了什么,所以我有这段代码:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSURL * movieURL = [filePathsArray objectAtIndex:indexPath.row];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL: movieURL];
[[player view] setFrame: [self.view bounds]];
[self.view addSubview: [player view]];
[player play];
}
但是这段代码有一个问题,NSURL * movieURL = [filePathsArray objectAtIndex:indexPath.row];
一直让模拟器崩溃。
我可能是个傻子,但我不知道如何解决这个问题。
编辑
问题是 filePathsArray
只返回视频文件的名称和扩展名,所以例如它只会显示 testvideo.mp4
当我应该得到完整的该文件的路径。有人知道如何解决这个问题吗?
提前致谢...
最佳答案
正如您所说,您只获取文件名;这是因为这些行:
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
cell.textLabel.text = [filePathsArray[indexPath.row] lastPathComponent];
如果你想要完整的路径,你应该这样做:
NSString *currentFileName = [filePathsArray[indexPath.row] lastPathComponent];
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:currentFileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
//Play the movie now
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL: fileURL];
[[player view] setFrame: [self.view bounds]];
[self.view addSubview: [player view]];
[player play];
关于ios - Objective-C:如何从 UITableView 中选择的单元格播放视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17419183/