UISearchBar example with Swift and Parse

In this video I am going to share with you how to create a search feature for your Swift mobile application that uses Parse Cloud as it’s mobile app backend. I will also show you how to run case sensitive and case insensitive search using Parse SDK.

To perform case sensitive search query against the custom Parse Class with a name “Friends”:

var firstNameQuery = PFQuery(className:”Friends”)
firstNameQuery.whereKey(“first_name”, containsString: searchBar.text)
var lastNameQuery = PFQuery(className:”Friends”)
lastNameQuery.whereKey(“last_name”, containsString: searchBar.text)
var query = PFQuery.orQueryWithSubqueries([firstNameQuery, lastNameQuery])
query.findObjectsInBackgroundWithBlock {
(results: [AnyObject]?, error: NSError?) -> Void in
if error != nil
{
// Display error message
return
}
if let objects = results as? [PFObject] {
self.searchResults.removeAll(keepCapacity: false)
for object in objects {
let firstName = object.objectForKey(“first_name”) as! String
let lastName = object.objectForKey(“last_name”) as! String
let fullName = firstName + ” ” + lastNameself.searchResults.append(fullName)
}dispatch_async(dispatch_get_main_queue()) {
self.myTable.reloadData()
self.mySearchBar.resignFirstResponder()}
}}

To perform case insensitive search query against the custom Parse Class with a name “Friends”:

var firstNameQuery = PFQuery(className:”Friends”)
lastNameQuery.whereKey(“first_name”, matchesRegex: “(?i)\(searchBar.text)”)
var lastNameQuery = PFQuery(className:”Friends”)
lastNameQuery.whereKey(“last_name”, matchesRegex: “(?i)\(searchBar.text)”)
var query = PFQuery.orQueryWithSubqueries([firstNameQuery, lastNameQuery])
query.findObjectsInBackgroundWithBlock {
(results: [AnyObject]?, error: NSError?) -> Void in
if error != nil
{
// Display error message
return
}
if let objects = results as? [PFObject] {
self.searchResults.removeAll(keepCapacity: false)
for object in objects {
let firstName = object.objectForKey(“first_name”) as! String
let lastName = object.objectForKey(“last_name”) as! String
let fullName = firstName + ” ” + lastNameself.searchResults.append(fullName)
}dispatch_async(dispatch_get_main_queue()) {
self.myTable.reloadData()
self.mySearchBar.resignFirstResponder()}
}}

Download source code.