OStack程序员社区-中国程序员成长平台

标题: ios - Swift解析json和数据传输 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:17
标题: ios - Swift解析json和数据传输

我是 iOS 开发的初学者。 摆在我面前的任务是使用 api GitHub 来获取关于用户 Gist 描述的数据。

这个想法是这样的: 我在第一个 viewcontroller (LoginViewController) 的 usernameTextField 中输入用户名 然后你按下 searchTapped,segue 被触发并把你扔到第二个 View Controller (GistsViewController),在 tableview 中显示收到的描述来自 json 来自 json 的数据被解码并添加到 gists 数组中,然后通过 segue 传递到 GistsViewController。 但是该项目没有错误,但它不能正常工作..有人可以帮我编辑我的代码吗?

这是我的模型:

struct Gists: Codable {
    let description: String?

    private enum CodingKeys: String, CodingKey {
        case description

    }
}

这是第一个 viewController:

class LoginViewController: UIViewController {

    @IBOutlet weak var warningLabel: UILabel!
    @IBOutlet weak var usernameTextField: UITextField!

    var gists = [String]()
    var username: String?

    func displayWarningLabel(withText text: String) {
        warningLabel.text = text
        UIView.animate(withDuration: 3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: { [weak self] in
            self?.warningLabel.alpha = 1
        }) { [weak self] complete in
            self?.warningLabel.alpha = 0
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        warningLabel.alpha = 0
    }

    @IBAction func unwindToMainScreen(segue: UIStoryboardSegue) {
        usernameTextField.text = ""
    }

    @IBAction func searchTapped(_ sender: UIButton) {
        guard let username = usernameTextField.text, username != "" else {
            displayWarningLabel(withText: "Information is incorrect")
            return
        }

        guard let gitUrl = URL(string: "https://api.github.com/users/\(username)/gists") else { return }
        URLSession.shared.dataTask(with: gitUrl) { (data, response, error) in 
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                let gitData = try decoder.decode([Gists].self, from: data)

                DispatchQueue.main.sync {
                    self.gists.append(gitData.description)
                }
            } catch let err {
                print("Err", err)
            }
            }.resume()

        performSegue(withIdentifier: "GistsSegue", sender: nil)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let dvc = segue.destination as? GistsViewController else { return }
        dvc.username = usernameTextField.text
        dvc.gists1 = gists
        }
}

这是第二个 viewController:

class GistsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var username: String!
    var gists1 = [String]()

    @IBOutlet weak var tableView: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return gists1.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.backgroundColor = .clear
        cell.textLabel?.text = gists1[indexPath.row]
        self.tableView.reloadData()
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = username
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.dataSource = self
        tableView.delegate = self
        print(gists1)
    }

    @IBAction func addTapped(_ sender: UIBarButtonItem) {
    }     
}

非常感谢任何帮助!



Best Answer-推荐答案


对api的调用是异步的,所以在完成 block 里面插入performSegue

guard let gitUrl = URL(string: "https://api.github.com/users/\(username)/gists") else { return }
URLSession.shared.dataTask(with: gitUrl) { (data, response, error) in
    guard let data = data else { return }
    do {
        let decoder = JSONDecoder()
        let gitData = try decoder.decode([Gists].self, from: data)

        DispatchQueue.main.sync {
            self.gists.append(contentsOf:gitData)
            performSegue(withIdentifier: "GistsSegue", sender: nil)
        }
    } catch let err {
        print("Err", err)
    }
    }.resume()

关于ios - Swift解析json和数据传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51080299/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4