问题描述
我正在登录并显示数据。用户登录时,数据将正确显示。当我注销并登录另一个帐户时,应该由observedObject更新的数据将调用该函数以重新加载数据。但是,当我登录到应用程序时,主视图仍然显示以前帐户的旧数据。我不知道是什么问题。我什至尝试注销时清除了课堂上的数据,也尝试了多种方法来解决问题,但是视图仍然没有更新。寻求帮助,tq。
struct ContentView: View {
@EnvironmentObject var authService:AuthService
var body: some View{
ZStack{
if(!authService.signedIn){
RegisterView()
}
else{
HomePageView()
}
}
}}
struct HomePageView: View {
@ObservedObject var shopList:ShopJSON = .shared
var body: some View {
TabView{
HomePromotionView(shopList: shopList)
.tabItem {
Image(systemName: "house")
}.tag(1)
NavigationView{
BookingView()
}
.tabItem {
Image(systemName: "calendar")
}.tag(3)
}
.onAppear(perform: ShopJSON.shared.reload) //I try to force reload data.
}
}
struct HomePromotionView: View {
@State private var selectedSegment = 0
@ObservedObject var shopList : ShopJSON
private let homeSegment = ["PROMOTION","HISTORY","MESSAGE"]
var body: some View {
NavigationView {
VStack {
ScrollView(.horizontal,showsIndicators: false){
HStack{
ForEach(shopList.shops){ item in
MerchantBar(name:item.name!,icon: item.icon!,id: item.shopID!)
}
class ShopJSON: ObservableObject {
@Published var shops = [Shops]()
@Published var bcsts = [Bcast]()
@Published var selectedID : Int?
static let shared = ShopJSON()
let auth = UserDefaults.standard.string(forKey: "Auth")
private init() {
load()
}
func reload() {
load()
}
func clear() {
self.shops = [Shops]()
self.bcsts = [Bcast]()
self.selectedID = nil
}
func load() {
let url = URL(string: "https://12345/shop/")!
var request = URLRequest(url: url)
request.setValue("application/json",forHTTPHeaderField: "Content-Type")
request.setValue(self.auth,forHTTPHeaderField: "token")
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { data,response,error in
guard let data = data else {
print("No data in response: \(error?.localizedDescription ?? "Unknown error").")
return
}
if let decodedShops = try? JSONDecoder().decode(Json4Swift_Base.self,from: data) {
DispatchQueue.main.async {
self.shops = decodedShops.shops!
self.bcsts = decodedShops.bcast!
退出按钮
Text("Sign Out")
.foregroundColor(Color.gray)
.onTapGesture {
self.authService.signOut()
UserDefaults.standard.set(nil,forKey: "Auth")
//self.shopList.clear() //force clean data but view didn't update while login with another account
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)