ios - Objective-C:如何从 UITableView 中选择的单元格播放视频?

标签 ios objective-c xcode

我希望用户能够在 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/

相关文章:

ios - CAEmitterCell 和 SKEmitterNode 的区别

ios - 如何使用参数在 swift 中创建单例

ios - 无法在 xcode 中调整 View 大小

ios - 在 App Purchase ios 中 - 产品详细信息未显示

objective-c - 努力存储日期以供以后使用

ios - 将当前用户的图像上传到 Firebase

iOS 获取特定语言字符串的本地化版本

iOS:如何移动球

ios - FireBase 存储下载错误域=FIRStorageErrorDomain 代码=-13000

ios - 在 WKWebView 和 HTTPCookieStorage 之间复制 cookie - 找不到 302 cookie