嘿,我有一个带有搜索栏的桌面视图。我用搜索词请求远程rest-api。 searchbar func看起来像这样(根据这篇文章:How to throttle search (based on typing speed) in iOS UISearchBar?)
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.searchTeams), object: nil)
self.perform(#selector(self.searchTeams), with: nil, afterDelay: 0.3)
}
searchTeams-Func看起来像这样,它用完成处理程序调用异步函数loadingJSON:
loadingJSON("APIPATH", postString:"STRING") {
parseJSON in
if(String(describing: parseJSON) == "-1"){
print("No Internet")
} else {
if let teams = parseJSON["teams"] as? [[String: AnyObject]] {
self.teams.removeAll()
for team in teams {
//Parse data
}
self.tableView.reloadData()
}
}
}
这几乎完美无缺。但有时应用程序在以下行中的cellForRowAt-indexPath-Methode中崩溃:
teamSearchResultsCell.TeamNameLable.text = self.teams[indexPath.row].teamName
indexPath.row = 0但是teams数组为空。所以我认为如果用户在函数清除数组但尚未重新加载tableview的那一刻正确地点击单元格,就会发生这种情况。有什么想法可以解决这个问题吗?
EDITED: loadingJSON-func为谁感兴趣:
func loadingJSON(_ link:String, postString:String, completionHandler: @escaping (_ JSONObject: AnyObject) -> ()) {
if(Reachability.isConnectedToNetwork() == false){
completionHandler("-1" as AnyObject)
return
}
let request = NSMutableURLRequest(url: URL(string: FinalVars.getMobileRequestURL() + link)!)
request.httpMethod = "POST"
request.timeoutInterval = FinalVars.getRequestTimeoutIntervalInSeconds() //=7 Set Timeout in Seconds
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
guard error == nil && data != nil else {
//TimeOutReached --> No Network Connection
print("error=\(String(describing: error))")
DispatchQueue.main.async(execute: {
completionHandler("-1" as AnyObject)
})
return
}
if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
//JSON successfull
do {
let parseJSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
DispatchQueue.main.async(execute: {
completionHandler(parseJSON as AnyObject)
});
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
task.resume()
}
答案 0 :(得分:0)
你应该有一条线让它安全......
if teams.count > 0 { .. do your stuff ... } else { .. do nothing - there are no teams .. }
假设您的团队阵列在此后不久填充,上述行将有助于确保一切正常,直到网络响应回复您的数据,然后一切都会花哨。希望这会有所帮助。