1

I'd like to be able to loop a live photo, for continuous playback.

So far, I'm trying to use the PHLivePhotoViewDelegate to accomplish this.

import Foundation
import SwiftUI
import PhotosUI
import iOSShared

struct LiveImageView: UIViewRepresentable {
    let view: PHLivePhotoView
    let model:LiveImageViewModel?
    let delegate = LiveImageLargeMediaDelegate()
    
    init(fileGroupUUID: UUID) {
        let view = PHLivePhotoView()
        // Without this, in landscape mode, I don't get proper scaling of the image.
        view.contentMode = .scaleAspectFit
        
        self.view = view
        
        // Using this to replay live image repeatedly.
        view.delegate = delegate
        
        model = LiveImageViewModel(fileGroupUUID: fileGroupUUID)
        
        guard let model = model else {
            return
        }
        
        model.getLivePhoto(previewImage: nil) { livePhoto in
            view.livePhoto = livePhoto
        }
    }
    
    func makeUIView(context: Context) -> UIView {
        return view
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        guard let model = model else {
            return
        }
        
        guard !model.started else {
            return
        }
        
        model.started = true
        view.startPlayback(with: .full)
    }
}

class LiveImageLargeMediaDelegate: NSObject, PHLivePhotoViewDelegate {
    func livePhotoView(_ livePhotoView: PHLivePhotoView, didEndPlaybackWith playbackStyle: PHLivePhotoViewPlaybackStyle) {
        livePhotoView.stopPlayback()
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) {
            livePhotoView.startPlayback(with: .full)
        }
    }
}

But without full success. It seems the audio does play again, but not the video. The livePhotoView.stopPlayback and the async aspect are just additional changes I was trying. I've tried it without those too.

Note that I don't want the user to have to manually change the live photo (e.g., see NSPredicate to not include Loop and Bounce Live Photos).

Thoughts?

Chris Prince
  • 7,288
  • 2
  • 48
  • 66

1 Answers1

0

ChrisPrince I tried your code and it works fine for me, I just add delegate and start playback inside of it and everything runs well and smoothly. I thought that there is no point in using stop playback because the function itself says that the playback ended.

func livePhotoView(_ livePhotoView: PHLivePhotoView, didEndPlaybackWith playbackStyle: PHLivePhotoViewPlaybackStyle) {
        livePhotoView.startPlayback(with: .full)
}
Ali Pishvaee
  • 303
  • 5
  • 7