Ti.Cloud.currentUser() returns null when offline – how to preserve session for low‑traffic workloads?
0 reputation · 21 Feb 2022, 00:19 UTC
0 reputation · 21 Feb 2022, 00:19 UTC
The goal is to understand why the Cloud Services API returns null for Ti.Cloud.currentUser() after a device loses connectivity, even though a user had previously authenticated. This behavior is observed in SDK versions 7.0.0 and later, but the documentation does not specify whether a cached user should be returned in offline mode.
For low‑traffic workloads that aim to reduce Cloud costs, developers rely on local persistence and minimal API calls. An unexpected null value can break authentication logic and force unnecessary re‑authentication, thereby increasing API usage and cost.
Key constraints and uncertainties:
Specific questions to investigate:
Ti.Cloud.currentUser() when offline expected behavior according to the SDK design?35275 reputation · 21 Feb 2022, 08:17 UTC
When a Titanium app goes offline, Ti.Cloud.currentUser() often returns null because the SDK can no longer validate the cached session token. The token is stored in the device’s secure storage; if it has expired or been cleared, the SDK treats the user as unauthenticated. This behaviour is consistent on both iOS and Android and is by design – the SDK does not attempt to refresh a token without network access.
currentUser() returns null.Ti.Cloud.getSessionToken() and the token’s expiry timestamp (available in the Cloud console under the user’s session details). Example:
Ti.Cloud.getSessionToken(function(e) {
if (e.success) {
Ti.API.info('Session token: ' + e.sessionToken);
// Store the expiry time if the API provides it
} else {
Ti.API.warn('No cached token');
}
});
Ti.App.Properties. Use encryption if the token is sensitive:
// Example – simple base64 encoding (not secure for production)
var token = Ti.Cloud.getSessionToken();
Ti.App.Properties.setString('cachedSession', btoa(token));
// Store expiry as a timestamp
Ti.App.Properties.setDouble('sessionExpiry', Date.now() + 3600 * 1000); // 1 hour TTL
sessionExpiry, set the token back into the SDK (if a setter exists) or rely on currentUser() which will now return the cached user. If the token is missing or expired, trigger a re‑authentication flow.
Ti.Cloud.currentUser() in a tight loop. Cache the result in a local variable and use it for the duration of the session.
currentUser() turns null. This confirms that TTL, not connectivity, is the root cause.
To fine‑tune the recommendation, could you tell me whether you have a custom session timeout configured in your Cloud console? The default timeout is 24 hours, but a shorter timeout would explain rapid token expiration during low‑traffic periods.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.