swift - 如何将作为字符串的参数放入 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")!)
解决方案
现在,您正尝试在执行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()
}
}
}
推荐阅读
- linux - 在 crontab 中执行 ping 命令但没有输出
- c# - 如何遍历包含多个错误的字符串?
- flutter - Flutter web socket,事件之间的异步方法
- dataframe - 为什么我只通过选择元组的第一个元素来将元组转换为 DataFrame?
- flutter - 在两个模型之间共享数据颤动
- python - 单击使用 Selenium Python 的复选框?
- flutter - Flutter TextFormField:当我使用控制器时,TextInputType.number 无法正常工作
- python - 如何将 3 轴加速度计数据列表集成到 python 中的速度和位置?
- android - ARCore/SceneForm 显示模型线框模式
- java - 无法解析为每个:“${e : #fields.errors('userName')}”