SwiftNetworkLayer is an example of writing a minimal networking layer using only native Cocoa Touch APIs in Swift 4.
Features:
- Create and cancel network requests
- Load images from the network
- Present / dismiss
LoadingViews while data is loading
I made this example because it seems like most Swift networking layers on GitHub are built atop either Alamofire or Moya. If you're looking to dive deeper into how networking works under the hood, I suggest you try writing your own! Also, if you have ways to make mine better, feel free to submit a pull request :)
The NetworkService class has two main functions:
request(...), which returns an object conforming toDecodablecancelRequest(...), for cancelling a request
Both methods take an Endpoint as an argument and return a generic Result<T> type, which is declared at the callsite.
An Endpoint contains contains the required URL and URLRequest information to make the network call.
The ImageLoader has three responsibilities:
- Fetching an image from the network, provided an image URL
- Caching a fetched image to memory after it has been retrieved from the network
- Keeping track of running image network tasks and their callbacks
The ImageLoader (and its sub-components, ImageLoaderCache and ImageLoaderTaskManager) are essential to avoiding redundant network calls and callbacks.
Loadable is a protocol which provide methods for presenting and dismissing a LoadingView.
A LoadingView simply contains a loading spinner and a dimmed background.
In the project, there is an Example folder with how SwiftNetworkLayer could be implemented in a project. This example uses the BandsInTown API.
To run the example:
- Open
SwiftNetworkLayer.xcodeproj - Press Run (
CMD+R)