Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public Task<bool> EnterAsync(string activityId, string token)
return Task.FromResult(false);
}

[System.Obsolete("Currently unsupported, avoid using this method.")]
public Task<bool> ExitAsync(string activityId)
{
SDKDebug.Warn("This feature is only available for iOS.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public Task<bool> EnterAsync(string activityId, string token)
return Task.FromResult(false);
}

[System.Obsolete("Currently unsupported, avoid using this method.")]
public Task<bool> ExitAsync(string activityId)
{
return Task.FromResult(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public interface ILiveActivitiesManager
/// </summary>
/// <remarks>iOS Only</remarks>
/// <returns>Awaitable boolean of whether the operation succeeded or failed</returns>
[System.Obsolete("Currently unsupported, avoid using this method.")]
Task<bool> ExitAsync(string activityId);

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ public async Task<bool> EnterAsync(string activityId, string token)
return await proxy;
}

[System.Obsolete("Currently unsupported, avoid using this method.")]
public async Task<bool> ExitAsync(string activityId)
{
var (proxy, hashCode) = WaitingProxy._setupProxy<bool>();
Expand Down
1 change: 1 addition & 0 deletions examples/demo/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ONESIGNAL_API_KEY=your_rest_api_key
5 changes: 5 additions & 0 deletions examples/demo/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ crashlytics-build.properties
# User-specific Unity Editor settings
/[Uu]serSettings/

# Environment files
.env
Assets/StreamingAssets/.env
Assets/StreamingAssets/.env.meta

# Gradle template backup files
*.backup
*.backup.meta
Expand Down
18 changes: 9 additions & 9 deletions examples/demo/Assets/App/Editor/iOS/BuildPostProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,19 @@
namespace App.Editor.iOS
{
/// <summary>
/// Adds the ExampleWidgetExtension to the iOS project frameworks to the iOS project and enables the main target
/// Adds the OneSignalWidgetExtension to the iOS project and enables the main target
/// for Live Activities.
/// </summary>
public class BuildPostProcessor : IPostprocessBuildWithReport
{
private static readonly string WdigetExtensionTargetRelativePath = "ExampleWidget";
private static readonly string WidgetExtensionTargetName = "ExampleWidgetExtension";
private static readonly string WidgetExtensionPath = Path.Combine("iOS", "ExampleWidget");
private static readonly string WidgetExtensionTargetRelativePath = "OneSignalWidget";
private static readonly string WidgetExtensionTargetName = "OneSignalWidgetExtension";
Comment thread
claude[bot] marked this conversation as resolved.
private static readonly string WidgetExtensionPath = Path.Combine("iOS", "OneSignalWidget");
private static readonly string[] WidgetExtensionFiles = new string[]
{
"Assets.xcassets",
"ExampleWidgetBundle.swift",
"ExampleWidgetLiveActivity.swift",
"OneSignalWidgetBundle.swift",
"OneSignalWidgetLiveActivity.swift",
};

/// <summary>
Expand Down Expand Up @@ -114,7 +114,7 @@ static void AddWidgetExtensionToProject(string outputPath)
if (!string.IsNullOrEmpty(extensionGuid))
return;

var widgetDestPath = Path.Combine(outputPath, WdigetExtensionTargetRelativePath);
var widgetDestPath = Path.Combine(outputPath, WidgetExtensionTargetRelativePath);

Directory.CreateDirectory(widgetDestPath);
CopyFileOrDirectory(
Expand All @@ -126,14 +126,14 @@ static void AddWidgetExtensionToProject(string outputPath)
project.GetUnityMainTargetGuid(),
WidgetExtensionTargetName,
$"{PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.iOS)}.{WidgetExtensionTargetName}",
$"{WdigetExtensionTargetRelativePath}/Info.plist"
$"{WidgetExtensionTargetRelativePath}/Info.plist"
);

var buildPhaseID = project.AddSourcesBuildPhase(extensionGuid);

foreach (var file in WidgetExtensionFiles)
{
var destPathRelative = Path.Combine(WdigetExtensionTargetRelativePath, file);
var destPathRelative = Path.Combine(WidgetExtensionTargetRelativePath, file);
var sourceFileGuid = project.AddFile(destPathRelative, destPathRelative);
project.AddFileToBuildSection(extensionGuid, buildPhaseID, sourceFileGuid);
CopyFileOrDirectory(
Expand Down
8 changes: 8 additions & 0 deletions examples/demo/Assets/Resources/Theme.uss
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,14 @@ Scroller {
max-height: 0;
}

.inline-input-field > .unity-text-field__input {
background-color: transparent;
border-width: 0;
-unity-text-align: upper-right;
color: var(--os-text-primary);
font-size: 14px;
}

.unity-base-slider {
display: none;
}
Expand Down
12 changes: 12 additions & 0 deletions examples/demo/Assets/Scripts/AppBootstrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using OneSignalSDK;
using OneSignalSDK.Debug.Models;
using OneSignalSDK.InAppMessages;
using OneSignalSDK.LiveActivities;
using OneSignalSDK.Notifications;
using UnityEngine;

Expand Down Expand Up @@ -40,12 +41,23 @@ private async void Start()
}

_apiService.SetAppId(appId);
_apiService.LoadApiKey();

OneSignal.Debug.LogLevel = LogLevel.Verbose;
OneSignal.ConsentRequired = _prefs.ConsentRequired;
OneSignal.ConsentGiven = _prefs.PrivacyConsent;
OneSignal.Initialize(appId);

#if UNITY_IOS
OneSignal.LiveActivities.SetupDefault(
new LiveActivitySetupOptions
{
EnablePushToStart = true,
EnablePushToUpdate = true,
}
);
#endif

OneSignal.InAppMessages.Paused = _prefs.IamPaused;
OneSignal.Location.IsShared = _prefs.LocationShared;

Expand Down
41 changes: 41 additions & 0 deletions examples/demo/Assets/Scripts/Editor/CopyEnvPreBuild.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.IO;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace OneSignalDemo.Editor
{
public class CopyEnvPreBuild : IPreprocessBuildWithReport
{
public int callbackOrder => 0;

public void OnPreprocessBuild(BuildReport report)
{
var projectRoot = Path.GetDirectoryName(Application.dataPath);
var source = Path.Combine(projectRoot, ".env");
var dest = Path.Combine(Application.streamingAssetsPath, ".env");

if (!File.Exists(source))
{
Debug.LogWarning(
"[OneSignalDemo] No .env file found at project root. "
+ "Live Activity API calls will be disabled. "
+ "Copy .env.example to .env and add your key."
);
if (File.Exists(dest))
{
File.Delete(dest);
Comment thread
claude[bot] marked this conversation as resolved.
var metaPath = dest + ".meta";
if (File.Exists(metaPath))
Comment thread
fadi-george marked this conversation as resolved.
File.Delete(metaPath);
}
return;
}

Directory.CreateDirectory(Application.streamingAssetsPath);
File.Copy(source, dest, overwrite: true);
Debug.Log("[OneSignalDemo] Copied .env to StreamingAssets");
}
}
}
2 changes: 2 additions & 0 deletions examples/demo/Assets/Scripts/Editor/CopyEnvPreBuild.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions examples/demo/Assets/Scripts/Repositories/OneSignalRepository.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using OneSignalDemo.Models;
using OneSignalDemo.Services;
using OneSignalSDK;
Expand Down Expand Up @@ -112,5 +113,19 @@ public async Task<bool> SendCustomNotification(string title, string body)

public async Task<UserData> FetchUser(string onesignalId) =>
await _apiService.FetchUser(onesignalId);

public bool HasApiKey() => _apiService.HasApiKey();

public void StartDefaultLiveActivity(
string activityId,
IDictionary<string, object> attributes,
IDictionary<string, object> content
) => OneSignal.LiveActivities.StartDefault(activityId, attributes, content);

public async Task<bool> UpdateLiveActivity(
string activityId,
string eventType,
JObject eventUpdates = null
) => await _apiService.UpdateLiveActivity(activityId, eventType, eventUpdates);
}
}
85 changes: 85 additions & 0 deletions examples/demo/Assets/Scripts/Services/OneSignalApiService.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,61 @@
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using OneSignalDemo.Models;
using UnityEngine;
using UnityEngine.Networking;

namespace OneSignalDemo.Services
{
public class OneSignalApiService
{
private string _appId;
private string _apiKey;

private const string NotificationImageUrl =
"https://media.onesignal.com/automated_push_templates/ratings_template.png";

private const string PlaceholderApiKey = "your_rest_api_key";

public void SetAppId(string appId) => _appId = appId;

public string GetAppId() => _appId;

public void LoadApiKey()
{
var envPath = Path.Combine(Application.dataPath, "..", ".env");
#if !UNITY_EDITOR
var streamingPath = Path.Combine(Application.streamingAssetsPath, ".env");
if (File.Exists(streamingPath))
envPath = streamingPath;
#endif
if (!File.Exists(envPath))
return;

foreach (var line in File.ReadAllLines(envPath))
{
var trimmed = line.Trim();
if (trimmed.StartsWith("#") || !trimmed.Contains("="))
continue;

var eqIndex = trimmed.IndexOf('=');
var key = trimmed.Substring(0, eqIndex).Trim();
var value = trimmed.Substring(eqIndex + 1).Trim();
int commentIdx = value.IndexOf('#');
if (commentIdx >= 0)
value = value.Substring(0, commentIdx).Trim();
value = value.Trim('"', '\'');

if (key == "ONESIGNAL_API_KEY")
_apiKey = value;
}
}

public bool HasApiKey() =>
!string.IsNullOrEmpty(_apiKey) && _apiKey != PlaceholderApiKey;

public async Task<bool> SendNotification(NotificationType type, string subscriptionId)
{
if (string.IsNullOrEmpty(subscriptionId) || string.IsNullOrEmpty(_appId))
Comment thread
claude[bot] marked this conversation as resolved.
Expand Down Expand Up @@ -108,6 +146,53 @@ public async Task<UserData> FetchUser(string onesignalId)
return result;
}

public async Task<bool> UpdateLiveActivity(
string activityId,
string eventType,
JObject eventUpdates = null
)
Comment thread
claude[bot] marked this conversation as resolved.
{
if (string.IsNullOrEmpty(activityId) || string.IsNullOrEmpty(_appId) || !HasApiKey())
return false;

var encodedId = Uri.EscapeDataString(activityId);
var url =
$"https://api.onesignal.com/apps/{_appId}/live_activities/{encodedId}/notifications";

var payload = new JObject
{
["event"] = eventType,
["name"] = "Unity Demo Update",
["priority"] = 10,
};

if (eventUpdates != null)
payload["event_updates"] = eventUpdates;

if (eventType == "end")
{
var unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
payload["dismissal_date"] = unixTimestamp;
}

var jsonPayload = payload.ToString();
var request = new UnityWebRequest(url, "POST");
var bodyRaw = Encoding.UTF8.GetBytes(jsonPayload);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", $"Key {_apiKey}");

var tcs = new TaskCompletionSource<bool>();
var operation = request.SendWebRequest();
operation.completed += _ => tcs.TrySetResult(true);
await tcs.Task;

bool success = request.responseCode >= 200 && request.responseCode < 300;
request.Dispose();
return success;
}

private async Task<bool> PostNotification(string jsonPayload)
{
var request = new UnityWebRequest("https://onesignal.com/api/v1/notifications", "POST");
Expand Down
13 changes: 11 additions & 2 deletions examples/demo/Assets/Scripts/UI/HomeScreenController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public class HomeScreenController : MonoBehaviour
private TriggersSectionController _triggersSection;
private TrackEventSectionController _trackEventSection;
private LocationSectionController _locationSection;
private LiveActivitiesSectionController _liveActivitiesSection;

private void OnEnable()
{
Expand Down Expand Up @@ -254,11 +255,18 @@ private void BuildSections()
_locationSection.OnInfoTap = () => ShowTooltip("location");
_contentRoot.Add(_locationSection.Root);

#if UNITY_IOS
_liveActivitiesSection = new LiveActivitiesSectionController(_viewModel);
_liveActivitiesSection.OnInfoTap = () => ShowTooltip("liveActivities");
_contentRoot.Add(_liveActivitiesSection.Root);
#endif

var nextButton = SectionBuilder.CreatePrimaryButton(
"NEXT ACTIVITY",
"next_activity_button",
"NEXT SCREEN",
"next_screen_button",
() => SceneManager.LoadScene("Secondary")
);
nextButton.style.marginTop = 24;
_contentRoot.Add(nextButton);
}

Expand All @@ -280,6 +288,7 @@ private void RefreshAll()
_tagsSection?.Refresh();
_triggersSection?.Refresh();
_locationSection?.Refresh();
_liveActivitiesSection?.Refresh();

var showLoading = _viewModel.IsLoading;
_loadingOverlay.style.display = showLoading ? DisplayStyle.Flex : DisplayStyle.None;
Expand Down
4 changes: 2 additions & 2 deletions examples/demo/Assets/Scripts/UI/SecondaryScreenController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ private void OnEnable()
backButton.AddToClassList("back-button");
appBar.Add(backButton);

var title = new Label("Secondary Activity");
var title = new Label("Secondary Screen");
title.AddToClassList("app-bar-title");
appBar.Add(title);

Expand All @@ -39,7 +39,7 @@ private void OnEnable()
var content = new VisualElement();
content.AddToClassList("centered-content");

var heading = new Label("Secondary Activity");
var heading = new Label("Secondary Screen");
heading.name = "secondary_heading";
heading.AddToClassList("page-heading");
content.Add(heading);
Expand Down
Loading
Loading