This document describes the migration from AFNetworking to Alamofire in the @nativescript-community/https plugin for iOS.
- Modern API: Alamofire provides a more modern, Swift-first API
- Better Maintenance: Alamofire is actively maintained with regular updates
- Security: Latest security features and SSL/TLS improvements
- Performance: Better performance characteristics in modern iOS versions
Before:
pod 'AFNetworking', :git => 'https://github.com/nativescript-community/AFNetworking'After:
pod 'Alamofire', '~> 5.9'Since Alamofire doesn't expose its APIs to Objective-C (no @objc annotations), we created Swift wrapper classes that bridge between NativeScript's Objective-C runtime and Alamofire:
- Main session manager wrapper
- Handles all HTTP requests (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)
- Manages upload/download progress callbacks
- Handles multipart form data uploads
- NEW: Streaming downloads for memory-efficient file downloads
- Clean, simplified API method names
- Implements error handling compatible with AFNetworking
- SSL/TLS security policy management
- Certificate pinning (public key and certificate modes)
- Domain name validation
- Implements
ServerTrustEvaluatingprotocol from Alamofire
- Wrapper for Alamofire's MultipartFormData
- Supports file uploads (URL and Data)
- Supports form field data
- Embedded in AlamofireWrapper.swift
- Handle request configuration (timeout, cache policy, cookies)
- Handle response deserialization (JSON and raw data)
The TypeScript implementation in src/https/request.ios.ts was updated to use the new Swift wrappers:
- Replaced
AFHTTPSessionManagerwithAlamofireWrapper - Replaced
AFSecurityPolicywithSecurityPolicyWrapper - Replaced
AFMultipartFormDatawithMultipartFormDataWrapper - Updated serializer references to use wrapper properties
- Added error key constants for AFNetworking compatibility
- NEW: Simplified method names for cleaner API
- NEW: Added
downloadFilePathoption for streaming downloads
Key changes:
- Manager initialization:
AlamofireWrapper.alloc().initWithConfiguration(configuration) - Security policy:
SecurityPolicyWrapper.defaultPolicy() - SSL pinning:
SecurityPolicyWrapper.policyWithPinningMode(AFSSLPinningMode.PublicKey) - HTTP requests:
manager.request(method, url, params, headers, uploadProgress, downloadProgress, success, failure) - Multipart uploads:
manager.uploadMultipart(url, headers, formBuilder, progress, success, failure) - Streaming downloads:
manager.downloadToFile(url, destinationPath, headers, progress, completionHandler)
All features from the AFNetworking implementation have been preserved and enhanced:
- GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
- All tested and working
- Upload progress tracking
- Download progress tracking
- Main thread / background thread dispatch
- multipart/form-data uploads
- application/x-www-form-urlencoded
- File uploads (File, NSURL, NSData, ArrayBuffer, Blob)
- Text form fields
- Certificate pinning (public key mode)
- Certificate pinning (certificate mode)
- Domain name validation
- Allow invalid certificates option
- noCache - prevent response caching
- onlyCache - return cached response only
- ignoreCache - ignore local cache
- Default - use protocol cache policy
- In-memory cookie storage
- Enable/disable cookies per request
- Shared HTTP cookie storage
- Custom headers
- Request timeout
- Cellular access control
- Request tagging for cancellation
- JSON deserialization
- Raw data responses
- Image conversion (UIImage)
- File saving via
.toFile()method - Error handling with status codes
Behavior: Response data is loaded into memory as NSData (matching Android OkHttp). Users inspect status code and headers, then decide to call .toFile(), .toArrayBuffer(), etc.
All Swift wrapper methods now use simplified, more intuitive names:
request()instead ofdataTaskWithHTTPMethod...uploadMultipart()instead ofPOSTParametersHeaders...uploadFile()instead ofuploadTaskWithRequestFromFile...uploadData()instead ofuploadTaskWithRequestFromData...
iOS now matches Android's response handling:
import { request } from '@nativescript-community/https';
// Request completes and returns with status/headers/data
const response = await request({
method: 'GET',
url: 'https://example.com/file.zip'
});
// Inspect response first
console.log('Status:', response.statusCode);
console.log('Headers:', response.headers);
// Then decide what to do with the data
const file = await response.content.toFile('/path/to/save/file.zip');
// OR
const buffer = await response.content.toArrayBuffer();
// OR
const json = response.content.toJSON();Benefits:
- Same behavior on iOS and Android
- Inspect status/headers before processing data
- Flexible response handling
- Simple, predictable API
The TypeScript API remains 100% compatible with the previous AFNetworking implementation. No changes are required in application code that uses this plugin.
After upgrading, test the following scenarios:
-
Basic Requests
- GET requests with query parameters
- POST requests with JSON body
- PUT/DELETE/PATCH requests
-
SSL Pinning
- Enable SSL pinning with a certificate
- Test with valid and invalid certificates
- Verify domain name validation
-
File Uploads
- Single file upload
- Multiple files in multipart form
- Large file uploads with progress tracking
-
File Downloads
- Small file downloads (traditional method)
- Large file downloads with streaming (using
downloadFilePath) - Progress tracking during downloads
- Memory usage with large files
-
Progress Callbacks
- Upload progress for large payloads
- Download progress for large responses
-
Cache Policies
- Test each cache mode (noCache, onlyCache, ignoreCache)
- Verify cache behavior matches expectations
-
Error Handling
- Network errors (timeout, no connection)
- HTTP errors (4xx, 5xx)
- SSL errors (certificate mismatch)
None. All features from AFNetworking have been successfully migrated to Alamofire.
Users of this plugin do NOT need to make any code changes. Simply update to the new version:
ns plugin remove @nativescript-community/https
ns plugin add @nativescript-community/https@latestThen rebuild the iOS platform:
ns clean
ns build iosThe Swift wrapper creates NSError objects with the same userInfo keys as AFNetworking:
AFNetworkingOperationFailingURLResponseErrorKey- Contains the HTTPURLResponseAFNetworkingOperationFailingURLResponseDataErrorKey- Contains response dataNSErrorFailingURLKey- Contains the failing URL
This ensures error handling code in TypeScript continues to work without changes.
Swift method names were created to match AFNetworking's Objective-C method signatures:
dataTaskWithHTTPMethodURLStringParametersHeadersUploadProgressDownloadProgressSuccessFailurePOSTParametersHeadersConstructingBodyWithBlockProgressSuccessFailureuploadTaskWithRequestFromFileProgressCompletionHandleruploadTaskWithRequestFromDataProgressCompletionHandler
Alamofire's Progress objects are compatible with NSProgress, so no conversion is needed for progress callbacks.
Potential improvements that could be made in future versions:
- Async/Await Support - Leverage Swift's modern concurrency
- Combine Integration - For reactive programming patterns
- Request Interceptors - More powerful request/response interception
- Custom Response Serializers - Plugin architecture for custom data types
- Metrics Collection - URLSessionTaskMetrics integration
For issues or questions:
- GitHub Issues: https://github.com/nativescript-community/https/issues
- Discord: NativeScript Community
- Original AFNetworking implementation by Eddy Verbruggen, Kefah BADER ALDIN, Ruslan Lekhman
- Alamofire migration by GitHub Copilot Agent