Home > Back-end >  How can I use UTType for comparing in a condition in Swift?
How can I use UTType for comparing in a condition in Swift?

Time:06-25

I am getting a folder url from user and then looking to find any mp3 files in that folder, the question itself in title and me just looking to use UTType in process.

As you can see I took all steps in codes just need last step in isMP3 function to finish the puzzle. So how can I use a path or URL and fining out the UTType of it and using it for comparing.

Also in my approach Xcode gave an error and says:

Cannot find 'UTType' in scope

Not sure why I have this error, normally it should Not be case, because it is type defined by Apple.

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 isMP3(path: unwrappedURL.path   "/"   item) {
                                    print(item)
                                }
                            }
                            
                        }
                        
                    }
                    
                case .failure(let error):
                    print("Error selecting file \(error.localizedDescription)")
                }
                
            })
        
    }
}


func isMP3(path: String) -> Bool {
    // trying use UTType here
    if URL(fileURLWithPath: path).??? == UTType.mp3 {
        return true
    }
    else {
        return false
    }
}

CodePudding user response:

To use UTType you have to import explicit package

import UniformTypeIdentifiers

it can be something like

func isMP3(path: String) -> Bool {
    if let type = UTType(filenameExtension: URL(fileURLWithPath: path).pathExtension), type == UTType.mp3 {
        return true
    }
    else {
        return false
    }
}
  • Related