Created
August 19, 2020 09:40
-
-
Save sathyarajshetigar/1520c002c271f4828c1cc8125c529574 to your computer and use it in GitHub Desktop.
OneSignal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections.Generic; | |
using OneSignalPush.MiniJSON; | |
using System; | |
using SimpleJSON; | |
using UnityEngine.SceneManagement; | |
using PhaseTen; | |
using System.Collections; | |
public class PushNotificationManager : MonoBehaviour | |
{ | |
protected PushNotificationManager() { } | |
public static PushNotificationManager instance = null; | |
private string _appID; | |
[HideInInspector] | |
public string localUserID; | |
public string senderID { get; private set; } | |
public string senderName { get; private set; } | |
void OnEnable() | |
{ | |
PlayFabManager.onPlayfabSetupCompleteEvent += onPlayfabSetupComplete; | |
OneSignal.permissionObserver += OneSignal_permissionObserver; | |
OneSignal.subscriptionObserver += OneSignal_subscriptionObserver; | |
OneSignal.emailSubscriptionObserver += OneSignal_emailSubscriptionObserver; | |
} | |
void OnDisable() | |
{ | |
PlayFabManager.onPlayfabSetupCompleteEvent -= onPlayfabSetupComplete; | |
OneSignal.permissionObserver -= OneSignal_permissionObserver; | |
OneSignal.subscriptionObserver -= OneSignal_subscriptionObserver; | |
OneSignal.emailSubscriptionObserver -= OneSignal_emailSubscriptionObserver; | |
} | |
void Awake() | |
{ | |
if (instance == null) | |
{ | |
instance = this; | |
DontDestroyOnLoad(gameObject); | |
_appID = IjsUiFramework.GameSkinData.gameSkin.currentGameData.oneSignalID; | |
//Init(); | |
} | |
else if (instance != this) | |
{ | |
Destroy(gameObject); | |
} | |
} | |
private void onPlayfabSetupComplete(bool success) | |
{ | |
#if UNITY_IOS && !UNITY_EDITOR | |
if (PlayerPreference.launchCount >= 2)//dont show on first launch. there is high chance player will not allow the notification | |
{ | |
Init(); | |
//DialogBox.Show(Game.GetLocTxt(LKeys.ALLOWNOTIFICATION), Game.GetLocTxt(LKeys.NOTIFICATIONPERMISSION), Game.GetLocTxt(LKeys.OK), (ok, didCancel) => | |
//{ | |
//}); | |
} | |
#else | |
Init(); | |
#endif | |
} | |
void Init() | |
{ | |
Debug.Log($"OneSignal Init----------------------------------------"); | |
// Enable line below to enable logging if you are having issues setting up OneSignal. (logLevel, visualLogLevel) | |
OneSignal.SetLogLevel(OneSignal.LOG_LEVEL.INFO, OneSignal.LOG_LEVEL.NONE); | |
OneSignal.StartInit(_appID) | |
.HandleNotificationOpened(HandleNotificationOpened) | |
.HandleNotificationReceived(HandleNotificationReceived) | |
.HandleInAppMessageClicked(HandlerInAppMessageClicked) | |
.EndInit(); | |
OneSignal.ClearOneSignalNotifications(); | |
OneSignal.inFocusDisplayType = OneSignal.OSInFocusDisplayOption.InAppAlert; | |
OneSignal.IdsAvailable(UserId); | |
var pushState = OneSignal.GetPermissionSubscriptionState(); | |
Debug.Log($"OneSignal Init pushState: {pushState} UserProvidedConsent ? {OneSignal.UserProvidedConsent()}"); | |
} | |
private void UserId(string playerID, string pushToken) | |
{ | |
localUserID = playerID; | |
if (!string.IsNullOrEmpty(localUserID)) | |
PlayFabManager.instance.UpdateUserData(Game.PLAYERDATA_PUSHID, localUserID, false); | |
else | |
Game.Log("PushNotificationManager onPlayfabSetupComplete localUserID is null"); | |
} | |
private void OneSignal_subscriptionObserver(OSSubscriptionStateChanges stateChanges) | |
{ | |
Debug.Log("SUBSCRIPTION stateChanges: " + stateChanges); | |
Debug.Log("SUBSCRIPTION stateChanges.to.userId: " + stateChanges.to.userId); | |
Debug.Log("SUBSCRIPTION stateChanges.to.subscribed: " + stateChanges.to.subscribed); | |
} | |
private void OneSignal_permissionObserver(OSPermissionStateChanges stateChanges) | |
{ | |
Debug.Log("PERMISSION stateChanges.from.status: " + stateChanges.from.status); | |
Debug.Log("PERMISSION stateChanges.to.status: " + stateChanges.to.status); | |
} | |
private void OneSignal_emailSubscriptionObserver(OSEmailSubscriptionStateChanges stateChanges) | |
{ | |
Debug.Log("EMAIL stateChanges.from.status: " + stateChanges.from.emailUserId + ", " + stateChanges.from.emailAddress); | |
Debug.Log("EMAIL stateChanges.to.status: " + stateChanges.to.emailUserId + ", " + stateChanges.to.emailAddress); | |
} | |
private void HandlerInAppMessageClicked(OSInAppMessageAction action) | |
{ | |
Game.Log($"HandlerInAppMessageClicked clickName {action.clickName} clickUrl {action.clickUrl} firstClick {action.firstClick}"); | |
} | |
// Called when your app is in focus and a notificaiton is recieved. | |
// The name of the method can be anything as long as the signature matches. | |
// Method must be static or this object should be marked as DontDestroyOnLoad | |
private void HandleNotificationReceived(OSNotification notification) | |
{ | |
Debug.Log($"HandleNotificationReceived {notification.payload.title}"); | |
} | |
// Called when a notification is opened. | |
// The name of the method can be anything as long as the signature matches. | |
// Method must be static or this object should be marked as DontDestroyOnLoad | |
private void HandleNotificationOpened(OSNotificationOpenedResult result) | |
{ | |
OSNotificationPayload payload = result.notification.payload; | |
Dictionary<string, object> additionalData = payload.additionalData; | |
Debug.Log($"Notification opened with text: additionalData.Count {additionalData?.Count}"); | |
foreach (KeyValuePair<string, object> item in result.notification.payload.additionalData) | |
{ | |
Debug.Log($"item Key {item.Key} Value {item.Value}"); | |
} | |
if (additionalData != null) | |
{ | |
if (additionalData.ContainsKey("data")) | |
{ | |
string jsonString = additionalData["data"].ToString(); | |
JSONNode json = JSON.Parse(jsonString); | |
Debug.Log(" Notification ShowMessage " + json.ToString()); | |
senderID = json["senderID"].Value; | |
senderName = json["senderName"].Value; | |
string roomName = json["roomName"]; | |
Debug.Log("HandleNotification roomName : " + roomName); | |
if (!string.IsNullOrEmpty(roomName)) | |
{ | |
DialogBox.Show(Game.GetLocTxt(LKeys.PRIVATEGAME), $"{senderName} {Game.GetLocTxt(LKeys.SENTUAREQUEST)}", Game.GetLocTxt(LKeys.JOIN), Game.GetLocTxt(LKeys.CANCEL), (join, didcancel) => | |
{ | |
if (join) | |
{ | |
DialogBox.ShowToastMessage($"{Game.GetLocTxt(LKeys.ROOMID)} { roomName}", 3f); | |
Game.SetGameMode(PlayModes.OnlinePrivate); | |
Game.acceptingInvite = true; | |
Game.roomCodeForInvitedGame = roomName; | |
if (Game.uiScreen >= UIScreens.PauseScreen) | |
{ | |
Game.joiningPrivatePushNotificationGameFromGameScene = true; | |
if (PhotonManager.instance.inRoom) | |
PhotonManager.instance.DisconnectFromPhoton(true); | |
else | |
StartCoroutine("ReloadGameSceneAndJoinTheGameNow"); | |
} | |
else if (Game.uiScreen < UIScreens.PauseScreen) | |
{ | |
GameManager.instance.introScreenUIController?.JoinPrivateGameThroughNotification(); | |
} | |
PlayFabManager.instance.LogEvent(GameEvents.AcceptedPrivateGameThroughPushNotification, new EventBody(GameEvents.AcceptedPrivateGameThroughPushNotification.ToString(), "true")); | |
} | |
else | |
{ | |
Game.acceptingInvite = false; | |
Game.roomCodeForInvitedGame = ""; | |
PlayFabManager.instance.LogEvent(GameEvents.AcceptedPrivateGameThroughPushNotification, new EventBody(GameEvents.AcceptedPrivateGameThroughPushNotification.ToString(), "false")); | |
} | |
}); | |
} | |
else | |
{ | |
Game.acceptingInvite = false; | |
Game.roomCodeForInvitedGame = ""; | |
PlayFabManager.instance.LogEvent(GameEvents.AcceptedPrivateGameThroughPushNotification, new EventBody(GameEvents.AcceptedPrivateGameThroughPushNotification.ToString(), "false")); | |
} | |
} | |
} | |
} | |
internal void ReloadGameSceneAndJoinTheGame() | |
{ | |
StartCoroutine("ReloadGameSceneAndJoinTheGameNow"); | |
} | |
IEnumerator ReloadGameSceneAndJoinTheGameNow() | |
{ | |
Game.Log($"Reloading the game scene now to join the private game {Game.roomCodeForInvitedGame}"); | |
PhaseTenGameManager.instance.DestroyGameInstance(); | |
DialogBox.ShowLoadingScreen(Game.GetLocTxt(LKeys.PLEASEWAIT)); | |
yield return new WaitForSeconds(1f); | |
Game.GCCollect(); | |
SceneManager.LoadSceneAsync(Game.GAMESCENENAME, LoadSceneMode.Single); | |
SceneManager.LoadSceneAsync(Game.GAMESCENEHUDNAME, LoadSceneMode.Additive); | |
} | |
public void Invite(string toUseID, string message, string data) | |
{ | |
var notification = new Dictionary<string, object>(); | |
notification["contents"] = new Dictionary<string, string>() { { "en", message } }; | |
notification["data"] = new Dictionary<string, string>() { { "data", data } }; | |
// Send notification to this device. | |
notification["include_player_ids"] = new List<string>() { toUseID }; | |
// Example of scheduling a notification in the future. | |
// notification["send_after"] = DateTime.Now.ToUniversalTime().AddSeconds(1).ToString("U"); | |
Debug.Log($"Posting notification now. to : {toUseID}"); | |
PlayFabManager.instance.LogEvent(GameEvents.InvitedOfflinePlayers, new EventBody("toID", toUseID)); | |
OneSignal.PostNotification(notification, (responseSuccess) => | |
{ | |
Debug.Log($"Notification posted successful! \n{Json.Serialize(responseSuccess)}"); | |
}, | |
(responseFailure) => | |
{ | |
Debug.Log($"Notification failed to post:\n{Json.Serialize(responseFailure)}"); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment