From 0a94e64a25fdab54826750776e9ff7786fd3e14c Mon Sep 17 00:00:00 2001 From: Jakob Haag Date: Sat, 2 May 2020 13:59:34 +0200 Subject: [PATCH] add GameCenterHelper to login to GameCenter and recognize authenticated user --- GoldWars/GoldWars/GameCenterHelper.swift | 47 ++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 GoldWars/GoldWars/GameCenterHelper.swift diff --git a/GoldWars/GoldWars/GameCenterHelper.swift b/GoldWars/GoldWars/GameCenterHelper.swift new file mode 100644 index 0000000..988a23f --- /dev/null +++ b/GoldWars/GoldWars/GameCenterHelper.swift @@ -0,0 +1,47 @@ +// +// GameCenterHelper.swift +// GoldWars +// +// Created by Jakob Haag on 02.05.20. +// Copyright © 2020 SP2. All rights reserved. +// + +import GameKit + +final class GameCenterHelper: NSObject { + typealias CompletionBlock = (Error?) -> Void + + // 1 + static let helper = GameCenterHelper() + + // 2 + var viewController: UIViewController? + + static var isAuthenticated: Bool { + return GKLocalPlayer.local.isAuthenticated + } + + override init() { + super.init() + + GKLocalPlayer.local.authenticateHandler = { gcAuthVC, error in + NotificationCenter.default + .post(name: .authenticationChanged, object: GKLocalPlayer.local.isAuthenticated) + + if GKLocalPlayer.local.isAuthenticated { + print("Authenticated to Game Center!") + } else if let vc = gcAuthVC { + self.viewController?.present(vc, animated: true) + } + else { + print("Error authentication to GameCenter: " + + "\(error?.localizedDescription ?? "none")") + } + } + } +} + +extension Notification.Name { + static let presentGame = Notification.Name(rawValue: "presentGame") + static let authenticationChanged = Notification.Name(rawValue: "authenticationChanged") +}