我正在尝试使用UISearchView
查询谷歌地点。这样做时,在文本更改时需要我UISearchBar
,我正在向 google 地点提出请求。问题是我宁愿将此调用反跳为每 250 毫秒仅请求一次,以避免不必要的网络流量。我不想自己编写这个功能,但如果需要的话我会编写。
我发现:https://gist.github.com/ShamylZakariya/54ee03228d955f458389 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, () -> ())
我该如何使用这个方法,或者在 iOS/Swift 中有更好的方法来做到这一点。