question

brendan avatar image
brendan asked

How to register a mobile device for push notifications -- C# Sample Code -- (APNS & GCM)

zacb
started a topic on Tue, 07 April 2015 at 11:14 AM

There are three distinct steps to enable Push notifications to a device. This post will primarily focus on step #2.

  1. Register your title -- This is a prerequisite, ran only once at the title level to set up the messaging pathway for your title.

  2. Register each device -- Each player must opt-in before receiving your push notifications.

  3. Send the push notification - There are a couple ways to accomplish this and a detailed guide is beyond the scope of this question; however, this simplest method is to send notifications with this (https://api.playfab.com/Documentation/Server/method/SendPushNotification) API call.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
brendan avatar image
brendan answered

Best Answer
zacb said on Mon, 08 June 2015 at 9:33 AM

Register each device -- Each player must opt-in before receiving your push notifications.

Attached you will find some sample C# code illustrating how to use our Unity3d plugin to register and activate the Android GCM service.

Remember to get the most up-to-date plugin (https://github.com/PlayFab/UnitySDK). Just remember to move the plugins out of the UnitySDK/PlayFabClientSDK/Playfab/ folder and into the root of your project (Assets/Plugins/...).

Note: this example also shows iOS because it is straightforward and should not* require a native plugin ( * exception).

Follow up here if you have any questions or run into issues along the way.


14 Comments
johntube said on Tue, 07 April 2015 at 4:50 PM

I just wanted to add that for those working in teams or building from different machines they may encounter a problem with GCM certificates (if they're not using the same shared one) for Android running Lollipop. Here's how to solve it.


naltradamus said on Thu, 04 June 2015 at 12:11 PM

Hi guys, im new to playfab and the API Calling structure so its been a challenge working through some of the basics. But I believe this plugin is very worth the effort and struggle to understand so im not giving up. I got everything to work as far as your sample code on my unity game exceptfor the request call itself. What am I suppose to put for the "onpushsuccess" and "onplayfaberror" voids? When tested on my mobile device got all the way down to "GCM Init Success" but nothing happens after that. Can anybody tell me what I missed?


zacb said on Mon, 08 June 2015 at 9:33 AM

Register each device -- Each player must opt-in before receiving your push notifications.

Attached you will find some sample C# code illustrating how to use our Unity3d plugin to register and activate the Android GCM service.

Remember to get the most up-to-date plugin (https://github.com/PlayFab/UnitySDK). Just remember to move the plugins out of the UnitySDK/PlayFabClientSDK/Playfab/ folder and into the root of your project (Assets/Plugins/...).

Note: this example also shows iOS because it is straightforward and should not* require a native plugin ( * exception).

Follow up here if you have any questions or run into issues along the way.


zacb said on Mon, 08 June 2015 at 10:11 AM

Hey Naltradamus,

"onpushsuccess" & "onplayfaberror" are delegates to callback functions. These functions are called after the API call succeeds or fails. The call back pattern provides the caller the ability to confirm that a remote API call has completed a round trip (to the PlayFab Service and back) as well as the result of the call (success or error).

I updated the sample code to show a very simple example of these methods. All PlayFab APIs use this callback pattern.

Let us know if you have any additional questions.

Zac


johntube said on Tue, 09 June 2015 at 12:00 PM

What's new here ?

The Unity SDK repository was not updated (last commit : Jun 2, 2015 but playfab github page says that it was Updated 21 hours ago)...anyway nothing has changed...maybe the attached txt file was updated and it may interest others.


zacb said on Thu, 18 June 2015 at 1:03 PM

Yes ,the attached code sample was updated. SDK will get updates as needed.

Johntube,

Are you looking / waiting for anything specific from SDK updates?


johntube said on Fri, 19 June 2015 at 6:54 AM

@Zach,

yes a lot of things...already posted as features requests...

urgent one : GCM fix and enhancement !


Jibran said on Thu, 27 August 2015 at 6:52 AM

Hi I am trying to implement RegisterForIOSPushNotification in unity 5 for my game?

1 I am not able to get the device token. Could someone please explain how to get the device token. I tried using UnityEngine.iOS.NotificationServices.deviceToken

2 Also when and where do i call RegisterForIOSPushNotification api. Ryt at the start or after the playfab login

3 Is ios 8 push notification supported in unity 5 or do i still need to follow the steps given in the following link

https://chsxf.wordpress.com/2014/09/24/unity-pro-tip-2-ios-8-push-notifications/


zacb said on Thu, 27 August 2015 at 2:23 PM

Hey Jibran,

1) & 2) -- This is poorly documented by Apple, but basically there is a flow through this whole process. The order of steps is more important than the timing. And getting the device token can happen before or after PlayFab authentication.

  1. You need to make sure Xcode is properly certifying your game on the build. If your developer cert is not attached in xcode, you will not be able to get the device token

  2. Around the point where you prompt the user to accept or decline push notifications, you will want to call RegisterForIOSPushNotification. It is important to note that the initial call will trigger a one time default Apple iOS Accept Push Notifications dialog. Regardless of what the user picks, this dialog will not be shown again ( iOS & game updates can reset this and the dialog will be shown once more). Modifying additional app push settings will have to be done in the application settings.

  3. Even though the dialog is not shown you will still need to call RegisterForIOSPushNotification prior to getting the token. Also it is important to note that the call is an asynchronous call with no callback, meaning it does not return immediately so there should be a short delay between when you call RegisterForIOSPushNotification and when you try and obtain the token.

  4. These steps should get you the token. Once you have the token you can pass that into PlayFab via RegisterForIOSPushNotification.

3) Yes, Unity 5.1 works with all versions of iOS now, the work-around is no longer needed.

I hope that helps get you going, but feel free to let us know if you have any further questions.

-Zac


Jibran said on Fri, 28 August 2015 at 3:59 AM

So i have changed my code to this according to the unity documentation

void Start(){

PlayFabSettings.TitleId = "";
PlayFabSettings.DeveloperSecretKey = "";
tokenSent = false;
NotificationServices.RegisterForNotifications(NotificationType.Alert | NotificationType.Badge | NotificationType.Sound);
}

void Update(){

if (!tokenSent) {
byte[] token = NotificationServices.deviceToken;
if (token != null) {
// send token to a provider
hexToken = System.BitConverter.ToString(token).Replace("-", "").ToLower();
NotificationRegister();

Debug.Log(token);
Debug.Log(hexToken);

tokenSent = true;
}
}

}



void NotificationRegister(){

Debug.Log(hexToken);
if(hexToken != null)
{
RegisterForIOSPushNotificationRequest request = new RegisterForIOSPushNotificationRequest();
request.DeviceToken = hexToken;
request.SendPushNotificationConfirmation = true;
request.ConfirmationMessage = " THIS IS THE CONFIRMATION MESSAGE!";
PlayFabClientAPI.RegisterForIOSPushNotification(request, OnPushSuccess, OnPushError);
Debug.Log ("Called"); 
}

}

now the issue is that this code runs only when the user is logged in. I was successful in calling the onpushsuccess method after the user was authenticated. So could u tell me is there something wrong with the above code.

Also i am at loss with respect to SendPushNotification. I know its a server api and i cant call it directly in unity. Could u please explain to me how to achieve that functionality. I tried sending a notification to a users playfab id through postman. this is the response i got

{

  "code": 200,

  "status": "OK",

  "data": {}

}

but the user never received any notification?

Help!


zacb said on Fri, 28 August 2015 at 11:28 AM

Hey Jibran,

It looks like you have things set up correctly. While getting the deviceToken can happen at anytime, you can only call our APIs after login. That seems to be working as expected. Secondly, the confirmation push often does not make it to the device; however, sending push notifications via postman or cloud script will work fine. Seeing that you got a 200 success result means that your device, title and accounts are all properly configured.

We have an issue with our Android GCM plugin, that can cause the message to not be displayed or the app to crash. We should have a fix for this out next week. For iOS, everything typically works fine, although, You will not get the toast message if the app is the primary / active app on the device or if the app has been forcibly closed on the device.

Can you try testing again with the app in the background; or confirm that you are still not seeing the toast message.

-Zac

P.S. Code to use in CloudScript for sending a push message:

//Called from postman, successful push notification moments later
handlers.SendPushNote = function (args) {
    var request = {};
    request.Recipient = args.ID == undefined || args.ID == null ? "" : args.ID;
    request.Message = args.MSG == undefined || args.MSG == null ? "" : args.MSG;
    request.SUBJECT = args.SUBJECT == undefined || args.SUBJECT == null ? "" : args.SUBJECT;

    server.SendPushNotification(request); 

}

Jibrangillani11 said on Sat, 29 August 2015 at 5:14 AM

hi I have already set up the cloud script with the code u mentioned. I was successful in calling the GetCloudScriptUrl in unity. But as to RunCloudScript url i dont know how to put values in request.Params or request.ParamsEncoded. Could u please give me a demo code for Unity C# with respect to PushNotifications?


Brendan Vanous said on Mon, 31 August 2015 at 11:28 AM

Hi again,

Certainly - to use the call, either fill in Params or ParamsEncoded (not both) with the data to be sent to the Cloud Script. In this example, you would call it like so:

    RunCloudScriptRequest request = new RunCloudScriptRequest(); 

                          request.ActionId = "onLevelComplete";

                          request.Params = "{\"ID\":\"{
                 {PlayFabId}}\",\"MSG\":\"{
                 {Message}}\",\"SUBJECT\":\"{
                 {Subject}}\"}"; 

    PlayFabClientAPI.RunCloudScript( request, RunCloudScriptResultCallback, OnPlayFabError );

