我有一个tableview,在取回请求完成后填充。每行包含一个在SFSafariViewController中打开的链接。一旦用户在SF Safari VC中点击Done按钮,tableview就会重新加载并再次调用fetch请求。我不希望这种情况发生,因为fetch请求有时会花费15秒以上,我担心它会使我的API调用计数加倍。
下面的代码-有什么我可以做,以防止表格视图重新加载一旦Safari VC被驳回?我尝试使用布尔跟踪它,但当viewDidLoad/appear被调用时,它会再次改变。我应该在viewdidload/appear之外调用我的取回请求吗?
import SafariServices
import UIKit
class ArticlesTVC: UITableViewController, SFSafariViewControllerDelegate {
var articles = [Article]()
let cellId = "articleCell"
var refresh: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
registerCell()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
refresh = true
if refresh == true {
DispatchQueue.main.async {
self.fetchArticles()
self.refresh = false
}
}
}
func registerCell() { tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId) }
override func numberOfSections(in tableView: UITableView) -> Int { return 1 }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return articles.count }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let article = articles[indexPath.row]
cell.textLabel?.text = article.title
cell.detailTextLabel?.text = article.description
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let article = articles[indexPath.row]
loadArticle(articleURL: article.url!)
}
func loadArticle(articleURL: String) {
if let url = URL(string: articleURL) {
let vc = SFSafariViewController(url: url)
vc.delegate = self
present(vc, animated: true)
}
}
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
dismiss(animated: true)
}
func fetchArticles() {
let baseURL = "url removed for privacy"
guard let url = URL(string: "(baseURL)") else {
print("url failed")
return
}
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { data, response, error in
if error != nil {
print(error)
return
}
if let safeData = data {
self.parseJSON(data: safeData)
}
}.resume()
}
func parseJSON(data: Data) {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(ArticleEnvelope.self, from: data)
let newsArticles = decodedData.news
for item in newsArticles {
let title = item.title
let description = item.description
let url = item.url
let image = item.image
let published = item.published
let article = Article(title: title, description: description, url: url, image: image, published: published)
DispatchQueue.main.async {
self.articles.append(article)
self.tableView.reloadData()
}
}
print("articles loaded successfully")
} catch {
print("Error decoding: (error)")
}
}
当然。你已经成功了90%。您的viewWillAppear(_:)
方法检查布尔标志refresh
,并且仅在refresh == true
时获取数据并重新加载表。但是,它显式地设置了refresh = true
。你的viewWillAppear(_:)
函数在每次你解散你的其他视图控制器并重新显示表格视图控制器时被调用。
将refresh = true
行移动到viewDidLoad()
行。问题解决了。(viewDidLoad()
只在视图控制器第一次创建时调用一次,而不是每次通过解散/弹出覆盖它的视图控制器来揭开它。)
编辑:
注意在这段代码中:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
refresh = true
if refresh == true {
DispatchQueue.main.async { //This bit is not needed
self.fetchArticles()
self.refresh = false
}
}
}
不需要调用DispatchQueue.main.async
,这会使获取数据稍微慢一些。viewWillAppear(_:)
总是在主线程上被调用。
重写如下:
override func viewDidLoad() {
super.viewDidLoad()
registerCell()
refresh = true //Moved from viewWillAppear
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
//Remove refresh = true from this function.
if refresh == true {
//No need to use DispatchQueue.main.async here
self.fetchArticles()
self.refresh = false
}
}