Authenticate GameKit local player using swift

2019-07-19 16:08发布

问题:

Im looking to migrate a game over to swift, the only trouble I am having is with blocks/closures. It's the syntax I just don't understand, whereas in Objective C I would use:

GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error){
    if (viewController != nil) {
        [self presentViewController:viewController animated:YES completion:nil];
    }
}

etc.etc. but I'm not sure how to go about doing the same in Swift. I know it's simple but I just can't get it to work, even after reading the Swift book and googling answers myself. I'm only a hobbyist programmer so I'm far from perfect at all this.

Any Help would be appreciated.

回答1:

This is how you would do it in Swift:

var localPlayer = CGLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {(viewController : UIViewController!, error : NSError!) -> Void in
    //handle authentication
}

The documentation for closures can be found here.



回答2:

This is how you authenticate in Swift using Xcode 6.1 +:

    var localPlayer = GKLocalPlayer.localPlayer()
    localPlayer.authenticateHandler = {(viewController : UIViewController!, error : NSError!) -> Void in
        if ((viewController) != nil) {
            self.presentViewController(viewController, animated: true, completion: nil)
        }else{

            println((GKLocalPlayer.localPlayer().authenticated))
        }
    }