我正在尝试使用A UISearchView查询Google地方。为此,在UISearchBar发给我的文字更改电话中,我正在向Google地方提出要求。问题是我宁愿将此呼叫退信以每250 ms仅请求一次,以避免不必要的网络流量。我不想自己编写此功能,但是如果需要的话,我会写的。
UISearchView
UISearchBar
我发现:https : //gist.github.com/ShamylZakariya/54ee03228d955f458389,但我不太确定如何使用它:
func debounce( delay:NSTimeInterval, #queue:dispatch_queue_t, action: (()->()) ) -> ()->() { var lastFireTime:dispatch_time_t = 0 let dispatchDelay = Int64(delay * Double(NSEC_PER_SEC)) return { lastFireTime = dispatch_time(DISPATCH_TIME_NOW,0) dispatch_after( dispatch_time( DISPATCH_TIME_NOW, dispatchDelay ), queue) { let now = dispatch_time(DISPATCH_TIME_NOW,0) let when = dispatch_time(lastFireTime, dispatchDelay) if now >= when { action() } } } }
这是我尝试使用上述代码的一件事:
let searchDebounceInterval: NSTimeInterval = NSTimeInterval(0.25) func findPlaces() { // ... } func searchBar(searchBar: UISearchBar!, textDidChange searchText: String!) { debounce( searchDebounceInterval, dispatch_get_main_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT), self.findPlaces ) }
产生的错误是 Cannot invoke function with an argument list of type '(NSTimeInterval, $T5, () -> ())
Cannot invoke function with an argument list of type '(NSTimeInterval, $T5, () -> ())
如何使用此方法,或者在iOS / Swift中有更好的方法来执行此操作。
将其放在文件的 顶层 ,以免使自己与Swift有趣的参数名称规则混淆。请注意,我已经删除了,#因此现在所有参数都没有名称:
#
func debounce( delay:NSTimeInterval, queue:dispatch_queue_t, action: (()->()) ) -> ()->() { var lastFireTime:dispatch_time_t = 0 let dispatchDelay = Int64(delay * Double(NSEC_PER_SEC)) return { lastFireTime = dispatch_time(DISPATCH_TIME_NOW,0) dispatch_after( dispatch_time( DISPATCH_TIME_NOW, dispatchDelay ), queue) { let now = dispatch_time(DISPATCH_TIME_NOW,0) let when = dispatch_time(lastFireTime, dispatchDelay) if now >= when { action() } } } }
现在,在您的实际课程中,您的代码将如下所示:
let searchDebounceInterval: NSTimeInterval = NSTimeInterval(0.25) let q = dispatch_get_main_queue() func findPlaces() { // ... } let debouncedFindPlaces = debounce( searchDebounceInterval, q, findPlaces )
现在debouncedFindPlaces是一个可以调用的函数,findPlaces除非delay自上次调用以来已经通过,否则将不会执行您的函数。
debouncedFindPlaces
findPlaces
delay