Here's the problem, iOS just tries to reuse the connection after the server drops it.
Why CFNetwork SHOULD NOT
About two years ago, I switched to CFNetwork to solve this problem, but I recently discovered that it is not possible to implement SSL binding with the CFNetwork API. So now I am considering the possibility of returning to NSURLSession.
Workaround
After some searching, I found that the system would NOT reuse connections through NSURLSession s, so creating new sessions over a period of time should solve the problem.
But I also found (at least on macOS): every connection made by NSURLSession can last for 180 seconds, and this connection does not close by version or reset the session, so you may need to implement some caching mechanism to avoid creating a large the number of compounds.
Here is a simple mechanism that I am currently using:
@interface HTTPSession : NSObject @property (nonatomic, strong) NSURLSession * urlSession; @property (nonatomic, assign) CFTimeInterval flushTime; @end + (NSURLSession *)reuseOrCreateSession { static NSMutableArray<HTTPSession *> * sessions = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sessions = [NSMutableArray<HTTPSession *> array]; }); const CFTimeInterval serverTimeoutSeconds = 10; const CFTimeInterval systemTimeoutSeconds = 40; CFTimeInterval now = CFAbsoluteTimeGetCurrent(); HTTPSession * resultSession = nil; for (HTTPSession * session in sessions) { CFTimeInterval lifeTime = now - session.flushTime; if (lifeTime < serverTimeoutSeconds) { resultSession = session; break; } if (lifeTime > systemTimeoutSeconds) { resultSession = session; resultSession.flushTime = now; break; } } if (!resultSession) { resultSession = [HTTPSession new]; NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
naituw
source share