ios - JSON 数据显示在 viewDidAppear 上而不是 viewDidLoad 上

标签 ios swift swifty-json

我有这个下载 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 上,数组为 10 个,但我没有知道如何从 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()
}

关于ios - JSON 数据显示在 viewDidAppear 上而不是 viewDidLoad 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51514509/

相关文章:

ios - 如何在 iOS 上启用/禁用设备明智的隐藏式字幕设置?

ios - 如何开始使用 OpenGL ES?

ios - iOS 中的平移和滑动有什么区别?

ios - 用户登录一次后,我在设置初始化 View Controller 时遇到问题

swift - 使用 Swiftyjson 从数组访问数据

ios - 控制中心信息未使用 AVSpeechSynthesizer 更新

ios - 在 TextField 中格式化部分文本

ios - 错误 - 预期返回 'UIInterfaceOrientationMask' 的函数中缺少返回值

ios - 无法将数据转换为字符周围的字符串

json - 无法将字符串转换为 Json 对象