2017-10-23 14 views
0

私は既に物を保存する方法を知っており、アプリを開くときに自動的に読み込むことができます。しかし、私はそれが終了すると、それらを保存する方法がわからない!私は今のところボタンを持っています。私はちょうど1つの値、StreakNumberを保存しようとしています。しかし、私が試してみると、私は失敗します。アプリの終了時にアプリを保存する

アプリデリゲートでは、私はViewController.AppSave(ViewController)と言ってみます。私はエラーを取得:

Editor placeholder in source file Expression resolves to an unused function

を、私はViewController.AppSave() を使用する場合、私は次のエラーを取得する:

Instance member 'SaveApp' cannot be used on type 'ViewController'; did you mean to use a value of this type instead?

import UIKit 
import UserNotifications 

class ViewController: UIViewController { 
    //TEST PLAY AREA// 

    @IBAction func SaveButton(_ sender: Any) { 
     SaveApp() 
    } 

    @IBAction func LoadButton(_ sender: Any) { 
     LoadApp() 
    } 

    ///TEST PLAY AREA ENDS 
    public var streakNumber = 0 
    public var streakNumberString = "" 

    public var activated = false 

    let defaults = UserDefaults.standard 
    //Labels 
    @IBOutlet var streakNumberLabel: UILabel! 

    @IBOutlet var remainingTimeTextLabel: UILabel! 

    @IBOutlet var remainingTimeNumberLabel: UILabel! 
    //Buttons 
    @IBAction func startButton(_ sender: Any) { 
     Activate() 

    } 
    @IBAction func stopButton(_ sender: Any) { 
     Deactivate() 
     seconds = 59 
     minutes = 59 
     hours = 47 

    } 

    //Timer 
    var timer = Timer() 
    var seconds = 0 
    var minutes = 0 
    var hours = 0 

    // Nitifications 
    //END 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     LoadApp() 

     // this enables notifications 
     UNUserNotificationCenter.current().requestAuthorization(options:[.alert , .sound , .badge], completionHandler:{ didAllow, error in 
     }) 
    } 

    func Activate(){ 
     if activated == false { 
      streakNumber += 1 

     } 
     activated = true 
     streakNumberLabel.text = String(streakNumber) 
    } 

    func Deactivate(){ 
     if activated == true{ 
      activated = false 
      ActivTimer() 

      // Notification 
      let content = UNMutableNotificationContent() 
      content.title = " 10 secodns are up " 
      content.subtitle = " yep time passed" 
      content.body = " The 10 seconds are really up!!" 
      content.badge = 1 
      let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 600, repeats:false) 
      let request = UNNotificationRequest(identifier: "timerDone", content: content , trigger: trigger) 
      UNUserNotificationCenter.current().add(request,withCompletionHandler:nil) 
     } 
    } 

    @objc func Clock(){ 
     seconds = seconds-1 
     if seconds == -1{ 
      seconds = 59 
      minutes = minutes-1 
     } 
     if minutes == -1{ 
      minutes = 59 
      hours = hours-1 
     } 
     remainingTimeNumberLabel.text = (String(hours) + ":" + String(minutes) + ":" + String(seconds)) 
     if seconds == 0 && hours == 0 && minutes == 0 { 

      timer.invalidate() 

     } 
    } 

    func ActivTimer(){ 
     timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.Clock), userInfo: nil, repeats: true) 
    }//SAVING STUFF DOESNT WORK 
    // 

    func SaveApp(){ 
     streakNumberString = String(streakNumber) 
     defaults.set(streakNumberString, forKey: "streakNumbers") 
     print("Saved" + String(defaults.integer(forKey: "streakNumbers"))) 

    } 

    func LoadApp(){ 
     streakNumberString = defaults.string(forKey: "streakNumbers")! 
     print (defaults.integer(forKey: "streakNumbers")) 
     streakNumber = Int(streakNumberString)! 
     streakNumberLabel.text = String(streakNumber) 
    }// 
} 
+0

appdidEnterBackground&willEnterforegroundが最適です。ご覧ください1. https://stackoverflow.com/questions/9011868/whats-the-best-way-to-detect-when-the-app-isenterating-the-background-for-my-vie 2。 https://stackoverflow.com/questions/9599431/is-there-any-notification-to-get-before-application-did-enter-background 3. https://stackoverflow.com/questions/9039606/refresh-フォアグラウンドに入る前のデータ 4. https://stackoverflow.com/questions/10648388/ios-app-applicationwillenterforeground-and-it-stucked-for-a-while –

+0

投稿したコードの大半は何もありませんあなたのエラーを引き起こすコードと関係がある。関連するコードを含めるように質問を編集してください。問題の原因となっている実際のコードを含めてください。 – rmaddy

答えて

0

エラーがそれをすべて言います。 ViewControllerSaveApp()を呼び出すことはできません。 SaveApp()を呼び出すには、実際にはViewControllerのインスタンスが必要です。

アプリの終了時にそのデータを保存するために、あなたのViewControllerインスタンスを希望される場合、アプリが同様に最小化し、終了前にされているときに呼び出されAppDelegateapplicationDidEnterBackground方法、からの通知を投稿できます

func applicationDidEnterBackground(_ application: UIApplication) { 

    NotificationCenter.default.post(Notification(name: Notification.Name("AppAboutToTerminateOrMinimize"))) 
} 

次に、あなたがあなたのViewController年代viewDidLoad()にその通知を購読することができます:

NotificationCenter.default.addObserver(self, 
             selector: #selector(AppSave), 
             name: Notification.Name("AppAboutToTerminateOrMinimize"), 
             object: nil) 

やコメントで述べたようrmaddy sの、あなただけのViewControllerviewDidLoad()に以下のコードを入れて、AppDelegate部分をスキップすることができます

NotificationCenter.default.addObserver(self, 
             selector: #selector(AppSave), 
             name: Notification(name: UIApplicationDidEnterBackgroundNotification, 
             object: nil) 

アプリは最小限に/(生きている場合)AppDelegate通知、ViewControllerインスタンスを送信します終了し、この方法は、受信しますそれとあなたは@objc

としてAppSave()方法に注釈を付ける必要があるだろうと、それはプロパティとメソッド/すなわち0123の命名lowerCamelCaseを使うようにするとよいでしょうAppSave()

を呼び出しますの代わりにAppSave()

+0

これを行うもっと良い方法があります。 'UIApplicationDidEnterBackground'通知のためにビューコントローラを登録させるだけです。カスタム通知の必要はありません。 'applicationDidEnterBackground'アプリケーションデリゲートメソッドに何かを投稿する必要はありません。 – rmaddy

+0

@rmaddy正解!それは私の心に来ていません:) – Dan

+0

@rmaddyどうすればいいですか? –

関連する問題