如何使用 UTType 在 Swift 中的条件中进行比较?

use*_*ser 0 swift

我从用户那里获取一个文件夹 url,然后寻找该文件夹中的任何 mp3 文件,问题本身在标题中,而我只是想在过程中使用UTType

正如你所看到的,我完成了代码中的所有步骤,只需要isMP3函数中的最后一步来完成拼图。那么我如何使用路径或 URL 并找出它的 UTType 并使用它进行比较。

同样在我的方法中,Xcode 给出了一个错误并说:

在范围内找不到“UTType”

不知道为什么会出现这个错误,通常情况下不应该是这样,因为它是苹果定义的类型。

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 6

要使用 UTType 你必须导入显式包

import UniformTypeIdentifiers
Run Code Online (Sandbox Code Playgroud)

它可以是这样的

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