Search code examples
swiftswiftuisleep

How can I put a time delay within an IF statement in Swift?


I'm developing a prototype for an iOS app for my computing course at college, which I'm using to prove the navigation and login system functions. So far I've been successful with this, with everything working as planned, although I doubt I've done it the proper way as I'm still new to the Swift programming language and XCode IDE.

My problem is, and I know it sound stupid, with how my app doesn't allow me to have a time delay before transitioning to a new view. When logging in successfully, it immediately transitions to my home page. However, I want the app to have a short delay between a successful login and opening the home page.

I've given this a try after searching for different methods of doing so, with the current method being sleep(UInt32(1.0)) pausing the app for 1s before opening the home page - the full code for this section is below:

// external if statement for when login succeeds
if authenticationDidSucceed {
    Text("Login succeeded!")
        .font(.headline)
        .frame(width: 250, height: 80)
        .background(Color.green)
        .cornerRadius(20.0)
        .foregroundColor(.white)
        .animation(Animation.default)
            
    // this is what's broken
    sleep(UInt32(1.0))
    // calling navigation bar containing other pages
    HostingTabBar()
}

This seems to return the error Static method 'buildBlock' requires that 'UInt32' conform to 'View', which I believe has something to do with the fact its within an if statement.

If anyone knows of any way to get around this issue it would be greatly appreciated, and if you need me to attach more code snippets or anything do say.

Many thanks for your help.


Solution

  • Taking aheze's code suggestion and adding it to my program in the proper position has worked, and now the app pauses for a second upon successful login. This doesn't work entirely as I need it to, as the successful login message simply does not appear now, probably due to the time delay, however I'm sure I can work around this as it appears to be simple issue!

    aheze's code inserted into my program:

    if self.username == storedUsername && self.password == storedPassword {
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
        
        self.authenticationDidSucceed = true
    }
    

    Once again, thanks for the help, and I hope I've done it right!