Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

Create ability to time limit tap on button with after week since last tap (SwiftUI)

On my app user can change it username. So not to increase firebase loads, i want to create time limit before last tap, (1 week i think will be ok), and in other time make this button gray color and not active with counter how many days remaining.

Here is my button code:

Button(action: {
                            let currentUser = Auth.auth().currentUser
                            if (currentUser != nil) {
                                self.loadingView = true
                                let id = currentUser!.uid
                               Ref.FIRESTORE_COLLECTION_USERS.document(id).updateData(["bio" : self.bio, "username" : self.name, "keywords" : self.name.splitStringToArray()]) { (err) in
                                    //Конструкция: если err (ошибка) не nil, значит ест ьошибка и что-то пошло не так
                                    // если nil, значит все хорошо
                                    if let err = err {
                                        //делаем что-то если ошибка
                                        //например показываем надпись с сообщением об ошибке
                                        print("Error updating document: (err)")
                                        self.loadingView = false
                                    } else {
                                        self.sessionStore.userSession?.bio = self.bio
                                        self.sessionStore.userSession?.username = self.name
                                        //то же самое только если все получилось
                                        print("Document successfully updated")
                                        if (self.imageData == nil) {
                                            self.loadingView = false
                                            self.showEditProfile = false
                                        }
                                    }
                                }
                                
                                //save image
                                //Если новая картинка выбрана
                                if (self.imageData != nil && self.sessionStore.userSession != nil) {
                                    //Сначала загружаем в хранилище, а затем ссылку на это фото обновляем в базе данных у пользователя
                                    let storageAvatarUserId = Ref.STORAGE_AVATAR_USERID(userId: Auth.auth().currentUser!.uid)
                                    let metadata = StorageMetadata()
                                    metadata.contentType = "image/jpg"
                                    //для био было
                                    self.sessionStore.userSession?.bio = self.bio
                                    //для логина - апдейт
                                    self.sessionStore.userSession?.username = self.name
                                    //cлушатель для обновления био
                                    NotificationCenter.default.post(name: NSNotification.Name("update_profile_bio"), object: nil)
                                    StorageService.updateAvatar(userId: self.sessionStore.userSession!.uid, username: self.sessionStore.userSession!.username, email: self.sessionStore.userSession!.email, imageData: self.imageData!, metaData: metadata, storageAvatarRef: storageAvatarUserId, onSuccses: {url in
                                        if url != nil {
                                            self.sessionStore.userSession?.profileImageUrl = url!
                                            NotificationCenter.default.post(name: NSNotification.Name("update_profile_image"), object: nil)
                                            self.loadingView = false
                                            self.showEditProfile = false
                                            
                                        } else {
                                            self.loadingView = false
                                        }
                                        
                                    })
                                }
                            }
                            
                            
                        }) {
                            HStack {
                                Spacer()
                                Text(LocalizedStringKey("Save changes")).fontWeight(.bold).foregroundColor(Color.white)
                                Spacer()
                            }.padding().background(Color.black)
                            
                        }.cornerRadius(5).shadow(radius: 10, x: 0, y: 10).padding()

So i want - when user press this button - make it avalible to tap after 7 days. And always use this rule.

question from:https://stackoverflow.com/questions/65862409/create-ability-to-time-limit-tap-on-button-with-after-week-since-last-tap-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is an extremely basic version of solving the problem. It has a bunch of architecture decisions you would have to make (I'll enumerate some) but it should get you started:

let interval : TimeInterval = 60 //number of seconds. 60 * 60 * 24 * 7 == one week

struct ContentView: View {
    @AppStorage("buttonPressDate") var buttonPressDate : TimeInterval = -1
    
    var isButtonDisabled : Bool {
        buttonPressDate >= Date().timeIntervalSince1970 - interval
    }
    
    var nextButtonPressAvailable : TimeInterval {
        buttonPressDate + interval - Date().timeIntervalSince1970
    }
    
    var body: some View {
        VStack {
            Button(action: {
                buttonPressDate = Date().timeIntervalSince1970
            }) {
                Text("Button")
                if isButtonDisabled {
                    Text("Next press in: (Int(nextButtonPressAvailable)) sec")
                }
            }
            .disabled(isButtonDisabled)
        }
        Text("Hello, World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

Concerns:

  1. This only checks the buttonPressDate when UserDefaults is updated or when the view is reloaded. If you want the button to become available at other times, you'd probably want to set a scheduled event somehow (Timer, etc)
  2. This is very low security -- a user could just alter UserDefaults to change the date. But, it gives you the foundation for how to do a more complex and secure setup.
  3. This stores the time locally -- you didn't specify whether you want the date stored locally or on the server, but it would be easy to store this value in Firebase instead

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...