Env:
Description: When use AFNetworking to post or get Json data, it will cause memory leak, I create a AFHTTPSessionManager like this:
private static func ConfigureAFManager(requestSerialization: HttpSerializationType = HttpSerializationType.HTTP,
responseSerialization: HttpSerializationType = HttpSerializationType.JSON,
timeout: TimeInterval = 30,
headers: [String: String]? = nil
) -> AFHTTPSessionManager {
let AFManager = AFHTTPSessionManager()
if requestSerialization == .JSON {
AFManager.requestSerializer = AFHTTPRequestSerializer()
}
if responseSerialization == .HTTP {
AFManager.responseSerializer = AFHTTPResponseSerializer()
}
for (key, value) in headers ?? [:] {
AFManager.requestSerializer.setValue(value, forHTTPHeaderField: key)
}
AFManager.requestSerializer.timeoutInterval = timeout;
return AFManager
}
then I use it to perform post action:
static func POST(httpURL: String,
parameter: Any?,
timeout: TimeInterval = 30,
headers: [String: String]? = nil,
requestSerialization: HttpSerializationType = HttpSerializationType.HTTP,
responseSerialization: HttpSerializationType = HttpSerializationType.JSON,
success: ((Any?) -> Void)?,
fail: ((Error?) -> Void)?) -> Void
{
let AFManager = self.ConfigureAFManager(requestSerialization: requestSerialization, responseSerialization: responseSerialization, timeout: timeout, headers: headers)
AFManager.post(httpURL, parameters: parameter, progress: nil, success: { (task, response) in
success?(response)
}) { (task, error) in
fail?(error)
}
}
When I clicked the Debug Memory Graph
on Xcode, I found that, there are some cycle reference between AFHTTPSessionManager
and __NSURLSessionLocal
.
Cycle reference Is this happening only in the 3.2.1 version of AFNetworking?
I know why, because AFNetWorking use URLSession it's delegate will establish a strong reference, so after use the AFHttpSessionManager should call invalidateSessionCancelingTasks