Download mp4 file from link and save to documents directory in IOS Swift or Objective-C

155 Views Asked by At

I would like app users to be able to to download MP4 files from a remote link and save them to the local app documents directory (not photos). I'm guessing this may create storage problems at some point but for the time being the files are short as in under a minute so probably okay to save locally.

I know how to play files from a remote URL. I also know how to save data from a remote link. What I don't know how to do is to save the data in MP4 format. Unlike with a UIImage, you can't get the image after displaying it in an ImageView as far as I know. Can anyone suggest how to save the data from the link as an MP4 file?

Here is how I play videos from a remote link.

//after importing AVFoundation
-(void) playVideo: (NSString*) surl {
    NSURL *videoURL = [NSURL URLWithString:surl];
    AVPlayer *player = [AVPlayer playerWithURL:videoURL];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame = self.videoView.bounds;
    [self.videoView.layer addSublayer:playerLayer];
}

Here is a way to download the data from a remote url as NSData

@objc func download(surl: NSString, completion : @escaping (NSData) -> Void ) {
        if surl == nil {
            return
        }
        guard let url = URL(string: String(surl)) else {  
            return }
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
      
        let task = session.dataTask(with: url) { data, response, error in
            if let data = data, error == nil {
                let nsdata = NSData(data: data)
                DispatchQueue.main.async {
                    completion(nsdata)
                }
            } else {
                print("Failure: %@", error?.localizedDescription);
            }
        }
        task.resume()
    }

For an image I could do something like:

if let img = UIImage(data: data as Data) {
          
                completion(img)
            }

But as far as I know there is no video equivalent of a UIImage or way to directly make a video out of Data. How can I convert the NSdata to an MP4 format file that I can work with locally...Or perhaps do I leave it as NSData... But if so, how does system know it is a video file eg MP4?

Any suggestions would be appreciated. Thank you.

0

There are 0 best solutions below