How to render a Swift component in ReactNative for Apple Game Kit

168 Views Asked by At

I'm trying to show the GameKit Leaderboards. Firstly I'm using React Native, but need to use the native modules from iOS to access the GK services, so I'm using swift. I have done the connection between both languages and can render a component made in .swift inside the .js scene correctly, and also log in to the game service, which displays a popup and if I click it it opens the profile and leaderboards too, but I can't open the leaderboards on command. When I try to, it throws an error saying

[Presentation] Attempt to present <GKGameCenterViewController: 0x7fca03022e00> on <RNGameKit: 0x7fca01a18250> (from <RNGameKit: 0x7fca01a18250>) whose view is not in the window hierarchy.

The code is, in RNGameKit.swift:

import Foundation
import UIKit
import GameKit
import React

@objc(RNGameKit)
class RNGameKit : UIViewController, GKGameCenterControllerDelegate {

...
  func showLeaderboards() {

    var gcViewController: GKGameCenterViewController = GKGameCenterViewController()
    gcViewController.gameCenterDelegate = self
    gcViewController.viewState = GKGameCenterViewControllerState.leaderboards
    gcViewController.leaderboardIdentifier = "pointsLeaderboard"
    self.show(gcViewController, sender: self)
    self.navigationController?.pushViewController(gcViewController, animated: true)
    self.present(gcViewController, animated: true, completion: nil)

Call from ViewManager.swift

import Foundation
import React
import GameKit


@objc(CounterViewManager)
class CounterViewManager: RCTViewManager, GKGameCenterControllerDelegate {
...
 override func view() -> UIView! {
   let kit = RNGameKit()
   kit.showLeaderboards()
    // this below is the component that renders a text inside the RN code/view
    let label = UILabel()
    label.text = "Swift Text"
    label.textAlignment = .center
    return label
...

ViewManager.m

#import <Foundation/Foundation.h>
#import "React/RCTViewManager.h"

@interface RCT_EXTERN_MODULE(CounterViewManager, RCTViewManager) // method 1

RCT_EXTERN_METHOD(authenticateUser) // this works
RCT_EXTERN_METHOD(showLeaderboards) // method 2
@end
// both methods throw the same error
0

There are 0 best solutions below