我正在尝试使用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()
}

我得到两个错误第一个是由于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

最佳答案

您应该在出现错误的行上设置一个断点,方法是单击行号并运行程序。使用左下角的调试器窗格窗口查找nil值。php - searchBar.resignFirstResponder()导致零值-LMLPHP
这将帮助你找到什么值是零,如果你已经知道什么变量是零,请告诉我们!

关于php - searchBar.resignFirstResponder()导致零值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44657389/

10-11 00:42