How do I rate limit my iOS network requests to one second
New in iOS 13, this functionality is built in. Pass your communication trigger through the Combine framework's debounce
operator and you're all set.
@implementation SomeNSOperationSubClass {
BOOL complete;
BOOL stopRunLoop;
NSThread *myThread;
}
-(void) rateLimitMonitor:(NSTimer *)theTimer {
[theTimer invalidate];
}
-(void) main {
myThread = [NSThread currentThread];
NSTimer *myTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(rateLimitMonitor:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];
[self doAsyncThing];
while ((!stopRunLoop || [myTimer isValid]) && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
complete = YES;
}
-(void) internalComplete {
stopRunLoop = YES;
}
-(void) setComplete {
[self performSelector:@selector(internalComplete) onThread:myThread withObject:nil waitUntilDone:NO];
}
-(BOOL) isFinished {
return complete;
}
@end
and in your async callback
[myNSOperationSubClass setComplete];