I am using this below code to print out all mp3 files in a folder, the issue with this code is that I can fool the function with a text file that has .mp3
, and this function would consider that text file with extension of mp3 as mp3, Note that I am not trying to play that mp3 at all, I just want make sure that the file itself is a valid mp3, and this valid mp3 file could have or not have issue itself about being playable. So being playable is not my issue, my issue is just being a valid mp3 itself. How can I solve this issue?
import SwiftUI
import UniformTypeIdentifiers
struct ContentView: View {
@State private var fileImporterIsPresented: Bool = false
var body: some View {
Button("Select your Folder") { fileImporterIsPresented = true }
.fileImporter(isPresented: $fileImporterIsPresented, allowedContentTypes: [.folder], allowsMultipleSelection: false, onCompletion: { result in
switch result {
case .success(let urls):
if let unwrappedURL: URL = urls.first {
if let contents = try? FileManager.default.contentsOfDirectory(atPath: unwrappedURL.path) {
contents.forEach { item in
if isValidMP3(path: unwrappedURL.path + "/" + item) {
print(item)
}
}
}
}
case .failure(let error):
print("Error selecting file \(error.localizedDescription)")
}
})
}
}
func isValidMP3(path: String) -> Bool {
if let type = UTType(filenameExtension: URL(fileURLWithPath: path).pathExtension), type == UTType.mp3 {
return true
}
else {
return false
}
}