Search as you type Swift

I am trying to implement a type search written in Swift. It works already, but I need a setup. I send every letter printed in

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

    let debouncedFindUser = debounce(
        Static.searchDebounceInterval,
        Static.q,
        findUser)

    debouncedFindUser()
}

backend request.

func findUser() -> () {
    SearchService.sharedInstance.getUser(0, numberOfItems: 100,
        searchString: searchUserBar.text.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        ,
        success: {SearchUserDto -> Void in
            if self.searchUserBar.text != nil {
                self.updateSearch()
            }
        },
        failure: {NSError -> Void in

    })
}

I tried implementing Debounce, found here. How can I cancel a method call?

My problem:

I want to "restart" a method call if it has been running for a certain time. So exaggerate a little.

The query should start only after the search text has not been entered within 2 seconds. Therefore, if I quickly type and type a letter every 0.5 seconds, the request should never be launched, except that I pause for at least 2 seconds.

+4
2

NSTimer. 2 . findUser, .

    var debounceTimer: NSTimer?

@IBAction func test() {
    if let timer = debounceTimer {
        timer.invalidate()
    }
    debounceTimer = NSTimer(timeInterval: 2.0, target: self, selector: Selector("getUser"), userInfo: nil, repeats: false)
    NSRunLoop.currentRunLoop().addTimer(debounceTimer!, forMode: "NSDefaultRunLoopMode")
}

func getUser() {
    println("yeah")
}
+6

, , , findUser, . debouncing , , "". , .

debounce , :

class MySearchController: ... {
    lazy var debouncedFindUser = debounce(
        Static.searchDebounceInterval,
        Static.q,
        self.findUser)

    ...

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        debouncedFindUser()
    }

    func findUser() {
        ...
    }
}
+1

All Articles