【问题标题】:AVPlayer playerWithURL not working after app restart应用程序重启后 AVPlayer playerWithURL 不起作用
【发布时间】:2017-09-29 18:17:38
【问题描述】:

我从用户照片库中挑选了一个视频,然后我将视频保存在用户文档文件夹中,以便即使用户从他的照片库中删除该视频也能够播放该视频。该文件的 URL 存储在 Core Data 中。 一切正常,直到我下次运行该应用程序。不知何故,该 URL 似乎不再有效,这很奇怪,因为当 [AVPlayer playerWithURL:videoURL] 失败时我能够删除视频文件。 以下是我选择视频 URL 的方式:

- (void) imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
NSURL* videoURL = info[UIImagePickerControllerMediaURL];}

这就是我保存视频的方式:

+ (NSURL*) saveVideoInDocumentsFolder:(NSURL*)videoURL name:(NSString*)name {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* pathComponent = [NSString stringWithFormat:@"/%@.%@", name, [videoURL pathExtension]];
NSString* path = [documentsDirectory stringByAppendingPathComponent:pathComponent];

NSError* error = nil;
NSData* videoData = [NSData dataWithContentsOfURL:videoURL options:0 error:&error];
if (error)
    return nil;

BOOL success = [videoData writeToFile:path options:NSDataWritingAtomic error:&error];
if (success)
    return [NSURL fileURLWithPath:path];

return nil;}

这就是我播放视频的方式:

AVPlayer* player = [AVPlayer playerWithURL:videoURL]; // <- AFTER I RESTART THE APP THIS METHOD ALWAYS RETURNS nil!!

AVPlayerViewController* viewController = [[AVPlayerViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
viewController.player = player;
[player play];

非常感谢!

【问题讨论】:

    标签: objective-c avplayer nsurl


    【解决方案1】:

    此文件的 URL 存储在 Core Data 中

    这就是问题所在。每次运行应用程序时,文档目录 URL 都会更改(因为您是沙盒),因此第二次无效。永远永远永远不要在 iOS 中保存绝对文件 URL!

    【讨论】:

    • 谢谢你,马特!在每个会话中找到指向文档文件夹的基本 URL 的最正确方法是什么?
    • 就像你做的那样。您只需在需要访问文档目录的任何时候重新计算documentsDirectory。 :) 它会在应用程序运行期间持续存在,但仅此而已。
    【解决方案2】:

    每次关闭和打开应用程序时都需要获取路径目录,因为当应用程序关闭时它会删除documentDirectory,所以你必须再次获取它,如果你想获取你的视频文件然后保存FILE NAME 将该视频的首选项或 Core Data 然后通过附加此视频名称文件获取 documentDirectory 路径,您将获得您的视频。

    看看: - (代码在 swift 中,您可以轻松转换它objective c

    let fileName = "recording.mp4"
    
    let tempPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    
    let tempDocumentsDirectory: AnyObject = tempPath[0] as AnyObject
    
    let tempDataPath = tempDocumentsDirectory.appendingPathComponent(fileName) as String as String
    

    那个FILE NAME你将保存在preference或coreData中

    当您关闭并打开应用程序时,只需检查您是否将文件名保存在首选项或核心数据中,如果是,则通过附加文档目录来获取它,您将获得您的视频

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多