Nuke icon indicating copy to clipboard operation
Nuke copied to clipboard

[Example] Nuke Video Minimal Working Example

Open lschaupp opened this issue 1 year ago • 2 comments
trafficstars

import AVKit
import Nuke
import NukeVideo
import NukeUI

extension UIView {
    /// Pins this view to it's superview.
    func pinToSuperview() {
        guard let superview = superview else { fatalError("UIView+pinToSuperview: \(description) has no superview.") }
        pin(to: superview)
    }
    
    /// Pins this view to another view.
    func pin(to view: UIView) {
        leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    }
}

struct NukeWrapper: UIViewRepresentable {
    var asset: URL

    init(asset: URL) {
        self.asset = asset
    }

    func makeUIView(context: Context) -> UIView {
        let contentView = UIView()
        let imageView = LazyImageView()
        imageView.makeImageView = { container in
            if let type = container.type, type.isVideo, let asset = container.userInfo[.videoAssetKey] as? AVAsset {
                let view = VideoPlayerView()
                view.asset = asset
                view.play()
                return view
            }
            return nil
        }
        imageView.url = self.asset
        let overlayView = UIView()
        overlayView.backgroundColor = UIColor(.blue)
        imageView.placeholderView = overlayView
        contentView.addSubview(imageView)
        imageView.pinToSuperview()
        
        return imageView
    }

    func updateUIView(_ uiView: UIView, context: Context) {
        // Handle updates if needed
    }
}

Usage: NukeWrapper(asset: url) in any SwiftUI View

This would have saved me some time. Therefore I am sharing it :)

lschaupp avatar Dec 22 '23 10:12 lschaupp

Hi thank you for making this! I gave this a spin, but I am only getting a blank image. Is that how it was supposed to work?

gimyeonghun avatar Dec 22 '23 13:12 gimyeonghun

@gimyeonghun I have tested this on the latest iOS version 17.2. Make sure that the URL you are providing works.

lschaupp avatar Dec 25 '23 14:12 lschaupp

Thanks you for posting it, @lschaupp. I hope other folks find it useful in the future.

kean avatar Feb 18 '24 17:02 kean