arrays - 访问从 API 解码的数组中的第一项

标签 arrays json swift api swiftui

大家好,节日快乐!

我是一名 SwiftUI 新手,刚刚开始使用 API。我设法习惯了解码 API,但当我尝试访问数组中的第一项时遇到问题。我正在使用 SwiftyJSON 进行解码。我尝试访问索引 0,但构建失败并出现错误:索引超出范围

任何提示都会非常有帮助,尤其是对于像我这样的新手。

提前谢谢您!

型号

struct  dataType: Identifiable {

var id: String
var title: String
var desc: String
var url: String
var image: String

解码 JSON

class getData: ObservableObject {

@Published var datas = [dataType]()

init() {

    let source = "https://newsapi.org/v2/top-headlines?country=ro&apiKey=c602e42864e148dea1144f1f55255888"

    let url = URL(string: source)!

    let session = URLSession(configuration: .default)

    session.dataTask(with: url) { (data, _, err) in

        if err != nil {

            print((err?.localizedDescription)!)
            return
        }

        let json = try! JSON(data: data!)

        for i in json["articles"]{

            let title = i.1["title"].stringValue
            let description = i.1["description"].stringValue
            let url = i.1["url"].stringValue
            let image = i.1["urlToImage"].stringValue
            let id = i.1["publishedAt"].stringValue

            DispatchQueue.main.async {
                self.datas.append(dataType(id: id, title: title, desc: description, url: url, image: image))
            }
        }
    }.resume()
}

最后是 View

struct ContentView: View {

@ObservedObject var list = getData()
var body: some View {

    VStack {

        WebImage(url: URL(string: list.datas[0].title), options: .highPriority, context: nil)
            .resizable()
            .frame(width:400, height:250)

        NavigationView {

                List(list.datas){i in

                    NavigationLink(destination: webView(url: i.url).navigationBarTitle("", displayMode: .inline))
                    {
                        HStack {

                            VStack(alignment: .leading, spacing: 10) {

                                Text(i.title).fontWeight(.heavy)

                                Text(i.desc)
                                    .lineLimit(3)
                            }

                            if i.image != "" {

                                WebImage(url: URL(string:i.image), options: .highPriority, context: nil)
                                    .resizable()
                                    .frame(width: 110, height: 135)
                                    .cornerRadius(20)
                            }

                        }.padding(.vertical, 15)
                    }

                }.navigationBarTitle("Noutati")
        }
    }
}

最佳答案

URLSession 异步执行 dataTask,因此一开始还没有数据,即。 datas 为空,因此尝试获取空数组的第一个(在 datas[0] 下面)元素会导致异常(如您所见)

WebImage(url: URL(string: list.datas[0].title), options: .highPriority, context: nil)
            .resizable()
            .frame(width:400, height:250)

相反,您需要显示一些 stub View ,直到加载数据,如下所示

if list.data.isEmpty {
   Text("Loading...")
} else {
    WebImage(url: URL(string: list.datas[0].title), options: .highPriority, context: nil)
                .resizable()
                .frame(width:400, height:250)
}

关于arrays - 访问从 API 解码的数组中的第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507299/

相关文章:

带有 ID 和描述的 PHP 数组 - 随机化数组并打印列表

c# - 使用 JSON.Net 的 Web API 的驼峰式大小写问题

快速检查文本字段输入

arrays - 识别没有数组公式的单元格

java - 为什么 Byte [] 在 JSON View 中被转换为 String

node.js - Docker 构建不使用 npm ci 的缓存

ios - 如何用二维数组填充表格 View ?

ios - 如何在 iOS 中使用 takePicture() 以编程方式拍照?

c - 访问由 C 中的函数修改的字符串数组时出现段错误

arrays - 在 NodeJS 中向数组 mongoose 中插入元素创建对象