Home > OS >  How can I have xcodeproj type for allowedContentTypes in fileImporter in SwiftUI?
How can I have xcodeproj type for allowedContentTypes in fileImporter in SwiftUI?

Time:06-26

I want be able to select Xcode projects in my native macOS app, I am using .xcodeproj for allowedContentTypes, but clearly Xcode or UniformTypeIdentifiers does not know about it! Is there a way around to make the codes works?

import SwiftUI
import UniformTypeIdentifiers

struct ContentView: View {
    @State private var fileImporterIsPresented: Bool = false
    var body: some View {
        
        Button("Select your Xcode projext") { fileImporterIsPresented = true }
            .fileImporter(isPresented: $fileImporterIsPresented, allowedContentTypes: [.xcodeproj], allowsMultipleSelection: false, onCompletion: { result in
                
                switch result {
                case .success(let urls):
                    
                    if let unwrappedURL: URL = urls.first {
                        print(unwrappedURL.path)
                    }
                    
                case .failure(let error):
                    print("Error selecting file \(error.localizedDescription)")
                }
                
            })
        
    }
}

CodePudding user response:

Theoretically it should work for the following UTType (even without additional configurations in Info.plist)

UTType(tag: "xcodeproj", tagClass: .filenameExtension, conformingTo: .compositeContent)

but it does not due to some bug in fileImporter I assume, because using native AppKit open panel works fine as expected

    Button("Open") {
        let panel = NSOpenPanel()
        panel.allowsMultipleSelection = false
        panel.allowedContentTypes = [xcodeproj]
        panel.canChooseDirectories = false
        if panel.runModal() == .OK {
            print(">> ", panel.urls)
        }
    }

Test module on GitHub

  • Related