'Synchronize block methods that trigger networking calls in objective c
I am working on a project that uses blocks pattern withCompletion to call a method
[ClientApiServicesProvider shared] influencerService] getLikesListWithOffset:offset :self.isSearchRequest :self.searchKey WithCompletion:^(NSDictionary * _Nullable likes, NSError * _Nullable error)
This method block is asynchronous and can be called by the user everytime he writes a new character in a textfield and every time a new character comes up it triggers a network call using NSURLSessionDataTask . These calls are asynchronous. I am calling the method above from my UIViewcontroller. Is there any way to cancel this network request before starting a new one? If there is no way what are the alternatives? I was thinking using @synchronized {} and put the above block method inside the brackets of @synchronized. Any help or ideas appreciated...
Solution 1:[1]
Most network APIs will have some means of cancelling them. In the case of NSURLSession
, data tasks have a -cancel
function (https://developer.apple.com/documentation/foundation/nsurlsessiontask/1411591-cancel). If you were using NSURLSession
, in order to achieve the functionality you desire, you would have to hold on to the previously submitted data task and then cancel it when a new request is submitted.
You should find out how your function -getLikesListWithOffset:WithCompletion:
makes calls to the network, and then appropriately hold on to previous requests in some manner so they can be potentially cancelled in the future. One way to do this might be returning a data task (in the case of NSURLSession
) from this method and then relying on the caller to cancel the data task if they make future requests.
As an aside, you may want to look into using "debounce" logic (https://css-tricks.com/debouncing-throttling-explained-examples/) in order to avoid making network requests over and over, every time the user taps a character.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aaron Wojnowski |