I am trying to create an iOS app using Swift and I need to implement a search feature using UISearchbar. It takes in a store name and searches for it in the database to return an array of store names. Below is the segment of the code which is giving me some errors. I followed this website closely http://swiftdeveloperblog.com/case-insensitive-search-with-swift-php-and-mysql/
func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
if(searchBar.text!.isEmpty)
{
return
}
doSearch(searchWord: searchBar.text!)
}
func doSearch(searchWord: String){
mysearchBar.resignFirstResponder()
let myURL = NSURL(string: "http://localhost:8080/searchStore.php")
var request = URLRequest(url:myURL! as URL)
request.httpMethod = "POST"
let postString = "name=\(searchWord)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request, completionHandler:{ (data: Data?, response: URLResponse!, error: Error!) -> Void in
DispatchQueue.main.async() {
if error != nil{
self.displayAlertMessage(userMessage: error.localizedDescription)
return
}
do{
var _: Error?
//STOPPED HERE AS OF NOW
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
self.results.removeAll(keepingCapacity: false)
self.tableView.reloadData()
if let parseJSON = json{
if let stores = parseJSON["stores"] as? [AnyObject]{
for storeOjb in stores{
let name = (storeOjb["name"] as! String)
self.results.append(name)
}
self.tableView.reloadData()
}else if(parseJSON["message"] != nil){
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil){
self.displayAlertMessage(userMessage: errorMessage!)
}
}
}
} catch {
print(error)
}
}
})
task.resume()
}
I get 2 errors the first one is due to mysearchBar.resignFirstResponder(). The app terminates and I keep getting
"fatal error: unexpectedly found nil while unwrapping an Optional value"
The second error is when I remove mysearchBar.resignFirstResponder() I get
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo=
{NSDebugDescription=No value.}
UPDATE: I fixed the 2nd problem by entering this line
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
However, it seems that my postString variable is facing a problem