This directory contains Swift wrapper classes that bridge between NativeScript's Objective-C runtime and Alamofire's Swift-only API.
Main session manager that wraps Alamofire's Session class.
This directory contains Swift wrapper classes that bridge between NativeScript's Objective-C runtime and Alamofire's Swift-only API.
Main session manager that wraps Alamofire's Session class.
Key Features:
- HTTP request methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)
- Upload/download progress tracking
- Multipart form data uploads
- File uploads
- Request/response serialization
- Security policy integration
- Cache policy management
@objc Methods (Clean API):
request(method:urlString:parameters:headers:uploadProgress:downloadProgress:success:failure:)- General HTTP requestsuploadMultipart(urlString:headers:constructingBodyWithBlock:progress:success:failure:)- Multipart form uploaduploadFile(request:fileURL:progress:completionHandler:)- File uploaduploadData(request:bodyData:progress:completionHandler:)- Data upload
Note: Response data is loaded into memory as NSData, matching Android OkHttp behavior. Users can inspect status code and headers, then decide to call .toFile(), .toArrayBuffer(), etc.
SSL/TLS security policy wrapper that implements Alamofire's ServerTrustEvaluating protocol.
Key Features:
- Certificate pinning (public key and certificate modes)
- Domain name validation
- Invalid certificate handling
- Compatible with AFSecurityPolicy API
Pinning Modes:
- 0 = None (default validation)
- 1 = PublicKey (pin to public keys)
- 2 = Certificate (pin to certificates)
Wrapper for Alamofire's EventMonitor protocol to enable network event tracking from TypeScript.
Key Features:
- Request lifecycle tracking (resume, suspend, cancel, finish)
- Data reception monitoring
- Request completion tracking with response/error
- @objc-compatible callback-based API
Available Callbacks:
setRequestDidResume- Called when request startssetRequestDidSuspend- Called when request is pausedsetRequestDidCancel- Called when request is cancelledsetRequestDidFinish- Called when request finishessetRequestDidComplete- Called with response/errorsetDataTaskDidReceiveData- Called as data is received
Wrapper for Alamofire's RequestInterceptor protocol to enable request modification and retry logic from TypeScript.
Key Features:
- Request adaptation (modify requests before sending)
- Automatic retry logic with custom conditions
- @objc-compatible callback-based API
Available Callbacks:
setAdapt- Modify URLRequest before sendingsetRetry- Return true to retry failed requests
Wrapper for building multipart form data requests.
Key Features:
- File uploads (URL and Data)
- Form field data
- Custom MIME types
- Multiple parts support
@objc Methods:
appendPartWithFileURLNameFileNameMimeTypeError- Add file from URLappendPartWithFileDataNameFileNameMimeType- Add file from DataappendPartWithFormDataName- Add text field
// Initialize manager
const configuration = NSURLSessionConfiguration.defaultSessionConfiguration;
const manager = AlamofireWrapper.alloc().initWithConfiguration(configuration);
// Configure serializers
manager.requestSerializerWrapper.timeoutInterval = 30;
manager.requestSerializerWrapper.httpShouldHandleCookies = true;
// Set security policy
const policy = SecurityPolicyWrapper.policyWithPinningMode(AFSSLPinningMode.PublicKey);
policy.allowInvalidCertificates = false;
policy.validatesDomainName = true;
manager.securityPolicyWrapper = policy;
// Make a request (clean API)
const task = manager.request(
'GET',
'https://api.example.com/data',
null,
headers,
uploadProgress,
downloadProgress,
success,
failure
);
task.resume();
// Response data is available in memory
// User can then call toFile(), toArrayBuffer(), etc. on the response// Create an event monitor to track network events
const eventMonitor = EventMonitorWrapper.alloc().init();
eventMonitor.setRequestDidResume((request) => {
console.log('Request started:', request.URL.absoluteString);
});
eventMonitor.setDataTaskDidReceiveData((request, data) => {
console.log('Received data:', data.length, 'bytes');
});
eventMonitor.setRequestDidComplete((request, response, error) => {
if (error) {
console.log('Request failed:', error.localizedDescription);
} else {
console.log('Request completed:', response.statusCode);
}
});
manager.addEventMonitor(eventMonitor);
// Create a request interceptor to modify requests and retry logic
const interceptor = RequestInterceptorWrapper.alloc().init();
interceptor.setAdapt((request) => {
// Add custom headers to all requests
const mutableRequest = request.mutableCopy();
mutableRequest.setValueForHTTPHeaderField('CustomToken', 'Authorization');
return mutableRequest;
});
interceptor.setRetry((request, error, retryCount) => {
// Retry up to 3 times on network errors
if (retryCount < 3) {
console.log(`Retrying request (attempt ${retryCount + 1})...`);
return true;
}
return false;
});
manager.addInterceptor(interceptor);Alamofire is a pure Swift library that doesn't expose its APIs to Objective-C. NativeScript's iOS runtime uses Objective-C bridging to call native code from JavaScript/TypeScript. These wrapper classes bridge the gap by:
- Using
@objcand@objcMembersto expose Swift classes to Objective-C - Converting between Swift types and Objective-C types
- Maintaining API compatibility with AFNetworking
Method names have been simplified from AFNetworking's verbose Objective-C conventions to cleaner, more Swift-like names:
request()- General HTTP requests (previouslydataTaskWithHTTPMethodURLStringParametersHeadersUploadProgressDownloadProgressSuccessFailure)uploadMultipart()- Multipart form uploads (previouslyPOSTParametersHeadersConstructingBodyWithBlockProgressSuccessFailure)uploadFile()- File uploads (previouslyuploadTaskWithRequestFromFileProgressCompletionHandler)uploadData()- Data uploads (previouslyuploadTaskWithRequestFromDataProgressCompletionHandler)
Response data is loaded into memory as NSData (matching Android OkHttp behavior). This allows users to:
- Inspect status code and headers immediately after request completes
- Decide whether to call
.toFile(),.toArrayBuffer(),.toJSON(), etc. - Have consistent behavior across iOS and Android platforms
Note: For large downloads, data will be loaded into memory. This matches Android's behavior where the response body is available and can be written to file when toFile() is called.
Errors are wrapped in NSError objects with userInfo dictionaries that match AFNetworking's error structure. This ensures existing error handling code continues to work.
Alamofire's Progress objects are compatible with Foundation's Progress class (which bridges to NSProgress in Objective-C), so no conversion is needed.
These Swift files are compiled as part of the NativeScript iOS build process. They are automatically included when the plugin is installed in a NativeScript project.
Requirements:
- Xcode 14.0+
- Swift 5.7+
- iOS 12.0+
- Alamofire 5.9+
All request methods accept callbacks that are executed on the main queue by default. This matches AFNetworking's behavior and ensures UI updates can be safely made from callbacks.
To test these wrappers:
- Install the plugin in a NativeScript app
- Build for iOS:
ns build ios - Run the app:
ns run ios - Test various request types and observe behavior
When modifying these files:
- Maintain @objc compatibility
- Keep method signatures matching AFNetworking where possible
- Test all request types (GET, POST, multipart, uploads)
- Verify SSL pinning still works
- Check progress callbacks function correctly
See LICENSE file in the repository root.