我有一个 UIRefreshControl 并创建了一个全局对象刷新控件。刷新多次或仅一次时应用程序崩溃并显示错误。
我的viewDidLoad函数
override func viewDidLoad() {
super.viewDidLoad()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(refresh), for: UIControlEvents.valueChanged)
tableView.addSubview(refreshControl)
tableView.register(UINib(nibName: "NewsCell", bundle: nil), forCellReuseIdentifier: "CellID")
tableView.rowHeight = 343
}
我的 View 将出现功能。这里加载的数据是全局声明的 bool 变量
override func viewWillAppear(_ animated: Bool) {
if !dataLoaded && newsArray.isEmpty {
let url = urls.sharedInstance.newsUrl + String(0)
loadDatafromUrl(uri:url)
}
}
我的刷新功能
func refresh(){
newsArray.removeAll()
let url = urls.sharedInstance.newsUrl + String(10)
loadDatafromUrl(uri: url)
}
从网络服务器下载数据的函数
func loadDatafromUrl(uri: String){
self.refreshControl.endRefreshing()
print(uri)
if let url = URL(string: uri){
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
let session = URLSession(configuration: config)
let task = session.dataTask(with: url, completionHandler: {
(rawData,response,error) in
if error != nil {
print("Couldnt load data")
print(error?.localizedDescription as Any)
self.navigationItem.title = "Connecting..."
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black]
self.dataLoaded = false
} else {
self.dataLoaded = true
self.navigationItem.title = ""
if let data = rawData {
do{
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [AnyObject]{
DispatchQueue.main.async {
for index in 0...json.count-1 {
if let datas = json[index] as? [String: AnyObject] {
if let title = datas["title"] as? String {
if title != "nil" {
let newsObj = News()
newsObj.title = title
newsObj.body = datas["body"] as? String
let photo: String? = datas["photo"] as? String
if let phot = photo {
let photourl: String? = "http://qproinnovations.com/projectpreview/unaninfo/admin/uploads/" + phot
newsObj.photo = photourl
print(photourl)
}
newsObj.meta = datas["meta"] as? Int
self.newsArray.append(newsObj)
}
}
}
}
self.tableView.reloadData()
}
}
}catch{
print("error")
}
}
}
})
task.resume()
}
}
最佳答案
延迟重新加载表。我也面临这个问题。重新加载表格甚至有 0.5 的延迟对我来说也很有效
关于ios - 刷新表格 View 时应用程序崩溃并出现 fatal error : Index out of range Swift3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43884563/