Search code examples
iosswiftuiuikitios18

How to Access SwiftUI's contactAccessPicker Directly from UIKit Without Extra View Layer in iOS 18?


I'm working on integrating a contactAccessPicker in a UIKit project. In SwiftUI, this function is an extension of View, so it's typically used like this:

yourView.contactAccessPicker(isPresented: $isPresented) { identifiers in 
// Fetch all contacts the app has access to.
}

I'm having trouble accessing contactAccessPicker from UIKit because it's an extension of View, so it can't be used directly in UIKit. I tried using a UIHostingController to present a SwiftUI view that includes the picker, but this ends up showing two views:

1. The initial `yourView`
2. Then `contactAccessPicker` on top of `yourView`

Is there a way to present contactAccessPicker directly without showing the extra view layer, or a more efficient way to achieve this in UIKit?

Senario: While we try to show contact access picker from the bottom sheet option

@available(iOS 18.0, *)
struct ContactAccessPicker: View {
    @State var presented = true
    var handler: ([String]) -> ()
    
    init(completionHandler: @escaping ([String]) -> ()) {
        handler = completionHandler
    }
    
    var body: some View {
        Spacer()
            .contactAccessPicker(isPresented: $presented, completionHandler: handler).background(content: {
            Color.white
        })
    }
}

func presentPicker() {
        if #available(iOS 18.0, *) {
            let pickerView = ContactAccessPickerHostingView(completionHandler: { [weak self] ids in
                print(ids)
               DispatchQueue.main.async {
        self.contactPickerViewReference?.view.removeFromSuperview()
        self.contactPickerViewReference?.didMove(toParent: nil)
        self.contactPickerViewReference?.removeFromParent()
    }
            })
            let hostingController = UIHostingController(rootView: pickerView)
            addChild(hostingController)
            let hostingView = hostingController.view!
            hostingView.isHidden = true
            hostingView.translatesAutoresizingMaskIntoConstraints = false
            hostingView.addSubview(hView)
            hostingView.pin(to: view)
        }
    }

removeFromParent() -> removing the presenter too


Solution

  • func presentContactAccessPicker() {
        if #available(iOS 18.0, *) {
            let pickerView = ContactAccessPickerHostingView(completionHandler: { [weak self] ids in
                guard let self else { return }
                DispatchQueue.main.async(execute: {
                    guard let presentedController = self.presentedViewController, presentedController.isBeingDismissed == false else { return }
                    self.dismiss(animated: true)
                })
             })
            let hostingController = UIHostingController(rootView: pickerView)
            hostingController.view.isHidden = true
            hostingController.modalPresentationStyle = .overCurrentContext
            self.present(hostingController, animated: false)
        }
    }
    
    @available(iOS 18.0, *)
    struct ContactAccessPickerHostingView: View {
        @State var presented = true
        var handler: ([String]) -> ()
        
        init(completionHandler: @escaping ([String]) -> ()) {
            handler = completionHandler
        }
        
        var body: some View {
            Spacer()
                .contactAccessPicker(isPresented: $presented, completionHandler: handler)
                .onChange(of: presented) { newValue in
                    if newValue == false {
                        handler([])
                    }
                }
        }
    }
    

    Here's :


    The ContactAccessPickerHostingView is a SwiftUI view that presents a contact picker and manages the user's selection. It utilizes a presented state variable to control the visibility of the picker. When displayed, users can select contacts, which are then passed to a handler—a closure that processes the selected contacts as an array of strings. The .onChange(of: presented) modifier listens for changes to this state variable. If the picker is dismissed without any selections (i.e., when presented becomes false), the handler is called with an empty array, ensuring proper management of cases with no selected contacts.

    The presentContactAccessPicker() function facilitates showing the SwiftUI contact picker within a UIKit app. It checks for compatibility, creates the contact picker with a completion handler, and safely captures a weak reference to self to prevent memory leaks. The line guard let presentedController = self.presentedViewController, presentedController.isBeingDismissed == false else { return } ensures there is a visible view controller that is not being dismissed; if this condition is not met, the function exits early. The picker is embedded in a UIHostingController and presented over the current context without animation, providing a smooth user experience. This approach effectively integrates SwiftUI and UIKit for managing contact selection in an iOS app.

    Overall, the .onChange(of: presented) modifier is crucial for handling the dismissal of the picker, especially when the user swipes down to close it. When presented changes to false, the associated closure is triggered, executing the handler with an empty array. This enables the app to respond appropriately to the visibility changes of the picker, ensuring a seamless user experience.