为什么加载图像时,我的TabView会变回“主页”选项卡?

时间:2019-10-29 09:31:27

标签: uiimage swiftui tabview urlsession

我创建了一个带有两个标签的TabView。一个是“家”,另一个是从NASA每日API图片中加载文本和图像。当我更改为当天的NASA图片时,看到“正在加载数据”,直到数据加载完毕。加载数据后,由于某种原因,选项卡将切换回“主页”选项卡。发生此错误后,我可以正常在两个选项卡之间来回切换,并且一切都已加载。为什么将选项卡切换回主页选项卡?谢谢!!

APIImageView代码:

import SwiftUI

struct ApiImageView: View {
    @ObservedObject var apiImage = ApiImage()

    var body: some View {
        Group {
            if apiImage.dataHasLoaded {
                VStack {

                    Text(apiImage.title!)
                        .font(.largeTitle)
                    Image(uiImage: apiImage.image!).resizable()
                        .cornerRadius(10)
                        .padding()
                    ScrollView(.vertical, showsIndicators: false) {
                        Text(apiImage.explanation!)
                            .font(.subheadline)
                            .padding()

                    }
                }
            } else {
                Text("Loading Data")
            }
        }.onAppear {
            self.apiImage.loadImageFromApi(urlString: "https://api.nasa.gov/planetary/apod?api_key=eaRYg7fgTemadUv1bQawGRqCWBgktMjolYwiRrHK")
        }
    }
}

struct ApiImageView_Previews: PreviewProvider {
    static var previews: some View {
        ApiImageView()
    }
}

APIImage代码:

import SwiftUI

class ApiImage: ObservableObject {
    @Published var dataHasLoaded = false
    @Published var image: UIImage? = nil
    @Published var title: String? = nil
    @Published var explanation: String? = nil

}

extension ApiImage {
    func loadImageFromApi(urlString: String) {
        let url = URL(string: urlString)!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        let task = URLSession.shared.dataTask(with: request, completionHandler: parseJsonObject)
        task.resume()
    }

    func parseJsonObject(data: Data?, urlResponse: URLResponse?, error: Error?) {
        guard error == nil else {
            print("\(error!)")
            return
        }

        guard let content = data else {
            print("No data")
            return
        }

        let json = try! JSONSerialization.jsonObject(with: content)
        let jsonmap = json as! [String : Any]
        let titleText = jsonmap["title"] as! String
        let explanationText = jsonmap["explanation"] as! String
        let urlString = jsonmap["url"] as! String

        print("\(urlString)")
        print("\(titleText)")
        print("\(explanationText)")

        DispatchQueue.main.async {
        self.title = titleText
        self.explanation = explanationText
        }

        let url = URL(string: urlString)!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        let task = URLSession.shared.dataTask(with: request, completionHandler: setImageFromData)
        task.resume()
    }

    func setImageFromData(data: Data?, urlResponse: URLResponse?, error: Error?) {
        guard error == nil else {
            print("\(error!)")
            return
        }

        guard let content = data else {
            print("No data")
            return
        }

        DispatchQueue.main.async {
            self.image = UIImage(data: content)
            self.dataHasLoaded = true
        }
    }
}

MainTabView代码:

import SwiftUI

struct MainTabView: View {
    var body: some View {
                    TabView {
                CategoryHome()

                    .tabItem {
                        Image(systemName: "house.fill")
                        Text("Landmarks")
                            .tag(0)

                }
                ApiImageView()

                    .tabItem {

                        Image(systemName: "flame.fill")
                        Text("NASA Pic")
                            //.tag(1)


            }
        }
    }
}

struct MainTabView_Previews: PreviewProvider {
    static var previews: some View {
        MainTabView()
    }
}

1 个答案:

答案 0 :(得分:0)

也许不是直接解决方案,但也很重要:MainTabView似乎并不完全正确(.tag()应该在.tabItem闭包之外)。这将是正确的版本:

import SwiftUI

struct MainTabView: View {
    var body: some View {
        TabView {
            CategoryHome()
                .tabItem {
                     Image(systemName: "house.fill")
                     Text("Landmarks")
                }.tag(0)

            ApiImageView()
                .tabItem {
                     Image(systemName: "flame.fill")
                     Text("NASA Pic")
                }.tag(1)
        }
    }
}

struct MainTabView_Previews: PreviewProvider {
    static var previews: some View {
        MainTabView()
    }
}

也许这已经是解决方案;如果没有,希望对您有所帮助! :)