gpt4 book ai didi

ios - 如何从 URLSession 获取数组

转载 作者:行者123 更新时间:2023-11-29 05:16:43 25 4
gpt4 key购买 nike

尝试为新闻网站制作一个程序。我通过 api 从网站获取信息,一切正常。

唯一的问题是,如何让这个数组脱离循环?

这是我的代码:

import UIKit

class ViewController: UIViewController {
var news:[News] = []

override func viewDidLoad() {
super.viewDidLoad()

getUsers()
print(news)
}

func getUsers() {
guard let url = URL(string: "http://prostir.news/swift/api2.php") else {return}
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
news = try JSONDecoder().decode([News].self, from: data)
// print(self.news)
} catch let error {
print(error)
}
}
}.resume()
}
}

最佳答案

struct News:Codable, CustomStringConvertible{
let href:String?
let site:String?
let title:String?
let time:String?

var description: String {
return "(href:- \(href), site:- \(site), title:- \(title), time:- \(time))"
}
}

在类中声明新闻数组,并在 getUsers 方法中将响应分配给该数组

var news:[News] = []

func getUsers(){
guard let url = URL(string: "https") else {return}
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
self.news = try JSONDecoder().decode([News].self, from: data)
print(self.news)
} catch let error {
print(error)
}
}
}.resume()
}

关于ios - 如何从 URLSession 获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114379/

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