Home > OS >  Count user views (SwiftUI)
Count user views (SwiftUI)

Time:10-26

How do I count user views?

For example, a user opened an app and got 1 view.

With each next opening of the application, 1 view will be added. and so on endlessly up to 100-200-300 and so on

image1

Image number one, zero views But when the user opens the app twice, there will be two views. Each new discovery will add plus one viewing

image2

If the user has opened the application a hundred times, then a hundred views will already be displayed

image3

Here is my code:

struct views: View {
   var body: some View {
        VStack {
            
            HStack {
                
                Image(systemName: "eye")
                    .resizable()
                    .scaledToFit()
                    .frame(width: 50, height: 50)
                Text("0")
                    .font(.system(size: 25))
                    .fontWeight(.bold)
                    .foregroundColor(Color.black)
                    .padding(.leading)
                
            }
            
        }
        .frame(width: 250, height: 150)
        .background(Color.gray.opacity(0.5))
        .cornerRadius(10)
    }
}

Help me please, I'm new to swift, I will be grateful for any your help, thanks!

CodePudding user response:

You can use @AppStorage to store the view count (https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-appstorage-property-wrapper).

To tell when the application has become active and add to the counter, you can use @Environment(\.scenePhase) (https://www.hackingwithswift.com/quick-start/swiftui/how-to-detect-when-your-app-moves-to-the-background-or-foreground-with-scenephase).

struct ContentView: View {
    @AppStorage("userViews") private var userViews = 0
    @Environment(\.scenePhase) var scenePhase
    
    var body: some View {
        VStack {
            HStack {
                Image(systemName: "eye")
                    .resizable()
                    .scaledToFit()
                    .frame(width: 50, height: 50)
                Text("\(userViews)")
                    .font(.system(size: 25))
                    .fontWeight(.bold)
                    .foregroundColor(Color.black)
                    .padding(.leading)
                
            }
        }
        .frame(width: 250, height: 150)
        .background(Color.gray.opacity(0.5))
        .cornerRadius(10)
        
        .onChange(of: scenePhase) { newPhase in
            if newPhase == .active {
                userViews  = 1
            }
        }
    }
}
  • Related