Advanced HTTP networking module for Titanium SDK with powerful features designed for modern mobile applications.
Ti.Network.Manager is a comprehensive networking solution that extends Titanium's capabilities with advanced features like Server-Sent Events streaming, certificate pinning, automatic retry logic, sophisticated caching, and more.
- Core 10 features for iOS
- Android support
- Upload/download queuing system
Ti.Network.Manager provides everything missing from Titanium's built-in HTTP client:
- Streaming Responses (SSE) - Real-time AI responses like ChatGPT
- Certificate Pinning - Prevent man-in-the-middle attacks
- Request/Response Interceptors - Global middleware for auth, logging
- Automatic Retry with Backoff - Handle flaky networks intelligently
- Advanced Caching - Multiple strategies (cache-first, network-first)
- Background Transfers - Downloads that continue when app is backgrounded
- Request Prioritization - QoS levels for critical vs. background requests
- Multipart Upload Progress - Real-time upload progress tracking
- HTTP/2 & HTTP/3 - Automatic protocol negotiation for better performance
- WebSocket Support - Bidirectional real-time communication
- Installation
- Quick Start
- Features
- Feature 1: Streaming Responses (SSE)
- Feature 2: Certificate Pinning
- Feature 3: Request/Response Interceptors
- Feature 4: Automatic Retry with Backoff
- Feature 5: Advanced Caching
- Feature 6: Background Transfers
- Feature 7: Request Prioritization
- Feature 8: Multipart Upload Progress
- Feature 9: HTTP/2 & HTTP/3 Support
- Feature 10: WebSocket Support
- API Reference
- License
Download the latest version from the releases page.
# Copy the compiled module to:
{YOUR_PROJECT}/modules/iphone/Add the module to your tiapp.xml:
<modules>
<module>ti.network.manager</module>
<!-- OR -->
<moduleplatform="iphone">ti.network.manager</module>
<moduleplatform="android">ti.network.manager</module>
</modules>Initialize the module once at the start of your application:
constNetworkManager=require('ti.network.manager');// Create a simple requestconstrequest=NetworkManager.createRequest({url: 'https://api.example.com/users',method: 'GET'});request.addEventListener('complete',(e)=>{if(e.success){constusers=JSON.parse(e.body);console.log('Users:',users);}});request.send();Server-Sent Events (SSE) streaming for real-time data delivery. Perfect for AI chatbots, live updates, and progressive data loading.
constNetworkManager=require('ti.network.manager');conststream=NetworkManager.createStreamRequest({url: 'https://api.example.com/ai/chat',method: 'POST',headers: {'Content-Type': 'application/json','Authorization': 'Bearer YOUR_TOKEN'},body: JSON.stringify({message: 'Tell me about Titanium SDK',stream: true})});// Receive chunks as they arrivestream.addEventListener('chunk',(e)=>{console.log('Received chunk:',e.data);// Update UI progressivelychatTextArea.value+=e.data;});stream.addEventListener('complete',(e)=>{console.log('Stream complete');console.log('Status:',e.statusCode);});stream.addEventListener('error',(e)=>{console.error('Stream error:',e.error);});stream.start();constNetworkManager=require('ti.network.manager');letchunkCount=0;lettotalBytes=0;conststream=NetworkManager.createStreamRequest({url: 'https://api.example.com/data/stream',method: 'GET',priority: NetworkManager.PRIORITY_HIGH});stream.addEventListener('chunk',(e)=>{chunkCount++;totalBytes+=e.data.length;console.log('Chunk #'+chunkCount+' ('+e.data.length+' bytes)');console.log('Total received: '+totalBytes+' bytes');// Process chunkprocessData(e.data);});stream.addEventListener('complete',(e)=>{console.log('Received '+chunkCount+' chunks');console.log('Total: '+totalBytes+' bytes');});stream.start();// Cancel streaming if neededsetTimeout(()=>{stream.cancel();},30000);// Cancel after 30 seconds- AI Chatbots - Stream responses from AI services like OpenAI, Anthropic, or Google Gemini for real-time user feedback.
- Live News Feeds - Receive breaking news updates as they happen without polling.
- Stock Market Data - Stream real-time stock prices and trading information.
- IoT Device Monitoring - Monitor sensor data from connected devices in real-time.
- Live Event Coverage - Stream sports scores, election results, or event updates as they occur.
Secure your API connections by validating server certificates against known public key hashes. Prevents man-in-the-middle attacks.
constNetworkManager=require('ti.network.manager');// Set certificate pins for your domainNetworkManager.setCertificatePinning('api.example.com',['sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=','sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=']);// Now all requests to api.example.com will validate certificatesconstrequest=NetworkManager.createRequest({url: 'https://api.example.com/secure/data',method: 'GET'});request.addEventListener('complete',(e)=>{if(e.success){console.log('Secure connection validated!');}});request.addEventListener('error',(e)=>{console.error('Certificate validation failed:',e.error);});request.send();constNetworkManager=require('ti.network.manager');// Pin multiple domainsNetworkManager.setCertificatePinning('api.example.com',['sha256/HASH1=','sha256/HASH2=']);NetworkManager.setCertificatePinning('cdn.example.com',['sha256/HASH3=','sha256/HASH4=']);// Requests to both domains will be pinnedUse OpenSSL to extract the public key hash:
# Get certificate hash for your domain
openssl s_client -servername api.example.com -connect api.example.com:443 < /dev/null \
| openssl x509 -pubkey -noout \
| openssl pkey -pubin -outform der \
| openssl dgst -sha256 -binary \
| openssl enc -base64- Banking Apps - Ensure all financial transactions are secure and validated.
- Healthcare Applications - Protect sensitive patient data with certificate validation.
- E-commerce - Secure payment processing and user account information.
- Enterprise Apps - Validate connections to corporate servers and prevent data breaches.
- Government Applications - Meet compliance requirements for secure communications.
Global middleware for modifying requests and responses. Perfect for adding authentication, logging, and error handling.
constNetworkManager=require('ti.network.manager');// Add global request interceptorNetworkManager.addRequestInterceptor((config)=>{console.log('Intercepting request to:',config.url);// Add authentication token to all requestsconfig.headers=config.headers||{};config.headers['Authorization']='Bearer '+getAuthToken();// Add timestampconfig.headers['X-Request-Time']=newDate().toISOString();// Log requestconsole.log('Request:',config.method,config.url);returnconfig;});// Now all requests will have the auth tokenconstrequest=NetworkManager.createRequest({url: 'https://api.example.com/protected/data',method: 'GET'});request.send();constNetworkManager=require('ti.network.manager');// Add global response interceptorNetworkManager.addResponseInterceptor((response)=>{console.log('Response status:',response.statusCode);// Handle authentication errors globallyif(response.statusCode===401){console.log('Unauthorized - refreshing token');refreshAuthToken();}// Handle rate limitingif(response.statusCode===429){console.log('Rate limited - backing off');showRateLimitWarning();}// Log responseconsole.log('Response received from:',response.headers);returnresponse;});constNetworkManager=require('ti.network.manager');// Request interceptor - Add auth and loggingNetworkManager.addRequestInterceptor((config)=>{config.headers=config.headers||{};config.headers['Authorization']='Bearer '+Ti.App.Properties.getString('authToken');config.headers['X-App-Version']=Ti.App.version;config.headers['X-Device-ID']=Ti.Platform.id;logAnalytics('api_request',{url: config.url,method: config.method});returnconfig;});// Response interceptor - Handle errors globallyNetworkManager.addResponseInterceptor((response)=>{// Handle token expirationif(response.statusCode===401){Ti.App.fireEvent('auth:expired');redirectToLogin();}// Handle server errorsif(response.statusCode>=500){showErrorNotification('Server error. Please try again.');}// Log response timeif(response.headers['X-Response-Time']){logAnalytics('api_response_time',{time: response.headers['X-Response-Time']});}returnresponse;});- Authentication Management - Automatically add and refresh authentication tokens for all requests.
- Analytics Tracking - Log all API calls for monitoring and debugging.
- Error Handling - Implement global error handling and user notifications.
- API Versioning - Add version headers to all requests automatically.
- Request Logging - Debug production issues by logging all network activity.
Automatically retry failed requests with configurable backoff strategies. Handles network instability gracefully.
constNetworkManager=require('ti.network.manager');constrequest=NetworkManager.createRequest({url: 'https://api.example.com/data',method: 'GET',retry: {max: 5,// Maximum 5 retry attemptsbackoff: NetworkManager.RETRY_BACKOFF_EXPONENTIAL,baseDelay: 1.0,// Start with 1 second delayretryOn: [500,502,503,504]// Retry on server errors}});request.addEventListener('error',(e)=>{if(e.willRetry){console.log('Request failed, will retry automatically');}else{console.log('Request failed after all retries');}});request.addEventListener('complete',(e)=>{console.log('Request succeeded!');});request.send();constNetworkManager=require('ti.network.manager');// Exponential backoff: 1s, 2s, 4s, 8s, 16sconstrequest=NetworkManager.createRequest({url: 'https://api.example.com/upload',method: 'POST',body: JSON.stringify({data: 'important'}),retry: {max: 5,backoff: NetworkManager.RETRY_BACKOFF_EXPONENTIAL,baseDelay: 1.0,retryOn: [408,500,502,503,504]// Timeout and server errors}});request.send();constNetworkManager=require('ti.network.manager');// Linear backoff: 2s, 4s, 6s, 8s, 10sconstrequest=NetworkManager.createRequest({url: 'https://api.example.com/process',method: 'POST',retry: {max: 5,backoff: NetworkManager.RETRY_BACKOFF_LINEAR,baseDelay: 2.0,retryOn: [429,500,503]// Rate limiting and server errors}});request.addEventListener('error',(e)=>{console.log('Error:',e.error);console.log('Will retry:',e.willRetry);});request.send();constNetworkManager=require('ti.network.manager');constrequest=NetworkManager.createRequest({url: 'https://api.example.com/critical',method: 'POST',retry: {max: 10,// More retries for critical operationsbackoff: NetworkManager.RETRY_BACKOFF_EXPONENTIAL,baseDelay: 0.5,// Start with shorter delayretryOn: [408,429,500,502,503,504,509]// Extensive retry conditions}});request.send();- Unstable Networks - Handle poor connectivity in mobile apps gracefully without user intervention.
- Critical Transactions - Ensure important operations like payments complete successfully.
- API Rate Limiting - Automatically retry when hitting rate limits with appropriate delays.
- Server Maintenance - Retry during brief server downtime or deployments.
- Background Sync - Reliably sync data even with intermittent connectivity.
Intelligent HTTP caching with multiple strategies and TTL support. Reduce API calls and improve performance.
constNetworkManager=require('ti.network.manager');// Use cached data if available, otherwise fetch from networkconstrequest=NetworkManager.createRequest({url: 'https://api.example.com/movies',method: 'GET',cache: {policy: NetworkManager.CACHE_POLICY_CACHE_FIRST,ttl: 3600// Cache for 1 hour (in seconds)}});request.addEventListener('complete',(e)=>{if(e.cached){console.log('Data loaded from cache');}else{console.log('Data fetched from network');}constmovies=JSON.parse(e.body);displayMovies(movies);});request.send();constNetworkManager=require('ti.network.manager');// Try network first, fallback to cache if network failsconstrequest=NetworkManager.createRequest({url: 'https://api.example.com/news',method: 'GET',cache: {policy: NetworkManager.CACHE_POLICY_NETWORK_FIRST,ttl: 1800// Cache for 30 minutes}});request.send();constNetworkManager=require('ti.network.manager');// Always fetch from network, never use cacheconstrequest=NetworkManager.createRequest({url: 'https://api.example.com/realtime-data',method: 'GET',cache: {policy: NetworkManager.CACHE_POLICY_NETWORK_ONLY}});request.send();constNetworkManager=require('ti.network.manager');// Clear cache for specific domainNetworkManager.clearCache('api.example.com');// Or clear all cacheNetworkManager.clearCache();constNetworkManager=require('ti.network.manager');// Product catalog with 1-hour cacheconstproductsRequest=NetworkManager.createRequest({url: 'https://api.example.com/products',method: 'GET',cache: {policy: NetworkManager.CACHE_POLICY_CACHE_FIRST,ttl: 3600}});productsRequest.addEventListener('complete',(e)=>{constproducts=JSON.parse(e.body);if(e.cached){console.log('Loaded '+products.length+' products from cache');showOfflineIndicator();}else{console.log('Fetched '+products.length+' products from network');}renderProductList(products);});productsRequest.send();// Clear cache when user explicitly refreshesrefreshButton.addEventListener('click',()=>{NetworkManager.clearCache('api.example.com');productsRequest.send();});- Product Catalogs - Cache product listings to reduce API calls and improve browsing speed.
- News Articles - Cache articles for offline reading and faster load times.
- User Profiles - Cache profile data to reduce server load and improve responsiveness.
- Static Content - Cache configuration, translations, and other static data.
- Offline Support - Provide functionality even when network is unavailable.
Upload and download files in the background, even when app is suspended. Includes pause/resume support.
constNetworkManager=require('ti.network.manager');constdownload=NetworkManager.createBackgroundTransfer({type: 'download',url: 'https://api.example.com/files/movie-trailer.mp4',destination: Ti.Filesystem.applicationDataDirectory+'trailer.mp4',headers: {'Authorization': 'Bearer '+getAuthToken()}});download.addEventListener('progress',(e)=>{constpercent=(e.sent/e.total*100).toFixed(1);console.log('Download progress: '+percent+'%');progressBar.value=percent;statusLabel.text='Downloading: '+percent+'%';});download.addEventListener('complete',(e)=>{console.log('Download complete!');console.log('File saved to:',e.path);playVideo(e.path);});download.addEventListener('error',(e)=>{console.error('Download failed:',e.error);});download.start();constNetworkManager=require('ti.network.manager');constvideoFile=Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'recorded-video.mp4');constupload=NetworkManager.createBackgroundTransfer({type: 'upload',url: 'https://api.example.com/videos/upload',file: videoFile.nativePath,headers: {'Authorization': 'Bearer '+getAuthToken(),'Content-Type': 'video/mp4'}});upload.addEventListener('progress',(e)=>{constpercent=(e.sent/e.total*100).toFixed(1);console.log('Upload progress: '+percent+'%');uploadProgress.value=percent;});upload.addEventListener('complete',(e)=>{console.log('Upload complete!');console.log('Response:',e.response);showSuccessMessage('Video uploaded successfully!');});upload.start();constNetworkManager=require('ti.network.manager');constdownload=NetworkManager.createBackgroundTransfer({type: 'download',url: 'https://api.example.com/files/large-file.zip',destination: Ti.Filesystem.applicationDataDirectory+'download.zip'});download.addEventListener('progress',(e)=>{progressBar.value=(e.sent/e.total)*100;});// Start downloaddownload.start();// Pause downloadpauseButton.addEventListener('click',()=>{download.pause();pauseButton.title='Resume';});// Resume downloadpauseButton.addEventListener('click',()=>{download.resume();pauseButton.title='Pause';});// Cancel downloadcancelButton.addEventListener('click',()=>{download.cancel();});constNetworkManager=require('ti.network.manager');constdownload=NetworkManager.createBackgroundTransfer({type: 'download',url: 'https://api.example.com/files/document.pdf',destination: Ti.Filesystem.applicationDataDirectory+'document.pdf'});letretryCount=0;download.addEventListener('error',(e)=>{if(retryCount<3){retryCount++;console.log('Download failed, retrying... ('+retryCount+'/3)');setTimeout(()=>{download.start();},2000);}else{console.error('Download failed after 3 retries');showErrorDialog('Download failed. Please try again later.');}});download.start();- Video Downloads - Download movie trailers, TV episodes, or user-generated content for offline viewing.
- Document Sync - Sync large documents or PDFs in the background without blocking the UI.
- Photo Uploads - Upload photos and videos to cloud storage without keeping app in foreground.
- App Updates - Download app content updates in the background.
- Podcast Downloads - Download podcast episodes for offline listening.
Control which requests get network resources first. Ensure critical operations complete quickly.
constNetworkManager=require('ti.network.manager');// High priority - Critical user actionconstloginRequest=NetworkManager.createRequest({url: 'https://api.example.com/auth/login',method: 'POST',body: JSON.stringify({email: email,password: password}),priority: NetworkManager.PRIORITY_HIGH});// Normal priority - Standard data fetchconstdataRequest=NetworkManager.createRequest({url: 'https://api.example.com/data',method: 'GET',priority: NetworkManager.PRIORITY_NORMAL});// Low priority - Background prefetchconstprefetchRequest=NetworkManager.createRequest({url: 'https://api.example.com/prefetch',method: 'GET',priority: NetworkManager.PRIORITY_LOW});constNetworkManager=require('ti.network.manager');// High priority: User's current actionconstsubmitOrder=NetworkManager.createRequest({url: 'https://api.example.com/orders',method: 'POST',body: JSON.stringify(orderData),priority: NetworkManager.PRIORITY_HIGH});submitOrder.addEventListener('complete',(e)=>{if(e.success){showOrderConfirmation();}});submitOrder.send();// Low priority: Prefetch next page dataconstprefetchNextPage=NetworkManager.createRequest({url: 'https://api.example.com/products?page=2',method: 'GET',priority: NetworkManager.PRIORITY_LOW});prefetchNextPage.send();constNetworkManager=require('ti.network.manager');functionfetchUserData(isUrgent){constrequest=NetworkManager.createRequest({url: 'https://api.example.com/user/profile',method: 'GET',priority: isUrgent ? NetworkManager.PRIORITY_HIGH : NetworkManager.PRIORITY_NORMAL});request.send();}// User clicked profile button - high priorityfetchUserData(true);// Background refresh - normal prioritysetInterval(()=>{fetchUserData(false);},300000);// Every 5 minutes- Payment Processing - Prioritize checkout and payment requests over other operations.
- Search Results - Give high priority to search queries for immediate user feedback.
- Image Loading - Load visible images with high priority, prefetch others with low priority.
- Chat Messages - Prioritize sending and receiving messages over loading history.
- Analytics - Send analytics data with low priority to not affect user experience.
Upload multiple files with per-file progress tracking. Perfect for photo galleries and document uploads.
constNetworkManager=require('ti.network.manager');constimage1=Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'photo1.jpg');constimage2=Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'photo2.jpg');constimage3=Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'photo3.jpg');constupload=NetworkManager.createMultipartUpload({url: 'https://api.example.com/upload/images',headers: {'Authorization': 'Bearer '+getAuthToken()},priority: NetworkManager.PRIORITY_HIGH,fields: [// Text fields{type: 'text',name: 'userId',value: getCurrentUserId()},{type: 'text',name: 'albumId',value: '12345'},// File fields{type: 'file',name: 'image1',filename: 'photo1.jpg',mimeType: 'image/jpeg',data: Ti.Utils.base64encode(image1.read()).text},{type: 'file',name: 'image2',filename: 'photo2.jpg',mimeType: 'image/jpeg',data: Ti.Utils.base64encode(image2.read()).text},{type: 'file',name: 'image3',filename: 'photo3.jpg',mimeType: 'image/jpeg',data: Ti.Utils.base64encode(image3.read()).text}]});// Overall upload progressupload.addEventListener('progress',(e)=>{constpercent=(e.progress*100).toFixed(1);console.log('Overall progress: '+percent+'%');overallProgressBar.value=percent;if(e.currentFile){statusLabel.text='Uploading '+e.currentFile;}});// Individual file progressupload.addEventListener('fileprogress',(e)=>{constpercent=(e.progress*100).toFixed(1);console.log('['+e.filename+'] '+percent+'%');updateFileStatus(e.filename,percent);});upload.addEventListener('complete',(e)=>{if(e.success){console.log('All files uploaded successfully!');showSuccessMessage('Upload complete!');}});upload.upload();constNetworkManager=require('ti.network.manager');constvideoFile=Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'video.mp4');constthumbFile=Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'thumb.jpg');constupload=NetworkManager.createMultipartUpload({url: 'https://api.example.com/videos/upload',headers: {'Authorization': 'Bearer '+getAuthToken()},fields: [{type: 'text',name: 'title',value: 'My Amazing Video'},{type: 'text',name: 'description',value: 'A great video about...'},{type: 'file',name: 'video',filename: 'video.mp4',mimeType: 'video/mp4',data: Ti.Utils.base64encode(videoFile.read()).text},{type: 'file',name: 'thumbnail',filename: 'thumb.jpg',mimeType: 'image/jpeg',data: Ti.Utils.base64encode(thumbFile.read()).text}]});upload.addEventListener('fileprogress',(e)=>{if(e.filename==='video.mp4'){videoProgress.value=e.progress*100;}elseif(e.filename==='thumb.jpg'){thumbProgress.value=e.progress*100;}});upload.upload();constNetworkManager=require('ti.network.manager');constdoc1=Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'report.pdf');constdoc2=Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'data.xlsx');constupload=NetworkManager.createMultipartUpload({url: 'https://api.example.com/documents/upload',fields: [{type: 'text',name: 'projectId',value: 'PROJECT-123'},{type: 'text',name: 'uploadDate',value: newDate().toISOString()},{type: 'file',name: 'document1',filename: 'report.pdf',mimeType: 'application/pdf',data: Ti.Utils.base64encode(doc1.read()).text},{type: 'file',name: 'document2',filename: 'data.xlsx',mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',data: Ti.Utils.base64encode(doc2.read()).text}]});upload.upload();constNetworkManager=require('ti.network.manager');functionuploadProfilePicture(imageBlob){constupload=NetworkManager.createMultipartUpload({url: 'https://api.example.com/user/profile/picture',headers: {'Authorization': 'Bearer '+getAuthToken()},fields: [{type: 'text',name: 'userId',value: getCurrentUserId()},{type: 'file',name: 'avatar',filename: 'avatar.jpg',mimeType: 'image/jpeg',data: Ti.Utils.base64encode(imageBlob).text}]});upload.addEventListener('progress',(e)=>{avatarProgress.value=e.progress*100;});upload.addEventListener('complete',(e)=>{if(e.success){constresponse=JSON.parse(e.body);userAvatar.image=response.avatarUrl;showSuccessMessage('Profile picture updated!');}});upload.upload();}- Photo Gallery Uploads - Upload multiple photos with individual progress tracking for each image.
- Video Sharing - Upload video files with thumbnails and metadata in a single request.
- Document Management - Upload multiple documents with descriptions and tags.
- Profile Updates - Update user profiles with avatar images and additional data.
- Form Submissions - Submit forms with file attachments and structured data.
Automatic support for modern HTTP protocols. Provides better performance through multiplexing and header compression.
⚠️ HTTP/3: Available on iOS 15+, not available on Android (OkHttp 4.x limitation)
HTTP/2 and HTTP/3 support is automatic and requires no special configuration. The module uses URLSession which automatically negotiates the best protocol with the server.
constNetworkManager=require('ti.network.manager');// This request will automatically use HTTP/2 or HTTP/3 if the server supports itconstrequest=NetworkManager.createRequest({url: 'https://api.example.com/data',method: 'GET'});request.addEventListener('complete',(e)=>{console.log('Request completed');// HTTP/2 or HTTP/3 was used automatically if available});request.send();constNetworkManager=require('ti.network.manager');// Make multiple parallel requests - HTTP/2 multiplexing makes this efficientconstrequests=['https://api.example.com/users','https://api.example.com/products','https://api.example.com/orders','https://api.example.com/analytics'];requests.forEach(url=>{constrequest=NetworkManager.createRequest({url: url,method: 'GET'});request.addEventListener('complete',(e)=>{console.log('Loaded:',url);// With HTTP/2, all requests share the same connection// Much faster than HTTP/1.1's connection per request});request.send();});- Parallel Data Loading - Load multiple resources simultaneously with efficient connection reuse.
- Real-time Applications - Reduced latency for time-sensitive operations.
- Mobile Performance - Better battery life and network efficiency.
- Large API Responses - Improved performance for data-heavy applications.
- Future-Proofing - Automatically benefit from protocol improvements.
Real-time bidirectional communication. Perfect for chat applications, live updates, and collaborative features.
constNetworkManager=require('ti.network.manager');constws=NetworkManager.createWebSocket({url: 'wss://api.example.com/realtime',headers: {'Authorization': 'Bearer '+getAuthToken()}});ws.addEventListener('open',()=>{console.log('WebSocket connected!');// Send a messagews.send(JSON.stringify({action: 'subscribe',channel: 'notifications'}));});ws.addEventListener('message',(e)=>{console.log('Message received:',e.data);constdata=JSON.parse(e.data);handleNotification(data);});ws.addEventListener('close',(e)=>{console.log('WebSocket closed');console.log('Code:',e.code);console.log('Reason:',e.reason);});ws.addEventListener('error',(e)=>{console.error('WebSocket error:',e.error);});ws.connect();constNetworkManager=require('ti.network.manager');constchatWS=NetworkManager.createWebSocket({url: 'wss://api.example.com/chat',headers: {'Authorization': 'Bearer '+getAuthToken()}});chatWS.addEventListener('open',()=>{console.log('Connected to chat server');statusLabel.text='Online';statusLabel.color='green';// Join chat roomchatWS.send(JSON.stringify({type: 'join',roomId: currentRoomId,userId: getCurrentUserId()}));});chatWS.addEventListener('message',(e)=>{constmessage=JSON.parse(e.data);switch(message.type){case'message':
displayMessage(message.user,message.text,message.timestamp);break;case'user_joined':
showNotification(message.user+' joined the chat');break;case'user_left':
showNotification(message.user+' left the chat');break;case'typing':
showTypingIndicator(message.user);break;}});// Send messagesendButton.addEventListener('click',()=>{consttext=messageInput.value;chatWS.send(JSON.stringify({type: 'message',text: text,timestamp: newDate().toISOString()}));messageInput.value='';});// Send typing indicatormessageInput.addEventListener('change',()=>{chatWS.send(JSON.stringify({type: 'typing',userId: getCurrentUserId()}));});chatWS.connect();constNetworkManager=require('ti.network.manager');constws=NetworkManager.createWebSocket({url: 'wss://api.example.com/live'});ws.addEventListener('open',()=>{console.log('WebSocket connected');// Send ping every 30 seconds to keep connection alivesetInterval(()=>{ws.ping();},30000);});ws.addEventListener('pong',()=>{console.log('Pong received - connection alive');});ws.connect();constNetworkManager=require('ti.network.manager');constws=NetworkManager.createWebSocket({url: 'wss://api.example.com/binary'});ws.addEventListener('open',()=>{// Send binary data (base64 encoded)constimageFile=Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'image.jpg');constbase64Data=Ti.Utils.base64encode(imageFile.read()).text;ws.sendBinary(base64Data);});ws.addEventListener('binary',(e)=>{// Receive binary data (base64 encoded)console.log('Binary data received');constdata=Ti.Utils.base64decode(e.data);// Process binary data});ws.connect();constNetworkManager=require('ti.network.manager');letreconnectAttempts=0;constmaxReconnectAttempts=5;functionconnectWebSocket(){constws=NetworkManager.createWebSocket({url: 'wss://api.example.com/live'});ws.addEventListener('open',()=>{console.log('WebSocket connected');reconnectAttempts=0;statusIndicator.backgroundColor='green';});ws.addEventListener('close',(e)=>{console.log('WebSocket closed');statusIndicator.backgroundColor='red';// Attempt to reconnectif(reconnectAttempts<maxReconnectAttempts){reconnectAttempts++;constdelay=Math.min(1000*Math.pow(2,reconnectAttempts),30000);console.log('Reconnecting in '+(delay/1000)+' seconds...');setTimeout(()=>{connectWebSocket();},delay);}else{console.log('Max reconnection attempts reached');showErrorMessage('Unable to connect. Please check your connection.');}});ws.addEventListener('error',(e)=>{console.error('WebSocket error:',e.error);});ws.connect();returnws;}constwebsocket=connectWebSocket();- Chat Applications - Real-time messaging with instant delivery and typing indicators.
- Live Notifications - Push notifications for order updates, social interactions, or system alerts.
- Collaborative Editing - Real-time document collaboration with multiple users.
- Live Sports Scores - Instant updates for sports events and games.
- Stock Trading - Real-time stock prices and trading information.
Create a standard HTTP request.
Parameters:
url(String) - The request URLmethod(String) - HTTP method (GET, POST, PUT, DELETE, etc.)headers(Object) - Request headersbody(String) - Request bodypriority(String) - Priority level (PRIORITY_HIGH, PRIORITY_NORMAL, PRIORITY_LOW)cache(Object) - Cache configurationpolicy(String) - Cache policyttl(Number) - Time to live in seconds
retry(Object) - Retry configurationmax(Number) - Maximum retry attemptsbackoff(String) - Backoff strategybaseDelay(Number) - Base delay in secondsretryOn(Array) - HTTP status codes to retry on
Returns:TNMRequestProxy
Events:
progress- Upload/download progresscomplete- Request completederror- Request failedcancelled- Request cancelled
Create a streaming HTTP request for SSE.
Parameters:
url(String) - The request URLmethod(String) - HTTP methodheaders(Object) - Request headersbody(String) - Request bodypriority(String) - Priority level
Returns:TiHTTPStreamProxy
Events:
chunk- Data chunk receivedcomplete- Stream completederror- Stream errorcancelled- Stream cancelled
Create a WebSocket connection.
Parameters:
url(String) - WebSocket URL (wss:// or ws://)headers(Object) - Connection headers
Returns:TNMWebSocketProxy
Events:
open- Connection openedmessage- Text message receivedbinary- Binary message receivedpong- Pong response receivedclose- Connection closederror- Connection error
Create a background transfer (download or upload).
Parameters:
type(String) - Transfer type ('download' or 'upload')url(String) - The request URLdestination(String) - Download destination path (for downloads)file(String) - Upload file path (for uploads)headers(Object) - Request headers
Returns:TNMBackgroundTransferProxy
Events:
progress- Transfer progresscomplete- Transfer completederror- Transfer errorpaused- Transfer pausedresumed- Transfer resumedcancelled- Transfer cancelled
Create a multipart upload request.
Parameters:
url(String) - The request URLheaders(Object) - Request headerspriority(String) - Priority levelfields(Array) - Array of field objects- Text field:
{ type: 'text', name: String, value: String } - File field:
{ type: 'file', name: String, filename: String, mimeType: String, data: String }
- Text field:
Returns:TNMMultipartUploadProxy
Events:
progress- Overall upload progressfileprogress- Individual file progresscomplete- Upload completederror- Upload errorcancelled- Upload cancelled
Configure certificate pinning for a domain.
Parameters:
domain(String) - Domain to pinhashes(Array) - Array of SHA-256 certificate hashes
Add a global request interceptor.
Parameters:
callback(Function) - Interceptor function that receives and returns config object
Add a global response interceptor.
Parameters:
callback(Function) - Interceptor function that receives and returns response object
Clear cached responses.
Parameters:
domain(String, optional) - Clear cache for specific domain, or all cache if omitted
PRIORITY_HIGH- High priority (0.75)PRIORITY_NORMAL- Normal priority (0.5)PRIORITY_LOW- Low priority (0.25)
CACHE_POLICY_NETWORK_ONLY- Never use cacheCACHE_POLICY_CACHE_FIRST- Use cache if available, otherwise networkCACHE_POLICY_NETWORK_FIRST- Try network first, fallback to cache
RETRY_BACKOFF_LINEAR- Linear backoff (1x, 2x, 3x, 4x...)RETRY_BACKOFF_EXPONENTIAL- Exponential backoff (1x, 2x, 4x, 8x...)
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request