Masoud Rezaei
Masoud Rezaei

Reputation: 23

How can i get list of all videos in swift

I want to get the list of all videos which are stored in iPhone internally. I want to show all the video files in my application.

Upvotes: 0

Views: 2394

Answers (1)

Shawn Frank
Shawn Frank

Reputation: 5153

Here is a small example I created for you. You should know basics of table view to work with this.

First - Add NSPhotoLibraryUsageDescription in info.plist

This helps you get permission from the user to access the photos library

Info.plist for getting Photos app permission in iOS swift

Working with Photos App

Here is some code that fetches videos from the Photos app on your device, loads it in a table view and plays it when the user taps on a specific video.

I have added comments in the code to help you understand

// Import Photos to work with Photos app
// Import AVKit to play videos
import UIKit
import Photos
import AVKit

class PhotosExperimentViewController: UITableViewController
{
    // Array to hold videos
    var videos: [PHAsset] = []
    
    // Create cell identifier for UITableView
    let tableViewCellIdentifier = "cell"
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        title = "Video Example"
        
        // Register a default UITableView Cell
        tableView.register(UITableViewCell.self,
                           forCellReuseIdentifier: tableViewCellIdentifier)
    }
    
    override func viewDidAppear(_ animated: Bool)
    {
        super.viewDidAppear(animated)
        
        // Request access to PhotosApp
        PHPhotoLibrary.requestAuthorization(for: .readWrite) { [weak self] status in
            
            // Handle restricted or denied state
            if status == .restricted || status == .denied
            {
                print("Status: Restricted or Denied")
            }
            
            // Handle limited state
            if status == .limited
            {
                self?.fetchVideos()
                print("Status: Limited")
            }
            
            // Handle authorized state
            if status == .authorized
            {
                self?.fetchVideos()
                print("Status: Full access")
            }
        }
    }
    
    func fetchVideos()
    {
        // Fetch all video assets from the Photos Library as fetch results
        let fetchResults = PHAsset.fetchAssets(with: PHAssetMediaType.video, options: nil)
        
        // Loop through all fetched results
        fetchResults.enumerateObjects({ [weak self] (object, count, stop) in
            
            // Add video object to our video array
            self?.videos.append(object)
        })
        
        // Reload the table view on the main thread
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return videos.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellIdentifier)!
        
        // Get video asset at current index
        let videoAsset = videos[indexPath.row]
        
        // Display video creation date
        cell.textLabel?.text = "Video from \(videoAsset.creationDate ?? Date())"
        
        // Load video thumbnail
        PHCachingImageManager.default().requestImage(for: videoAsset,
                                                     targetSize: CGSize(width: 100, height: 100),
                                                     contentMode: .aspectFill,
                                                     options: nil) { (photo, _) in
            
            cell.imageView?.image = photo
            
        }
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        // Get video asset at current index
        let videoAsset = videos[indexPath.row]
        
        // Fetch the video asset
        PHCachingImageManager.default().requestAVAsset(forVideo: videoAsset, options: nil) { [weak self] (video, _, _) in
            if let video = video
            {
                // Launch video player in the main thread
                DispatchQueue.main.async {
                    self?.playVideo(video)
                }
            }
        }
    }
    
    // Function to play video player in AVPlayerViewController
    private func playVideo(_ video: AVAsset)
    {
        let playerItem = AVPlayerItem(asset: video)
        let player = AVPlayer(playerItem: playerItem)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        
        present(playerViewController, animated: true) {
            playerViewController.player!.play()
        }
    }
}

Running this code will give you these results

First permissions, I select allow access to all photos:

Photos App Permissions

Load all videos in your table view

Retrieve or get or load videos and photos from Photos App in UITableView

Tapping on any cell plays the video in AVPlayerViewController

Play video PHAsset from Photos Library in AVPlayerViewController

Here is an example of the full experience

PhotoKit get Videos from iOS device using swift and display it in a UITableView and play it in an AVPlayerViewController

Now you have everything you need to explore further. I recommend reading the documentation properly.

Upvotes: 4

Related Questions