doudu7626 2017-06-20 15:36
浏览 59
已采纳

searchBar.resignFirstResponder()导致nil值

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

breakpoint check photo

  • 写回答

1条回答 默认 最新

  • duanhui9840 2017-06-20 16:06
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办