Mobile Development 11 min read

Network AOP Approaches for iOS Apps: Comparison and Implementation in Dada Express

To enable encrypted transmission and traffic monitoring across multiple iOS apps with diverse networking frameworks, this article compares several network AOP solutions—including AFNetworking, Moya, custom frameworks, runtime method swizzling, and NSURLProtocol—evaluates their pros and cons, and details the chosen NSURLProtocol-based implementation with plugin architecture.

Dada Group Technology
Dada Group Technology
Dada Group Technology
Network AOP Approaches for iOS Apps: Comparison and Implementation in Dada Express

Introduction

Due to business requirements, Dada Express needs to encrypt network traffic and monitor data flow for several iOS apps that each use different networking frameworks. A unified framework would simplify this, but because the apps use multiple frameworks, a lightweight solution based on Aspect‑Oriented Programming (AOP) is explored.

1. AOP Overview

AOP (Aspect Oriented Programming) complements object‑oriented programming by allowing cross‑cutting concerns to be modularised. In iOS, AOP is commonly used for silent analytics and security. Network AOP focuses on intercepting requests and responses at the network layer for secondary processing.

2. Comparison of Network AOP Schemes

1. Implement AOP via Existing Network Frameworks

AFNetworking

AFNetworking provides task‑state notifications that can be used for monitoring and logging.

Moya

Moya, built on top of Alamofire, uses Swift protocols to expose a PluginType interface, allowing request and response interception—an embodiment of AOP.

Custom Network Framework

Most projects expose a unified entry point; adding an AOP layer there is straightforward, though it only captures requests made through that framework.

2. Runtime Hooking

Libraries such as FLEX hook system delegate functions to capture traffic. Since NSURLConnection is deprecated, only NSURLSession needs to be considered for custom hooks.

3. NSURLProtocol

NSURLProtocol is part of the URL Loading System and can intercept all requests that use it. By subclassing and registering a custom NSURLProtocol, the system automatically creates an instance to handle each request.

方案

核心思路

优点

缺点

基于AFN的实现

监听AFN提供的各时机通知,获取相应的数据

1.代码量很小。

2.结构依靠AFN提供的通知串联,逻辑简单。

1.只能监控AFN发起的请求。

2.不能修改请求/响应数据。

基于Moya的实现

实现PluginType协议,操作相应数据

1.Moya是GitHub上高星项目,维护活跃,稳定性强。

2.基于协议实现,对 Swift 支持好。

3.支持对请求/响应数据的读写。

1.Moya只能在 Swift 项目中使用。

2.仅限于 Moya 框架。

基于自定义网络框架的实现

在统一出入口处制作切面,通过通知/代理实现转发功能

1.实现方式自由,问题易定位。

2.自定义框架可针对 app 做更多优化。

3.支持对请求/响应数据的读写。

1.对小公司成本相对较高。

2.无法拦截其他网络库及 SDK 的请求。

基于 runtime 的实现

对 NSURLSession 等系统请求类进行方法交换

1.方案思路明确,易于理解。

2.基于底层实现,对上层代码无影响。

3.支持对请求/响应数据的读写。

1.需要交换的方法数量多,代码量大。

2.实现复杂,风险较大。

基于 NSURLProtocol

实现 NSURLProtocol 子类并注册,系统自动创建实例处理请求

1.苹果官方推荐。

2.可移植。

3.支持对请求/响应数据的读写。

同一请求只能有一个 NSURLProtocol 响应并处理。

3. Network AOP in Dada App

Because Dada’s apps use multiple networking frameworks, the three framework‑based AOP schemes are unsuitable. The team chose between runtime hooking and NSURLProtocol; considering the complexity and risk of runtime, NSURLProtocol was selected as the most universal solution.

1. Overall Structure

Registering a custom NSURLProtocol subclass intercepts all URL Loading System requests. To avoid a monolithic class, the protocol acts as an entry point that forwards requests to a plugin system. Plugins are registered in order, and their registration order determines execution order.

When a request is intercepted, it is passed to a singleton forwarder, which iterates over the plugin array. Each enabled plugin that implements the relevant delegate method receives the request. After all plugins have processed the request, the forwarder returns the modified request to the interceptor, which finally issues the network call. Response handling follows the same flow.

2. Design Details

The plugin architecture is illustrated in the accompanying diagram (omitted). Each plugin operates independently, preventing a single plugin from affecting the whole system.

3. Development Issues

Issue 1: HTTPBody is Empty for POST Requests

POST requests may have an empty HTTPBody because the data resides in HTTPBodyStream . The following code extracts the stream data and assigns it to HTTPBody :

if ([method isEqualToString:@"post"]) {
    newRequest = request.mutableCopy;
    NSMutableData *httpBody = [NSMutableData data];
    NSInputStream *stream = request.HTTPBodyStream;
    [stream open];
    NSInteger maxLength = 1024;
    uint8_t buffer[maxLength];
    BOOL isReadEnd = NO;
    while (!isReadEnd) {
        NSInteger readLength = [stream read:buffer maxLength:maxLength];
        if (stream.streamError == nil && readLength > 0) {
            [httpBody appendBytes:buffer length:readLength];
        } else {
            isReadEnd = YES;
        }
    }
    newRequest.HTTPBody = httpBody;
}

Issue 2: Local Network Congestion Causing Subsequent Request Timeouts

When intercepting multipart/form‑data requests, failing to write the body back after reading the stream leads to local congestion and timeouts. Even if no modification is needed, the body must be rewritten.

NSMutableData *httpBody = [NSMutableData data];
NSInputStream *stream = request.HTTPBodyStream;
[stream open];
NSInteger maxLength = 1024;
uint8_t buffer[maxLength];
BOOL isReadEnd = NO;
while (!isReadEnd) {
    NSInteger readLength = [stream read:buffer maxLength:maxLength];
    if (stream.streamError == nil && readLength > 0) {
        [httpBody appendBytes:buffer length:readLength];
    } else {
        isReadEnd = YES;
    }
}
[stream close];
newRequest.HTTPBody = httpBody;

Conclusion

By evaluating several AOP schemes, a low‑risk, easily extensible network interception layer was built for native iOS apps. While the current solution works well for native requests, WKWebView presents a special case that requires a separate approach; future work will explore WKWebView interception to achieve a truly “zero‑blind‑spot” network AOP.

iOSRuntimeNSURLProtocolAFNetworkingMoyaNetwork AOP
Dada Group Technology
Written by

Dada Group Technology

Sharing insights and experiences from Dada Group's R&D department on product refinement and technology advancement, connecting with fellow geeks to exchange ideas and grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.