UIAlertController только в определенное время - PullRequest
0 голосов
/ 30 октября 2018

Можно ли показывать предупреждение UIAlertController только в определенное время, не нажимая UIButton? Например, когда пользователь запускает мою игру в третий раз. Но если он нажмет «Отмена», он больше никогда его не увидит.

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let opensCount = UserDefaults.standard.integer(forKey: "open_count") + 1
        UserDefaults.standard.set(opensCount, forKey: "open_count")
        UserDefaults.standard.synchronize()

        return true
    }

и

import UIKit
import SpriteKit
import GameplayKit

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if UserDefaults.standard.integer(forKey: "open_count") == 3 {
            self.showAlert()
        }

...
    }

1 Ответ

0 голосов
/ 30 октября 2018

да, вы можете добавить целое число, чтобы подсчитать количество открытий приложения и сохранить его в пользовательских значениях по умолчанию, затем вы проверите его, если оно равно 3, вы увидите предупреждение, и если оно отменено пользователем Вы также сохраняете значение в пользовательских значениях по умолчанию, чтобы предупреждение не отображалось.

Ваш код может быть таким:

 \\this function to create the alert and present it 
 func showAlert(){
    let alertController = UIAlertController(title: "Your Title", message: "Your Message", preferredStyle: .alert)
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
        /*do your action here on cancel*/
    }
    let okAction = UIAlertAction(title: "Ok", style: .default) { _ in
        /*do your action here on ok*/
    }
    alertController.addAction(cancelAction)
    alertController.addAction(okAction)
    self.present(alertController, animated: true, completion: nil)

}

и в вызове viewdidload вы можете сделать так:

 override func viewDidLoad() {
    super.viewDidLoad()
    if UserDefaults.standard.integer(forKey: "open_count") == 3 {
        self.showAlert()
    }
}

Вы можете добавить этот код в делегат приложения, этот метод будет вызываться каждый раз, когда приложение завершает запуск:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //initial count + 1 the count of this current open
    let opensCount = UserDefaults.standard.integer(forKey: "open_count") + 1
    //set the new count value
    UserDefaults.standard.set(opensCount, forKey: "open_count")
    //dont forget to synchronize your user defaults
    UserDefaults.standard.synchronize()

    return true
 }
...