我正在尝试通过Swift 5中的HTTP get方法从API提取数据。它在启动时成功加载了数据,但是当我刷新页面时,它说“索引超出范围”,这是因为数据是不再会在我的日志中读取,因此索引中没有任何内容。这是一个常见问题,还是仅与我有关?我在下面附加了我的代码,并突出显示了错误出现的位置。谢谢!

import UIKit
import Foundation

class TheClass: UIViewController, UITableViewDataSource, UITableViewDelegate {


    @IBOutlet weak var pageView: UITableView!




    struct StocksObject {
    var volume: String?

    }


struct Response: Codable {
    let _type: String?
    let readLink: String?
    let totalEstimatedMatches: Int?
    let value: [Value]?

}

struct QueryContext: Codable {
    let originalQuery: String?
    let adultIntent: Bool?
}

struct Value: Codable {
    let name: String?
}

    var stocks_object = [StocksObject]()
    var news_object = [Value]()


    override func viewDidAppear(_ animated: Bool) {
        self.news_object.removeAll()
        self.getNews()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        getData()
        getNews()



        pageView.delegate = self
        pageView.dataSource = self



    }




    func getNews() {





        let request = NSMutableURLRequest(url: NSURL(string: "https://example.com")! as URL,
            cachePolicy: .useProtocolCachePolicy,
        timeoutInterval: 10.0)

        request.httpMethod = "GET"
        request.allHTTPHeaderFields = headers

        URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in

            guard let data = data else { return }
            do {
                let obj: Response = try JSONDecoder().decode(Response.self, from: data)

                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)


                let objectReview = Value(name: obj.value?[0].name)

                self.news_object.append(objectReview)


                print("\(String(describing: obj.value?[0].name))")
                print("\(String(describing: obj.value?[2].name))")

                } catch {

                print("ERROR: \(error)")
                    self.performSegue(withIdentifier: "InvalidSymbol", sender: nil)

                    }

                }.resume()

            }


    func getData() {

        let url = URL(string: "https://example2.com")!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"


        NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {
            (response, data, error) in

            if let data = data {

                do {
                    let json = try JSONDecoder().decode(Root.self,from: data)

                    let Volume = json.data.first?.volume


                    struct Root: Codable {
                        let data: [Datum]
                    }
                    struct Datum: Codable {
                        let volume: String



                    }

                    print(json)


                    let object = StocksObject(volume: Volume)
                    self.stocks_object.append(object)
                    DispatchQueue.main.async {
                        self.pageView.reloadData()

                    }

                } catch {
                    print(error)

                }
            }
        }
    }


    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 825
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return stocks_object.count

    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! StockCell

        let object = stocks_object[indexPath.row]

//Error is coming in here:

        let objectNews = news_object[indexPath.row]


        cell.volume.text = object.volume


        cell.newsOne.text = objectNews.name


        return cell

    }
}

最佳答案

在viewDidAppear内部,您需要在页面加载时清空“news_object”数组,然后在viewDidAppear内部调用self.getNews()。

内部viewDidAppear:

self.news_object.removeAll()
self.getNews()

由于您已编辑问题,因此这是您遇到此错误的原因。

对于上面的代码,您需要创建switch语句来检查要返回的array.count并在cellForRowAt中执行相同的操作。因为它们都有不同的长度,这就是您面临错误“超出范围”的原因

我希望现在就清楚了。

关于ios - 第二次API调用后应用崩溃(快速),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60936203/

10-12 12:55