我正在使用Firestore和Swift开发iOS应用。
该应用是用于注册您喜欢的电影的应用。
该屏幕包含:
您可以使用下面的代码将电影添加到收藏夹。
从“ MovieSearchView”转到“ MovieDetailView”,然后单击“添加”按钮。
然后,由于某种原因,它将自动返回到“电影搜索视图”。
即使按下“添加”按钮,如何仍可以停留在“ MovieDetailView”中?
谢谢。
import SwiftUI
import FirebaseFirestore
import Foundation
struct FavoriteMovieListView: View {
@ObservedObject var favoriteMoviesFetcher = FavoriteMoviesFetcher()
@State private var modalPresented: Bool = false
var body: some View {
VStack {
Button(action: {
self.modalPresented.toggle()
}) {
Text("Search")
}
.sheet(isPresented: self.$modalPresented) {
MovieSearchView(onDismiss: {
self.modalPresented = false
})
}
List(self.favoriteMoviesFetcher.data) { movie in
Text(movie.title)
}
}
}
}
struct MovieSearchView: View {
@ObservedObject var allMovieFetcher = AllMovieFetcher()
var onDismiss: () -> ()
var body: some View {
NavigationView {
List(allMovieFetcher.data) { movie in
NavigationLink(
destination: MovieDetailView(
movie: movie
)
) {
Text(movie.title)
}
}
}
}
}
struct MovieDetailView: View {
@State var movie: MovieModel
var body: some View {
Button(action: {
FavoriteMoviesService().addMovie(movie: self.movie)
}) {
Text("Add")
}
}
}
class FavoriteMovieFetcher: ObservableObject {
@Published var data: [MovieModel] = []
private var db: Firestore!
private var uid: String
init() {
db = Firestore.firestore()
uid = UserDefaults.standard.object(forKey: "userUid") as! String
fetchData()
}
private func fetchData() {
self.db.collection("favoriteMovies/\(uid)/movies").addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .added) {
self.data.append(MovieModel(
movieId: diff.document.documentID,
title: diff.document.data()["title"]as! String
))
} else if (diff.type == .modified) {
} else if (diff.type == .removed) {
self.data = self.data.filter { $0.movieId != diff.document.documentID }
}
}
self.isLoading = false
}
}
}
class AllMovieFetcher: ObservableObject {
@Published var data: [MovieModel] = []
private var db: Firestore!
init() {
db = Firestore.firestore()
fetchData()
}
private func fetchData() {
self.db.collection("movies").getDocuments { (snaps, err) in
if let err = err {
print("Error getting documents: \(err)")
}
guard let snaps = snaps else { return }
for document in snaps.documents {
self.data.append(
MovieModel(
movieId: document.documentID,
title: document.data()["title"]as! String
)
)
}
}
}
}
class FavoriteMoviesService: ObservableObject {
private var db: Firestore!
private var uid: String
init() {
db = Firestore.firestore()
uid = UserDefaults.standard.object(forKey: "userUid") as! String
}
func addMovie(movie: MovieModel) {
self.db.collection("favoriteMovies/\(uid)/movies").document(movie.movieId).setData([
"title": movie.title
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
}
}
}
}
struct MovieModel: Identifiable {
var id = UUID()
var movieId: String
var title: String
}