decrement int from string time 4:01 to 3:51 in swift











up vote
0
down vote

favorite












hi I want to make a local notification from string time, I want the notification launch 10 minute before given time. I have trouble how to make the time from 4:01 into 3:51, please help. this is my code



let a = "4:01"

func startNoftification(prayer: String) {
let time = prayer.split(separator: ":").map { (x) -> Int in
return Int(String(x))!
}
let content = UNMutableNotificationContent()
content.title = "Adzan"
content.body = "it's time to sholat dzuhur"

let gregorian = Calendar(identifier: .gregorian)
var component = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
component.hour = time[0]
component.minute = time[1] - 10

guard let date = gregorian.date(from: component) else { return }
let triggerDaily = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: "Hijrah", content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request) { (error) in
if let err = error {
print("Notif error:", err)
return
}
}
}









share|improve this question




























    up vote
    0
    down vote

    favorite












    hi I want to make a local notification from string time, I want the notification launch 10 minute before given time. I have trouble how to make the time from 4:01 into 3:51, please help. this is my code



    let a = "4:01"

    func startNoftification(prayer: String) {
    let time = prayer.split(separator: ":").map { (x) -> Int in
    return Int(String(x))!
    }
    let content = UNMutableNotificationContent()
    content.title = "Adzan"
    content.body = "it's time to sholat dzuhur"

    let gregorian = Calendar(identifier: .gregorian)
    var component = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
    component.hour = time[0]
    component.minute = time[1] - 10

    guard let date = gregorian.date(from: component) else { return }
    let triggerDaily = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
    let request = UNNotificationRequest(identifier: "Hijrah", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) { (error) in
    if let err = error {
    print("Notif error:", err)
    return
    }
    }
    }









    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      hi I want to make a local notification from string time, I want the notification launch 10 minute before given time. I have trouble how to make the time from 4:01 into 3:51, please help. this is my code



      let a = "4:01"

      func startNoftification(prayer: String) {
      let time = prayer.split(separator: ":").map { (x) -> Int in
      return Int(String(x))!
      }
      let content = UNMutableNotificationContent()
      content.title = "Adzan"
      content.body = "it's time to sholat dzuhur"

      let gregorian = Calendar(identifier: .gregorian)
      var component = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
      component.hour = time[0]
      component.minute = time[1] - 10

      guard let date = gregorian.date(from: component) else { return }
      let triggerDaily = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
      let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
      let request = UNNotificationRequest(identifier: "Hijrah", content: content, trigger: trigger)

      UNUserNotificationCenter.current().add(request) { (error) in
      if let err = error {
      print("Notif error:", err)
      return
      }
      }
      }









      share|improve this question















      hi I want to make a local notification from string time, I want the notification launch 10 minute before given time. I have trouble how to make the time from 4:01 into 3:51, please help. this is my code



      let a = "4:01"

      func startNoftification(prayer: String) {
      let time = prayer.split(separator: ":").map { (x) -> Int in
      return Int(String(x))!
      }
      let content = UNMutableNotificationContent()
      content.title = "Adzan"
      content.body = "it's time to sholat dzuhur"

      let gregorian = Calendar(identifier: .gregorian)
      var component = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
      component.hour = time[0]
      component.minute = time[1] - 10

      guard let date = gregorian.date(from: component) else { return }
      let triggerDaily = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
      let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
      let request = UNNotificationRequest(identifier: "Hijrah", content: content, trigger: trigger)

      UNUserNotificationCenter.current().add(request) { (error) in
      if let err = error {
      print("Notif error:", err)
      return
      }
      }
      }






      ios swift datetime notifications uilocalnotification






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 at 7:40

























      asked Nov 22 at 7:32









      ferryawijayanto

      507




      507
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          Is this what you need?



          let time = "4:01"

          let dateFormatter = DateFormatter()
          dateFormatter.dateFormat = "hh:mm"

          guard let date = dateFormatter.date(from: time) else {
          return
          }

          let targetTime = Date(timeInterval: -(10 * 60), since: date) // Change time interval to required value in seconds
          let targetTimeString = dateFormatter.string(from: targetTime)
          print(targetTimeString) // Prints 3:51


          Or if your countdown time has a lot of time components, use DateComponents.



          var dateComponents = DateComponents()
          dateComponents.minute = -10
          // Other components

          if let targetTime = Calendar.current.date(byAdding: dateComponents, to: date)
          print(dateFormatter.string(from: targetTime))
          }





          share|improve this answer























          • your code is work, now my problem is how to setup in user notification. thank your for your reply
            – ferryawijayanto
            Nov 22 at 10:08










          • @ferryawijayanto that should be asked as a separate question. You current question did include that.
            – Rakesha Shastri
            Nov 22 at 10:09












          • sorry if my question is not clear enough, but I will try using your code to setup local notification.
            – ferryawijayanto
            Nov 22 at 10:12


















          up vote
          0
          down vote













          Here I have solution combine with rakesha Shastri answer, hopefully it can helps others.



          First import UserNotification in appDelegate and in your controller



          import UserNotification


          and add code for didFinishWithLaunchingWithOptions



          func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

          UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge]) { (granted, error) in
          if let err = error {
          print("Notifications permission denied because:", err)
          return
          }

          if granted {
          print("Notifications permission granted.")
          }
          }
          }


          and you can make a function and add string time parameters either from API or arbitrary string, since I'm not using function so I pass my solution in viewDidLoad



          let adzan = "4:01"

          let content = UNMutableNotificationContent()
          content.title = "Adzan"
          content.body = "It's time for sholat"
          content.sound = UNNotificationSound.default

          // Format the date first from string time
          let dateFormatter = DateFormatter()
          dateFormatter.dateFormat = "HH:mm"

          //addingTimeInterval is where you want to set notification before or after deciding time in this case I set it 10 minute before deciding time
          guard let date = dateFormatter.date(from: adzan)?.addingTimeInterval(-600) else { return }

          // and convert our date into dateComponents
          let triggerDate = Calendar.current.dateComponents([.hour, .minute, .second], from: date)

          let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

          let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

          UNUserNotificationCenter.current().add(request)





          share|improve this answer





















            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%2f53425898%2fdecrement-int-from-string-time-401-to-351-in-swift%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            3
            down vote



            accepted










            Is this what you need?



            let time = "4:01"

            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "hh:mm"

            guard let date = dateFormatter.date(from: time) else {
            return
            }

            let targetTime = Date(timeInterval: -(10 * 60), since: date) // Change time interval to required value in seconds
            let targetTimeString = dateFormatter.string(from: targetTime)
            print(targetTimeString) // Prints 3:51


            Or if your countdown time has a lot of time components, use DateComponents.



            var dateComponents = DateComponents()
            dateComponents.minute = -10
            // Other components

            if let targetTime = Calendar.current.date(byAdding: dateComponents, to: date)
            print(dateFormatter.string(from: targetTime))
            }





            share|improve this answer























            • your code is work, now my problem is how to setup in user notification. thank your for your reply
              – ferryawijayanto
              Nov 22 at 10:08










            • @ferryawijayanto that should be asked as a separate question. You current question did include that.
              – Rakesha Shastri
              Nov 22 at 10:09












            • sorry if my question is not clear enough, but I will try using your code to setup local notification.
              – ferryawijayanto
              Nov 22 at 10:12















            up vote
            3
            down vote



            accepted










            Is this what you need?



            let time = "4:01"

            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "hh:mm"

            guard let date = dateFormatter.date(from: time) else {
            return
            }

            let targetTime = Date(timeInterval: -(10 * 60), since: date) // Change time interval to required value in seconds
            let targetTimeString = dateFormatter.string(from: targetTime)
            print(targetTimeString) // Prints 3:51


            Or if your countdown time has a lot of time components, use DateComponents.



            var dateComponents = DateComponents()
            dateComponents.minute = -10
            // Other components

            if let targetTime = Calendar.current.date(byAdding: dateComponents, to: date)
            print(dateFormatter.string(from: targetTime))
            }





            share|improve this answer























            • your code is work, now my problem is how to setup in user notification. thank your for your reply
              – ferryawijayanto
              Nov 22 at 10:08










            • @ferryawijayanto that should be asked as a separate question. You current question did include that.
              – Rakesha Shastri
              Nov 22 at 10:09












            • sorry if my question is not clear enough, but I will try using your code to setup local notification.
              – ferryawijayanto
              Nov 22 at 10:12













            up vote
            3
            down vote



            accepted







            up vote
            3
            down vote



            accepted






            Is this what you need?



            let time = "4:01"

            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "hh:mm"

            guard let date = dateFormatter.date(from: time) else {
            return
            }

            let targetTime = Date(timeInterval: -(10 * 60), since: date) // Change time interval to required value in seconds
            let targetTimeString = dateFormatter.string(from: targetTime)
            print(targetTimeString) // Prints 3:51


            Or if your countdown time has a lot of time components, use DateComponents.



            var dateComponents = DateComponents()
            dateComponents.minute = -10
            // Other components

            if let targetTime = Calendar.current.date(byAdding: dateComponents, to: date)
            print(dateFormatter.string(from: targetTime))
            }





            share|improve this answer














            Is this what you need?



            let time = "4:01"

            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "hh:mm"

            guard let date = dateFormatter.date(from: time) else {
            return
            }

            let targetTime = Date(timeInterval: -(10 * 60), since: date) // Change time interval to required value in seconds
            let targetTimeString = dateFormatter.string(from: targetTime)
            print(targetTimeString) // Prints 3:51


            Or if your countdown time has a lot of time components, use DateComponents.



            var dateComponents = DateComponents()
            dateComponents.minute = -10
            // Other components

            if let targetTime = Calendar.current.date(byAdding: dateComponents, to: date)
            print(dateFormatter.string(from: targetTime))
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 22 at 7:58

























            answered Nov 22 at 7:41









            Rakesha Shastri

            6,43421031




            6,43421031












            • your code is work, now my problem is how to setup in user notification. thank your for your reply
              – ferryawijayanto
              Nov 22 at 10:08










            • @ferryawijayanto that should be asked as a separate question. You current question did include that.
              – Rakesha Shastri
              Nov 22 at 10:09












            • sorry if my question is not clear enough, but I will try using your code to setup local notification.
              – ferryawijayanto
              Nov 22 at 10:12


















            • your code is work, now my problem is how to setup in user notification. thank your for your reply
              – ferryawijayanto
              Nov 22 at 10:08










            • @ferryawijayanto that should be asked as a separate question. You current question did include that.
              – Rakesha Shastri
              Nov 22 at 10:09












            • sorry if my question is not clear enough, but I will try using your code to setup local notification.
              – ferryawijayanto
              Nov 22 at 10:12
















            your code is work, now my problem is how to setup in user notification. thank your for your reply
            – ferryawijayanto
            Nov 22 at 10:08




            your code is work, now my problem is how to setup in user notification. thank your for your reply
            – ferryawijayanto
            Nov 22 at 10:08












            @ferryawijayanto that should be asked as a separate question. You current question did include that.
            – Rakesha Shastri
            Nov 22 at 10:09






            @ferryawijayanto that should be asked as a separate question. You current question did include that.
            – Rakesha Shastri
            Nov 22 at 10:09














            sorry if my question is not clear enough, but I will try using your code to setup local notification.
            – ferryawijayanto
            Nov 22 at 10:12




            sorry if my question is not clear enough, but I will try using your code to setup local notification.
            – ferryawijayanto
            Nov 22 at 10:12












            up vote
            0
            down vote













            Here I have solution combine with rakesha Shastri answer, hopefully it can helps others.



            First import UserNotification in appDelegate and in your controller



            import UserNotification


            and add code for didFinishWithLaunchingWithOptions



            func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge]) { (granted, error) in
            if let err = error {
            print("Notifications permission denied because:", err)
            return
            }

            if granted {
            print("Notifications permission granted.")
            }
            }
            }


            and you can make a function and add string time parameters either from API or arbitrary string, since I'm not using function so I pass my solution in viewDidLoad



            let adzan = "4:01"

            let content = UNMutableNotificationContent()
            content.title = "Adzan"
            content.body = "It's time for sholat"
            content.sound = UNNotificationSound.default

            // Format the date first from string time
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "HH:mm"

            //addingTimeInterval is where you want to set notification before or after deciding time in this case I set it 10 minute before deciding time
            guard let date = dateFormatter.date(from: adzan)?.addingTimeInterval(-600) else { return }

            // and convert our date into dateComponents
            let triggerDate = Calendar.current.dateComponents([.hour, .minute, .second], from: date)

            let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

            let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

            UNUserNotificationCenter.current().add(request)





            share|improve this answer

























              up vote
              0
              down vote













              Here I have solution combine with rakesha Shastri answer, hopefully it can helps others.



              First import UserNotification in appDelegate and in your controller



              import UserNotification


              and add code for didFinishWithLaunchingWithOptions



              func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

              UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge]) { (granted, error) in
              if let err = error {
              print("Notifications permission denied because:", err)
              return
              }

              if granted {
              print("Notifications permission granted.")
              }
              }
              }


              and you can make a function and add string time parameters either from API or arbitrary string, since I'm not using function so I pass my solution in viewDidLoad



              let adzan = "4:01"

              let content = UNMutableNotificationContent()
              content.title = "Adzan"
              content.body = "It's time for sholat"
              content.sound = UNNotificationSound.default

              // Format the date first from string time
              let dateFormatter = DateFormatter()
              dateFormatter.dateFormat = "HH:mm"

              //addingTimeInterval is where you want to set notification before or after deciding time in this case I set it 10 minute before deciding time
              guard let date = dateFormatter.date(from: adzan)?.addingTimeInterval(-600) else { return }

              // and convert our date into dateComponents
              let triggerDate = Calendar.current.dateComponents([.hour, .minute, .second], from: date)

              let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

              let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

              UNUserNotificationCenter.current().add(request)





              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                Here I have solution combine with rakesha Shastri answer, hopefully it can helps others.



                First import UserNotification in appDelegate and in your controller



                import UserNotification


                and add code for didFinishWithLaunchingWithOptions



                func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge]) { (granted, error) in
                if let err = error {
                print("Notifications permission denied because:", err)
                return
                }

                if granted {
                print("Notifications permission granted.")
                }
                }
                }


                and you can make a function and add string time parameters either from API or arbitrary string, since I'm not using function so I pass my solution in viewDidLoad



                let adzan = "4:01"

                let content = UNMutableNotificationContent()
                content.title = "Adzan"
                content.body = "It's time for sholat"
                content.sound = UNNotificationSound.default

                // Format the date first from string time
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "HH:mm"

                //addingTimeInterval is where you want to set notification before or after deciding time in this case I set it 10 minute before deciding time
                guard let date = dateFormatter.date(from: adzan)?.addingTimeInterval(-600) else { return }

                // and convert our date into dateComponents
                let triggerDate = Calendar.current.dateComponents([.hour, .minute, .second], from: date)

                let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

                let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

                UNUserNotificationCenter.current().add(request)





                share|improve this answer












                Here I have solution combine with rakesha Shastri answer, hopefully it can helps others.



                First import UserNotification in appDelegate and in your controller



                import UserNotification


                and add code for didFinishWithLaunchingWithOptions



                func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge]) { (granted, error) in
                if let err = error {
                print("Notifications permission denied because:", err)
                return
                }

                if granted {
                print("Notifications permission granted.")
                }
                }
                }


                and you can make a function and add string time parameters either from API or arbitrary string, since I'm not using function so I pass my solution in viewDidLoad



                let adzan = "4:01"

                let content = UNMutableNotificationContent()
                content.title = "Adzan"
                content.body = "It's time for sholat"
                content.sound = UNNotificationSound.default

                // Format the date first from string time
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "HH:mm"

                //addingTimeInterval is where you want to set notification before or after deciding time in this case I set it 10 minute before deciding time
                guard let date = dateFormatter.date(from: adzan)?.addingTimeInterval(-600) else { return }

                // and convert our date into dateComponents
                let triggerDate = Calendar.current.dateComponents([.hour, .minute, .second], from: date)

                let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

                let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

                UNUserNotificationCenter.current().add(request)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 22 at 15:36









                ferryawijayanto

                507




                507






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53425898%2fdecrement-int-from-string-time-401-to-351-in-swift%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

                    Contact image not getting when fetch all contact list from iPhone by CNContact

                    count number of partitions of a set with n elements into k subsets

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks