首页 > 解决方案 > 如何将作为字符串的参数放入 URL 的路径中?

问题描述

这是我尝试过的,我收到了这个错误:

调用初始化程序时没有完全匹配

struct VideoBox: View {
    var videoname : String
    var ext : String
    var filepath1 : String
    var filepath2 : String
    var fullfilepath : String
    
    init(videoname: String) {
        self.videoname = videoname
        ext = "mp4"
        
        filepath1 = "fileURLWithPath: Bundle.main.path(forResource: "
        filepath2 = ", ofType: \"\(ext)\")!)"
        fullfilepath = "\(filepath1) \"\(self.videoname)\" \(filepath2)"
      }
    
    
   @State var player = AVPlayer (url: URL(fullfilepath))

我的电话VideoBox是这样的:

struct ContentView: View {
     
    let videoname = "3mintestvideo"
    var body: some View {
        VideoBox (videoname: videoname)
    }
} 

fullfilepath值打印为:

fileURLWithPath: Bundle.main.path(forResource: "3mintestvideo, ofType: "mp4")!)

标签: swifturlavplayerfilepath

解决方案


现在,您正尝试在执行String时将代码包含在"fileURLWithPath: Bundle.main.path(forResource: ". 相反,您应该使用实际Bundle.main代码(在字符串之外)。您也可以URL直接从捆绑包中获取 - 您无需在路径和 URL 之间进行转换。

struct SampleView : View {
    @State var player : AVPlayer
    
    init(videoname: String) {
        if let url = Bundle.main.url(forResource: videoname, withExtension: "mp4") {
            _player = State(initialValue: AVPlayer(url: url))
        } else {
            _player = State(initialValue: AVPlayer())
        }
    }
    
    var body: some View {
        Text("test")
    }
}

View请注意,在a中做太多init可能是危险的——如果它View被多次加载,您可能需要考虑将播放器移动到只调用一次加载代码的视图模型onAppear

struct SampleView : View {
    var videoname : String
    @StateObject private var sampleViewModel : SampleViewModel()
    
    var body: some View {
        Text("test").onAppear {
            sampleViewModel.loadVideo(videoname: videoname)
        }
        if let player = sampleViewModel.player {
            //use the player here
        }
    }
}

class SampleViewModel : ObservableObject {
    @Published var player : AVPlayer?
    
    func loadVideo(videoname : String) {
        if let url = Bundle.main.url(forResource: videoname, withExtension: "mp4") {
            player = AVPlayer(url: url)
        } else {
            player = AVPlayer()
        }
    }
}

推荐阅读