searchBar.resignFirstResponder()导致nil值

时间:2017-06-20 15:36:11

标签: php mysql swift

我正在尝试使用Swift创建iOS应用程序,我需要使用UISearchbar实现搜索功能。它接收商店名称并在数据库中搜索它以返回商店名称数组。下面是代码段,它给了我一些错误。我密切关注了这个网站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()
}

我得到2个错误,第一个是mysearchBar.resignFirstResponder()。该应用程序终止,我一直在

"fatal error: unexpectedly found nil while unwrapping an Optional value"

第二个错误是当我删除mysearchBar.resignFirstResponder()时我得到了

Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo=
{NSDebugDescription=No value.}

更新: 我通过输入这一行修正了第二个问题

request.addValue("application/json", forHTTPHeaderField: "Content-Type")

但是,似乎我的postString变量面临问题

breakpoint check photo

1 个答案:

答案 0 :(得分:0)

您应该通过单击行号并运行程序,在给出错误的行上设置断点。使用左下角的调试器窗格窗口查找nil值。debugger pane

这将帮助您找到什么值是零,如果您已经知道哪个变量是零,请告诉我们!