首页 > 解决方案 > 从用户那里获得一次性许可

问题描述

我在获得用户许可时遇到问题,我的应用程序是关于用户询问和应用程序回答的。
如何制作弹出窗口,当用户第一次打开应用程序时,会出现弹出窗口并询问是否允许保存问题。

标签: swift

解决方案


1. 显示警报视图:

let alert = UIAlertController()

alert.title = "This is your title of the alert"
alert.message = "This is your question"

alert.addAction(UIAlertAction(title: "Answer one", style: .default , handler:{ (UIAlertAction)in
// Let's save the user's choice for later
UserDefaults.standard.set("UserChoseOptionOne", forKey: "myReallyImportantQuestion")    
}))

alert.addAction(UIAlertAction(title: "Answer two", style: .default , handler:{ (UIAlertAction)in
// Let's save the user's choice for later 
UserDefaults.standard.set("UserChoseOptionTwo", forKey: "myReallyImportantQuestion")     

}))

alert.addAction(UIAlertAction(title: "Ask me later", style: .cancel, handler:{ (UIAlertAction)in

 // Let's not do anything here. 
 // The user can't decide at the moment and let's ask the next time your app is opened again 

}))

self.present(alert, animated: true, completion: nil)

2. 在你的 viewDidLoad

// Here we have to differentiate between three cases!

// Case 1: This is the very first time our dear user opened our cool app
// or
// Case 2: This is not the first time, we already asked our important question and we have an answer already!
// or
// Case 3: This is not the first time, the last time we asked our question, the user decided to choose later. Later is now!

if let option = UserDefaults.standard.string(forKey: "myReallyImportantQuestion") {

    // Here we handle Case 2. Maybe you don't want to do anything here
    // We already have the user's choice saved in option
    // We can do whatever we want with that

}else{

    // Here are the cases 1 and 3.
    // In here you can paste the code from "1. Display an alert view"
    // If you feel fancy today, you can also make a function out of "1. Display an alert view" and call it in here
}

推荐阅读