Search code examples
iosswiftuiuikitgame-centergamekit

How to show Gamekit add friend screen from Swiftui


How can the Game Center add friends screen be shown from SwiftUi?

The UIViewController can't be passed in as shown below. Adding gamekit to project and authorization would also have to be done before this, but how to do that is well documented. The critical issue is how to display the add friend sheet from SwiftUI, I can't find anyone who has written an answer to this online.

import SwiftUI
import GameKit

struct ContentView: View {
var body: some View {
    // Attempt to show add friend sheet, does not work
    Button(action: {
        do {
            try GKLocalPlayer.local.presentFriendRequestCreator(from: UIViewController())
        } catch {
            
        }
    }) {
        Text("Add Friend")
    }
}
}

Solution

  • You have to pass the root ViewController:

    guard let rootViewController = UIApplication.shared.windows.first.rootViewController else {return}
    try GKLocalPlayer.local.presentFriendRequestCreator(from: rootViewController)
    

    Edit:

    To silence the warning, you can use the following:

    guard let rootViewController = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first?.rootViewController else {return}