Thanks to the updates to GameKit API in iOS 6, I am finally able to implement my turn-based board game the way it should be, complete with turn timeouts and better programmatic creation of matches. However, I am running into an issue that I cannot seem to solve. My desire is to have Game Center running entirely invisible to the end-user, so that everything is programmatic and uses my own custom interfaces. Therefore, I use my own custom table view to display matches, not the default GKTurnBasedMatchmakerViewController. Right now, I have no problem displaying open matches using the -loadMatchesWithCompletionHandler: method. I also use a custom screen to create a match, with a direct creation for auto-match (not a problem) and a table view that loads Game Center friends of the localPlayer for invitation. Since the playersToInvite attribute can now be filled with playerID's, this is possible in iOS 6.
My main problem is handling the invitation on the recipient's side. I send the invitation with the following code
-(void)invitarAmigoMio:(NSArray*)losAmigos
{
GKMatchRequest *request = [[GKMatchRequest alloc] init];
request.minPlayers = 2;
request.maxPlayers = 2;
request.defaultNumberOfPlayers=2;
request.playersToInvite = losAmigos;
request.inviteMessage = #"Your Custom Invitation Message Here";
request.inviteeResponseHandler = ^(NSString *playerID, GKInviteeResponse
response)
{
if (response==GKInviteeResponseAccepted)
{
NSLog(#"INVITACION ACEPTADA");
}
else
{
NSLog(#"INVITACION RECHAZADA");
}
};
}
I have a delegate that handles the notifications. The following code is launch when the user is authenticated
-(void)registroNotificaciones
{
NSLog(#"registroNotificaciones");
[GKMatchmaker sharedMatchmaker].inviteHandler = ^(GKInvite* acceptedInvite, NSArray *playersToInvite)
{
if(acceptedInvite != nil)
{
// Get a match for the invite we obtained...
[[GKMatchmaker sharedMatchmaker] matchForInvite:acceptedInvite completionHandler:^(GKMatch *match, NSError *error)
{
if(match != nil)
{
NSLog(#"match != nil: ");
}
else if(error != nil)
{
NSLog(#"ERROR: From matchForInvite: %#", [error description]);
}
else
{
NSLog(#"ERROR: Unexpected return from matchForInvite...");
}
}];
}
};
NSLog(#"FIN registroNotificaciones");
}
Why notifications are not send?Or notifications are not received?Is there another way to send notification to invite to play a game?
I checked and my sandbox accounts of Game Center allow invitations, and I dont know what´s going on
You did pretty much all that is needed to create the invite; you just need to send it with this code:
[[GKMatchmaker sharedMatchmaker] findMatchForRequest:request withCompletionHandler:^(GKMatch* match, NSError *error) {
if (error)
{
//Invite has not been sent
}
else if (match != nil)
{
//whatever you want to do when the receiver accepts the invite
}
}];
I know you are looking to use custom displays but I haven't made my own view controllers for this, instead I used GKMatchmakerViewController which handles the 'send' invites for me and I think that's what's missing in your code.
Here is my code for that, maybe you can try it and check how GKMatchmakerViewController works internally (if possible):
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = minPlayers;
request.maxPlayers = maxPlayers;
request.playersToInvite = pendingPlayersToInvite;
GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithMatchRequest:request] autorelease];
mmvc.matchmakerDelegate = self;
[myPresentingViewController presentModalViewController:mmvc animated:YES];
I have almost the same code you have that handles the notifications (registroNotificaciones) and it gets executed as soon as the user authenticates with GameCenter and is one of the first things the app does when launched too, from what you say, it looks like this code is working properly, just . Hope it helps!
Related
Note for the readers: this question is specific for Codename One only.
I'm developing an app that needs some initial data from a server to run properly. The first shown Form doesn't need this data and there is also a splash screen on the first run, so if the Internet connection is good there is enought time to retrive the data... but the Internet connection can be slow or absent.
I have in the init a call to this method:
private void getStartData() {
Runnable getBootData = () -> {
if (serverAPI.getSomething() && serverAPI.getXXX() && ...) {
isAllDataFetched = true;
} else {
Log.p("Connection ERROR in fetching initial data");
}
};
EasyThread appInfo = EasyThread.start("APPINFO");
appInfo.run(getBootData);
}
Each serverAPI method in this example is a synchronous method that return true if success, false otherwise. My question is how to change this EasyThread to repeat again all the calls to (serverAPI.getSomething() && serverAPI.getXXX() && ...) after one second if the result is false, and again after another second and so on, until the result is true.
I don't want to shown an error or an alert to the user: I'll show an alert only if the static boolean isAllDataFetched is false when the requested data is strictly necessary.
I tried to read carefully the documentation of EasyThread and of Runnable, but I didn't understand how to handle this use case.
Since this is a thread you could easily use Thread.sleep(1000) or more simply Util.sleep(1000) which just swallows the InterruptedException. So something like this would work:
while(!isAllDataFetched) {
if (serverAPI.getSomething() && serverAPI.getXXX() && ...) {
isAllDataFetched = true;
} else {
Log.p("Connection ERROR in fetching initial data");
Util.sleep(1000);
}
}
How can I get data back as an array or generic list from a Firebase database in Unity3D without knowing ahead of time what the name (key) of the children are?
I have been trying out the new Unity Firebase plugin, and I am having an issue figuring out how to get all the children in a specific location, and put the names (the key) and the values into arrays or generic lists so that I can work on the data locally. Forgive me for being so new to Firebase and probably using bad techniques to do this, and this plugin being so new its pretty hard for me to get much outside help, as there are not a lot of docs and tutorials out there on Firebase Unity.
In this particular case I am trying to create "instant messaging" like functionality, without the use of Firebase messaging, and just using regular Firebase database stuff instead. It might have been easier to use Firebase messaging, but mostly for the sake of learning and customization I want to do this on my own with just the Firebase database.
I insert data into the database like this:
public void SendMessage(string toUser, string msg)
{
Debug.Log(String.Format("Attempting to send message from {0} to {1}", username, toUser));
DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("Msgs");
string date = Magnet.M.GetCurrentDate();
// send data to the DB
reference.Child(toUser).Child(username).Child(date).SetValueAsync(msg);
// user receiving message / user sending message > VALUE = "hello dude|20170119111325"
UpdateUsers();
}
And then I try and get it back like this:
public string[] GetConversation(string userA, string userB)
{
// get a conversation between two users
string[] convo = new string[0];
FirebaseDatabase.DefaultInstance.GetReference("Msgs").GetValueAsync().ContinueWith(task =>
{
Debug.Log("Getting Conversation...");
if (task.IsFaulted || task.IsCanceled)
{
Debug.LogError("ERROR: Task error in GetConversation(): " + task.Exception);
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
string[] messagesA = new string[0], messagesB = new string[0];
if(snapshot.HasChild(userA))
{
// userA has a record of a conversation with other users
if(snapshot.Child(userA).HasChild(userB)) // userB has sent messages to userA before
{
Debug.Log("Found childA");
long count = snapshot.Child(userA).Child(userB).ChildrenCount;
messagesA = new string[count];
var kids = snapshot.Child(userA).Child(userB).Children;
Debug.Log(kids);
for (int i = 0; i < count; i++)
{
// this won't work, but is how I would like to access the data
messagesA[i] = kids[i].Value.ToString(); // AGAIN.... will not work...
}
}
}
if(snapshot.HasChild(userB))
{
if(snapshot.Child(userB).HasChild(userA)) // userA sent a message to userB before
{
Debug.Log("Found childB");
long count = snapshot.Child(userB).Child(userA).ChildrenCount;
messagesA = new string[count];
var kids = snapshot.Child(userB).Child(userA).Children;
Debug.Log(kids);
// messy incomplete testing code...
}
}
// HERE I WOULD ASSIGN ALL THE MESSAGES BETWEEN A AND B AS 'convo'...
}
Debug.Log("Done Getting Conversation.");
});
return convo;
}
But obviously this won't work, because DataSnapshot won't let me access it like an array or generic list using indices, and I can't figure out how to treat the data when I don't know the names (the keys) of all the children, and just want to get them out one by one in any order... and since they are named by the date/time they are entered into the DB, I won't know ahead of time what the childrens names (keys) are, and I can't just say "GetChild("20170101010101")" because that number is generated when its sent to the DB from any client.
FYI here is what the DB looks like:
Figured out the answer to your question. Here's my code snippet. Hope this would help!
void InitializeFirebase() {
FirebaseApp app = FirebaseApp.DefaultInstance;
app.SetEditorDatabaseUrl ("https://slol.firebaseio.com/");
FirebaseDatabase.DefaultInstance
.GetReference ("Products").OrderByChild ("category").EqualTo("livingroom")
.ValueChanged += (object sender2, ValueChangedEventArgs e2) => {
if (e2.DatabaseError != null) {
Debug.LogError (e2.DatabaseError.Message);
}
if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0) {
foreach (var childSnapshot in e2.Snapshot.Children) {
var name = childSnapshot.Child ("name").Value.ToString ();
text.text = name.ToString();
Debug.Log(name.ToString());
//text.text = childSnapshot.ToString();
}
}
};
}
Firebase developer here.
Have you tried to use Value at the top level Snapshot? It should return to you an IDictionary where the values can also be lists or nested dictionaries. You will have to use some dynamic inspection to figure out what the values are.
I am developing a turn based game using the Game Center. I handle the invitations to play using the following code::
GKMatchmaker sharedMatchmaker].inviteHandler = ^(GKInvite* acceptedInvite, NSArray *playersToInvite)
{
if(acceptedInvite != nil)
{
// Get a match for the invite we obtained...
NSLog(#"Valor de la invitacion %#",acceptedInvite);
[[GKMatchmaker sharedMatchmaker] matchForInvite:acceptedInvite completionHandler:^(GKMatch *match, NSError *error)
{
if(match != nil)
{
NSLog(#"match != nil: ");
}
else if(error != nil)
{
NSLog(#"ERROR: From matchForInvite: %#", [error description]);
}
else
{
NSLog(#"ERROR: Unexpected return from matchForInvite...");
}
}];
}
};
I woudl like to have a list of all the GKInvite that I received to have them in a tableview, and later the user will decide to accept the invitation to play the game or reject it. Of course I am using my own view to handle all the Game Center options.
Any solution??
For turn- based games, you'll have to use GKTurnBasedMatchmaker instead of GKMatchmaker.
Furthermore, I believe you'll only see GKTurnBasedMatch objects for games that the user has accepted by swiping the invitation.
I'm programming a simple 2 players board game with GameKit and the GKTurnBased API, my problem is at the end of my game, when I want to detect that a player won and another lost.
First at all, the handleTurnEventForMatch:didBecomeActive: method fired, in this method, I check the other participant status:
// Test other players status
for(GKTurnBasedParticipant *participant in match.participants)
{
if([participant.playerID isEqualToString:[GKLocalPlayer localPlayer].playerID])
continue;
if(participant.matchOutcome == GKTurnBasedMatchOutcomeQuit || participant.matchOutcome == GKTurnBasedMatchOutcomeLost)
{
[self findMeInMatch:match].matchOutcome = GKTurnBasedMatchOutcomeWon;
[match endMatchInTurnWithMatchData:match.matchData
completionHandler:nil];
return;
}
else if(participant.matchOutcome == GKTurnBasedMatchOutcomeWon)
{
[self findMeInMatch:match].matchOutcome = GKTurnBasedMatchOutcomeLost;
[match endMatchInTurnWithMatchData:match.matchData
completionHandler:nil];
return;
}
else if(participant.matchOutcome == GKTurnBasedMatchOutcomeTied)
{
[self findMeInMatch:match].matchOutcome = GKTurnBasedMatchOutcomeTied;
[match endMatchInTurnWithMatchData:match.matchData
completionHandler:nil];
return;
}
else
{
// OK
}
}
[...]
My problem now is that the handleMatchEnded: method is never called... The weird thing is that this method is part of the same delegate protocol as handleTurnEventForMatch:didBecomeActive: which actually works.
Any idea is welcome.
Cheers.
UPDATE 03/17:
As my first player quitted is turn, and the second one end the match, I think the two players are not going to receive the event. This event is probably made for other players in game, or when players are not within the app when the others leave. Didn't find anything related in the documentation, but it seem's logical.
Cyril
Is there anyway to know which user is calling the WCF Ria service on server side? Client side is siverlight, user has to be authenticated first in order to use the system.
I need to know which user is actually calling the service in my current task, thanks, i searched a lot, but seems no good findings.
Once the client side has successfully cleared your authentication challenge, the server can issue a token to the caller on the client side. In subsequent calls to the server, the client would send the token as one of the arguments and the server would verify the token and respond accordingly.
The token can contain a segment of information that identifies a given user, and implementing this will provide the functionality you are seeking.
The only guidelines for generating tokens is that they are unique, non-predictable and expirable. I have always encrypted my tokens so that they appear as gibberish, but step this is optional.
I've also done very much "googleing" and got a lot of headache before I got the solution.
I don't use RIA-Services - but it should be (hopefully) the same...:
The SL-Client sends a "login-request" to the server.
On the (WCF) server-side, I do the following (LoginData = Return-Info for SL-Client):
public LoginData LoginRequest() {
(...)
OperationContext context = OperationContext.Current;
System.ServiceModel.Channels.MessageProperties prp = context.IncomingMessageProperties;
System.ServiceModel.Channels.RemoteEndpointMessageProperty endPrp = prp[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
(...)
try {
clientIP = endPrp.Address;
System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(clientIP);
System.Net.IPHostEntry ipHostEntry = System.Net.Dns.GetHostEntry(ipAddress);
(...)
If you want to check the users WindowsPrincipal, you can do the following (securityGroup = server-side setting, which users can login):
(...)
switch (securityGroup) {
case SecurityGroup.AllClientsCanAccess: {
clientCanLogin = true;
} break;
case SecurityGroup.UseWindowsCredentials: {
if (OperationContext.Current.ServiceSecurityContext != null && OperationContext.Current.ServiceSecurityContext.WindowsIdentity != null) {
if (OperationContext.Current.ServiceSecurityContext.WindowsIdentity.IsAuthenticated) {
if (subSecurityInfo1 == true) { // only clients in specific roles can log in
bool userRoleFound = false;
WindowsPrincipal userPrincipal = new WindowsPrincipal(OperationContext.Current.ServiceSecurityContext.WindowsIdentity);
if (userPrincipal == null)
break;
foreach (string userRoleToPass in subSecurityList) { // subSecurityList = settings, which roles can pass
loginError.ErrorInfo += string.Format("{0}\n", userRoleToPass);
if (userPrincipal.IsInRole(userRoleToPass)) {
clientCanLogin = userRoleFound = true;
break;
}
}
if (userRoleFound) {
loginError.ErrorInfo = string.Empty;
break;
}
else {
loginError.ErrorNo = LoginErrorCodeNoEnum.UserIsNotInRole;
}
}
(...)
Hope it helps...