应用重启后AVPlayer playerWithURL不起作用 [英] AVPlayer playerWithURL not working after app restart

查看:81
本文介绍了应用重启后AVPlayer playerWithURL不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am picking a video from the user photo library and than I save the video in the user Documents Folder to be able to play the video even if the user deletes this video from his photo Library. The URL to this file is stored in Core Data. Everything works fine until the next time I run the App. Somehow it seems like the URL is no longer valid, which is strange because I am able to delete the video file when [AVPlayer playerWithURL:videoURL] fails. Here is how I pick the video URL:

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

这是我保存视频的方式:

This is how I save the video:

+ (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;}

这是我播放视频的方式:

This is how I play the video:

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];

非常感谢!

推荐答案

此文件的URL存储在核心数据中

The URL to this file is stored in Core Data

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

That's the problem. The documents directory URL changes every time you run the app (because you are sandboxed), so it isn't valid the second time. Never never never save an absolute file URL in iOS!

这篇关于应用重启后AVPlayer playerWithURL不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