In‑Depth Analysis of AFNetworking Architecture and Design for iOS
This article provides a comprehensive technical walkthrough of AFNetworking, covering its core classes, request and response serialization, task management, network activity indicator handling, reachability monitoring, and SSL pinning security policies, illustrating how the library abstracts NSURLSession for iOS developers.
AFNetworking is a widely used iOS networking library that wraps NSURLSession to simplify HTTP requests, offering high‑level APIs such as GET , POST , and multipart uploads.
The core hierarchy consists of AFURLSessionManager and its subclass AFHTTPSessionManager ; the former manages NSURLSession , task creation, and delegate forwarding, while the latter provides convenient request methods that ultimately return an NSURLSessionDataTask which is resumed by the caller.
Request serialization is handled by AFHTTPRequestSerializer and related serializers. Parameters are converted to JSON or URL‑encoded strings via AFQueryStringPair , and multipart form data is built through the AFMultipartFormData protocol, allowing files and data to be attached easily.
Response serialization is performed by a family of serializers (e.g., AFJSONResponseSerializer , AFXMLParserResponseSerializer ) that validate content types, decode data, and recursively remove NSNull values to prevent crashes.
The AFNetworkActivityIndicatorManager uses notifications ( AFNetworkingTaskDidResumeNotification , AFNetworkingTaskDidSuspendNotification ) and activation/completion timers to avoid flickering the status‑bar spinner during short‑lived requests.
Network reachability is monitored by AFNetworkReachabilityManager , which creates a SCNetworkReachabilityRef from a host or address, registers a callback with the run‑loop, and posts status changes to observers.
Security is encapsulated in AFSecurityPolicy , offering three SSL‑pinning modes ( None , Certificate , PublicKey ) and options to allow invalid certificates or validate domain names. Self‑signed certificates are loaded from bundled .cer files and compared against the server’s trust chain.
Overall, AFNetworking demonstrates clean separation of concerns, extensible delegate‑based design, and thoughtful handling of edge cases such as task identifier collisions, connection reuse, and UI feedback, making it a solid reference for building robust mobile networking layers.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.