GameKitService 由 Sascha Muellner **用 ❥ 创建并维护**。
这是一个支持 iOS/macOS/tvOS 的 **Swift** 包,专注于将当前的 GameKit 实现桥接到一个单一的服务结构,利用 Combine 来简化和现代化 GameKit 的匹配处理。
GameKitService 的最新版本需要
使用 SPM 将以下内容添加到您的依赖项中
'GameKitService', 'master', 'https://github.com/SwiftPackageRepository/GameKitService.swift.git'
假设您已经验证了用户身份并启动了一个匹配,例如使用 GCHelper 或 GameKitUI,您现在可以使用 GameKitService 中的 start 方法启动它
import GameKit
import GameKitService
let match: GKMatch
GameKitService
.shared
.start(match)
可以使用 GameKitService 订阅以下匹配数据更改。
订阅 authenticated: CurrentValueSubject<Bool, Never>
CurrentValueSubject,以在用户在 GameCenter 验证身份时接收通知。
import GameKit
import GameKitService
let match: GKMatch
GameKitService
.shared
.authenticated(match)
订阅 started: PassthroughSubject<GKMatch, Never>
PassthroughSubject,以接收有关匹配开始的数据。
var cancellable: AnyCancellable?
self.cancellable = GameKitService
.ended
.received.sink { (match: GKMatch) in
// match: the ending match
}
订阅 received: PassthroughSubject<(match: GKMatch, data: Data, player: GKPlayer), Never>
PassthroughSubject,以接收来自匹配中另一玩家设备的数据。
var cancellable: AnyCancellable?
self.cancellable = GameKitService
.shared
.received.sink { (match: GKMatch, data: Data, player: GKPlayer) in
// match: the current match
// data: the data send from
// player: the player that did send the data
}
订阅 ended: PassthroughSubject<GKMatch, Never>
PassthroughSubject,以接收有关匹配结束的数据。
var cancellable: AnyCancellable?
self.cancellable = GameKitService
.ended
.received.sink { (match: GKMatch) in
// match: the ending match
}
要将数据发送给匹配中的其他玩家,有两种可能性。第一种是将数据发送给匹配中的所有玩家
let data = "Hello Players!".data(using: .utf8)!
do {
try GameKitService
.shared
.send(data)
} catch {
}
第二种可能性允许您将数据发送给匹配中的一个专用组(一个或多个)的玩家。
let playerOne: GKPlayer
let data = "Hello Player One!".data(using: .utf8)!
do {
try GameKitService
.shared
.send(data, players: [playerOne])
} catch {
}