While many best practices for Alamofire depend on the server you're communicating with, there are some which are generally applicable. This thread attempts to document some of these, with the intention of eventually adding a summary to Alamofire's documentation.
-
URLSessionbest practices apply to Alamofire too! Since an AlamofireSessionManagerwraps aURLSession, you can treat aSessionManagerlike aURLSession. This means:- You should never create one
SessionManagerper request. A general rule is to have oneSessionManagerper host, if possible. At most, oneSessionManagerper unique host configuration is a good limit. This prevents duplication of resources and allows the system to optimizeURLSessionusage. - While you can increase the number of simultaneous
URLSessionTasks in flight at once by increasing theURLSessionConfiguration.httpMaximumConnectionsPerHostvalue before initializing yourSessionManager, it's not usually necessary or a good idea. SinceURLSesssion'sdelegateQueueis serial, there is a limit to the amount of benefit that can buy you, andURLSessionmay have undocumented maximums that you'll run into regardless of this value.
- You should never create one
- Be careful how many Alamofire
Requests you enqueue at once. Enqueuing more than a few dozen at a time can negatively impact system performance, as each AlamofireRequesthas it's own internalDispatchQueue, so trying to enqueue thousands at a time can lead to system resource contention and your app being killed by the system watchdog. This issue will be fixed in Alamofire 5, which redoes Alamofire's queue usage to better follow recommended best practices. - Embrace Alamofire's generics and our
URLRequestConvertibleprotocol, as it can form the basis of a powerful system to let you easily convert from Swift types to network requests. Even something as simple as theRouteroutlined in our documentation can make network layers much less code intensive by requiring only the bare minimum of configuration per request. It also lets you build more reusable components that you plug only the definition of your API and types into, much like Moya does.
What other best practices would be good to include in our documentation?