gpt4 book ai didi

ios - 在数组上追加元素后,它只显示在追加方法上,当我们从另一个方法调用时为空 swift 3

转载 作者:行者123 更新时间:2023-11-28 21:20:52 25 4
gpt4 key购买 nike

在数组上追加元素后,它只显示在追加方法上,当我们从另一个方法调用时为空 swift 3

导入 UIKit进口 Alamofire导入 SwiftyJSON

ViewController 类:UIViewController、UITableViewDelegate、UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

let JSONUrl = "https://jsonplaceholder.typicode.com/posts"
var JSONData: JSON = nil

var JSONDataUserId = [Int]()
var JSONDataId = [Int]()
var JSONDataTitle = [String]()
var JSONDataBody = [String]()

override func viewDidLoad() {
super.viewDidLoad()


getDataFromJSON(url: JSONUrl)
dispalyData()
}

func getDataFromJSON(url: String) {
Alamofire.request(url).responseJSON { (response) in
switch response.result{
case .success(let data):
self.JSONData = JSON(data)
for i in 0..<self.JSONData.count{
self.JSONDataUserId.append(self.JSONData[i]["userId"].intValue)
self.JSONDataId.append(self.JSONData[i]["id"].intValue)
self.JSONDataTitle.append(self.JSONData[i]["title"].stringValue)
self.JSONDataBody.append(self.JSONData[i]["body"].stringValue)
}

case .failure(let error):
print("Error Due to \(error)")
}
print(self.JSONDataUserId)

}
}

func displayData() {

print(self.JSONDataUserId)
}

在上面的方法 getDataFromJson 中,语句 print(self.JSONDataUserId) 工作并显示数据,但是方法 displayData print(self.JSONDataUserId) 不显示任何内容。我也想要 displayData 方法的相同结果。

最佳答案

你正在使用异步代码块,所以试试这个。您正在发送服务器请求,然后并行调用 getdatafrom 服务器方法。更多信息请查看Apple Api Reference

    import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

let JSONUrl = "https://jsonplaceholder.typicode.com/posts"
var JSONData: JSON = nil

var JSONDataUserId = [Int]()
var JSONDataId = [Int]()
var JSONDataTitle = [String]()
var JSONDataBody = [String]()

override func viewDidLoad() {
super.viewDidLoad()


getDataFromJSON(url: JSONUrl) { success, data in
if success {
for i in 0..< data.count{
self.JSONDataUserId.append(self.JSONData[i]["userId"].intValue)
self.JSONDataId.append(self.JSONData[i]["id"].intValue)
self.JSONDataTitle.append(self.JSONData[i]["title"].stringValue)
self.JSONDataBody.append(self.JSONData[i]["body"].stringValue)
}
dispalyData()
}

}

}

func getDataFromJSON(url: String, completionHandler: @escaping (Bool, JSON) -> ()) {
Alamofire.request(url).responseJSON { (response) in
switch response.result{
case .success(let data):
completionHandler(true, JSON(data))
case .failure(let error):
print("Error Due to \(error)")
completionHandler(false, nil)
}
}
}

func displayData() {

print(self.JSONDataUserId)
}
}

关于ios - 在数组上追加元素后,它只显示在追加方法上,当我们从另一个方法调用时为空 swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39856493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com