Mig70 Mig70 - 3 years ago 127
Objective-C Question

AVPlayer playerWithURL not working after app restart

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


Many thanks in advance!

Answer Source

The URL to this file is stored in Core Data

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download