Пример #1
0
    // 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 ? 720.0f : 630.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));
            });
        }

        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);
        }
    }
Пример #2
0
        /// <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;
        }