Reputation: 1273
I would like to be able to select files other than the ones predefined?
import SwiftUI
struct ContentView: View {
@State var fileName = ""
@State var openFile = false
var body: some View {
VStack(spacing: 25) {
Text(fileName)
Button(action: {openFile.toggle()}, label: {
Text("Open")
})
}
.fileImporter(isPresented: $openFile, allowedContentTypes: []) { (res) in
}
}
}
I'm able to specify general types like .audio for allowedContentTypes, but I would like a specific file extension to be allowed.
I followed the directions on this page, but it didn't work.
I ended up with this in my Info.plist:
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.txt</string>
</array>
<key>UTTypeIdentifier</key>
<string>com.company.srt-document</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>srt</string>
</array>
</dict>
</dict>
</array>
Upvotes: 4
Views: 2368
Reputation: 51831
First of all do you need to change the conforms to type in the Info.plist to
public.text
Then in your code you need to create an UTType
object for your file type.
import UniformTypeIdentifiers
struct ContentView: View {
let srtType = UTType(exportedAs: "com.company.srt-document", conformingTo: .text)
and then use it in the file import call
.fileImporter(isPresented: $openFile, allowedContentTypes: [srtType]) { (res) in
//...
}
I had some issues getting this to work even though everything looked correct but by deleting the project folder under DerivedData so that everything got built/generated from start the next time I did a build in Xcode I got my test app to see and import the .srt files I had created.
Upvotes: 5