我从用户那里得到一个文件夹url,然后查找该文件夹中的任何mp3文件,问题本身在标题中,我只是想在过程中使用UTType。
如您所见,我在代码中完成了所有步骤,只需在isMP3函数中执行最后一步就可以完成这个难题。那么,我如何使用路径或URL,并细化它的UTType,并使用它进行比较。
在我的方法中,Xcode给出了一个错误,并说:
无法在作用域中找到“UTType”
不知道为什么我会有这个错误,通常不应该是这样的,因为它是由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
}
}发布于 2022-06-24 11:28:54
要使用UTType,必须导入显式包
import UniformTypeIdentifiers它可以类似于
func isMP3(path: String) -> Bool {
if let type = UTType(filenameExtension: URL(fileURLWithPath: path).pathExtension), type == UTType.mp3 {
return true
}
else {
return false
}
}https://stackoverflow.com/questions/72743372
复制相似问题