0

I have an Alamofire function that calls an API. How do I make this function trigger every hour since the first time the function is triggered?

I currently have this function but looks like this code is work with delay of 1 hour after it's called. I need the function to be called with interval of 1 hour after the first API is called. So I called the API for the first time, and for the next one hour I just use the data that I called earlier.

func getAdds() {
    
    addsViewModel.timer.setEventHandler {
      self.addsViewModel.getAddsImage { [weak self] response, fileType   in
        if response == 200 {
          self?.addsViewModel.filterPromotion()
          self!.setupAdds(typeFile: fileType, data: self!.addsViewModel.filteredPromotion!.coverFileName!)
        }else if response != 200 || self!.addsViewModel.dataPromotion[0].visible == false &&  self!.addsViewModel.dataPromotion[0].active == false || self!.addsViewModel.bannerAdds?.isEmpty == true {
          self?.dismiss(animated: false)
        }else{
          self?.dismiss(animated: false)
        }
      }
    }
    addsViewModel.timer.schedule(deadline: .now() + .seconds(3600), repeating: .seconds(3600), leeway: .seconds(60))
    addsViewModel.timer.activate()
}

Does anyone know how to make this work as I want?

HangarRash
  • 7,314
  • 5
  • 5
  • 32
afi permana
  • 207
  • 3
  • 17
  • 1
    Background Tasks is the closest thing but be aware that they are not guaranteed – lorem ipsum Mar 01 '23 at 16:02
  • @loremipsum what if i compare current device time with the time when the func get called? – afi permana Mar 01 '23 at 16:17
  • 1
    `Timer` doesn't survive in the background for long, it doesn't matter how you check the time – lorem ipsum Mar 01 '23 at 16:19
  • even if i save time Timer in my cache? @loremipsum – afi permana Mar 01 '23 at 18:23
  • 1
    Give it a try, see how long it lasts – lorem ipsum Mar 01 '23 at 19:53
  • I like your optimism that your users will stay in the app for that long time :)) – arturdev Mar 01 '23 at 20:18
  • I believe the linked question addresses this. There is no difference in this case between once a minute and once an hour. Both are impossible without push notifications (with some limitations; even push notifications cannot do this perfectly). You can display a notification to the user periodically, but you cannot run arbitrary code in the background. If you have specific needs, like updating content before the user launches, see https://developer.apple.com/documentation/backgroundtasks (but there's no promise they will run) – Rob Napier Mar 01 '23 at 22:43
  • okay thank you all, this requirement is ask by my GM and i try to said it cant be done but my android developer said it can be done, so i just walking in the same place for weeks now on to handle this – afi permana Mar 02 '23 at 04:16
  • Apple isn’t android, ask him to show you. – lorem ipsum Mar 04 '23 at 10:10

0 Answers0