Some startBrowsingForNearbyPlayersWithReachableHandler questions

后端 未结 3 497
余生分开走
余生分开走 2021-01-13 11:22

I\'m trying to get local matchmaking working in GameKit using [[GKMatchmaker sharedMatchmaker] startBrowsingForNearbyPlayersWithReachableHandler:]. Essentially,

3条回答
  •  感动是毒
    2021-01-13 11:57

    So, keep in mind the differences between iOS7 and iOS8. This code will work on either version and call 'updateNearbyPlayer' in turn.

    if ( IS_IOS8 )
    {
        [[GKMatchmaker sharedMatchmaker] startBrowsingForNearbyPlayersWithHandler:^(GKPlayer *gkPlayer, BOOL reachable) 
         {
             NSLog(@"PLAYER ID %@ is %@",gkPlayer.playerID,reachable?@"reachable" : @"not reachable");
             [self updateNearbyPlayer:gkPlayer reachable:reachable];
         }];
    
    } else {
        /*
         *  iOS 7...
         */
        [[GKMatchmaker sharedMatchmaker] startBrowsingForNearbyPlayersWithReachableHandler:^(NSString *playerID, BOOL reachable) 
         {
             NSLog(@"PLAYER ID %@ is %@",playerID,reachable?@"reachable" : @"not reachable");
    
             [GKPlayer loadPlayersForIdentifiers:@[playerID] withCompletionHandler:^(NSArray *players, NSError *error) {
                 NSLog(@"Loaded: %@, error= %@",players,error);
                 GKPlayer *gkPlayer = [players objectAtIndex:0];
                 [self updateNearbyPlayer:gkPlayer reachable:reachable];
             }];
         }];
    }
    

    With some delay due to the underlying Bonjour services, this mechanism works great. However, it needs to be balanced with an appropriate call to:

    [[GKMatchmaker sharedMatchmaker] stopBrowsingForNearbyPlayers];
    

    Whenever you use one of the GKPlayers/PlayerIDs reported to establish a match or to add it to an existing match, you should stop browsing. Once the match has been finished, closed or cancelled, start browsing again. Otherwise, on the second attempt to connect to a nearby device, you'll fail.

提交回复
热议问题