public void HandleNotificationOpened(OSNotificationOpenedResult result) { OSNotificationPayload payload = result.notification.payload; string message = payload.body; string actionID = result.action.actionID; print("GameControllerExample:HandleNotificationOpened: " + message); id = "Notification opened with text: " + message; Dictionary <string, object> additionalData = payload.additionalData; if (additionalData == null) { Debug.Log("[HandleNotificationOpened] Additional Data == null"); } else { Debug.Log("[HandleNotificationOpened] message " + message + ", additionalData: " + Json.Serialize(additionalData) as string); } if (actionID != null) { // actionSelected equals the id on the button the user pressed. // actionSelected will equal "__DEFAULT__" when the notification itself was tapped when buttons were present. //id = "Pressed ButtonId: " + actionID; OneSignal.IdsAvailable((userId, pushToken) => { id = "UserID:\n" + userId + "\n\nPushToken:\n" + pushToken; }); } }
// ************************** // Public functions // ************************** public void Start() { // 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.INFO); OneSignal.StartInit("764072f7-5054-4058-b5a6-f5bb724fead1") .HandleNotificationOpened(HandleNotificationOpened) .HandleNotificationReceived(HandleNotificationReceived) .InFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification) .EndInit(); OneSignal.IdsAvailable((userId, pushToken) => { m_oneSignalPlayerID = userId; m_oneSignalPushToken = pushToken; if (Debug.isDebugBuild) { Debug.Log("------- VREEL: UserID: " + userId + " - PushToken: " + pushToken); } }); // Call syncHashedEmail anywhere in your app if you have the user's email. // This improves the effectiveness of OneSignal's "best-time" notification scheduling feature. // OneSignal.syncHashedEmail(userEmail); if (Debug.isDebugBuild) { OneSignal.SetLogLevel(OneSignal.LOG_LEVEL.DEBUG, OneSignal.LOG_LEVEL.DEBUG); } }
/// <summary> /// /// </summary> /// <param name="intent"></param> /// <param name="flags"></param> /// <param name="startId"></param> /// <returns></returns> public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { Log.Debug("OneSignalNotificationBackgroundService", "on start"); IsServiceRunning = true; new Task(() => { //Connect to OneSignal OneSignal.Init(this, "1077123816365", "ee8851b0-f171-4de0-b86b-74ef18eefa02", new NotificationOpenedHandler(), new NotificationReceivedHandler(this)); OneSignal.SetSubscription(true); OneSignal.IdsAvailable(new IdsAvailableHandler()); }); return(StartCommandResult.Sticky); }
public static void Create() { // 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.INFO); OneSignal.StartInit("30aeaac5-eace-4f2b-a39d-c28318eb6d73") .HandleNotificationOpened(HandleNotificationOpened) .EndInit(); OneSignal.inFocusDisplayType = OneSignal.OSInFocusDisplayOption.Notification; // Call syncHashedEmail anywhere in your app if you have the user's email. // This improves the effectiveness of OneSignal's "best-time" notification scheduling feature. // OneSignal.syncHashedEmail(userEmail); OneSignal.IdsAvailable((id, tocken) => { Id = id; Tocken = tocken; }); }
// Use this for initialization void Start() { #if !UNITY_EDITOR OneSignal.SetLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE); OneSignal.StartInit("d1637280-1caa-4fbe-a688-a10c9bb36890") .HandleNotificationReceived(HandleNotificationReceived) .HandleNotificationOpened(HandleNotificationOpened) .InFocusDisplaying(OneSignal.OSInFocusDisplayOption.None) .EndInit(); OneSignal.IdsAvailable((userId, pushToken) => { id = userId; //StartCoroutine (onCoroutine()); }); #endif }
/// <summary> /// Registers to receive remote notifications via Push Notification service. /// </summary> /// <description> /// Call this method to initiate the registration process with Push Notification service. /// When registration process completes, <see cref="DidFinishRegisterForRemoteNotificationEvent"/> is fired. /// If registration succeeds, then you should pass device token to the server you use to generate remote notifications. /// </description> /// <remarks> /// \note If you want your app’s remote notifications to display alerts, play sounds etc you must call the <see cref="RegisterNotificationTypes"/> method before registering for remote notifications. /// </remarks> public void RegisterForRemoteNotifications() { #if (!USES_ONE_SIGNAL || UNITY_EDITOR) m_platform.RegisterForRemoteNotifications(); #else if (!m_registeredForOneSignalPushNotifications) { m_registeredForOneSignalPushNotifications = true; OneSignal.RegisterForPushNotifications(); OneSignal.SetSubscription(true); OneSignal.IdsAvailable(DidReceiveIDsAvaialble); //DidRegisterRemoteNotification(null); } #endif }
protected virtual void SendNotification(string message, int addedHours, int addedMinutes, int addedSeconds) { OneSignal.IdsAvailable((userId, token) => { if (token == null) { return; } extraMessage = "Waiting to get a OneSignal userId. Uncomment OneSignal. SetLogLevel in the 'Start' method if it hangs here to debug the issue."; var localTime = System.DateTime.Now.ToUniversalTime(); var notification = new Dictionary <string, object>(); notification["contents"] = new Dictionary <string, string>() { { "en", string.Format("{0} ({1}:{2}:{3})", message, localTime.Hour.ToString("00"), localTime.Minute.ToString("00"), localTime.Second.ToString("00")) } }; // Send notification to this device. notification["include_player_ids"] = new List <string>() { userId }; // Example of scheduling a notification in the future. notification["send_after"] = localTime.AddSeconds(addedSeconds).AddMinutes(addedMinutes).AddHours(addedHours).ToString("U"); extraMessage = "Posting test notification now."; OneSignal.PostNotification(notification, (responseSuccess) => { extraMessage = "Notification posted successful! Delayed by a predetermined time amount to give you time to press the home button to see a notification vs an in-app alert.\n" + Json.Serialize(responseSuccess); }, (responseFailure) => { extraMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure); }); OneSignal.ClearOneSignalNotifications(); }); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState, Resource.Layout.ListSeekiosLayout, true); var drawerToggle = new ActionBarDrawerToggle(this, DrawerNavigation, ToolbarPage, Resource.String.open_drawer, Resource.String.close_drawer); DrawerNavigation.SetDrawerListener(drawerToggle); drawerToggle.SyncState(); _dispatcher = (ServiceLocator.Current.GetInstance <IDispatchOnUIThread>() as DispatchService); GetObjectsFromView(); SetDataToView(); CurrentActivity = this; // Connect to OneSignal OneSignal.Init(this, "1077123816365" , "ee8851b0-f171-4de0-b86b-74ef18eefa02" , new NotificationOpenedHandler() , new NotificationReceivedHandler(this)); OneSignal.SetSubscription(true); OneSignal.IdsAvailable(new IdsAvailableHandler()); // Display popup if the new reload credit is available App.Locator.ListSeekios.PopupRelaodCreditMonthly(); // Display a popup if the notification push are not registered App.Locator.ListSeekios.PopupNotificationNotAvailable(() => { using (var intent = new Android.Content.Intent(Android.Content.Intent.ActionView , Android.Net.Uri.Parse(App.TutorialNotificationLink))) { StartActivity(intent); } }); // Register to SignalR App.Locator.ListSeekios.SubscribeToSignalR(); // Get the uidDevice (required by webservice for identify the sender of the broadcast) App.UidDevice = Helper.DeviceInfoHelper.GetDeviceUniqueId(this); }
void Start() { firstimer.SetActive(false); if (PlayerPrefs.GetString("lewat") == "tidak") { firstimer.SetActive(true); PlayerPrefs.SetString("lewat", "Lain"); } loading.SetActive(true); #if !UNITY_EDITOR OneSignal.SetLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE); OneSignal.StartInit("30b6cca5-db55-40a5-8541-0187696d22a7") .HandleNotificationReceived(HandleNotificationReceived) .HandleNotificationOpened(HandleNotificationOpened) .InFocusDisplaying(OneSignal.OSInFocusDisplayOption.None) .EndInit(); #endif #if UNITY_EDITOR id = "123456789"; #endif long milisecond = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; //room_invite = PlayerPrefs.GetString (Link.EMAIL) + "@" + milisecond.ToString (); Debug.Log(milisecond); StartCoroutine(onCoroutineCekInviting()); OneSignal.IdsAvailable((userId, pushToken) => { id = userId; StartCoroutine(onCoroutine()); StartCoroutine(onCoroutineCekInviting()); }); }
// Test Notification private void SendNotification() { var extraMessage = ""; OneSignal.IdsAvailable((userId, pushToken) => { userId = OneSignal.GetPermissionSubscriptionState().subscriptionStatus.userId; if (pushToken != null) { // See http://documentation.onesignal.com/docs/notifications-create-notification for a full list of options. // You can not use included_segments or any fields that require your OneSignal 'REST API Key' in your app for security reasons. // If you need to use your OneSignal 'REST API Key' you will need your own server where you can make this call. var notification = new Dictionary <string, object>(); notification["contents"] = new Dictionary <string, string>() { { "en", "Made with Unity" } }; // Send notification to this device. notification["include_player_ids"] = new List <string>() { userId }; // Example of scheduling a notification in the future. notification["send_after"] = DateTime.Now.ToUniversalTime().AddSeconds(0).ToString("U"); extraMessage = "Posting test notification now."; OneSignal.PostNotification(notification, (responseSuccess) => { extraMessage = "Notification posted successful! Delayed by about 30 secounds to give you time to press the home button to see a notification vs an in-app alert.\n" + Json.Serialize(responseSuccess); }, (responseFailure) => { extraMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure); }); } else { extraMessage = "ERROR: Device is not registered."; } }); }
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { OneSignal.NotificationReceived exampleNotificationReceivedDelegate = delegate(OSNotification notification) { try { System.Console.WriteLine("OneSignal Notification Received: {0}", notification.payload.body); Dictionary <string, object> additionalData = notification.payload.additionalData; if (additionalData.Count > 0) { System.Console.WriteLine("additionalData: {0}", additionalData); } } catch (System.Exception e) { System.Console.WriteLine(e.StackTrace); } }; // Notification Opened Delegate OneSignal.NotificationOpened exampleNotificationOpenedDelegate = delegate(OSNotificationOpenedResult result) { try { System.Console.WriteLine("OneSignal Notification opened: {0}", result.notification.payload.body); Dictionary <string, object> additionalData = result.notification.payload.additionalData; List <Dictionary <string, object> > actionButtons = result.notification.payload.actionButtons; if (additionalData.Count > 0) { System.Console.WriteLine("additionalData: {0}", additionalData); } if (actionButtons.Count > 0) { System.Console.WriteLine("actionButtons: {0}", actionButtons); } } catch (System.Exception e) { System.Console.WriteLine(e.StackTrace); } }; // Initialize OneSignal OneSignal.StartInit("b2f7f966-d8cc-11e4-bed1-df8f05be55ba") .HandleNotificationReceived(exampleNotificationReceivedDelegate) .HandleNotificationOpened(exampleNotificationOpenedDelegate) .InFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification) .Settings(new Dictionary <string, bool> { { OneSignal.kOSSettingsKeyAutoPrompt, true }, { OneSignal.kOSSettingsKeyInAppLaunchURL, false } }) .EndInit(); OneSignal.IdsAvailable((playerID, pushToken) => { try { System.Console.WriteLine("Player ID: " + playerID); if (pushToken != null) { System.Console.WriteLine("Push Token: " + pushToken); } } catch (System.Exception e) { System.Console.WriteLine(e.StackTrace); } }); return(true); }
// Test Menu // Includes SendTag/SendTags, getting the userID and pushToken, and scheduling an example notification void OnGUI() { GUIStyle customTextSize = new GUIStyle("button"); customTextSize.fontSize = 30; GUIStyle guiBoxStyle = new GUIStyle("box"); guiBoxStyle.fontSize = 30; GUI.Box(new Rect(10, 10, 390, 340), "Test Menu", guiBoxStyle); if (GUI.Button(new Rect(60, 80, 300, 60), "SendTags", customTextSize)) { // You can tags users with key value pairs like this: OneSignal.SendTag("UnityTestKey", "TestValue"); // Or use an IDictionary if you need to set more than one tag. OneSignal.SendTags(new Dictionary <string, string>() { { "UnityTestKey2", "value2" }, { "UnityTestKey3", "value3" } }); // You can delete a single tag with it's key. // OneSignal.DeleteTag("UnityTestKey"); // Or delete many with an IList. // OneSignal.DeleteTags(new List<string>() {"UnityTestKey2", "UnityTestKey3" }); } if (GUI.Button(new Rect(60, 170, 300, 60), "GetIds", customTextSize)) { OneSignal.IdsAvailable((userId, pushToken) => { extraMessage = "UserID:\n" + userId + "\n\nPushToken:\n" + pushToken; }); } if (GUI.Button(new Rect(60, 260, 300, 60), "TestNotification", customTextSize)) { extraMessage = "Waiting to get a OneSignal userId. Uncomment OneSignal.SetLogLevel in the Start method if it hangs here to debug the issue."; OneSignal.IdsAvailable((userId, pushToken) => { if (pushToken != null) { // See http://documentation.onesignal.com/docs/notifications-create-notification for a full list of options. // You can not use included_segments or any fields that require your OneSignal 'REST API Key' in your app for security reasons. // If you need to use your OneSignal 'REST API Key' you will need your own server where you can make this call. var notification = new Dictionary <string, object>(); notification["contents"] = new Dictionary <string, string>() { { "en", "Test Message" } }; // Send notification to this device. notification["include_player_ids"] = new List <string>() { userId }; // Example of scheduling a notification in the future. notification["send_after"] = System.DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U"); extraMessage = "Posting test notification now."; OneSignal.PostNotification(notification, (responseSuccess) => { extraMessage = "Notification posted successful! Delayed by about 30 secounds to give you time to press the home button to see a notification vs an in-app alert.\n" + Json.Serialize(responseSuccess); }, (responseFailure) => { extraMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure); }); } else { extraMessage = "ERROR: Device is not registered."; } }); } if (extraMessage != null) { guiBoxStyle.alignment = TextAnchor.UpperLeft; guiBoxStyle.wordWrap = true; GUI.Box(new Rect(10, 390, Screen.width - 20, Screen.height - 400), extraMessage, guiBoxStyle); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); OneSignal.NotificationReceived exampleNotificationReceivedDelegate = delegate(OSNotification notification) { try { System.Console.WriteLine("OneSignal Notification Received:\nMessage: {0}", notification.payload.body); Dictionary <string, object> additionalData = notification.payload.additionalData; if (additionalData.Count > 0) { System.Console.WriteLine("additionalData: {0}", additionalData); } } catch (System.Exception e) { System.Console.WriteLine(e.StackTrace); } }; // Notification Opened Delegate OneSignal.NotificationOpened exampleNotificationOpenedDelegate = delegate(OSNotificationOpenedResult result) { try { System.Console.WriteLine("OneSignal Notification opened:\nMessage: {0}", result.notification.payload.body); Dictionary <string, object> additionalData = result.notification.payload.additionalData; if (additionalData.Count > 0) { System.Console.WriteLine("additionalData: {0}", additionalData); } List <Dictionary <string, object> > actionButtons = result.notification.payload.actionButtons; if (actionButtons.Count > 0) { System.Console.WriteLine("actionButtons: {0}", actionButtons); } } catch (System.Exception e) { System.Console.WriteLine(e.StackTrace); } }; // Initialize OneSignal OneSignal.StartInit("b2f7f966-d8cc-11e4-bed1-df8f05be55ba") .HandleNotificationReceived(exampleNotificationReceivedDelegate) .HandleNotificationOpened(exampleNotificationOpenedDelegate) .InFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification) .Settings(new Dictionary <string, bool> { { OneSignal.kOSSettingsKeyAutoPrompt, true }, { OneSignal.kOSSettingsKeyInAppLaunchURL, false } }) .EndInit(); OneSignal.IdsAvailable((playerID, pushToken) => { try { System.Console.WriteLine("Player ID: " + playerID); if (pushToken != null) { System.Console.WriteLine("Push Token: " + pushToken); } } catch (System.Exception e) { System.Console.WriteLine(e.StackTrace); } }); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button> (Resource.Id.myButton); button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); }; }
/// <summary> /// Initializes local and remote notification services. /// </summary> public static void Init() { if (sIsInitialized) { Debug.Log("Notifications module has been initialized. Ignoring this call."); return; } // Get the listener. sListener = GetNotificationListener(); // Subscibe to internal notification events. if (sListener != null) { sListener.LocalNotificationOpened += InternalOnLocalNotificationOpened; sListener.RemoteNotificationOpened += InternalOnRemoteNotificationOpened; } // Initialize OneSignal push notification service if it's used. if (EM_Settings.Notifications.PushNotificationService == PushNotificationProvider.OneSignal) { #if EM_ONESIGNAL // Get the applicable data privacy consent for push notifications. var consent = GetApplicableDataPrivacyConsent(); // Init OneSignal. var osBuilder = OneSignal.StartInit(EM_Settings.Notifications.OneSignalAppId); osBuilder.HandleNotificationReceived(sListener.OnOneSignalNotificationReceived) .HandleNotificationOpened(sListener.OnOneSignalNotificationOpened) .InFocusDisplaying(OneSignal.OSInFocusDisplayOption.None); // Set as requiring consent if one is specified. if (consent != ConsentStatus.Unknown) { osBuilder.SetRequiresUserPrivacyConsent(true); } // Finalize init. osBuilder.EndInit(); // Apply the provided consent. If the consent is Unknown it is ignored and the initialization // will proceed as normal. If the consent is Granted, the initialization will also complete. // If the consent is Revoked the initialization never completes and the device won't be registered // with OneSignal and won't receive notifications. // Note that if the device has been registered to OneSignal (during previous initialization) // and then the consent is revoked, the notifications will still be delivered to the device // but won't be forwarded to the app, because the initialization is now not completed. if (consent != ConsentStatus.Unknown) { OneSignal.UserDidProvideConsent(consent == ConsentStatus.Granted); } // Handle when the OneSignal token becomes available. // Must be called after StartInit. // If the consent is revoked we won't register this to avoid warning from OneSignal. if (consent != ConsentStatus.Revoked) { OneSignal.IdsAvailable((playerId, pushToken) => { PushToken = pushToken; if (PushTokenReceived != null) { PushTokenReceived(pushToken); } }); } #else Debug.LogError("SDK missing. Please import OneSignal plugin for Unity."); #endif } // Initialize Firebase push notification service if it's used. if (EM_Settings.Notifications.PushNotificationService == PushNotificationProvider.Firebase) { #if EM_FIR_MESSAGING // To offer users a chance to opt-in to FCM, the dev must manually disable FCM's auto-initialization // https://firebase.google.com/docs/cloud-messaging/unity/client. // If the consent is granted, we'll help re-enable FCM automatically. var consent = GetApplicableDataPrivacyConsent(); if (consent == ConsentStatus.Granted) { Firebase.Messaging.FirebaseMessaging.TokenRegistrationOnInitEnabled = true; } // FirebaseMessaging will initialize once we subscribe to // the TokenReceived or MessageReceived event. Firebase.Messaging.FirebaseMessaging.TokenReceived += (_, tokenArg) => { // Cache the registration token and fire event. PushToken = tokenArg.Token; if (PushTokenReceived != null) { PushTokenReceived(tokenArg.Token); } // Subscribe default Firebase topics if any. // This must be done after the token has been received. if (EM_Settings.Notifications.FirebaseTopics != null) { foreach (string topic in EM_Settings.Notifications.FirebaseTopics) { if (!string.IsNullOrEmpty(topic)) { Firebase.Messaging.FirebaseMessaging.SubscribeAsync(topic); } } } }; // Register the event handler to be invoked once a Firebase message is received. Firebase.Messaging.FirebaseMessaging.MessageReceived += (_, param) => sListener.OnFirebaseNotificationReceived(param); #else Debug.LogError("SDK missing. Please import FirebaseMessaging plugin for Unity."); #endif } // Initialize local notification client. LocalNotificationClient.Init(EM_Settings.Notifications, sListener); // Done initializing. sIsInitialized = true; }
public void IdsAvailable() { OneSignal.IdsAvailable(IdsAvailableHandler); }
private Task Needs_Login() { return(new Task() { Mission = "Needs_Login", Action = (seekTo, currentTask, nextTask, delivery) => { if (FB.IsLoggedIn) { if (File.Exists(Config.Directories.Identity)) { FileStream stream = new FileStream(Config.Directories.Identity, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(stream); string json = reader.ReadToEnd(); reader.Close(); stream.Close(); Variables.Self = JsonConvert.DeserializeObject <JsonSelf>(json); if (Variables.Self.fbId != AccessToken.CurrentAccessToken.UserId) { File.Delete(Config.Directories.Identity); currentTask(null); } else { nextTask(null); } } else { FB.API("/me?fields=name,email,picture.type(large)", HttpMethod.POST, (graphResult) => { Variables.Self = new JsonSelf() { key = "", fbId = graphResult.ResultDictionary["id"].ToString(), email = graphResult.ResultDictionary["email"].ToString(), name = graphResult.ResultDictionary["name"].ToString(), picture = ((graphResult.ResultDictionary["picture"] as Dictionary <string, object>)["data"] as Dictionary <string, object>)["url"].ToString() }; (Variables.UI["txtConsole"] as UIText).Element.text = "Logged you in..."; #if UNITY_EDITOR nextTask(null); #endif #if !UNITY_EDITOR OneSignal.IdsAvailable(HandleID); Variables.nextTask = nextTask; #endif }); } } else { Directives.App_First = true; (Variables.UI["txtConsole"] as UIText).Element.text = "Need to log you in..."; List <string> perms = new List <string>() { "public_profile", "email", "user_friends" }; FB.LogInWithReadPermissions(perms, (result) => { if (result.Cancelled) { Application.Quit(); } if (FB.IsLoggedIn) { FB.API("/me?fields=name,email,picture.type(large)", HttpMethod.POST, (graphResult) => { Variables.Self = new JsonSelf() { key = "", fbId = graphResult.ResultDictionary["id"].ToString(), email = graphResult.ResultDictionary["email"].ToString(), name = graphResult.ResultDictionary["name"].ToString(), picture = ((graphResult.ResultDictionary["picture"] as Dictionary <string, object>)["data"] as Dictionary <string, object>)["url"].ToString() }; (Variables.UI["txtConsole"] as UIText).Element.text = "Logged you in..."; #if UNITY_EDITOR nextTask(null); #endif #if !UNITY_EDITOR OneSignal.IdsAvailable(HandleID); Variables.nextTask = nextTask; #endif }); } }); } } }); }
// Test Menu // Includes SendTag/SendTags, getting the userID and pushToken, and scheduling an example notification void OnGUI() { GUIStyle customTextSize = new GUIStyle("button"); customTextSize.fontSize = 30; GUIStyle guiBoxStyle = new GUIStyle("box"); guiBoxStyle.fontSize = 30; GUIStyle textFieldStyle = new GUIStyle("textField"); textFieldStyle.fontSize = 30; float itemOriginX = 50.0f; float itemWidth = Screen.width - 120.0f; float boxWidth = Screen.width - 20.0f; float boxOriginY = 120.0f; float boxHeight = requiresUserPrivacyConsent ? 980.0f : 890.0f; float itemStartY = 200.0f; float itemHeightOffset = 90.0f; float itemHeight = 60.0f; GUI.Box(new Rect(10, boxOriginY, boxWidth, boxHeight), "Test Menu", guiBoxStyle); float count = 0.0f; if (GUI.Button(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), "SendTags", customTextSize)) { // You can tags users with key value pairs like this: OneSignal.SendTag("UnityTestKey", "TestValue"); // Or use an IDictionary if you need to set more than one tag. OneSignal.SendTags(new Dictionary <string, string>() { { "UnityTestKey2", "value2" }, { "UnityTestKey3", "value3" } }); // You can delete a single tag with it's key. // OneSignal.DeleteTag("UnityTestKey"); // Or delete many with an IList. // OneSignal.DeleteTags(new List<string>() {"UnityTestKey2", "UnityTestKey3" }); } count++; if (GUI.Button(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), "GetIds", customTextSize)) { OneSignal.IdsAvailable((userId, pushToken) => { extraMessage = "UserID:\n" + userId + "\n\nPushToken:\n" + pushToken; }); } count++; if (GUI.Button(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), "TestNotification", customTextSize)) { extraMessage = "Waiting to get a OneSignal userId. Uncomment OneSignal.SetLogLevel in the Start method if it hangs here to debug the issue."; OneSignal.IdsAvailable((userId, pushToken) => { if (pushToken != null) { // See http://documentation.onesignal.com/docs/notifications-create-notification for a full list of options. // You can not use included_segments or any fields that require your OneSignal 'REST API Key' in your app for security reasons. // If you need to use your OneSignal 'REST API Key' you will need your own server where you can make this call. var notification = new Dictionary <string, object>(); notification["contents"] = new Dictionary <string, string>() { { "en", "Test Message" } }; // Send notification to this device. notification["include_player_ids"] = new List <string>() { userId }; // Example of scheduling a notification in the future. notification["send_after"] = System.DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U"); extraMessage = "Posting test notification now."; OneSignal.PostNotification(notification, (responseSuccess) => { extraMessage = "Notification posted successful! Delayed by about 30 secounds to give you time to press the home button to see a notification vs an in-app alert.\n" + Json.Serialize(responseSuccess); }, (responseFailure) => { extraMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure); }); } else { extraMessage = "ERROR: Device is not registered."; } }); } count++; email = GUI.TextField(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), email, customTextSize); count++; if (GUI.Button(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), "SetEmail", customTextSize)) { extraMessage = "Setting email to " + email; OneSignal.SetEmail(email, () => { Debug.Log("Successfully set email"); }, (error) => { Debug.Log("Encountered error setting email: " + Json.Serialize(error)); }); } count++; if (GUI.Button(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), "LogoutEmail", customTextSize)) { extraMessage = "Logging Out of [email protected]"; OneSignal.LogoutEmail(() => { Debug.Log("Successfully logged out of email"); }, (error) => { Debug.Log("Encountered error logging out of email: " + Json.Serialize(error)); }); } count++; externalId = GUI.TextField(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), externalId, customTextSize); count++; if (GUI.Button(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), "SetExternalId", customTextSize)) { extraMessage = "Setting External User Id"; OneSignal.SetExternalUserId(externalId); } count++; if (GUI.Button(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), "RemoveExternalId", customTextSize)) { extraMessage = "Removing External User Id"; OneSignal.RemoveExternalUserId(); } if (requiresUserPrivacyConsent) { count++; if (GUI.Button(new Rect(itemOriginX, itemStartY + (count * itemHeightOffset), itemWidth, itemHeight), (OneSignal.UserProvidedConsent() ? "Revoke Privacy Consent" : "Provide Privacy Consent"), customTextSize)) { extraMessage = "Providing user privacy consent"; OneSignal.UserDidProvideConsent(!OneSignal.UserProvidedConsent()); } } if (extraMessage != null) { guiBoxStyle.alignment = TextAnchor.UpperLeft; guiBoxStyle.wordWrap = true; GUI.Box(new Rect(10, boxOriginY + boxHeight + 20, Screen.width - 20, Screen.height - (boxOriginY + boxHeight + 40)), extraMessage, guiBoxStyle); } }
// Initialization void Awake() { // UUID management #if UNITY_WEBGL && !UNITY_EDITOR string uuid = GetUUID(); uuid = (uuid.Length == 0 ? System.Guid.NewGuid().ToString("N") : uuid); SetUUID(uuid); AppConstants.UUID = uuid; #else PlayerPrefs.SetString(AppConstants.UniqueIdentifier, SystemInfo.deviceUniqueIdentifier); PlayerPrefs.Save(); AppConstants.UUID = PlayerPrefs.GetString(AppConstants.UniqueIdentifier); #endif // OneSignal initialization OneSignal.StartInit("927cbb8d-88bc-4468-a8b7-f810a72594a4").EndInit(); OneSignal.inFocusDisplayType = OneSignal.OSInFocusDisplayOption.InAppAlert; OneSignal.IdsAvailable(OnOneSignalIDsAvailable); Application.targetFrameRate = AppConstants.TargetFPS; HUD.SetActive(false); map.OnTileLoad.AddListener((tile) => { OnTileLoaded(); }); // Logging in Utils.Web.GetJSON(AppConstants.LoginUrl + "USER_ID=" + AppConstants.UUID + AppConstants.PlayerDeviceIdentifierID, (loginSuccess, json) => { loggedIn = loginSuccess; if (loggedIn) { PlayerPrefs.SetString(AppConstants.NickTag, Utils.JSON.GetString(json, "nick")); PlayerPrefs.SetInt(AppConstants.FractionTag, (int)Utils.JSON.GetLong(json, "fraction")); PlayerPrefs.SetInt(AppConstants.PatchCreatedTag, (int)Utils.JSON.GetLong(json, "patchCreated")); if (!PlayerPrefs.HasKey(AppConstants.EnergyTag)) { PlayerPrefs.SetFloat(AppConstants.EnergyTag, float.Parse(Utils.JSON.GetString(json, "resource0"))); } if (!PlayerPrefs.HasKey(AppConstants.BiomassTag)) { PlayerPrefs.SetFloat(AppConstants.BiomassTag, float.Parse(Utils.JSON.GetString(json, "resource1"))); } if (!PlayerPrefs.HasKey(AppConstants.GadgetsTag)) { PlayerPrefs.SetFloat(AppConstants.GadgetsTag, float.Parse(Utils.JSON.GetString(json, "resource2"))); } if (!PlayerPrefs.HasKey(AppConstants.FuelTag)) { PlayerPrefs.SetFloat(AppConstants.FuelTag, float.Parse(Utils.JSON.GetString(json, "resource3"))); } if (!PlayerPrefs.HasKey(AppConstants.GeneratorVisitTimestampTag)) { PlayerPrefs.SetInt(AppConstants.GeneratorVisitTimestampTag, (int)Utils.JSON.GetLong(json, "generatorVisitTimestamp")); } PlayerPrefs.SetInt(AppConstants.NaturePoints, (int)Utils.JSON.GetLong(json, "naturePoints")); PlayerPrefs.SetInt(AppConstants.CommercyPoints, (int)Utils.JSON.GetLong(json, "industryPoints")); PlayerPrefs.SetInt(AppConstants.IndustryPoints, (int)Utils.JSON.GetLong(json, "commercyPoints")); PlayerPrefs.SetInt(AppConstants.ProjectObjectsCountTag, (int)Utils.JSON.GetLong(json, "projectObjectCount")); PlayerPrefs.SetInt(AppConstants.GeneratorCreatedTag, (int)Utils.JSON.GetLong(json, "generatorCreated")); PlayerPrefs.SetInt(AppConstants.ConverterCreatedTag, (int)Utils.JSON.GetLong(json, "converterCreated")); PlayerPrefs.SetInt(AppConstants.BatteryCreatedTag, (int)Utils.JSON.GetLong(json, "batteryCreated")); PlayerPrefs.Save(); } else { PlayerPrefs.DeleteAll(); } }); }