In this code, you would replace the items in curly brackets with the values you need for your game. So:

{ {PlayFabId}} - Replace this with the PlayFab ID of the player to whom the message is to be sent.

{ {Message}} - Replace this with the actual message that is to be sent.

{ {Subject}} - Replace this with the subject line for the message to be sent.

Brendan


zacb said on Mon, 31 August 2015 at 11:57 AM

Sure,

There are 2 steps required for successfully executing CloudScript commands on the client.

  1. Obtain the CloudScript endpoint by running GetCloudScriptUrl.

  2. Build the request and run RunCloudScript.

After making the GetCloudScriptUrl, you have now given the SDK everything it needs to successfully call RunCloudScript. The SDK will cache the endpoint URL for all subsequent RunCloudScript calls.

As for building requests, the request.Params variable accepts an anonymous c# object and will deserialize the data automatically.

RunCloudScriptRequest request = new RunCloudScriptRequest();
request.ActionId = "Hello World";
request.Params = new { VariableOne_String = playerId, VariableTwo_List = myList };

PlayFabClientAPI.RunCloudScript(request,  OnRequestSuccess, OnRequestError);

The request.ParamsEncoded allows you to manually serialize and send your objects:

RunCloudScriptRequest request = new RunCloudScriptRequest();
request.ActionId = "Hello World";
request.ParamsEncoded = "{\"VariableThree_Int\":1}"; 


