I am creating a SwiftUI List with Details.
This list is fetching JSON data from Firebase Realtime. The data consist of 5 birds with an ID, a name and an image URL.
My problem is the following:
Each time I click on the back button after I navigate to details, the data get doubled every single time, what am I doing wrong? (see screenshots).
I am using MVVM design pattern, I am listening and removing that listener every time the View appears and disappears.
Please, find the code below:
Main View:
var body: some View {
NavigationStack {
List(viewModel.birds) { bird in
NavigationLink(destination: DetailsView(bird: bird)) {
HStack {
VStack(alignment: .leading) {
Text(bird.name).font(.title3).bold()
}
Spacer()
AsyncImage(url: URL(string: bird.imageURL)) { phase in
switch phase {
// downloading image here
}
}
}
}
}.onAppear {
viewModel.listentoRealtimeDatabase()
}
.onDisappear {
viewModel.stopListening()
}.navigationTitle("Birds")
}
}
DetailsView:
struct DetailsView: View {
var bird: Bird
var body: some View {
Text("\(bird.name)")
}
}
Model:
struct Bird: Identifiable, Codable {
var id: String
var name: String
var imageURL: String
}
View Model:
final class BirdViewModel: ObservableObject {
#Published var birds: [Bird] = []
private lazy var databasePath: DatabaseReference? = {
let ref = Database.database().reference().child("birds")
return ref
}()
private let encoder = JSONEncoder()
private let decoder = JSONDecoder()
func listentoRealtimeDatabase() {
guard let databasePath = databasePath else {
return
}
databasePath
.observe(.childAdded) { [weak self] snapshot in
guard
let self = self,
var json = snapshot.value as? [String: Any]
else {
return
}
json["id"] = snapshot.key
do {
let birdData = try JSONSerialization.data(withJSONObject: json)
let bird = try self.decoder.decode(Bird.self, from: birdData)
self.birds.append(bird)
} catch {
print("an error occurred", error)
}
}
}
func stopListening() {
databasePath?.removeAllObservers()
}
}
screenshot how it should be
Related
Trying to save some data in UserDefaults but I'm getting nil in the view.
I don't know where is the problem
This is my code in ContentView:
var saveButton: some View {
Button("Save Meal") {
let meal = Meal(name: self.mealGenerator.currentMeal!.name,
imageUrlString: self.mealGenerator.currentMeal!.imageUrlString,
ingredients: self.mealGenerator.currentMeal!.ingredients,
instructions: self.mealGenerator.currentMeal!.instructions,
area: self.mealGenerator.currentMeal!.area,
category: self.mealGenerator.currentMeal!.category)
self.savedMeals.meals.append(meal)
self.savedMeals.saveMeals()
}
This is my class I'm trying to save:
class SavedMeals: ObservableObject {
#Published var meals: [Meal]
func saveMeals() {
if let encoded = try? JSONEncoder().encode(meals) {
UserDefaults.standard.set(encoded, forKey: "Meals")
}
}
init() {
if let meals = UserDefaults.standard.data(forKey: "Meals") {
if let decoded = try? JSONDecoder().decode([Meal].self, from: meals) {
self.meals = decoded
return
}
}
self.meals = []
}
}
And I'm trying to list in a view:
struct SavedMealsView: View {
#ObservedObject var savedMeals: SavedMeals
var body: some View {
NavigationView {
List(savedMeals.meals) { meal in
Text(meal.name)
}
.navigationBarTitle("Saved Meals", displayMode: .inline)
}
}
}
You do meals = [] at the end of your init regardless of what you decode. Perhaps this will work better:
init() {
if data = UserDefaults.standard.data(forKey: "Meals") {
do {
meals = try JSONDecoder().decode([Meal].self, from: meals)
} catch {
assertionFailure("Oops!")
meals = []
}
} else {
meals = []
}
}
So I have this code, where I fetch a url from firestore and then append it to an array, which is then stored in userDefaults(temporarily).
In the view I basically just iterate over the array stored in userdefaults and display the images.
But the problem is, that I have to rerender the view before the images show.
How can i fix this?
struct PostedImagesView: View {
#State var imagesUrls : [String] = []
#ObservedObject var postedImagesUrls = ProfileImages()
var body: some View {
VStack{
ScrollView{
ForEach(postedImagesUrls.postedImagesUrl, id: \.self) { url in
ImageWithURL(url)
}
}
}
.onAppear{
GetImage()
print("RAN GETIMAGE()")
}
}
// Get Img Url from Cloud Firestore
func GetImage() {
guard let userID = Auth.auth().currentUser?.uid else { return }
let db = Firestore.firestore()
db.collection("Users").document(userID).collection("PostedImages").document("ImageTwoTester").getDocument { (document, error) in
if let document = document, document.exists {
// Extracts the value of the "Url" Field
let imageUrl = document.get("Url") as? String
UserDefaults.standard.set([], forKey: "postedImagesUrls")
imagesUrls.append(imageUrl!)
UserDefaults.standard.set(imagesUrls, forKey: "postedImagesUrls")
} else {
print(error!.localizedDescription)
}
}
}
}
I have the following code, How can i accomplish this without changing struct into class. Escaping closure captures mutating 'self' parameter,
struct RegisterView:View {
var names = [String]()
private func LoadPerson(){
FirebaseManager.fetchNames(success:{(person) in
guard let name = person.name else {return}
self.names = name //here is the error
}){(error) in
print("Error: \(error)")
}
init(){
LoadPerson()
}a
var body:some View{
//ui code
}
}
Firebasemanager.swift
struct FirebaseManager {
func fetchPerson(
success: #escaping (Person) -> (),
failure: #escaping (String) -> ()
) {
Database.database().reference().child("Person")
.observe(.value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: Any] {
success(Person(dictionary: dictionary))
}
}) { (error) in
failure(error.localizedDescription)
}
}
}
SwiftUI view can be created (recreated) / copied many times during rendering cycle, so View.init is not appropriate place to load some external data. Use instead dedicated view model class and load explicitly only when needed.
Like
class RegisterViewModel: ObservableObject {
#Published var names = [String]()
func loadPerson() {
// probably it also worth checking if person has already loaded
// guard names.isEmpty else { return }
FirebaseManager.fetchNames(success:{(person) in
guard let name = person.name else {return}
DispatchQueue.main.async {
self.names = [name]
}
}){(error) in
print("Error: \(error)")
}
}
struct RegisterView: View {
// in SwiftUI 1.0 it is better to inject view model from outside
// to avoid possible recreation of vm just on parent view refresh
#ObservedObject var vm: RegisterViewModel
// #StateObject var vm = RegisterViewModel() // << only SwiftUI 2.0
var body:some View{
Some_Sub_View()
.onAppear {
self.vm.loadPerson()
}
}
}
Make the names property #State variable.
struct RegisterView: View {
#State var names = [String]()
private func LoadPerson(){
FirebaseManager.fetchNames(success: { person in
guard let name = person.name else { return }
DispatchQueue.main.async {
self.names = [name]
}
}){(error) in
print("Error: \(error)")
}
}
//...
}
I'm building a SwiftUI app that retrieves an array of movies by genre from The Movie Database API.
Once the user selects a movie, I make a second API to get details for that specific movie. I'm using #Published to notify the view of changes however I am getting the I get the error "Missing argument for parameter 'from' in call" whenever I call an instance of the Model.
Here's the Model:
import Foundation
// MARK: - MovieList
struct MovieList: Codable {
let page: Int
let totalResults: Int
let totalPages: Int
let movie: [Movie]
enum CodingKeys: String, CodingKey {
case page
case totalResults = "total_results"
case totalPages = "total_pages"
case movie = "results"
}
}
// MARK: - Movie
struct Movie: Codable {
let popularity: Double
let voteCount: Int
let video: Bool
let posterPath: String?
let id: Int
let adult: Bool
let backdropPath: String?
let title: String
let voteAverage: Double
let overview: String
let releaseDate: String?
let runTime: Int?
enum CodingKeys: String, CodingKey {
case popularity
case voteCount = "vote_count"
case video
case posterPath = "poster_path"
case id, adult
case backdropPath = "backdrop_path"
case title
case voteAverage = "vote_average"
case overview
case releaseDate = "release_date"
case runTime = "runtime"
}
}
And here's the View Model:
import Foundation
class DetailViewModel: ObservableObject {
#Published var fetchedMovie = Movie() // getting error here
func getMovieDetails(id: Int) {
WebService().getMovieDetails(movie: id) { movie in
if let movieDetails = movie {
self.fetchedMovie = movieDetails
}
}
}
}
And here's the network call:
func getMovieDetails(movie: Int, completion: #escaping (Movie?) -> ()) {
guard let url = URL(string: "https://api.themoviedb.org/3/movie/\(movie)?api_key=5228bff935f7bd2b18c04fc3633828c0") else {
fatalError("Invalid URL")
}
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: url) { data, response, error in
// Check for errors
guard error == nil else {
print ("error: \(error!)")
return
}
// Check that data has been returned
guard let data = data else {
print("No data")
return
}
do {
let decoder = JSONDecoder()
let movieDetails = try decoder.decode(Movie.self, from: data)
DispatchQueue.main.async {
completion(movieDetails)
}
} catch let err {
print("Err", err)
}
}
// execute the HTTP request
task.resume()
}
}
And the View code:
import SwiftUI
struct MovieDetailView: View {
#ObservedObject private var detailVM = DetailViewModel() // error here: Missing argument for parameter 'movie' in call
var movie: DetailViewModel
var body: some View {
VStack {
URLImage(url: "\(movie.backdropURL)")
.aspectRatio(contentMode: .fit)
Text("\(detailVM.movieRunTime) mins")
Text(movie.movieOverview)
.padding()
Spacer()
}.onAppear {
self.detailVM.getMovieDetails(id: self.movie.id)
}
.navigationBarTitle(movie.movieTitle)
}
}
struct MovieDetailView_Previews: PreviewProvider {
static var previews: some View {
MovieDetailView(movie: DetailViewModel(movie: Movie.example))
}
}
Any help would be greatly appreciated.
You cant initialise Movie object like this ... it needs Decoder object or all member wise intialization ---
You can define your function like this
class DetailViewModel: ObservableObject {
#Published var fetchedMovie : Movie?
func getMovieDetails(id: Int) {
WebService().getMovieDetails(movie: id) { movie in
if let movieDetails = movie {
self.fetchedMovie = movieDetails
}
}
}
}
I have a function that goes out to an api and gets a stock price. I have the function returning a double and I can see the correct price print out to the console when I run the code. When I try to set that price to a variable inside the function so the function can return it, I just get 0.000 in the text view. Can someone tell me what I'm doing wrong? My code is below.
import SwiftUI
struct ListView: View {
var body: some View {
List {
HStack {
Text("Stock Price (15 Min. delay)")
Spacer()
Text("\(getStockPrice(stock: symbol))")
}
}
}
func getStockPrice(stock: String) -> Double {
var thePrice = Double()
guard let url = URL(string: "my url to get data") else {
fatalError("URL does not work!")
}
URLSession.shared.dataTask(with: url) { jsonData, _, _ in
guard let jData = jsonData else {return}
do {
if let json = try JSONSerialization.jsonObject(with: jData, options: []) as? [String: Any] {
if let pricer = json["latestPrice"] as? Double {
print(pricer)
thePrice = pricer
}
}
} catch let err {
print(err.localizedDescription)
}
}.resume()
return thePrice
}
}
You can update your UI with changing the #State variable, like in code below:
struct UpdatingPriceAsync: View {
#State var stockPrice: Double = 0.0
var body: some View {
List {
HStack {
Text("Stock Price (15 Min. delay)")
Spacer()
Text("\(stockPrice)")
.onAppear() {
self.updateStockPrice(stock: "something")
}
}
}
}
private func updateStockPrice(stock: String) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { // sort of URL session task
DispatchQueue.main.async { // you need to update it in main thread!
self.stockPrice = 99.9
}
}
}
}