Search code examples
iosobjective-cgame-centergamekit

not sure why my loadmatcheswithmatchdata isn't working


I'm creating a public method to return all of my matches from my gamecenterhelper.m

I have this:

+(NSArray *)retrieveMatchesWithMatchData {
    __block NSArray *myMatches = nil;
    [GKTurnBasedMatch loadMatchesWithCompletionHandler:^(NSArray *matches, NSError *error) {
        if (error) {
            NSLog(@"There was an error loading matches");
        }
        else {
            myMatches = matches;
        }
    }];
    return myMatches;
}

but this returns null when I call it, even though I have active matches. the call method looks like this:

NSLog(@"My matches: %@",[GameCenterHelper retrieveMatchesWithMatchData]);

Thanks for your time!


Solution

  • Thats the nature of blocks. Your block is executed asynchronously. You cannot load Game Center matches synchronously. Let's make this an instance method:

    -(void)retrieveMatchesWithMatchData {
        [GKTurnBasedMatch loadMatchesWithCompletionHandler:^(NSArray *matches, NSError *error) {
            if (error) {
                NSLog(@"There was an error loading matches");
            }
            else {
                [self matchesLoaded:matches];
            }
        }];
    }
    

    Then you process the matches in this method:

    -(void)matchesLoaded:(NSArray *)matches {
        //do something with your matches
    }
    

    EDIT:

    There is an easy way to do what you want. You can use Apples standard view controller to show current matches:

    GKMatchRequest *request = [[GKMatchRequest alloc] init]; 
    request.minPlayers = minPlayers;     
    request.maxPlayers = maxPlayers;
    
    GKTurnBasedMatchmakerViewController *mmvc = 
    [[GKTurnBasedMatchmakerViewController alloc] 
     initWithMatchRequest:request];
    mmvc.turnBasedMatchmakerDelegate = self;
    mmvc.showExistingMatches = YES;
    [self presentViewController:mmvc animated:NO completion:nil];