PlayFabClientAPI.RunCloudScript(request,  OnRequestSuccess, OnRequestError);

Once you have this set up and compiling, you can access these parameters via the args object in the Cloud Script handler.

// inside of your cloud script

// This is a Cloud Script handler function. It runs in the PlayFab cloud and 
// has full access to the PlayFab Game Server API 
// (https://api.playfab.com/Documentation/Server). You can invoke the function 
// from your game client by calling the "RunCloudScript" API 
// (https://api.playfab.com/Documentation/Client/method/RunCloudScript) and 
// specifying "helloWorld" for the "ActionId" field.
handlers.helloWorld = function (args) {

    // You can retrieve your params like so:

    var v1 = args.VariableOne_String;
    var v2 = args.VariableTwo_List;
    var v3 = args.VariableThree_Int;


    // "currentPlayerId" is initialized to the PlayFab ID of the player logged-in on the game client. 
    // Cloud Script handles authenticating the player automatically.
    var message = "Hello " + currentPlayerId + "!";

    // You can use the "log" object to write out debugging statements.  You can view 
    // these statements in the Logs tab in the Servers section of the Game Manager website. 
    // The "log" object has three functions corresponding to logging level: debug, info, and error.
    log.info(message);

    // Whatever value you return from a CloudScript handler function is passed back 
    // to the game client. It is set in the "Results" property of the object returned by the 
    // RunCloudScript API. Any log statments generated by the handler function are also included 
    // in the "ActionLog" field of the RunCloudScript result, so you can use them to assist in
    // debugging and error handling.
    return { messageValue: message };
}

Let me know if you have any other questions.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.