Sascha Wise
Home Photos Apps About

SPHWNetworking, A Minimalistic Swift HTTP Client December 26, 2015


For Intercept, my simple multi-protcol middleware based server, I needed a Networking library for Swift that would have its functionality cleanly exposed, and behave in a simplistic way. The HTTP spec outlines many things that a client should not do in a realistic scenario, such as send a GET request with a body. Apple’s built-in libraries follow this dutifully; the issue arises when you need to work against these rules. RESTer of course is an HTTP tester, and I am not in the business of telling people how their APIs should be designed. And Intercept functions partially as a proxy. It would be a pretty shitty proxy if it couldn’t forward the header when there was a GET request. So I need to be able to send bodies with GET. SPHWNetworking can be thought of as a more friendly swiftly alternative to the many built in Apple HTTP systems – it does not try to parse JSON for you, nor does it make it explicitly easy to make an HTTP request. But its goal is not to make it hard to make an HTTP request either. It is designed to be minimalistic. Since it is so simple, any undefined behavior (and there shouldn’t be much), will hopefully be answered by the sourcecode. SPHWNetworking is great if you need the utmost control out of your HTTP Client. As of right now it is built on top of CFHTTPMessage, which means that there is no HTTP 2.0 support for now. This will change soon though.

Install


SPHWNetworking can be installed easily via cocoa pods

pod 'SPHWNetworking'

The sourcecode can also be found on GitHub

Usage


The basic usage of it is simple. You first create a request object. Then you set a url and a method.

var request = Request()
request.url = "http://google.com"
request.method = .GET

Then you can setup the body, which can come in two forms NSData or a string. The NSData takes precedent over the string

request.dataBody = NSData()

OR

request.body = "FOO"
let netRequest = NetworkingRequest(request, jar: CookieJar(), progressCB: {
progress in
// Do stuff with the progress
}) { response, jar in
// Do stuff with the resulting jar and response
}
netRequest.run()

The request object has all the options embeded in it. Real documentation is to come soon. The response object mirrors the request object for the most part. There are a couple more things of note. #1 there are some current design issues that are subject to change, as it is in alpha. And there are some extra features that will be removed as their goal was to make working with a UI simple. Most of this has been refactored out, but some may still remain.