How to dynamically update my gallery data

39 views Asked by At

Hello Respected Comrades,

I made a gallery app. initially I get a data of media from phone. but when i add some new photos to device. i cant see them until :

  1. re install app
  2. fetching in view will appear (this is just a temperory fix)

I want to update my data dynamically with respect to phone data

code: import UIKit import Foundation import Photos import CoreData

enum MediaType{ case video, photo }

View model

class GalleryPageViewModel : BaseViewModel{
    var mediaArray = Spectator<MediaArray?>(value:
    [])
    var title = "Gallery"
    var appDelegate:AppDelegate?
    var context : NSManagedObjectContext?
    let responder : AppResponder
    var tempMedia = [MediaModel]()
    
    init(with responder:AppResponder){
        self.responder = responder
        super.init()
    }
}

extension GalleryPageViewModel{
    func populatePhotos(){
        mediaArray.value = []
        tempMedia = []
        PHPhotoLibrary.requestAuthorization{ [weak self] status in
            if status == .authorized{
                let assets = PHAsset.fetchAssets(with: nil)
                assets.enumerateObjects{ (object,_,_) in
                    var image = UIImage()
                    image = self!.conversionPhotoToImage(asset: object)
                    var mediaType : MediaType = .photo
                    if object.mediaType == .video{
                        mediaType = .video
                    }
                    let media = MediaModel(img: image, asset: object, mediaType: mediaType)
                    self?.tempMedia.append(media)
                }
            }
            else{
                print("auth failed")
            }
            self?.setUpData()

        }
    }
    
    func conversionPhotoToImage(asset : PHAsset) -> UIImage{
        let manager = PHImageManager.default()
        var media = UIImage()
        let requestOptions=PHImageRequestOptions()
        requestOptions.isSynchronous=true
        requestOptions.deliveryMode = .highQualityFormat
        
        manager.requestImage(for: asset, targetSize: CGSize(width: 1000, height: 1000), contentMode:.aspectFill, options: requestOptions) { image,_ in
            media = image!
        }
        return media
    }
    
    func setUpData(){
        self.mediaArray.value = tempMedia
    }
    
    
}

extension GalleryPageViewModel{
    func numberOfItemsInSection() -> Int{
        return mediaArray.value?.count ?? 0
    }
    
    func didSelectAtRow(index:IndexPath){
        self.responder.pushToDetailVc(data: mediaArray.value![index.row])
    }
}


extension GalleryPageViewModel{
    func setUpCoreData(){
        appDelegate = UIApplication.shared.delegate as! AppDelegate
        context = appDelegate?.persistentContainer.viewContext
    }
    
    func storeInCoreData(){
        let entity = NSEntityDescription.entity(forEntityName: "MediaData", in: context!)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        var i = 1
        for data in mediaArray.value!{
            newUser.setValue(data.img, forKey: "image")
            newUser.setValue(data.duration, forKey: "duration")
            newUser.setValue("data", forKey: "mediaType")
            newUser.setValue(data.location, forKey: "location")
            newUser.setValue(data.creationDate, forKey: "creationDate")
            var id = String()
            if data.mediaType == .photo{
                id = "imgEn\(i)"
            }
            else{
                id = "vidEn\(i)"
            }
            i+=1
            newUser.setValue(id, forKey: "id")
        }
     
    }
}

View controller


import UIKit
import Photos

class GalleryPageViewController: BaseViewController {
    
    var galleryCollectionView : UICollectionView?
    
    var galleryCollectionViewFlowLayout : UICollectionViewFlowLayout? = nil
    
    var viewModel: GalleryPageViewModel? {
        didSet {
            self.bindViewModel()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = viewModel?.title
        

        view.backgroundColor = .systemBackground
        setUpFlowLayout()
        galleryCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: galleryCollectionViewFlowLayout!)
        galleryCollectionView?.register(MediaCollectionViewCell.self, forCellWithReuseIdentifier: "cell")

        setUpCollectionView()
        viewConstraintsForGalleryPage()
        viewModel?.populatePhotos()


    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    
}


// MARK: - UI WORKS

extension GalleryPageViewController{
    func setUpFlowLayout(){
        galleryCollectionViewFlowLayout = UICollectionViewFlowLayout()
        galleryCollectionViewFlowLayout?.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        galleryCollectionViewFlowLayout?.itemSize = CGSize(width: (view.frame.width/2) - 20, height: (self.view.frame.width/2)-10)
    }
    func setUpCollectionView(){
        
        galleryCollectionView?.dataSource = self
        galleryCollectionView?.delegate = self
    }
    
    func viewConstraintsForGalleryPage(){
        // adding sub view to maintain heirarchy.
        view.addSubview(galleryCollectionView!)
        
        // constraints for views in this page
        
        // collection view
        galleryCollectionView?.translatesAutoresizingMaskIntoConstraints = false
//        galleryCollectionView?.backgroundColor = .blue
        galleryCollectionView?.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 10).isActive = true
        galleryCollectionView?.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
        galleryCollectionView?.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,constant: 10).isActive = true
        galleryCollectionView?.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true

        
    }
}

//MARK: - COLLECTION VIEW DELEGATE AND DATA SOURCE

extension GalleryPageViewController : UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        vc.data = viewModel?.mediaArray.value?[indexPath.row]
        viewModel?.didSelectAtRow(index: indexPath)
    }
}

extension GalleryPageViewController : UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.numberOfItemsInSection() ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MediaCollectionViewCell
        let cellData = viewModel?.mediaArray.value?[indexPath.row]
        cell.imageView.image = cellData?.img
        if cellData?.mediaType == .video{
            cell.playBtn.isHidden = false
            cell.durationLabel.isHidden = false
            let manager = PHImageManager.default()
            manager.requestAVAsset(forVideo: (cellData?.asset)!, options: nil){asset,_,_ in
                let duration = asset?.duration
                let durationTime = CMTimeGetSeconds(duration!)
                let finalTime = durationTime/60
                
                DispatchQueue.main.async {
                    cell.durationLabel.text = "\(Int(finalTime)) : \(Int(durationTime) % 60)"
                }
               
            }
        }
        else{
            cell.playBtn.isHidden = true
            cell.durationLabel.isHidden = true
        }
        return cell
    }
}

//MARK: - BINDING VARIABLES

extension GalleryPageViewController{
    private func bindViewModel(){
        viewModel?.mediaArray.bind { [weak self] _ in
            print("i am gonna reload")
            print(self?.viewModel?.mediaArray.value?.isEmpty)
            DispatchQueue.main.async {
                self?.galleryCollectionView?.reloadData()
            }
        }
    }
}



0

There are 0 answers