Nate Stedman

Networking with µframeworks

March 3rd, 2016

There’s a few different components to a networking stack for an iOS app:

  • Describing request parameters in a programmer-friendly manner (NSURLQueryItem, to some extent).
  • Encoding those parameters to URL request values (NSURLRequest).
  • Sending URL requests (NSURLSession).
  • Handling conditions that may arise during requests (NSURLSessionDelegate).
  • Decoding response values (NSURLResponse/NSHTTPURLResponse, NSData).
  • Delivering the data to clients asynchronously (callback functions).

Most iOS networking frameworks provide all of these, calling out to NSURLSession internally. I’m interested in building small frameworks that provide a single component and communicate in a relatively standard way, so that they can be composed with other frameworks of the developer’s choice. Smaller frameworks tend to be easier to understand, and the Swift Package Manager documentation suggests that they are preferable:

As a rule of thumb: more modules is probably better than fewer modules.

Current Frameworks

For asynchronous data delivery, I prefer ReactiveCocoa, which allows asynchronous values to be represented as a value, passed around, and composed, an huge improvement over callback functions. While ReactiveCocoa isn’t a small framework, its use in networking is mostly limited to the SignalProducer type, which is fairly simple to understand.

Although ReactiveCocoa provides some basic integration with NSURLSession, I’ve written Shirley to provide more direct integration. Shirley allows networking sessions to take in requests and output asynchronous data, with shared transformations applied on various stages of the process. Shirley only extends the functionality of NSURLSession, so delegate behavior can be applied independently.

For describing URL requests, I’ve built Endpoint. URL requests can be described by properties of Swift structures, and the implementation to create an NSURLRequest value is automatically provided. Although Shirley and Endpoint don’t directly integrate, it’s easy to make a SessionType accept an EndpointType or BaseURLEndpointType. However, it’s not required - Endpoint can output URL requests for any other framework, and Shirley can accept them from any other framework.

Future Frameworks

While those frameworks cover most of my networking needs, there are a few areas that are missing. Endpoint doesn’t provide any support for encoding specific types of HTTP bodies, and I consider that out-of-scope for the framework. A framework providing multipart/form-data encoding would be useful.

Since Shirley can use any URL session, the delegate can be provided manually. However, a framework providing a simplified interface for creating a URL session would make the process easier.