I have a flutter application which is an audio guide. But i have the audio files in many languages so i want to use on demand resources on the IOS side. I opened the Runner from the ios folder in Xcode and added the assets and gave them tags. The audio files are of the type wav.
But when requesting the images with the tag german
i get no results.
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()
}
}
In the code i have the tag german
which is given, but the resourceRequest.bundle.url
does still not find the ressource audio.
I tried to get the path of Bundle.main and looked there for the audio but that didn't work. I gave the name to the method and it did still not find it. I looked inside the path of the resourcerequest bundle but did still not find the audio files. I tried with the Bundle.main method but still no luck in finding the images.
I managed to solve it with NSDataAsset. When i pass it the name of the file i get it back and then can either save it with FileManager in Swift or send the bytes to 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))
}
or with
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))