SwiftUI中如何添加项目内的本地视频?
Play Local Video in Your SwiftUI/UIKit Video Player
No problem at all! Let's tweak your existing code to play a local video file from your project bundle instead of a remote URL. Here's the updated version, with explanations of the key changes:
Modified Code
import AVKit import UIKit import SwiftUI class UIVideoPlayer: UIView { var playerLayer = AVPlayerLayer() var player: AVPlayer? // Make player a property for easier playback control later override init(frame: CGRect) { super.init(frame: frame) // 1. Fetch URL for your local video file in the app bundle // Replace "your-local-video" with your actual video filename (without .mp4) guard let url = Bundle.main.url(forResource: "your-local-video", withExtension: "mp4") else { print("Error: Local video file not found in bundle!") return } // 2. Initialize player with local URL (keeps your original playback settings) player = AVPlayer(url: url) player?.isMuted = true player?.play() // 3. Attach player to layer and configure layout playerLayer.player = player playerLayer.videoGravity = .resizeAspectFill // Cleaner syntax for the same aspect fill behavior layer.addSublayer(playerLayer) } override func layoutSubviews() { super.layoutSubviews() playerLayer.frame = bounds // Ensure the player layer matches the view's size } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Optional: Add helper methods if you need to control playback later func play() { player?.play() } func pause() { player?.pause() } } struct Players: UIViewRepresentable { func makeUIView(context: Context) -> UIVideoPlayer { return UIVideoPlayer() } func updateUIView(_ uiView: UIVideoPlayer, context: Context) { // No changes needed here unless you want to add dynamic playback updates later } }
Key Changes Explained
- Local File URL: Replaced the remote URL with
Bundle.main.url(forResource:withExtension:)to access files stored directly in your app's bundle. Remember to swap"your-local-video"with your actual video filename (leave off the.mp4extension here). - Player Property: Made
playera class property so you can easily add playback controls (like play/pause buttons) down the line if you need them. - Simplified Syntax: Used the shorter
.resizeAspectFillenum case instead of the raw value syntax—it does the exact same thing, just looks cleaner.
Critical Setup Step
Before testing, make sure your local video is properly added to your Xcode project:
- Drag and drop the video file into your project navigator.
- When prompted, check "Copy items if needed" and select your app target under "Add to targets".
- Double-check that the file appears in your target's Build Phases > Copy Bundle Resources list—this ensures it gets included in the final app bundle.
内容的提问来源于stack exchange,提问作者user16253979
相关产品推荐
相关产品推荐

