How do I save state between app launched using UserDefaults?











up vote
0
down vote

favorite












I am trying to display, using a UILabel, the time/date (Date or NSDate), formatted using a DateFormatter of each previous app launch when I start the app.



So, every time I launch the app there should be another date that is displayed on the screen.



For example, if this is the first time launching, it will display Nov 18 2018, 13:15. And the second launch it should display



Nov 18 2018, 13:15 
Nov 18 2018, 13:16


The third launch it should display something like



 Nov 18 2018, 13:15 
Nov 18 2018, 13:16
Nov 18 2018, 13:17


Currently, my code only displays the time of the launch but does not record previous launches. If anyone can give me some directions on how to use UserDefaults to achieve this I will really appreciate it!



import UIKit

class ViewController: UIViewController {

@IBOutlet weak var Timelabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd, yyyy HH:mm:ss"

let DisplayTime: Date = Date()
print(dateFormatterPrint.string(from: DisplayTime))
Timelabel.text = "Current Time: (dateFormatterPrint.string(from: DisplayTime))"

}

}









share|improve this question




























    up vote
    0
    down vote

    favorite












    I am trying to display, using a UILabel, the time/date (Date or NSDate), formatted using a DateFormatter of each previous app launch when I start the app.



    So, every time I launch the app there should be another date that is displayed on the screen.



    For example, if this is the first time launching, it will display Nov 18 2018, 13:15. And the second launch it should display



    Nov 18 2018, 13:15 
    Nov 18 2018, 13:16


    The third launch it should display something like



     Nov 18 2018, 13:15 
    Nov 18 2018, 13:16
    Nov 18 2018, 13:17


    Currently, my code only displays the time of the launch but does not record previous launches. If anyone can give me some directions on how to use UserDefaults to achieve this I will really appreciate it!



    import UIKit

    class ViewController: UIViewController {

    @IBOutlet weak var Timelabel: UILabel!

    override func viewDidLoad() {
    super.viewDidLoad()
    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "MMM dd, yyyy HH:mm:ss"

    let DisplayTime: Date = Date()
    print(dateFormatterPrint.string(from: DisplayTime))
    Timelabel.text = "Current Time: (dateFormatterPrint.string(from: DisplayTime))"

    }

    }









    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am trying to display, using a UILabel, the time/date (Date or NSDate), formatted using a DateFormatter of each previous app launch when I start the app.



      So, every time I launch the app there should be another date that is displayed on the screen.



      For example, if this is the first time launching, it will display Nov 18 2018, 13:15. And the second launch it should display



      Nov 18 2018, 13:15 
      Nov 18 2018, 13:16


      The third launch it should display something like



       Nov 18 2018, 13:15 
      Nov 18 2018, 13:16
      Nov 18 2018, 13:17


      Currently, my code only displays the time of the launch but does not record previous launches. If anyone can give me some directions on how to use UserDefaults to achieve this I will really appreciate it!



      import UIKit

      class ViewController: UIViewController {

      @IBOutlet weak var Timelabel: UILabel!

      override func viewDidLoad() {
      super.viewDidLoad()
      let dateFormatterPrint = DateFormatter()
      dateFormatterPrint.dateFormat = "MMM dd, yyyy HH:mm:ss"

      let DisplayTime: Date = Date()
      print(dateFormatterPrint.string(from: DisplayTime))
      Timelabel.text = "Current Time: (dateFormatterPrint.string(from: DisplayTime))"

      }

      }









      share|improve this question















      I am trying to display, using a UILabel, the time/date (Date or NSDate), formatted using a DateFormatter of each previous app launch when I start the app.



      So, every time I launch the app there should be another date that is displayed on the screen.



      For example, if this is the first time launching, it will display Nov 18 2018, 13:15. And the second launch it should display



      Nov 18 2018, 13:15 
      Nov 18 2018, 13:16


      The third launch it should display something like



       Nov 18 2018, 13:15 
      Nov 18 2018, 13:16
      Nov 18 2018, 13:17


      Currently, my code only displays the time of the launch but does not record previous launches. If anyone can give me some directions on how to use UserDefaults to achieve this I will really appreciate it!



      import UIKit

      class ViewController: UIViewController {

      @IBOutlet weak var Timelabel: UILabel!

      override func viewDidLoad() {
      super.viewDidLoad()
      let dateFormatterPrint = DateFormatter()
      dateFormatterPrint.dateFormat = "MMM dd, yyyy HH:mm:ss"

      let DisplayTime: Date = Date()
      print(dateFormatterPrint.string(from: DisplayTime))
      Timelabel.text = "Current Time: (dateFormatterPrint.string(from: DisplayTime))"

      }

      }






      ios swift






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 19 at 0:18









      Damon

      424317




      424317










      asked Nov 18 at 18:30









      user7544590

      126




      126
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          Use it as following



          class ViewController: UIViewController {

          // your other @IBOutlet / properties
          let ARR_KEY = "launch_time"

          override func viewDidLoad() {
          // your other code.
          // remove your TimeLabel.text = ... line

          let formattedDateTime = dateFormatterPrint.string(from: DisplayTime)


          // storing the launch date time
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          arr.append(formattedDateTime)
          UserDefaults.standard.set(arr, forKey: ARR_KEY)
          } else {
          UserDefaults.standard.set([formattedDateTime], forKey: ARR_KEY)
          }

          displayLaunchTimeInSimpleLabel()
          }

          func displayLaunchTimeInSimpleLabel() {
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          var string = ""
          for launchTime in arr {
          string = string + launchTime + "n"
          }
          Timelabel.text = string
          }
          }
          }





          share|improve this answer























          • Is it legal to append to arr? Isn't it a constant since you used let?
            – user7544590
            Nov 18 at 19:05












          • thanks, yes it is illegal. updated the code.
            – Ratul Sharker
            Nov 18 at 19:08










          • It still only displays the current time. Do I have to connect the UILabel to something?
            – user7544590
            Nov 18 at 19:12






          • 1




            Don't suggest value(forKey unless you can explain why KVC is mandatory. There is array(forKey
            – vadian
            Nov 18 at 19:13






          • 1




            @RatulSharker From what I'm aware of, there is no downside of calling the synchronize method, other than it is unnecessary, which even if it's just for clean code sake, I don't think you should use. I'm unaware of the technical implications of it tho. I'm assuming calling the synchronize method must have some type of performance implication. Like even if Apple's implementation of the method does absolutely nothing (which is probably unlikely), I still think that would have some type of performance implication. It might be SUPER minor tho.
            – Charlie Fish
            Nov 19 at 4:50











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53364175%2fhow-do-i-save-state-between-app-launched-using-userdefaults%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          Use it as following



          class ViewController: UIViewController {

          // your other @IBOutlet / properties
          let ARR_KEY = "launch_time"

          override func viewDidLoad() {
          // your other code.
          // remove your TimeLabel.text = ... line

          let formattedDateTime = dateFormatterPrint.string(from: DisplayTime)


          // storing the launch date time
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          arr.append(formattedDateTime)
          UserDefaults.standard.set(arr, forKey: ARR_KEY)
          } else {
          UserDefaults.standard.set([formattedDateTime], forKey: ARR_KEY)
          }

          displayLaunchTimeInSimpleLabel()
          }

          func displayLaunchTimeInSimpleLabel() {
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          var string = ""
          for launchTime in arr {
          string = string + launchTime + "n"
          }
          Timelabel.text = string
          }
          }
          }





          share|improve this answer























          • Is it legal to append to arr? Isn't it a constant since you used let?
            – user7544590
            Nov 18 at 19:05












          • thanks, yes it is illegal. updated the code.
            – Ratul Sharker
            Nov 18 at 19:08










          • It still only displays the current time. Do I have to connect the UILabel to something?
            – user7544590
            Nov 18 at 19:12






          • 1




            Don't suggest value(forKey unless you can explain why KVC is mandatory. There is array(forKey
            – vadian
            Nov 18 at 19:13






          • 1




            @RatulSharker From what I'm aware of, there is no downside of calling the synchronize method, other than it is unnecessary, which even if it's just for clean code sake, I don't think you should use. I'm unaware of the technical implications of it tho. I'm assuming calling the synchronize method must have some type of performance implication. Like even if Apple's implementation of the method does absolutely nothing (which is probably unlikely), I still think that would have some type of performance implication. It might be SUPER minor tho.
            – Charlie Fish
            Nov 19 at 4:50















          up vote
          0
          down vote



          accepted










          Use it as following



          class ViewController: UIViewController {

          // your other @IBOutlet / properties
          let ARR_KEY = "launch_time"

          override func viewDidLoad() {
          // your other code.
          // remove your TimeLabel.text = ... line

          let formattedDateTime = dateFormatterPrint.string(from: DisplayTime)


          // storing the launch date time
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          arr.append(formattedDateTime)
          UserDefaults.standard.set(arr, forKey: ARR_KEY)
          } else {
          UserDefaults.standard.set([formattedDateTime], forKey: ARR_KEY)
          }

          displayLaunchTimeInSimpleLabel()
          }

          func displayLaunchTimeInSimpleLabel() {
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          var string = ""
          for launchTime in arr {
          string = string + launchTime + "n"
          }
          Timelabel.text = string
          }
          }
          }





          share|improve this answer























          • Is it legal to append to arr? Isn't it a constant since you used let?
            – user7544590
            Nov 18 at 19:05












          • thanks, yes it is illegal. updated the code.
            – Ratul Sharker
            Nov 18 at 19:08










          • It still only displays the current time. Do I have to connect the UILabel to something?
            – user7544590
            Nov 18 at 19:12






          • 1




            Don't suggest value(forKey unless you can explain why KVC is mandatory. There is array(forKey
            – vadian
            Nov 18 at 19:13






          • 1




            @RatulSharker From what I'm aware of, there is no downside of calling the synchronize method, other than it is unnecessary, which even if it's just for clean code sake, I don't think you should use. I'm unaware of the technical implications of it tho. I'm assuming calling the synchronize method must have some type of performance implication. Like even if Apple's implementation of the method does absolutely nothing (which is probably unlikely), I still think that would have some type of performance implication. It might be SUPER minor tho.
            – Charlie Fish
            Nov 19 at 4:50













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          Use it as following



          class ViewController: UIViewController {

          // your other @IBOutlet / properties
          let ARR_KEY = "launch_time"

          override func viewDidLoad() {
          // your other code.
          // remove your TimeLabel.text = ... line

          let formattedDateTime = dateFormatterPrint.string(from: DisplayTime)


          // storing the launch date time
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          arr.append(formattedDateTime)
          UserDefaults.standard.set(arr, forKey: ARR_KEY)
          } else {
          UserDefaults.standard.set([formattedDateTime], forKey: ARR_KEY)
          }

          displayLaunchTimeInSimpleLabel()
          }

          func displayLaunchTimeInSimpleLabel() {
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          var string = ""
          for launchTime in arr {
          string = string + launchTime + "n"
          }
          Timelabel.text = string
          }
          }
          }





          share|improve this answer














          Use it as following



          class ViewController: UIViewController {

          // your other @IBOutlet / properties
          let ARR_KEY = "launch_time"

          override func viewDidLoad() {
          // your other code.
          // remove your TimeLabel.text = ... line

          let formattedDateTime = dateFormatterPrint.string(from: DisplayTime)


          // storing the launch date time
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          arr.append(formattedDateTime)
          UserDefaults.standard.set(arr, forKey: ARR_KEY)
          } else {
          UserDefaults.standard.set([formattedDateTime], forKey: ARR_KEY)
          }

          displayLaunchTimeInSimpleLabel()
          }

          func displayLaunchTimeInSimpleLabel() {
          if var arr = UserDefaults.standard.stringArray(forKey: ARR_KEY){
          var string = ""
          for launchTime in arr {
          string = string + launchTime + "n"
          }
          Timelabel.text = string
          }
          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 19 at 2:37

























          answered Nov 18 at 18:46









          Ratul Sharker

          2,56811525




          2,56811525












          • Is it legal to append to arr? Isn't it a constant since you used let?
            – user7544590
            Nov 18 at 19:05












          • thanks, yes it is illegal. updated the code.
            – Ratul Sharker
            Nov 18 at 19:08










          • It still only displays the current time. Do I have to connect the UILabel to something?
            – user7544590
            Nov 18 at 19:12






          • 1




            Don't suggest value(forKey unless you can explain why KVC is mandatory. There is array(forKey
            – vadian
            Nov 18 at 19:13






          • 1




            @RatulSharker From what I'm aware of, there is no downside of calling the synchronize method, other than it is unnecessary, which even if it's just for clean code sake, I don't think you should use. I'm unaware of the technical implications of it tho. I'm assuming calling the synchronize method must have some type of performance implication. Like even if Apple's implementation of the method does absolutely nothing (which is probably unlikely), I still think that would have some type of performance implication. It might be SUPER minor tho.
            – Charlie Fish
            Nov 19 at 4:50


















          • Is it legal to append to arr? Isn't it a constant since you used let?
            – user7544590
            Nov 18 at 19:05












          • thanks, yes it is illegal. updated the code.
            – Ratul Sharker
            Nov 18 at 19:08










          • It still only displays the current time. Do I have to connect the UILabel to something?
            – user7544590
            Nov 18 at 19:12






          • 1




            Don't suggest value(forKey unless you can explain why KVC is mandatory. There is array(forKey
            – vadian
            Nov 18 at 19:13






          • 1




            @RatulSharker From what I'm aware of, there is no downside of calling the synchronize method, other than it is unnecessary, which even if it's just for clean code sake, I don't think you should use. I'm unaware of the technical implications of it tho. I'm assuming calling the synchronize method must have some type of performance implication. Like even if Apple's implementation of the method does absolutely nothing (which is probably unlikely), I still think that would have some type of performance implication. It might be SUPER minor tho.
            – Charlie Fish
            Nov 19 at 4:50
















          Is it legal to append to arr? Isn't it a constant since you used let?
          – user7544590
          Nov 18 at 19:05






          Is it legal to append to arr? Isn't it a constant since you used let?
          – user7544590
          Nov 18 at 19:05














          thanks, yes it is illegal. updated the code.
          – Ratul Sharker
          Nov 18 at 19:08




          thanks, yes it is illegal. updated the code.
          – Ratul Sharker
          Nov 18 at 19:08












          It still only displays the current time. Do I have to connect the UILabel to something?
          – user7544590
          Nov 18 at 19:12




          It still only displays the current time. Do I have to connect the UILabel to something?
          – user7544590
          Nov 18 at 19:12




          1




          1




          Don't suggest value(forKey unless you can explain why KVC is mandatory. There is array(forKey
          – vadian
          Nov 18 at 19:13




          Don't suggest value(forKey unless you can explain why KVC is mandatory. There is array(forKey
          – vadian
          Nov 18 at 19:13




          1




          1




          @RatulSharker From what I'm aware of, there is no downside of calling the synchronize method, other than it is unnecessary, which even if it's just for clean code sake, I don't think you should use. I'm unaware of the technical implications of it tho. I'm assuming calling the synchronize method must have some type of performance implication. Like even if Apple's implementation of the method does absolutely nothing (which is probably unlikely), I still think that would have some type of performance implication. It might be SUPER minor tho.
          – Charlie Fish
          Nov 19 at 4:50




          @RatulSharker From what I'm aware of, there is no downside of calling the synchronize method, other than it is unnecessary, which even if it's just for clean code sake, I don't think you should use. I'm unaware of the technical implications of it tho. I'm assuming calling the synchronize method must have some type of performance implication. Like even if Apple's implementation of the method does absolutely nothing (which is probably unlikely), I still think that would have some type of performance implication. It might be SUPER minor tho.
          – Charlie Fish
          Nov 19 at 4:50


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53364175%2fhow-do-i-save-state-between-app-launched-using-userdefaults%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Paul Cézanne

          UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

          Angular material date-picker (MatDatepicker) auto completes the date on focus out