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 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。