Skip to content

Instantly share code, notes, and snippets.

@gauravkeshre
Last active January 13, 2019 19:51
Show Gist options
  • Save gauravkeshre/76af5a9553605326edfaae3a8cce1dba to your computer and use it in GitHub Desktop.
Save gauravkeshre/76af5a9553605326edfaae3a8cce1dba to your computer and use it in GitHub Desktop.
A simple playground gist that demonstrates how we can leverage performSelector for achieving basic polling-like behaviour in swift.

How to implement polling using performSelector

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true


class Manager: NSObject {
    var i = 0
    func fetchDataFromApi(then: () -> ()) {
        print("long api call page : \(i)")
        sleep(2)
        self.i += 1
        then()
    }
    
    @objc func pollAPI(stop: () -> (Bool)) {
        guard !stop() else {
            stopPolling()
            return
        }
        
        fetchDataFromApi {
            print("polling next")
            self.perform(#selector(pollAPI), with: nil, afterDelay: 5) /// 5 seconds
        }
    }
    
    func stopPolling() {
         print("stop polling")
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pollAPI), object: nil)
    }
}


let m = Manager()

let end = Date() + 40 // must stop after 120 seconds

m.pollAPI { () -> Bool in
    return Date() >= end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment