0

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
    }
}
ios coder
  • 1
  • 4
  • 31
  • 91
  • 1
    https://en.wikipedia.org/wiki/List_of_file_signatures You'd need to read the first byte and see if it as least check with the "magic bytes" of the MP3 file – Larme Jun 24 '22 at 12:36
  • @Larme: Wow! I was looking for such approach, so should I read the url as Data and then read the first bytes? Do you have any example or link to the approach? – ios coder Jun 24 '22 at 12:58
  • 1
    "swift read first bytes of file" lead me to: https://stackoverflow.com/questions/55884381/how-to-read-a-block-of-data-from-file-instead-of-a-whole-file-in-swift – Larme Jun 24 '22 at 13:01

0 Answers0