![](/img/trans.png)
[英]How to request JSON data in the viewDidAppear method or viewDidLoad?
[英]JSON data shown on viewDidAppear and not viewDidLoad
我有這個下載JSON並將其附加到數組中
func downloadDetails(completed: @escaping DownloadComplete){
Alamofire.request(API_URL).responseJSON { (response) in
let result = response.result
let json = JSON(result.value!).array
let jsonCount = json?.count
let count = jsonCount!
for i in 0..<(count){
let image = json![i]["urls"]["raw"].stringValue
self.imagesArray.append(image)
}
self.tableView.reloadData()
print(self.imagesArray)
completed()
}
}
我知道viewDidLoad
首先加載, viewDidAppear
加載。 我正在嘗試檢索包含所有信息的數組,但由於該數組為空,因此未在viewDidLoad
顯示,但在帶有十個數組的viewDidAppear
上顯示,我不知道如何從viewDidAppear
獲取該信息。
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var imageList: Image!
var imagesArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad " ,imagesArray)
setupDelegate()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
downloadDetails {
DispatchQueue.main.async {
}
print("viewDidAppear ", self.imagesArray)
}
}
輸出如下
viewDidLoad []
viewDidAppear ["https://images.unsplash.com/photo-1464550883968-cec281c19761", "https://images.unsplash.com/photo-1464550838636-1a3496df938b", "https://images.unsplash.com/photo-1464550580740-b3f73fd373cb", "https://images.unsplash.com/photo-1464547323744-4edd0cd0c746", "https://images.unsplash.com/photo-1464545022782-925ec69295ef", "https://images.unsplash.com/photo-1464537356976-89e35dfa63ee", "https://images.unsplash.com/photo-1464536564416-b73260a9532b", "https://images.unsplash.com/photo-1464536194743-0c49f0766ef6", "https://images.unsplash.com/photo-1464519586905-a8c004d307cc", "https://images.unsplash.com/photo-1464519046765-f6d70b82a0df"]
什么是訪問包含信息的陣列的正確方法?
那是因為請求是異步的,它不是作為代碼的串行行執行的,所以根據網絡狀態應該有一個延遲,除了您甚至不調用viewDidLoad
內部的downloadDetails
//
您還需要在此處重新加載表格
downloadDetails { // Alamofire callback by default runs in main queue
self.tableView.reloadData()
}
只需調用您的方法
viewDidLoad()
也許您應該了解有關iOS生命周期的更多信息,以便可以發現viewDidLoad和viewDidAppear之間的區別😉
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.