Show a View on First Launch Only - Swift 3

我的未来我决定 提交于 2019-12-23 05:08:27

问题


I am implementing a Terms & Conditions view into my app and the user has to accept them to proceed, then when they do accept them, they no longer have to go through the Terms & Conditions view. I followed a tutorial on how to integrate UserDefaults and store the value locally if someone does accept the terms. However I am stuck with implementing it into the root view controller. Specifically stuck on my viewDidAppear function. What goes in the if and else statements?

class TermsAndConditionsViewController: UIViewController, UITextViewDelegate {

@IBOutlet weak var termsTextView: UITextView! {
    didSet {
        termsTextView.delegate = self
    }
}

@IBOutlet weak var acceptButton: UIButton! {
    didSet {
        acceptButton.isHidden = true
    }
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    acceptButton.isHidden = scrollView.contentOffset.y + scrollView.bounds.height < scrollView.contentSize.height
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if UserDefaults.standard.bool(forKey: "termsAccepted") {

    } else {

    }
}

@IBAction func acceptButtonTapped(_ sender: Any) {
    performSegue(withIdentifier: "toPeekView", sender: sender)
}

}


回答1:


Probably, you mean "Show a ViewController on First Launch Only".

Using UserDefaults for this purpose is a good idea, however, checking if the term accepted should not be at the TermsAndConditionsViewController layer, instead, it should be in AppDelegate - application:didFinishLaunchingWithOptions, you can decide in it whether the root ViewController should be the TermsAndConditionsViewController or the other ViewController (HomeViewController for example).

AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let rootViewController = storyboard.instantiateViewController(withIdentifier: UserDefaults.standard.bool(forKey: "termsAccepted") ? "termsViewControllerID" : "homeViewControllerID")

    window?.rootViewController = rootViewController

    return true
}

TermsAndConditionsViewController:

class TermsAndConditionsViewController: UIViewController {
    //...

    @IBAction func acceptButtonTapped(_ sender: Any) {
        UserDefaults.standard.set(true, forKey: "termsAccepted")

        performSegue(withIdentifier: "toPeekView", sender: sender)
    }

    //...
}

Hope this helped.



来源:https://stackoverflow.com/questions/41811070/show-a-view-on-first-launch-only-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!