How to make a SwiftUI DocumentGroup app without starting on the file picker?

3.1k views Asked by At

If a user uses the Document App template in Xcode to create a SwiftUI app, macOS starts them off with a new document. This is good. I can work with that to present onboarding UI within a new document.

However, with that same app running on iOS, the user is instead greeted by the stock document view controller to create or pick a document.

This is not helpful in that I don't have a way to present onboarding or any other custom information.

I did notice that if you add a WindowGroup to the Scene, the app will display that window group. But then I don't know how to get the user to the picker UI.

Has anyone figured out how to do things like present onboarding on top of this DocumentGroup-based app?

Here is a full document app

import SwiftUI
import UniformTypeIdentifiers

@main
struct DocumentTestApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: DocumentTestDocument()) { file in
            ContentView(document: file.$document)
        }
    }
}

struct ContentView: View {
    @Binding var document: DocumentTestDocument

    var body: some View {
        TextEditor(text: $document.text)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(document: .constant(DocumentTestDocument()))
    }
}

extension UTType {
    static var exampleText: UTType {
        UTType(importedAs: "com.example.plain-text")
    }
}

struct DocumentTestDocument: FileDocument {
    var text: String

    init(text: String = "Hello, world!") {
        self.text = text
    }

    static var readableContentTypes: [UTType] { [.exampleText] }

    init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents,
              let string = String(data: data, encoding: .utf8)
        else {
            throw CocoaError(.fileReadCorruptFile)
        }
        text = string
    }
    
    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        let data = text.data(using: .utf8)!
        return .init(regularFileWithContents: data)
    }
}
3

There are 3 answers

0
MScottWaller On BEST ANSWER

Looks like this is now possible as of iOS 16 with the documentation here.

@main
struct Mail: App {
    var body: some Scene {
        WindowGroup(id: "mail-viewer") {
            MailViewer()
        }
    }
}


struct NewViewerButton: View {
    @Environment(\.openWindow) private var openWindow


    var body: some View {
        Button("Open new mail viewer") {
            openWindow(id: "mail-viewer")
        }
    }
}

So, when the scene appears you can open on onboarding window.

1
Asperi On

App shows first window scene by default, so place first on-boarding window scene and afterwards a DocumentGroup. Somewhere at the end of on boarding process (success path) call document controller to create new document (DocumentGroup is based on same NSDocumentController engine inside).

Update: below is for macOS

*just recognised that original question is for iOS

So a possible approach is

@main
struct DocumentTestApp: App {
    var body: some Scene {
        WindowGroup("On-Boarding") {
          // ContentView()

          // In some action at the end of this scene flow
          // just close current window and open new document
          Button("Demo") {
            NSApp.sendAction(#selector(NSWindow.performClose(_:)), to: nil, from: nil)
            NSDocumentController.shared.newDocument(nil)
          }
        }

        DocumentGroup(newDocument: DocumentTestDocument()) { file in
            ContentView(document: file.$document)
        }
    }
}
1
MScottWaller On

Alright friends, here is a nice and hacky way to get things going, reaching into the key windows, and setting up onboarding/paywall/whatever you want!

import SwiftUI

@main
struct ExampleApp: App {
    @StateObject var captain = Captain()
    
    var body: some Scene {
        DocumentGroup(newDocument: ExampleOfDocumentGroupAndOnboardingPaywallDocument()) { file in
            ContentView(document: file.$document)
        }
    }
}

class Captain: ObservableObject {
    var onboardingSheet: UIViewController?
    @objc func loadData() {
        onboardingSheet = try? OnboardingOrPaywall(dismissHandler: dismissSheet).presentFromDocumentGroup()
    }
    
    func dismissSheet() {
        onboardingSheet?.dismiss(animated: true)
    }
    
    init() {
        NotificationCenter.default.addObserver(self,
                                                      selector: #selector(loadData),
                                                      name: UIApplication.didBecomeActiveNotification,
                                                      object: nil)
    }
}

public protocol DocumentGroupSheet: View {}

struct OnboardingOrPaywall: DocumentGroupSheet {
    var dismissHandler: () -> Void
    var body: some View {
        Button("Done") {
            dismissHandler()
        }
        Text("Let me introduce you to this delicious app!")
    }
}

public enum DocumentGroupSheetError: Error {
    
    case noParentWindow
}

public extension DocumentGroupSheet {
    
    func presentFromDocumentGroup() throws -> UIViewController  {
        let window = UIApplication.shared.activeKeyWindows.first
        let parent = window?.rootViewController
        guard let parent = parent else { throw DocumentGroupSheetError.noParentWindow }
        let sheet = UIHostingController(rootView: body)
        sheet.modalPresentationStyle = .fullScreen
        parent.present(sheet, animated: false, completion: nil)
        return sheet
    }
}

public extension UIApplication {
    
    var activeWindowScenes: [UIWindowScene] {
        connectedScenes
            .filter { $0.activationState == .foregroundActive }
            .compactMap { $0 as? UIWindowScene }
    }
    
    var activeWindows: [UIWindow] {
        activeWindowScenes
            .flatMap { $0.windows }
    }

    var activeKeyWindows: [UIWindow] {
        activeWindows
            .filter { $0.isKeyWindow }
    }
}