首先让我说,我是编程新手,也许我想做的事情是不可能的,至少不是我尝试做的方式!我已经做了很多搜索,但我一定是在搜索错误的东西,因为我在任何地方都找不到答案。 :(
简而言之,我想做的是让我的应用计算它的启动次数,并在达到特定值时向用户显示警报。我的做法如下所述。
我声明了一个变量如下:
var numberoflaunches :Int! = 0
我创建了以下函数:
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()
}}}
最后,在我的 viewDidLoad 中有以下代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
LoadNumberOfLaunches()
SaveNumberOfLaunches()
ShowReviewPrompt()
}
现在,我不确定将上述代码放在 viewDidLoad 中是否是最佳位置,因为我假设每次加载 View 时都会触发我的函数,所以顺便说一句,我会对更好的方法感兴趣。
然而,回到这个问题的重点,我可以在模拟器和实际设备上运行该应用程序,但我从未看到我的警报消息出现。
那么,我只是犯了一个新手错误,还是这实际上应该有效?或者有其他方法可以实现我正在做的事情吗?
最佳答案
如果你真的想跟踪你的应用程序被打开的次数,那么在任何 View Controller 中这样做都会因为你的应用程序的导航流而给你无关的结果。如果他的用户离开主页然后返回到主页,那么 viewDidAppear
可能会在一个 session 中被调用多次,我认为这不是您想要实现的。因此,您应该在 appDelegate
中监控它,可能在 applicationDidFinishLaunching:withOptions
中,这可能更准确地表示应用程序已打开的次数。
关于swift - 在 Swift 中,如何检测应用程序启动次数以显示警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938771/