Swiftpack.co - Package - MLSDev/TRON

Build Status   codecov.io CocoaPod platform   CocoaPod version   Carthage compatible Packagist

TRON is a lightweight network abstraction layer, built on top of Alamofire. It can be used to dramatically simplify interacting with RESTful JSON web-services.


  • [x] Generic, protocol-based implementation
  • [x] Built-in response and error parsing
  • [x] Support for any custom mapper (SwiftyJSON implementation provided). Defaults to Codable protocol.
  • [x] Support for upload tasks
  • [x] Support for download tasks and resuming downloads
  • [x] Robust plugin system
  • [x] Stubbing of network requests
  • [x] Modular architecture
  • [x] Support for iOS/Mac OS X/tvOS/watchOS/Linux
  • [x] Support for CocoaPods/Carthage/Swift Package Manager
  • [x] RxSwift extension
  • [x] Complete documentation


We designed TRON to be simple to use and also very easy to customize. After initial setup, using TRON is very straightforward:

let request: APIRequest<User,APIError> = tron.codable.request("me")
request.perform(withSuccess: { user in
  print("Received User: \(user)")
}, failure: { error in
  print("User request failed, parsed error: \(error)")


  • Xcode 10 and higher
  • Swift 4 and higher
  • iOS 10 / macOS 10.12 / tvOS 10.0 / watchOS 3.0



pod 'TRON', '~> 5.0.0-beta.1'

Only Core subspec, without SwiftyJSON dependency:

pod 'TRON/Core', '~> 5.0.0-beta.1'

RxSwift extension for TRON:

pod 'TRON/RxSwift', '~> 5.0.0-beta.1'


github "MLSDev/TRON", ~> 5.0.0-beta.1

Migration Guides

Project status

TRON is under active development by MLSDev Inc. Pull requests are welcome!

Request building

TRON object serves as initial configurator for APIRequest, setting all base values and configuring to use with baseURL.

let tron = TRON(baseURL: "https://api.myapp.com/")

You need to keep strong reference to TRON object, because it holds Alamofire.Manager, that is running all requests.


URLBuildable protocol is used to convert relative path to URL, that will be used by request.

public protocol URLBuildable {
    func url(forPath path: String) -> URL

By default, TRON uses URLBuilder class, that simply appends relative path to base URL, which is sufficient in most cases. You can customize url building process globally by changing urlBuilder property on TRON or locally, for a single request by modifying urlBuilder property on APIRequest.

Sending requests

To send APIRequest, call perform(withSuccess:failure:) method on APIRequest:

let alamofireRequest = request.perform(withSuccess: { result in }, failure: { error in})

Alternatively, you can use performCollectingTimeline(withCompletion:) method that contains Alamofire.Response inside completion closure:

request.performCollectingTimeline(withCompletion: { response in

In both cases, you can additionally chain Alamofire.Request methods, if you need:

request.perform(withSuccess: { result in }, failure: { error in }).progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
    print(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)

Response parsing

Generic APIRequest implementation allows us to define expected response type before request is even sent. On top of Alamofire DataResponseSerializerProtocol, we are adding one additional protocol for error-handling.

public protocol DataResponseSerializerProtocol {
    associatedtype SerializedObject

    public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Self.SerializedObject

public protocol ErrorSerializable: Error {
    init?(serializedObject: Any?, request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?)


Parsing models using Swift4 Codable protocol is simple, implement Codable protocol:

struct User: Codable {
  let name : String
  let id: Int

And send a request:

let request: APIRequest<User,APIError> = tron.codable.request("me")
request.perform(withSuccess: { user in
  print("Received user: \(user.name) with id: \(user.id)")

It's possible to customize decoders for both model and error parsing:

let userDecoder = JSONDecoder()

let request : APIRequest<User,APIError> = tron.codable(modelDecoder: userDecoder).request("me")


TRON provides JSONDecodable protocol, that allows us to parse models using SwiftyJSON:

public protocol JSONDecodable {
    init(json: JSON) throws

To parse your response from the server using SwiftyJSON, all you need to do is to create JSONDecodable conforming type, for example:

class User: JSONDecodable {
  let name : String
  let id: Int

  required init(json: JSON) {
    name = json["name"].stringValue
    id = json["id"].intValue

And send a request:

let request: APIRequest<User,MyAppError> = tron.swiftyJSON.request("me")
request.perform(withSuccess: { user in
  print("Received user: \(user.name) with id: \(user.id)")

There are also default implementations of JSONDecodable protocol for Swift built-in types like String, Int, Float, Double and Bool, so you can easily do something like this:

let request : APIRequest<String,APIError> = tron.swiftyJSON.request("status")
request.perform(withSuccess: { status in
    print("Server status: \(status)") //

You can also use Alamofire.Empty struct in cases where you don't care about actual response.

Some concepts for response serialization, including array response serializer, are described in Response Serializers document

It's possible to customize JSONSerialization.ReadingOptions, that are used by SwiftyJSON.JSON object while parsing data of the response:

let request : APIRequest<String, APIError> = tron.swiftyJSON(readingOptions: .allowFragments).request("status")


let request : APIRequest<Foo, APIError> = tron.codable.request("foo")
_ = request.rxResult().subscribe(onNext: { result in
let multipartRequest : UploadAPIREquest<Foo,APIError> = tron.codable.upload("foo", formData: { _ in })
multipartRequest.rxMultipartResult().subscribe(onNext: { result in

Error handling

TRON includes built-in parsing for errors. APIError is an implementation of ErrorSerializable protocol, that includes several useful properties, that can be fetched from unsuccessful request:

request.perform(withSuccess: { response in }, failure: { error in
    print(error.request) // Original URLRequest
    print(error.response) // HTTPURLResponse
    print(error.data) // Data of response
    print(error.fileURL) // Downloaded file url, if this was a download request
    print(error.error) // Error from Foundation Loading system
    print(error.serializedObject) // Object that was serialized from network response


struct Users
    static let tron = TRON(baseURL: "https://api.myapp.com")

    static func create() -> APIRequest<User,APIError> {
        let request: APIRequest<User,MyAppError> = tron.codable.request("users")
        request.method = .post
        return request

    static func read(id: Int) -> APIRequest<User, APIError> {
        return tron.codable.request("users/\(id)")

    static func update(id: Int, parameters: [String:Any]) -> APIRequest<User, APIError> {
        let request: APIRequest<User,MyAppError> = tron.codable.request("users/\(id)")
        request.method = .put
        request.parameters = parameters
        return request

    static func delete(id: Int) -> APIRequest<User,APIError> {
        let request: APIRequest<User,MyAppError> = tron.codable.request("users/\(id)")
        request.method = .delete
        return request

Using these requests is really simple:

Users.read(56).perform(withSuccess: { user in
  print("received user id 56 with name: \(user.name)")

It can be also nice to introduce namespacing to your API:

enum API {}
extension API {
  enum Users {
    // ...

This way you can call your API methods like so:

API.Users.delete(56).perform(withSuccess: { user in
  print("user \(user) deleted")


Stubbing is built right into APIRequest itself. All you need to stub a successful request is to set apiStub property and turn stubbingEnabled on:

let request = API.Users.get(56)
request.apiStub = APIStub(data: User.fixture().asData)
request.apiStub.isEnabled = true

request.perform(withSuccess: { stubbedUser in
  print("received stubbed User model: \(stubbedUser)")

Stubbing can be enabled globally on TRON object or locally for a single APIRequest. Stubbing unsuccessful requests is easy as well:

let request = API.Users.get(56)
request.apiStub = APIStub(error: CustomError())
request.perform(withSuccess: { _ in }, failure: { error in
  print("received stubbed api error")

You can also optionally delay stubbing time:

request.apiStub.stubDelay = 1.5


  • From file:
let request = tron.codable.upload("photo", fromFileAt: fileUrl)
  • Data:
let request = tron.codable.upload("photo", data: data)
  • Stream:
let request = tron.codable.upload("photo", fromStream: stream)
  • Multipart-form data:
let request: UploadAPIRequest<EmptyResponse,MyAppError> = tron.codable.uploadMultipart("form") { formData in
    formData.append(data, withName: "cat", mimeType: "image/jpeg")
request.perform(withSuccess: { result in
    print("form sent successfully")


let responseSerializer = TRONDownloadResponseSerializer { _,_, url,_ in url }
let request: DownloadAPIRequest<URL?, APIError> = tron.download("file",
                                                                to: destination,
                                                                responseSerializer: responseSerializer)


TRON includes plugin system, that allows reacting to most of request events.

Plugins can be used globally, on TRON instance itself, or locally, on concrete APIRequest. Keep in mind, that plugins that are added to TRON instance, will be called for each request. There are some really cool use-cases for global and local plugins.

By default, no plugins are used, however two plugins are implemented as a part of TRON framework.


NetworkActivityPlugin serves to monitor requests and control network activity indicator in iPhone status bar. This plugin assumes you have only one TRON instance in your application.

let tron = TRON(baseURL: "https://api.myapp.com", plugins: [NetworkActivityPlugin()])


NetworkLoggerPlugin is used to log responses to console in readable format. By default, it prints only failed requests, skipping requests that were successful.

Local plugins

There are some very cool concepts for local plugins, some of them are described in dedicated PluginConcepts page.


We are dedicated to building best possible tool for interacting with RESTful web-services. However, we understand, that every tool has it's purpose, and therefore it's always useful to know, what other tools can be used to achieve the same goal.

TRON was heavily inspired by Moya framework and LevelUPSDK


TRON is released under the MIT license. See LICENSE for details.

About MLSDev


TRON is maintained by MLSDev, Inc. We specialize in providing all-in-one solution in mobile and web development. Our team follows Lean principles and works according to agile methodologies to deliver the best results reducing the budget for development and its timeline.

Find out more here and don't hesitate to contact us!


Stars: 479
Help us keep the lights on


5.0.0-beta.3 - May 17, 2019


  • Ability to traverse json to any level when using SwiftyJSONDecodable.


  • Improved response serializer behavior for cases where requests were stubbed using URLProtocol.
  • TRON 5 requires RxSwift 5 and SwiftyJSON 5
  • Core is now a default subspec for CocoaPods installation method. To use SwiftyJSON, add following to Podfile:
pod 'TRON/SwiftyJSON'

4.2.2 - Apr 8, 2019

  • Swift 4.2 version is now specified in podspec for users of CocoaPods 1.6.x.

This is the last release that supports Xcode 9 and Swift 3.

5.0.0-beta.2 - Apr 6, 2019


  • ErrorSerializable protocol changed to have non-optional initializer and to not accept serializedObject. It no longer can be used for additional object validation, but behavior should be more predictable and straightforward - ErrorSerializable should only be created if somebody (URL loading system, Alamofire or Model serialization) actually reported error.
  • codable is now a lazy stored property instead of computed property.
  • CodableSerializer API has been made open to allow easy customization in subclasses.
  • NetworkLoggerPlugin now has a constructor that allows to easily configure it's behavior.


  • Properties that worked with Alamofire.SessionManager have been renamed to session to be in line with Alamofire renaming of SessionManager to Session.


  • TRON.defaultAlamofireManager() method. TRON initializer now uses Alamofire.Session.default as a replacement.
  • TRON.processingQueue property

5.0.0-beta.1 - Mar 12, 2019

TRON now requires:

  • Xcode 10
  • Swift 4 and higher
  • iOS/tvOS 10 and higher
  • watchOS 3 and higher
  • macOS 10.12 and higher


  • Complete documentation
  • TRONDataResponseSerializer and TRONDownloadResponseSerializer structs to encapsulate serialization of responses using closure.
  • All test suite now uses StubbingURLProtocol to stop tests from sending network requests. Closes #21.
  • Additional JSONDecodable conformances have been added for arithmetic types such as Int8...Int64, UInt8...64.


  • EmptyResponse type was replaced with Alamofire.Empty struct to not interfere with Alamofire.EmptyResponse protocol.
  • TRON.stubbingShouldBeSuccessful property since now each stub directly defines it's behavior instead of global setting
  • Conditional conformance of Array to JSONDecodable
  • Convenience download methods on CodableSerializer and JSONDecodableSerializer
  • AuthorizationRequirement enum. Please use Alamofire.RequestAdapter and Session.adapter property to adapt request, when additional headers are needed.
  • HeaderBuildable protocol and HeaderBuilder types. Please use BaseRequest.headers property of type Alamofire.HTTPHeaders directly.
  • ErrorHandlingDataResponseSerializerProtocol and ErrorHandlingDownloadResponseSerializer protocol. Now, ErrorModel on all requests conforms to ErrorSerializable protocol, that contains initializer that allows to create it directly.
  • CodableDownloadParser and JSONDecodableDownloadParser, replacement class DownloadSerializer has been introduced, it allows to create a data model by implementing DownloadResponseSerializerProtocol


  • headers property of BaseRequest now contains HTTPHeaders type instead of [String: String]. Please note that along with HeaderBuilder removal TRON no longer sends 'Accept':'application/json' header by default.
  • APIError is changed to be able to accept SerializedObject and is now a class with nullable initializer. Also, DownloadAPIError type has been introduced for download errors, that do not have Data in them, but have fileURL instead.
  • Plugin methods that previously accepted APIError<ErrorModel> now accept ErrorModel directly. Added didSuccessfullyParseDownloadResponse and didReceiveDownloadResponse methods.
  • All concrete implementations of DataResponseSerializerProtocol such as CodableParser and JSONDecodableParser now have only one generic argument - Model and are only parsing model type.
  • JSONDecodableParser and CodableParser now have only one generic argument - Model, since ErrorModel is now moved to ErrorSerializable protocol, that does not depend on any particular serializer.
  • APIStub has been rewritten from scratch to allow injecting only results of network request(URLRequest, HTTPURLResponse, Data, Error and fileURL) as opposed to actual Model and errorModel as well as definition of successful/unsuccessful requests. APIStub now is been attached to Alamofire.Request when stubbing for this particular request has been enabled. Rewrite also allows plugin callbacks to be called more consistently for both stubbed and unstubbed cases.
  • rxMultipartResult method on UploadRequest method was removed since UploadRequest for multipart requests in Alamofire 5 is now synchronous and now does not require special handling. You can now call rxResult replacement method instead.

4.2.0 - Apr 12, 2018

  • Implemented JSONDecodable support for Arrays, whose Element is JSONDecodable. Requires Swift 4.1 to work.