首先让我说我是编程新手,也许我想做的事情是不可能的,至少不是我想要做的事情!我已经做了很多搜索,但我一定是在搜索错误的东西,因为我在任何地方都找不到答案。:(
简而言之,我想要做的是让我的应用程序计算它已启动的次数,并在达到特定值时向用户显示警报。我这样做的方法如下所述。
我已经声明了一个变量如下:
var numberoflaunches :Int! = 0
Run Code Online (Sandbox Code Playgroud)
我创建了以下功能:
func LoadNumberOfLaunches()
{
let defaults = NSUserDefaults.standardUserDefaults()
numberoflaunches = defaults.integerForKey("Launches")
}
func SaveNumberOfLaunches()
{
numberoflaunches = numberoflaunches + 1
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(numberoflaunches, forKey: "Launches")
}
func ShowReviewPrompt()
{
if (numberoflaunches == 10 || numberoflaunches == 50 || numberoflaunches == 100){
// create the alert
if #available(iOS 8.0, *) {
let alert = UIAlertController(title: "Friendly prompt", message: "Would you consider reviewing this App? It really makes a difference! If not, perhaps you'd like to send me a suggestion to improve it instead?", preferredStyle: UIAlertControllerStyle.Alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Review app", style: UIAlertActionStyle.Destructive, handler: {action in
self.ReviewApp()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Send suggestion", style: UIAlertActionStyle.Destructive, handler: {action in
self.SendFeedback()
}))
// show the alert
self.presentViewController(alert, animated: true, completion: nil)
} else {
// For pre-iOS 8 users
let alert = UIAlertView()
alert.title = "Friendly prompt"
alert.message = "Would you consider reviewing this App? It really makes a difference! If not, perhaps instead you'd like to send me a suggestion to improve it? You can do either from the Info page."
alert.addButtonWithTitle("Ok")
alert.show()
}}}
Run Code Online (Sandbox Code Playgroud)
最后,在我的 viewDidLoad 中,我有以下代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
LoadNumberOfLaunches()
SaveNumberOfLaunches()
ShowReviewPrompt()
}
Run Code Online (Sandbox Code Playgroud)
现在,我不确定将上面的代码放在 viewDidLoad 中是否是最好的地方,因为我假设每次加载视图时它都会触发我的函数,所以顺便说一句,我会对更好的方法感兴趣。
但是,回到这个问题的重点,我可以在模拟器和实际设备上运行该应用程序,但我从未看到我的警报消息出现。
那么,我只是犯了一个新手错误,还是应该这样做?还是有另一种方法来实现我正在做的事情?
如果您真的想跟踪应用程序打开的次数,那么在任何视图控制器中执行此操作都会由于应用程序的导航流程而给您带来无关的结果。如果他的用户导航离开主页然后返回到它,则viewDidAppear可以在一个会话中多次调用,我认为这不是您想要实现的。因此,您应该在appDelegate可能的情况下监控这一点,applicationDidFinishLaunching:withOptions这可能更准确地表示应用程序已打开的次数。
| 归档时间: |
|
| 查看次数: |
798 次 |
| 最近记录: |