簡體   English   中英

JSON數據顯示在viewDidAppear而非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生命周期的更多信息,以便可以發現viewDidLoadviewDidAppear之間的區別😉

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM