提问人:Lukas Kompatscher 提问时间:11/14/2023 最后编辑:Lukas Kompatscher 更新时间:11/15/2023 访问量:26
如何使用按需资源在 swift 中找到 Ressource 路径/Ressource 本身
How to find the Ressource Path/Ressource itself in swift with on demand resources
问:
我有一个颤振应用程序,它是一个音频指南。但是我有多种语言的音频文件,所以我想在IOS端使用点播资源。我从 Xcode 的 ios 文件夹中打开了 Runner,并添加了资产并为其添加了标签。音频文件的类型为 wav。但是当请求带有标签的图像时,我没有得到任何结果。german
private func getDownloadRessources(tag: String, result: @escaping FlutterResult) {
let resourceRequest = NSBundleResourceRequest(tags: [tag])
resourceRequest.beginAccessingResources { (error: Error?) in
if let error = error {
// Handle the error.
print("Error accessing resources: \(error)")
result(FlutterError(code: "RESOURCE_ERROR", message: "\(error) tag:\(tag)", details: error.localizedDescription))
} else {
guard let resourceURL = resourceRequest.bundle.url(forResource: nil, withExtension: "wav") else {
print("Resource not found for tag: \(tag)")
result(FlutterError(code: "RESOURCE_NOT_FOUND", message: "Resource not found for tag: \(tag)", details: nil))
return
}
print("Resource URL: \(resourceURL.absoluteString)")
result(resourceURL.absoluteString)
}
resourceRequest.endAccessingResources()
}
}
在代码中,我有给定的标签,但仍然找不到资源音频。german
resourceRequest.bundle.url
我试图获取 Bundle.main 的路径并在那里寻找音频,但这不起作用。我给方法起了名字,但它仍然没有找到它。我查看了 resourcerequest 包的路径,但仍然没有找到音频文件。我尝试使用Bundle.main方法,但仍然没有找到图像。
答:
0赞
Lukas Kompatscher
11/15/2023
#1
我设法用NSDataAsset解决了它。当我将文件名传递给它时,我会将其取回,然后可以在 Swift 中使用 FileManager 保存它或将字节发送到 flutter。
if let asset = NSDataAsset(name:"audio1") {
print(asset)
result(asset.data)
} else {
print("Resource not found for tag: \(tag)")
result(FlutterError(code: "RESOURCE_NOT_FOUND",
message: "Resource not found for tag: \(tag)",
details: nil))
}
或使用
if let asset = NSDataAsset(name:"audio1") {
// Get the directory to save the file
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// Specify the file name and type
let fileURL = dir.appendingPathComponent("audio1.mp3")
// Write the NSDataAsset to the file
do {
try asset.data.write(to: fileURL)
print("File saved to \(fileURL.absoluteString)")
result(fileURL.absoluteString)
} catch {
print("Error saving file: \(error)")
result(FlutterError(code: "ERROR_SAVING_FILE",
message: "Error saving file: \(error)",
details: nil))
}
} else {
print("Resource not found for tag: \(tag)")
result(FlutterError(code: "RESOURCE_NOT_FOUND",
message: "Resource not found for tag: \(tag)",
details: nil))
评论