首页 > 解决方案 > Why is my local video file path within the document directory not working after some time? [Swift]

问题描述

I have a custom video recording view controller, in which I save using a URL:

Sample URL: file:///var/mobile/Containers/Data/Application/802497BB-8413-4245-B33A-708EF8DD9CAF/Documents/FA6AF78A-2692-4CC8-8BE2-7F18140C3C98.mp4

The URL is generated using these functions:

// Gets the directory that the video is stored in
    func getPathDirectory() -> URL {
        // Searches a FileManager for paths and returns the first one
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentDirectory = paths[0]
        return documentDirectory
    }

    func generateURL() -> URL? {
        let path = getPathDirectory().appendingPathComponent(NSUUID().uuidString + ".mp4")
        return path
    }


I then replay the video once in a separate playback controller, and it works no problem. I have included it right below:

import AVFoundation

class VideoPlaybackController: UIViewController {
    
    let avPlayer = AVPlayer()
    var avPlayerLayer: AVPlayerLayer!
    
    var videoURL: URL!
    
    @IBOutlet weak var videoView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        print("VideoPlaybackController: \(videoURL!)")
        
        avPlayerLayer = AVPlayerLayer(player: avPlayer)
        avPlayerLayer.frame = view.bounds
        avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        videoView.layer.insertSublayer(avPlayerLayer, at: 0)
        
        view.layoutIfNeeded()
        
        let playerItem = AVPlayerItem(url: self.videoURL as URL)
        avPlayer.replaceCurrentItem(with: playerItem)
        
        avPlayer.play()
    }
}

While the video works, after some time, the video cannot be replayed, even though I saved it within the document directory. I downloaded the xcappdata and looked within the contents of the app, and saw that the video file is still there, so I am confused as to why the video is not available after some time.

Is there something that I am missing? Thank you for your time.

标签: swifturl

解决方案


推荐阅读