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
12 changes: 12 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignal.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,13 @@
A5048F01A1B2C3D4E5F6100B /* OSFeatureFlagsRefreshServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5048F01A1B2C3D4E5F6100A /* OSFeatureFlagsRefreshServiceTests.swift */; };
A5062F01A1B2C3D4E5F60002 /* OSDeviceGestureDetector.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5062F01A1B2C3D4E5F60001 /* OSDeviceGestureDetector.swift */; };
A5162F01A1B2C3D4E5F60002 /* OSSessionService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5162F01A1B2C3D4E5F60001 /* OSSessionService.swift */; };
A5162F01A1B2C3D4E5F60014 /* OSSessionsRequests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5162F01A1B2C3D4E5F60013 /* OSSessionsRequests.swift */; };
A5162F01A1B2C3D4E5F60012 /* OSSessionsBackendService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5162F01A1B2C3D4E5F60011 /* OSSessionsBackendService.swift */; };
A5426001A1B2C3D4E5F60002 /* OSInputGuard.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5426001A1B2C3D4E5F60001 /* OSInputGuard.swift */; };
A5426001A1B2C3D4E5F60004 /* OSInputGuardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5426001A1B2C3D4E5F60003 /* OSInputGuardTests.swift */; };
A5062F01A1B2C3D4E5F60004 /* OSDeviceGestureDetectorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5062F01A1B2C3D4E5F60003 /* OSDeviceGestureDetectorTests.swift */; };
A5162F01A1B2C3D4E5F60004 /* OSSessionServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5162F01A1B2C3D4E5F60003 /* OSSessionServiceTests.swift */; };
A5162F01A1B2C3D4E5F60016 /* OSSessionsBackendServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5162F01A1B2C3D4E5F60015 /* OSSessionsBackendServiceTests.swift */; };
C781A33FED62B4B54221A09A /* OSLogCrashHandlerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B6A59620B83538CEFF77269 /* OSLogCrashHandlerTests.swift */; };
32D3A6EA8AD44274B5CE378A /* FileLogStoreRetentionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CC252C94ECB485E8D0380E9 /* FileLogStoreRetentionTests.swift */; };
B96A3B6BA8CC49EE4796D9BF /* OSRemoteLoggingController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A72F938F8A3808AC1FF7F3C /* OSRemoteLoggingController.swift */; };
Expand Down Expand Up @@ -1909,10 +1912,13 @@
A5048F01A1B2C3D4E5F6100A /* OSFeatureFlagsRefreshServiceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSFeatureFlagsRefreshServiceTests.swift; sourceTree = "<group>"; };
A5062F01A1B2C3D4E5F60001 /* OSDeviceGestureDetector.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSDeviceGestureDetector.swift; sourceTree = "<group>"; };
A5162F01A1B2C3D4E5F60001 /* OSSessionService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSSessionService.swift; sourceTree = "<group>"; };
A5162F01A1B2C3D4E5F60013 /* OSSessionsRequests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSSessionsRequests.swift; sourceTree = "<group>"; };
A5162F01A1B2C3D4E5F60011 /* OSSessionsBackendService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSSessionsBackendService.swift; sourceTree = "<group>"; };
A5426001A1B2C3D4E5F60001 /* OSInputGuard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSInputGuard.swift; sourceTree = "<group>"; };
A5426001A1B2C3D4E5F60003 /* OSInputGuardTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSInputGuardTests.swift; sourceTree = "<group>"; };
A5062F01A1B2C3D4E5F60003 /* OSDeviceGestureDetectorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSDeviceGestureDetectorTests.swift; sourceTree = "<group>"; };
A5162F01A1B2C3D4E5F60003 /* OSSessionServiceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSSessionServiceTests.swift; sourceTree = "<group>"; };
A5162F01A1B2C3D4E5F60015 /* OSSessionsBackendServiceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSSessionsBackendServiceTests.swift; sourceTree = "<group>"; };
3B6A59620B83538CEFF77269 /* OSLogCrashHandlerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSLogCrashHandlerTests.swift; sourceTree = "<group>"; };
9CC252C94ECB485E8D0380E9 /* FileLogStoreRetentionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileLogStoreRetentionTests.swift; sourceTree = "<group>"; };
8A72F938F8A3808AC1FF7F3C /* OSRemoteLoggingController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSRemoteLoggingController.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -2418,6 +2424,8 @@
4710EA522B8FCFB200435356 /* OSDispatchQueue.swift */,
A5062F01A1B2C3D4E5F60001 /* OSDeviceGestureDetector.swift */,
A5162F01A1B2C3D4E5F60001 /* OSSessionService.swift */,
A5162F01A1B2C3D4E5F60013 /* OSSessionsRequests.swift */,
A5162F01A1B2C3D4E5F60011 /* OSSessionsBackendService.swift */,
A5426001A1B2C3D4E5F60001 /* OSInputGuard.swift */,
DEFB3E642BB7346D00E65DAD /* OSLiveActivities.swift */,
DEFB3E662BB735B500E65DAD /* OSStubLiveActivities.swift */,
Expand Down Expand Up @@ -2747,6 +2755,7 @@
A5048F01A1B2C3D4E5F6100A /* OSFeatureFlagsRefreshServiceTests.swift */,
A5062F01A1B2C3D4E5F60003 /* OSDeviceGestureDetectorTests.swift */,
A5162F01A1B2C3D4E5F60003 /* OSSessionServiceTests.swift */,
A5162F01A1B2C3D4E5F60015 /* OSSessionsBackendServiceTests.swift */,
A5426001A1B2C3D4E5F60003 /* OSInputGuardTests.swift */,
3B6A59620B83538CEFF77269 /* OSLogCrashHandlerTests.swift */,
9CC252C94ECB485E8D0380E9 /* FileLogStoreRetentionTests.swift */,
Expand Down Expand Up @@ -4667,6 +4676,8 @@
A5048F01A1B2C3D4E5F60008 /* OSFeatureFlagsRefreshService.swift in Sources */,
A5062F01A1B2C3D4E5F60002 /* OSDeviceGestureDetector.swift in Sources */,
A5162F01A1B2C3D4E5F60002 /* OSSessionService.swift in Sources */,
A5162F01A1B2C3D4E5F60014 /* OSSessionsRequests.swift in Sources */,
A5162F01A1B2C3D4E5F60012 /* OSSessionsBackendService.swift in Sources */,
A5426001A1B2C3D4E5F60002 /* OSInputGuard.swift in Sources */,
3C4F9E4428A4466C009F453A /* OSOperationRepo.swift in Sources */,
3C14E3B02FAE54C006ED053 /* IOSLogger.swift in Sources */,
Expand Down Expand Up @@ -4864,6 +4875,7 @@
A5048F01A1B2C3D4E5F6100B /* OSFeatureFlagsRefreshServiceTests.swift in Sources */,
A5062F01A1B2C3D4E5F60004 /* OSDeviceGestureDetectorTests.swift in Sources */,
A5162F01A1B2C3D4E5F60004 /* OSSessionServiceTests.swift in Sources */,
A5162F01A1B2C3D4E5F60016 /* OSSessionsBackendServiceTests.swift in Sources */,
A5426001A1B2C3D4E5F60004 /* OSInputGuardTests.swift in Sources */,
C781A33FED62B4B54221A09A /* OSLogCrashHandlerTests.swift in Sources */,
32D3A6EA8AD44274B5CE378A /* FileLogStoreRetentionTests.swift in Sources */,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/*
Modified MIT License

Copyright 2026 OneSignal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

import Foundation
import OneSignalCore

struct OSCreateSessionRequestBody: Equatable {
let onesignalId: String
let subscriptionId: String
let startTime: Date
let idempotencyKey: String
let directAttributionId: String?

init(onesignalId: String, subscriptionId: String, startTime: Date, idempotencyKey: String, directAttributionId: String? = nil) {
self.onesignalId = onesignalId
self.subscriptionId = subscriptionId
self.startTime = startTime
self.idempotencyKey = idempotencyKey
self.directAttributionId = directAttributionId
}
}

struct OSUpdateSessionRequestBody: Equatable {
let onesignalId: String
let subscriptionId: String
/// Cumulative for the whole session, so a retried or reordered update cannot double count.
let durationSeconds: Int64
let idempotencyKey: String
/// Set only on the update that ends the session.
let endTime: Date?

init(onesignalId: String, subscriptionId: String, durationSeconds: Int64, idempotencyKey: String, endTime: Date? = nil) {
self.onesignalId = onesignalId
self.subscriptionId = subscriptionId
self.durationSeconds = durationSeconds
self.idempotencyKey = idempotencyKey
self.endTime = endTime
}
}

enum OSSessionsApiResult<Value> {
case success(Value)
/// No response, 5xx, 408, 429, or a create success without a session ID.
/// Wait at least `retryAfterSeconds` when set.
case retry(statusCode: Int, retryAfterSeconds: Int?)
/// Any other 4xx, or a request the client rejected before sending. It will never succeed as sent.
case drop(statusCode: Int)
}

extension OSSessionsApiResult: Equatable where Value: Equatable {}

/// Typed client for the sessions API.
final class OSSessionsBackendService {
static let defaultRetryAfterSeconds = 60

private let client: () -> IOneSignalClient

convenience init() {
self.init(client: { OneSignalCoreImpl.sharedClient() })
}

init(client: @escaping () -> IOneSignalClient) {
self.client = client
}

/// On success the result holds the backend session ID.
func createSession(
appId: String,
body: OSCreateSessionRequestBody,
completion: @escaping (OSSessionsApiResult<String>) -> Void
) {
let request = OSRequestCreateSession(appId: appId, body: body)
client().execute(request) { response in
guard let sessionId = Self.sessionId(from: response) else {
// Retrying with the same idempotency key returns the session the backend already created.
OneSignalLog.onesignalLog(.LL_WARN, message: "OSSessionsBackendService: create session response is missing data.session_id")
completion(.retry(statusCode: Self.statusCode(of: response), retryAfterSeconds: nil))
return
}
completion(.success(sessionId))
} onFailure: { error in
completion(Self.classifyFailure(error, emptySuccess: .retry(statusCode: error.code, retryAfterSeconds: nil)))
}
}

/// Reports the session's cumulative duration, and ends it when `body.endTime` is set.
func updateSession(
appId: String,
sessionId: String,
body: OSUpdateSessionRequestBody,
completion: @escaping (OSSessionsApiResult<Void>) -> Void
) {
let request = OSRequestUpdateSession(appId: appId, sessionId: sessionId, body: body)
client().execute(request) { _ in
completion(.success(()))
} onFailure: { error in
completion(Self.classifyFailure(error, emptySuccess: .success(())))
}
}

private static func sessionId(from response: [AnyHashable: Any]?) -> String? {
guard let data = response?["data"] as? [String: Any],
let sessionId = data["session_id"] as? String,
!sessionId.isEmpty
else {
return nil
}
return sessionId
}

private static func statusCode(of response: [AnyHashable: Any]?) -> Int {
(response?["httpStatusCode"] as? NSNumber)?.intValue ?? 202
}

/// `emptySuccess` covers a 2xx whose body failed to parse, which `OneSignalClient` reports as a failure.
private static func classifyFailure<Value>(
_ error: OneSignalClientError,
emptySuccess: OSSessionsApiResult<Value>
) -> OSSessionsApiResult<Value> {
let code = error.code
if (200..<300).contains(code) {
return emptySuccess
}
// 0 means no HTTP response: no network, timeout, or missing privacy consent. The client's
// only negative code is a missing app ID, which a retry cannot fix.
if code == 0 || code == 408 || code == 429 || code >= 500 {
return .retry(statusCode: code, retryAfterSeconds: retryAfterSeconds(error))
}
return .drop(statusCode: code)
}

/// Only the delay-seconds form is supported, not the HTTP-date form.
static func retryAfterSeconds(_ error: OneSignalClientError) -> Int? {
let value = error.responseHeaders?.first { key, _ in
(key as? String)?.caseInsensitiveCompare("Retry-After") == .orderedSame
}?.value
if let value {
return Int("\(value)".trimmingCharacters(in: .whitespaces)) ?? defaultRetryAfterSeconds
}
return error.code == 429 ? defaultRetryAfterSeconds : nil
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
Modified MIT License

Copyright 2026 OneSignal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

import Foundation
import OneSignalCore

/// RFC 3339 in UTC with milliseconds, e.g. `2023-11-14T22:13:20.000Z`.
enum OSSessionTimestamp {
private static let formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return formatter
}()

static func string(from date: Date) -> String {
formatter.string(from: date)
}
}

/// `POST apps/{app_id}/sessions`
final class OSRequestCreateSession: OneSignalRequest {
override var description: String {
"<OSRequestCreateSession with parameters: \(parameters ?? [:])>"
}

init(appId: String, body: OSCreateSessionRequestBody) {
super.init()
var parameters: [String: Any] = [
"onesignal_id": body.onesignalId,
"subscription_id": body.subscriptionId,
"device_type": DEVICE_TYPE_PUSH,
"start_time": OSSessionTimestamp.string(from: body.startTime),
"idempotency_key": body.idempotencyKey
]
if let directAttributionId = body.directAttributionId {
parameters["direct_attribution_id"] = directAttributionId
}
self.parameters = parameters
self.method = POST
self.path = "apps/\(appId)/sessions"
}
}

/// `PATCH apps/{app_id}/sessions/{session_id}`
final class OSRequestUpdateSession: OneSignalRequest {
override var description: String {
"<OSRequestUpdateSession with parameters: \(parameters ?? [:])>"
}

init(appId: String, sessionId: String, body: OSUpdateSessionRequestBody) {
super.init()
var parameters: [String: Any] = [
"onesignal_id": body.onesignalId,
"subscription_id": body.subscriptionId,
"duration_seconds": body.durationSeconds,
"idempotency_key": body.idempotencyKey
]
if let endTime = body.endTime {
parameters["end_time"] = OSSessionTimestamp.string(from: endTime)
}
self.parameters = parameters
self.method = PATCH
self.path = "apps/\(appId)/sessions/\(sessionId)"
}
}
Loading
Loading