GameCenter multiplayer connection util
- Download and drop
GCConnection.swift
in your project. - Congratulations!
For detailed usage check out the demo ViewController.swift file.
In your AppDelegate invoke authenticate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
GCConnection.shared.authenticate()
return true
}
Later on in your ViewControlelr you can check the authenticate status
switch GCConnection.shared.authStatus {
case .undef:
// not authenticated
case .loginCancelled:
// login canccelled 🙅♀️
case .error(let err):
// auth err
case .loginRequired(let viewController):
// login required
// show present ciewController - it is the GC login view
case .ok(let localPlayer):
// authenticated 🥳
}
You can also listen to authentication state changes!
Implement the AuthHandler protocol and set the authHandler property
override func viewDidLoad() {
super.viewDidLoad()
GCConnection.shared.authHandler = self
}
extension ViewController : AuthHandler{
func handle(connection: GCConnection, authStatusChanged: AuthStatus) {
// your code ...
}
}
To create a match simply call findMatch.
To listen on status updates you should set the handler property on the match.
let match = try! GCConnection.shared.findMatch(minPlayers: 2, maxPlayers: 2)
match.handler = self
Example implementation of the MatchHandler protocol:
extension ViewController : MatchHandler{
func handle(_ error: Error) {
// error
}
func handle(_ state: MatchState) {
// status update
}
func handle(data: Data, fromPlayer: GKPlayer) {
// received data from given player
}
func handle(playerDisconnected: GKPlayer) {
// given player has disconnected
}
}
You can always cancel a match with
match.cancel()
The active match is always accessible on the shared GCConnection instance
GCConnection.shared.activeMatch
To send data use broadCast method
let data = "hello".data(using: .utf8)
try! GCConnection.shared.activeMatch!.broadCast(data: data!, withMode: GKMatch.SendDataMode.reliable)
First you should enable the GameCenter feature in your ap.
Go to Project/Capabilities and enable GameCenter
After that you have to register your app in App Store Connect.
Login with your account and go to My Apps
On the Dashboard add a new App
Enter the needed information.
IMPORTANT: The BundleIdentifier should match your Project setting
During my tests I found out that GameCenter will not recognize your app until you create at least one leaderboard.
Goto /Features/Game Center/Leaderboard
Cocoa Rocks: a gallery of beatiful Cocoa Controls
awesome-cocoa: an awesome list of cocoa controls
Make sure to read these guides before getting started:
GCConnection is available under the MIT License. See LICENSE for details.