Rawan Al Rawan Al - 9 months ago 38
MySQL Question

searchBar.resignFirstResponder() causing nil values

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)

doSearch(searchWord: searchBar.text!)

func doSearch(searchWord: String){


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)
var _: Error?
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

self.results.removeAll(keepingCapacity: false)

if let parseJSON = json{

if let stores = parseJSON["stores"] as? [AnyObject]{

for storeOjb in stores{
let name = (storeOjb["name"] as! String)


}else if(parseJSON["message"] != nil){

let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil){
self.displayAlertMessage(userMessage: errorMessage!)

} catch {



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.}

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

breakpoint check photo

Answer Source

You should set a breakpoint on the line that is giving you the error by clicking on the line number and run the program. Look for nil values by using the bottom left debugger pane window.debugger pane

This will help you find what value is nil and if you already know what variable is nil please tell us!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download