Non-Nil User Crashing When Unwrapped - Firebase, SwiftUI - firebase

Unwrapping values the conventional way in SwiftUI views is not allowed, but you can do so within the body of, say, an HStack or a VStack. Below I am trying to unwrap a user I was certain was not nil. My LoginView lets a user create an account on Firebase Firestore, logs you in if a user enters the correct values, and shows an alert view if not.
In my HomeView.swift, the first screen after launch, I crash when trying to present the user image. However, when I unwrap the user, the user is still nil in the console. I think this is because Firebase doesn't have time to load the image before the view initializes. But I could be wrong. Help.
struct HomeProfileView: View {
#EnvironmentObject var session: SessionStore
#State var showDashboard = false
var user: User?
var body: some View {
if user != nil {
URLImage(URL(string: user!.profileImageUrl)!, content: {
$0.image
.resizable()
.aspectRatio(contentMode: .fill)
.clipShape(Circle())
})
.frame(width: 50, height: 50)
.background(Color(#colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1)))
.clipShape(Circle())
.shadow(color: Color.black.opacity(0.1), radius: 1, x: 0, y: 1)
.shadow(color: Color.black.opacity(0.2), radius: 10, x: 0, y: 10)
.sheet(isPresented: $showDashboard) {
DashboardView(showDashboard: $showDashboard)
}
}
}
}
I don't think I need an optional user, here, but I do not know how to safely unwrap the user otherwise. Another version is using the session EnvironmentObject to access the currently logged user.
struct HomeProfileView: View {
#EnvironmentObject var session: SessionStore
#State var showDashboard = false
var body: some View {
if session.isLoggedIn {
URLImage(URL(string: session.userSession!.profileImageUrl)!, content: {
$0.image
.resizable()
.aspectRatio(contentMode: .fill)
.clipShape(Circle())
})
.frame(width: 50, height: 50)
.background(Color(#colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1)))
.clipShape(Circle())
.shadow(color: Color.black.opacity(0.1), radius: 1, x: 0, y: 1)
.shadow(color: Color.black.opacity(0.2), radius: 10, x: 0, y: 10)
.sheet(isPresented: $showDashboard) {
DashboardView(showDashboard: $showDashboard)
}
}
}
}
The session property belongs to a SessionStore class and is essentially an optional User.
import Foundation
import Combine
import Firebase
class SessionStore: ObservableObject {
#Published var isLoggedIn: Bool = UserDefaults.standard.bool(forKey: "isLoggedIn") {
didSet {
UserDefaults.standard.set(self.isLoggedIn, forKey: "isLoggedIn")
}
}
var userSession: User?
var handle: AuthStateDidChangeListenerHandle?
func listenAuthenticationState() {
handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
if let user = user {
print(user.email as Any)
let firestoreUserId = Ref.FIRESTORE_DOCUMENT_USERID(userId: user.uid)
firestoreUserId.getDocument { (document, error) in
if let dict = document?.data() {
guard let decodeUser = try? User.init(fromDictionary: dict) else { return }
self.userSession = decodeUser
}
}
self.isLoggedIn = true
} else {
print("User is Logged Out")
self.isLoggedIn = false
self.userSession = nil
}
})
}
}
The logged in user is indeed logged in but I cannot access any properties.

Set isLoggedIn exactly at the place you set userSession, because it is done in async callback, and do this on main queue (to update UI properly)
firestoreUserId.getDocument { (document, error) in
if let dict = document?.data() {
guard let decodeUser = try? User.init(fromDictionary: dict) else { return }
DispatchQueue.main.async {
self.userSession = decodeUser
self.isLoggedIn = true
}
}
}

I have this working. Not sure how scalable it is but I am doing a not equals nil. I also put it in a button to toggle it versus an onTapGesture.
struct HomeProfileView: View {
#EnvironmentObject var session: SessionStore
#State var showDashboard = false
var body: some View {
if session.isLoggedIn {
if (session.userSession?.profileImageUrl) != nil {
Button(action: { self.showDashboard.toggle() } ) {
URLImage(URL(string: session.userSession!.profileImageUrl)!, content: {
$0.image
.resizable()
.aspectRatio(contentMode: .fill)
.clipShape(Circle())
})
.frame(width: 50, height: 50)
.background(Color(#colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1)))
.clipShape(Circle())
.shadow(color: Color.black.opacity(0.1), radius: 1, x: 0, y: 1)
.shadow(color: Color.black.opacity(0.2), radius: 10, x: 0, y: 10)
.sheet(isPresented: $showDashboard) {
DashboardView(showDashboard: $showDashboard)
}
}
}
}
}
}

Related

Display data from firestore

I am trying to display the data I get back from the firestore in my swiftUI app but am having some trouble.
Here is where I get the data
import Foundation
import Firebase
class RecipesViewModel: ObservableObject {
#Published var userRecipes = [RecipesData]()
func getData() {
// Get a reference to the database
let db = Firestore.firestore()
// Read the documents at a specific path
db.collection("Recipes").getDocuments { snapshot, error in
// Check for errors
if error == nil {
// No errors
if let snapshot = snapshot {
// Update the list property in the main thread
DispatchQueue.main.async {
self.userRecipes = snapshot.documents.map { d in
return RecipesData(id: d["id"] as? String ?? "", name: d["name"] as? String ?? "", cuisine: d["cuisine"] as? String ?? "", difficulty: d["difficulty"] as? String ?? "", dishType: d["dishType"] as? String ?? "", prepMins: d["prepMins"] as? Int ?? 0, prepHours: d["prephours"] as? Int ?? 0, cookMins: d["cookMins"] as? Int ?? 0, cookHours: d["cookHours"] as? Int ?? 0, restMins: d["restMins"] as? Int ?? 0, restHours: d["restHours"] as? Int ?? 0, likes: d["lkies"] as? Int ?? 0)
}
}
}
}
else {
}
}
}
}
and here is where the data gets stored
import SwiftUI
import FirebaseFirestoreSwift
struct RecipesData: Identifiable{
var id: String
var name: String
var cuisine: String
var difficulty: String
var dishType: String
var prepMins: Int
var prepHours: Int
var cookMins: Int
var cookHours: Int
var restMins: Int
var restHours: Int
var likes: Int
}
I can get the Data and if I choose to display the name of each recipe in a list I can do that.
But what I want to do is to have my data too like this when being displayed
import SwiftUI
struct AllRecipesView: View {
#ObservedObject var model = RecipesViewModel()
private var gridCollum = [GridItem(.flexible(),spacing: 0), GridItem(.flexible(),spacing: 0)]
var body: some View {
VStack{
LazyVGrid(columns: gridCollum, spacing: 0){
ForEach(model.userRecipes) {item in
overlayView()
}
}
}
}
init(){
model.getData()
}
}
struct AllRecipesView_Previews: PreviewProvider {
static var previews: some View {
AllRecipesView()
}
}
struct overlayView:View{
#ObservedObject var model = RecipesViewModel()
var body: some View{
ForEach(model.userRecipes) {item in
VStack{
VStack{
Spacer()
HStack{
HStack{
Image(systemName: "star")
.foregroundColor(.white)
.font(.system(size: 20))
Text(item.likes)
.foregroundColor(.white)
.font(.system(size: 15))
}
.padding(.trailing)
Text(item.prepMins)
.foregroundColor(.white)
.font(.system(size: 15))
.padding(.horizontal)
}
.padding(.bottom)
}
.frame(width:180,height:130)
.background(Color.red)
.cornerRadius(8)
.shadow(color: .black, radius: 3, x: 2, y: 2)
.padding(.bottom)
Text("Salmon and Rice")
Text("Some User")
}
}
}
init(){
model.getData()
}
}
But I keep getting error saying No exact matches in call to initializer on the lines
Text(item.likes)
and
Text(prepMins)
How can I fix my errors please
try something like this example code, using #StateObject var model = RecipesViewModel() and passing it using #EnvironmentObject.
To fix the errors you get, remenber Text() needs a string, such as, Text(String(item.likes)) or Text("\(item.likes)").
struct AllRecipesView: View {
#StateObject var model = RecipesViewModel() // <-- here
private var gridCollum = [GridItem(.flexible(),spacing: 0), GridItem(.flexible(),spacing: 0)]
var body: some View {
VStack{
LazyVGrid(columns: gridCollum, spacing: 0){
ForEach(model.userRecipes) {item in
OverlayView()
}
}
}
.environmentObject(model) // <-- here
.onAppear {
model.getData() // <-- here
}
}
}
struct OverlayView:View{
#EnvironmentObject var model: RecipesViewModel // <-- here
var body: some View{
ForEach(model.userRecipes) {item in
VStack{
VStack{
Spacer()
HStack{
HStack{
Image(systemName: "star")
.foregroundColor(.white)
.font(.system(size: 20))
Text(String(item.likes)) // <-- here
.foregroundColor(.white)
.font(.system(size: 15))
}
.padding(.trailing)
Text(String(item.prepMins)) // <-- here
.foregroundColor(.white)
.font(.system(size: 15))
.padding(.horizontal)
}
.padding(.bottom)
}
.frame(width:180,height:130)
.background(Color.red)
.cornerRadius(8)
.shadow(color: .black, radius: 3, x: 2, y: 2)
.padding(.bottom)
Text("Salmon and Rice")
Text("Some User")
}
}
}
}

Why does the Navigation Bar from the View still remain after Signing Out a User

I'm working on a very simple app to try to wrap my mind around SwiftUI and Firebase. I have a Login View, a SignUp View, and the FirstView that gets presented once the user is logged in.
Once a User is logged in and the SignOut button is tapped, the Navigation Bar that was only visible in the FirstView, all of a sudden appears superimposed on the LoginView as well. That's not supposed to happen and I'm trying to understand why that happens. Perhaps I'm not dismissing the FirstView correctly?
As a side question, I'm also running into an issue where my User Data is presented/Updated on the FirstView after Signing In, but with a noticeable delay between the Text change for the fields within the view.
Any help would be greatly appreciated.
Here is the relevant code...
#main
struct AWSupportLoggerApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#StateObject var viewModel = AppViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(viewModel)
}
}
class AppDelegate:NSObject,UIApplicationDelegate{
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
}
}
class AppViewModel: ObservableObject {
private var db = Firestore.firestore()
#Published var userInfo: User?
#Published var signedIn: Bool = false
var handle: AuthStateDidChangeListenerHandle?
let authRef = Auth.auth()
var authHandle : AuthStateDidChangeListenerHandle?
var rootInfoCollection : CollectionReference!
var userIdRef = ""
func fetchUserData(){
db.collection("Users").document("\(userIdRef)").getDocument { document, error in
// Check for error
if error == nil {
// Check that this document exists
if document != nil && document!.exists {
self.userInfo = document.map { (documentSnapshot) -> User in
let data = documentSnapshot.data()
let uid = data?["uid"] as? UUID ?? UUID()
let company = data?["company"] as? String ?? ""
let name = data?["name"] as? String ?? ""
let admin = data?["admin"] as? Bool ?? false
let photo = data?["photo"] as? String ?? ""
return User(uid: uid, company: company, name: name, admin: admin, photo: photo)
}
}
}
}
}
func listen(){
handle = authRef.addStateDidChangeListener({ auth, user in
print(user?.email ?? "No User Found")
if let user = auth.currentUser {
self.userIdRef = user.uid
self.rootInfoCollection = Firestore.firestore().collection("/Users/")
DispatchQueue.main.async {
self.fetchUserData()
}
self.signedIn = true
} else {
self.signedIn = false
}
})
}
func signIn(email: String, password: String){
authRef.signIn(withEmail: email, password: password) { result, error in
guard result != nil, error == nil else {
return
}
}
}
func signOut(){
do {
try authRef.signOut()
} catch {
print(error)
}
}
func signUp(email: String, password: String, company: String, name: String, admin: Bool, photo: String){
authRef.createUser(withEmail: email, password: password) { result, error in
guard result != nil, error == nil else {
return
}
let db = Firestore.firestore()
//Success
db.collection("Users").document("\(result!.user.uid)").setData(["company" : "\(company)", "name" : "\(name)", "admin" : admin, "photo" : "\(photo)", "uid":result!.user.uid]) { error in
if error != nil {
print(error!)
}
}
}
}
func unbind() {
if let handle = handle {
authRef.removeStateDidChangeListener(handle)
}
}
}
struct ContentView: View {
#EnvironmentObject var viewModel: AppViewModel
var body: some View {
NavigationView {
if viewModel.signedIn {
FirstView()
} else {
//.onAppear method is used for keyboard management (See Misc Functions...)
SignInView()
.onAppear(perform: UIApplication.shared.addTapGestureRecognizer)
}
}
.onAppear {
viewModel.listen()
}
}
}
struct FirstView: View {
#EnvironmentObject private var appViewModel: AppViewModel
var body: some View {
VStack{
Spacer()
VStack(spacing: 50){
NavigationLink(destination: Text("Test")){
awButton(content: "Request Support", backColor: Color(#colorLiteral(red: 0, green: 0.723585546, blue: 0.9907287955, alpha: 1)))
.shadow(color: Color.primary.opacity(0.5), radius: 20, x: 0, y: 20)
.rotation3DEffect(Angle(degrees:10), axis: (x: 10.0, y: 0, z: 0))
}
NavigationLink(destination: Text("Test")){
awButton(content: "Request Quote", backColor: Color(#colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)))
.shadow(color: Color.primary.opacity(0.5), radius: 20, x: 0, y: 20)
.rotation3DEffect(Angle(degrees:10), axis: (x: 10.0, y: 0, z: 0))
}
NavigationLink(destination: Text("Test")){
awButton(content: "Ticket Status", backColor: Color(#colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)))
.shadow(color: Color.primary.opacity(0.5), radius: 20, x: 0, y: 20)
.rotation3DEffect(Angle(degrees:10), axis: (x: 10.0, y: 0, z: 0))
}
}
Spacer()
}
.navigationBarBackButtonHidden(true)
.navigationTitle(appViewModel.userInfo?.company ?? "Test")
.navigationBarItems(leading: Button(action: {
appViewModel.signOut()
}) {
HStack {
Text("Sign Out")
}
},trailing: HStack{
Image(systemName: "bell")
Text(appViewModel.userInfo?.name ?? "Tester")
.font(.system(size: 20))
})
}
}
Try to hide it explicitly, like
if viewModel.signedIn {
FirstView()
.navigationBarHidden(true) // << here !!
} else {
Hiding the navigationBar will cause lots of problems if you need it in other views .the better answer in my opinion is to
1 - create a splash view and set it as your starting view in #main file
2 - add a StateObject for tracking user loginState :
class LoginState: ObservableObject {
#Published var isLogin : Bool = false
}
3 - add navigationView to splash view
4 - pass loginState , StateObject as .environmentObject(loginState) to navigationView
5- now you can change login state when ever you want from anywhere without need of hiding the navigation bar

Slight delay/lag when fetching Firestore User data to update View

I'm currently building a simple app with a SignIn/SignUp View in order to better understand how to integrate SwiftUI with Firebase.
I've run into a bit of an issue when I try to update User Data. I noticed that after Signing Out as one User and then Signing In as a different User, there is a split second delay before the User information is updated on the FirstView after the Sign In button is tapped. I'm trying to figure out how to avoid this delay from happening.
As a side, I'm also having trouble figuring out how to smoothly navigate from my LoginView() to my FirstView(). I have my FirstView() inside of a Navigation Stack, but the transition between the views is very abrupt and devoid of the NavigationLink animation. How can I correct this issue?
Much appreciated!
Here is the relevant code...
#main
struct AWSupportLoggerApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#StateObject var viewModel = AppViewModel()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(viewModel)
}
}
class AppDelegate:NSObject,UIApplicationDelegate{
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
}
}
struct ContentView: View {
#EnvironmentObject var viewModel: AppViewModel
var body: some View {
NavigationView {
if viewModel.signedIn {
FirstView()
} else {
//.onAppear method is used for keyboard management (See Misc Functions...)
SignInView()
.onAppear(perform: UIApplication.shared.addTapGestureRecognizer)
.navigationBarHidden(true)
}
}
.onAppear {
viewModel.listen()
}
}
}
class AppViewModel: ObservableObject {
private var db = Firestore.firestore()
#Published var userInfo: User?
#Published var signedIn: Bool = false
var handle: AuthStateDidChangeListenerHandle?
let authRef = Auth.auth()
var authHandle : AuthStateDidChangeListenerHandle?
var rootInfoCollection : CollectionReference!
var userIdRef = ""
func fetchUserData(){
db.collection("Users").document("\(userIdRef)").getDocument { document, error in
// Check for error
if error == nil {
// Check that this document exists
if document != nil && document!.exists {
self.userInfo = document.map { (documentSnapshot) -> User in
let data = documentSnapshot.data()
let uid = data?["uid"] as? UUID ?? UUID()
let company = data?["company"] as? String ?? ""
let name = data?["name"] as? String ?? ""
let admin = data?["admin"] as? Bool ?? false
let photo = data?["photo"] as? String ?? ""
return User(uid: uid, company: company, name: name, admin: admin, photo: photo)
}
}
}
}
}
func listen(){
handle = authRef.addStateDidChangeListener({ auth, user in
print(user?.email ?? "No User Found")
if let user = auth.currentUser {
self.userIdRef = user.uid
self.rootInfoCollection = Firestore.firestore().collection("/Users/")
DispatchQueue.main.async {
self.fetchUserData()
}
self.signedIn = true
} else {
self.signedIn = false
}
})
}
func signIn(email: String, password: String){
authRef.signIn(withEmail: email, password: password) { result, error in
guard result != nil, error == nil else {
return
}
}
}
func signOut(){
do {
try authRef.signOut()
} catch {
print(error)
}
}
func signUp(email: String, password: String, company: String, name: String, admin: Bool, photo: String){
authRef.createUser(withEmail: email, password: password) { result, error in
guard result != nil, error == nil else {
return
}
let db = Firestore.firestore()
//Success
db.collection("Users").document("\(result!.user.uid)").setData(["company" : "\(company)", "name" : "\(name)", "admin" : admin, "photo" : "\(photo)", "uid":result!.user.uid]) { error in
if error != nil {
print(error!)
}
}
}
}
func unbind() {
if let handle = handle {
authRef.removeStateDidChangeListener(handle)
}
}
}
struct FirstView: View {
#EnvironmentObject private var appViewModel: AppViewModel
var body: some View {
VStack{
Spacer()
VStack(spacing: 50){
NavigationLink(destination: Text("Test")){
awButton(content: "Request Support", backColor: Color(#colorLiteral(red: 0, green: 0.723585546, blue: 0.9907287955, alpha: 1)))
.shadow(color: Color.primary.opacity(0.5), radius: 20, x: 0, y: 20)
.rotation3DEffect(Angle(degrees:10), axis: (x: 10.0, y: 0, z: 0))
}
NavigationLink(destination: Text("Test")){
awButton(content: "Request Quote", backColor: Color(#colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)))
.shadow(color: Color.primary.opacity(0.5), radius: 20, x: 0, y: 20)
.rotation3DEffect(Angle(degrees:10), axis: (x: 10.0, y: 0, z: 0))
}
NavigationLink(destination: Text("Test")){
awButton(content: "Ticket Status", backColor: Color(#colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)))
.shadow(color: Color.primary.opacity(0.5), radius: 20, x: 0, y: 20)
.rotation3DEffect(Angle(degrees:10), axis: (x: 10.0, y: 0, z: 0))
}
}
Spacer()
}
.navigationBarBackButtonHidden(true)
.navigationTitle(appViewModel.userInfo?.company ?? "Test")
.navigationBarItems(leading: Button(action: {
appViewModel.signOut()
}) {
HStack {
Text("Sign Out")
}
},trailing: HStack{
Image(systemName: "bell")
.font(.system(size: 30))
// selectedImageArray.first!
// .resizable()
// .scaledToFit()
// .clipShape(Circle())
// .frame(width: 50, height: 50)
Text(appViewModel.userInfo?.name ?? "Tester")
.font(.system(size: 20))
})
}
}
Your navigation state depends on signedIn. In your auth listener, you do this:
DispatchQueue.main.async {
self.fetchUserData()
}
self.signedIn = true
This will set signedIn to true, which will change your navigation state and then at an indeterminate time in the future, fetchUserData will finish and update the user data (once the network call has completed).
To avoid this delay (or, really, to just avoid seeing the information not update on the screen -- the delay is an inevitability of the network call), don't set signedIn until fetchUserData completes. So, remove the line inside the listener and instead, set it after your self.userInfo = line.

How do I fetch the post id's for Wordpress posts using their Rest API with SwiftUI

I'm trying to include some blog posts from my WordPress site into my app. I've tested the API using the individual post Ids for each post and I got it to load the data in my view. However, I'm now trying to fetch an array but it doesn't seem to be fetching the IDs related to the posts to populate the view. What am I doing wrong here?
let content: MarkdownData
#State var beholdarticles: BeholdArticle?
#State private var htmlContent = ""
let articles: [BeholdArticle] = []
private func loadArticle() {
guard let url = URL(string: "https://behold.hagleyparksda.com/wp-json/wp/v2/posts") else {
return
}
URLSession.shared.dataTask(with: url) {data, response, error in
guard let data = data else { return }
if let decodedData = try? JSONDecoder().decode(BeholdArticle.self, from: data){
DispatchQueue.main.async {
self.beholdarticles = decodedData
}
}
}.resume()
}
This is the ForEach loop
var body: some View {
ScrollView (.horizontal) {
ForEach(articles) { item in
ZStack {
if beholdarticles?.thumbnail != nil {
WebImage(url: URL(string: beholdarticles!.thumbnail)!)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width:350, height: 450)
} else {
Image("behold_imagecard")
.resizable()
.aspectRatio(contentMode: .fill)
}
HStack {
VStack (alignment: .leading) {
Text(beholdarticles?.title.rendered ?? "Loading...")
.font(.system(size: 30, weight: .bold))
.foregroundColor(Color.white)
.frame(width: 270)
// Text(beholdarticles?.title.rendered ?? "Loading...")
// .font(.system(size: 18, weight: .regular))
// .foregroundColor(Color.white)
// .frame(width: 270)
}
Spacer()
}
VStack {
Spacer()
HStack {
Image(uiImage: #imageLiteral(resourceName: "healthicon"))
Text("Spirituality")
.font(.system(size: 23))
.foregroundColor(Color.white)
Spacer()
}
.background(VisualEffectBlurView(blurStyle: .systemUltraThinMaterial))
}.onAppear{
loadArticle()
}
} .frame(width:350, height: 450)
.shadow(color: Color(#colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)) .opacity(0.2), radius: 20, x: /*#START_MENU_TOKEN#*/0.0/*#END_MENU_TOKEN#*/, y:14)
.cornerRadius(30)
}
}
My data model
struct BeholdArticle: Decodable, Identifiable {
var id: Int
var slug: String
var link: String
var thumbnail: String
var title: BeholdArticleTitle
var content: BeholdArticleContent
enum CodingKeys: String, CodingKey {
case thumbnail = "jetpack_featured_media_url"
case slug, link, title, content
case id = "id"
}
}
struct BeholdArticleTitle: Decodable {
var rendered: String
}
struct BeholdArticleContent: Decodable {
var rendered: String
}
I'm simply trying to populate my loop with the data, but it doesnt seem to be grabbing the ID's from api call. Need some help here
I still have the image URL wrapped in a conditional statement. At current the images wont come through. How do I adjust this to the updated setup?
if beholdarticles?.thumbnail != nil {
WebImage(url: URL(string: item.thumbnail)!)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width:350, height: 450)
} else {
Image("behold_imagecard")
.resizable()
.aspectRatio(contentMode: .fill)
}
Here's the updated image code:
ForEach(articles) { article in
ZStack {
if article.thumbnail != nil {
WebImage(url: URL(string: article.thumbnail)!)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width:350, height: 450)
} else {
Image("behold_imagecard")
.resizable()
.aspectRatio(contentMode: .fill)
}
If you want to decode the JSON from that URL endpoint, you're going to need to use [BeholdArticle].self instead of BeholdArticle.self, since it's an array of data.
Also, instead of calling loadArticle on each element of the ForEach (which will never get called, since it doesn't have data in it at the beginning), call it at the top level of the view.
Here's a pared down example:
struct ContentView: View {
#State private var articles : [BeholdArticle] = []
var body: some View {
ScrollView {
VStack (alignment: .leading) {
ForEach(articles) { article in
Text(article.title.rendered)
.multilineTextAlignment(.leading)
if let thumbnailURL = URL(string: article.thumbnail) {
WebImage(url: thumbnailURL)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width:350, height: 450)
}
}
}
}
.onAppear {
loadArticles()
}
}
private func loadArticles() {
guard let url = URL(string: "https://behold.hagleyparksda.com/wp-json/wp/v2/posts") else {
return
}
URLSession.shared.dataTask(with: url) {data, response, error in
guard let data = data else { return }
if let decodedData = try? JSONDecoder().decode([BeholdArticle].self, from: data){
DispatchQueue.main.async {
self.articles = decodedData
}
}
}.resume()
}
}

swiftUI how to disabled a button for 2sec?

i have a bug, if i click on button before the animation before the card flip back. i think for me the best it would be to disable the button for 2 sec, but i made some research and didnt find anything!
struct CardBack: View {
var body: some View {
Image("back_card")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 250)
}
}
struct ContentView: View {
#State var flipped = false
#State private var cardsFront = ["bigCard1", "bigCard2", "bigCard3", "bigCard4", "bigCard5" ]
#State private var cardBack = "back_card"
#State private var disablled = true
var body: some View {
VStack {
Spacer()
ZStack {
Image(flipped ? self.cardsFront.randomElement()! : self.cardBack)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 250)
.rotation3DEffect(Angle(degrees: flipped ? 180 : 0 ), axis: (x: 0, y: 1, z: 0))
}
Spacer()
HStack {
Button(action: {
withAnimation(.spring()) {
self.flipped.toggle()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
withAnimation(.spring()) {
self.flipped.toggle()
}
}
}) {
Image("circle")
.renderingMode(.original)
}
Button(action: {
}) {
Image("plus")
.renderingMode(.original)
}
iOS 13, Swift 5
You can set the button as disabled initially and then enable it using the same sort of logic I used here.
import SwiftUI
struct ContentView: View {
#State var changeColor = false
var body: some View {
TextView(changeColor: $changeColor)
}
}
struct TextView: View {
#Binding var changeColor: Bool
var body: some View {
Text("Hello World")
.foregroundColor(changeColor ? Color.black: Color.red)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.changeColor.toggle()
}
}
}
}
You are almost there, you just need to use the .appear tag in your code to do this.

Resources