UIAlertView只显示一次

时间:2017-05-23 00:40:19

标签: ios swift xcode uialertcontroller

我有一个条款协议,只需要弹出一次,但是每次启动应用程序时都会弹出,我怎么能让它只弹出一次,当被按下时同意不再弹出,除非app是删除并重载。我正在尝试关注How can I show a view on the first launch only?

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        if !UserDefaults.standard.bool(forKey: "Walkthrough") {
            UserDefaults.standard.set(false, forKey: "Walkthrough")
        }
    }

}

class FirstViewController: UIViewController, UIAlertViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        if UserDefaults.standard.bool(forKey: "Walkthrough") {
            print("already shown")
            // Terms have been accepted, proceed as normal
        } else {
            agree()
        }
    }

}

我同意的功能是警报控制器

2 个答案:

答案 0 :(得分:0)

我忘了在同意()之后添加

UserDefaults.standard.set(true, forKey: "Walkthrough")

答案 1 :(得分:0)

如果同意或不同意,只需在UserDefaults中保存一个bool,并检查是否存在“WalkThrough”键。如果没有,如果发现什么都不做,你会告诉他警报。

将其添加到viewDidAppear方法中的初始viewController:

    let alert = UIAlertController(title: "Message", message: "You need to agree to terms and conditions", preferredStyle: .alert)
    let action = UIAlertAction(title: "Not Agreed", style: .default) { (action) in

        UserDefaults.standard.set(false, forKey: "WalkThrough")

        alert.dismiss(animated: true, completion: nil)
    }
    let action2 = UIAlertAction(title: "Agreed", style: .default) { (action) in

        UserDefaults.standard.set(true, forKey: "WalkThrough")

        alert.dismiss(animated: true, completion: nil)
    }

    alert.addAction(action)
    alert.addAction(action2)


    if (UserDefaults.standard.object(forKey: "WalkThrough") == nil) {
        //show alert and save answer
        self.present(alert, animated: true, completion: nil)

    }