Skip to main content

UIDatePicker with UserNotifications | iOS | Swift

Local Notifications


The big problem with APNS is that it requires you to run a server somewhere that interacts with APNS to push a notification to a device. For applications that already have a client-server architecture such as an IM client this is no big deal. There are also a number of third parties who can provide a cost efficient service for small scale users who do not want the trouble of running their own server. However for many applications this is still way too complicated.

This blog helps us in triggering the notification at specific time which is being selected by user in date picker.
For that you have to take textField and two buttons.

And don,t forget to edit AppDelegate method.

import UserNotifications

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKeyAny]?) -> Bool {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        }
        // Override point for customization after application launch.
        return true

    }

ViewController.m
import UIKit
import UserNotifications
import UserNotificationsUI

class ViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var datePickerView: UIView!
    @IBOutlet weak var txtDatePicker: UITextField!
    let datePicker = UIDatePicker()
    let requestIdentifier = "prem"

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func showDatePicker(_ textField : UITextField){
        //Formate Date
        datePicker.frame = CGRect.init(x: 0, y: 30, width: datePickerView.bounds.width, height: datePickerView.bounds.height-50)
        datePicker.datePickerMode = .dateAndTime

        txtDatePicker.inputView = self.datePicker

        
        //ToolBar
        let toolbar = UIToolbar();
        toolbar.frame = CGRect.init(x: 0, y: 0, width: datePickerView.bounds.width, height: 30)
        toolbar.backgroundColor = UIColor.blue
//        toolbar.sizeToFit()
        
        //done button & cancel button
        let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(ViewController.donedatePicker))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.done, target: self, action: #selector(ViewController.cancelDatePicker))
        toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)
        
        //datePickerView.addSubview(toolbar)
        txtDatePicker.inputAccessoryView = toolbar

       
        
        
    }
    
    func donedatePicker(){
        //For date formate
        let formatter = DateFormatter()
        formatter.dateFormat = "dd/MM/yyyy"
        txtDatePicker.text = formatter.string(from: datePicker.date)
        //dismiss date picker dialog
        txtDatePicker.resignFirstResponder()
        
    }
    

    func cancelDatePicker(){
        txtDatePicker.resignFirstResponder()
        
    }
        
    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.showDatePicker(self.txtDatePicker)
    }
    
    @IBAction func triggerButton(_ sender: Any) {
        
        print("Notification will be triggered in 2 sec. Hold on...")
        let content = UNMutableNotificationContent()
        content.title = "Intro to Notifications"
        content.subtitle = "Hello"
        content.body = "I learnt local notification"
        content.sound = UNNotificationSound.default()
        
        //Delivering the notification in two seconds.
        let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: datePicker.date)
        let trigger = UNCalendarNotificationTrigger.init(dateMatching: triggerDate, repeats: false)
        let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
        UNUserNotificationCenter.current().add(request){(error) in
            
            if (error != nil){
                
                print(error?.localizedDescription as Any )
            }
        }
        
    }
    
    
    @IBAction func stopButton(_ sender: Any) {
        print("Remove pending request.")
        let centre = UNUserNotificationCenter.current()
        centre.removePendingNotificationRequests(withIdentifiers: [requestIdentifier])
        
    }
}

    


extension ViewController: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        print("Tapped in notification")
    }
    
    //This is key callback to present notification while the app is in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        print("Notification being triggered")
        //You can either present alert ,sound or increase badge while the app is in foreground too with ios 10
        //to distinguish between notifications
        if notification.request.identifier == requestIdentifier{
            
            completionHandler( [.alert,.sound,.badge])
            
        }
    }
    
}



Comments

Popular posts from this blog

Draggable Marker and Drawing the routes between them using Google Maps | IOS | Swift

This blog is about how we can make the marker draggable and get the current location from it and to draw the routes between them. For that we have to install the pods of Google maps from developer.google.com. Then we have to add the following    pod 'GoogleMaps'   pod 'GooglePlaces'   pod 'GooglePlacesAPI'   pod 'SwiftyJSON' And we have to save the pods into the pod file. Then, we have to install all the pods through terminal. Again we have to make the outlet for textfield and button as discussed below. 2 TextField and 3 Buttons. Hope you will enjoy the coding. Happy coding.! import UIKit import GoogleMaps import GooglePlaces import SwiftyJSON import Alamofire enum Location { case startLocation case destinationLocation } class ViewController: UIViewController , GMSMapViewDelegate ,  CLLocationManagerDelegate { @IBOutlet weak var googleMaps: GMSMapView ! @IBOutlet weak

Route between two places using Google Maps iOS SDK.

Its very interesting to have the Google maps  Firstly. We have to install the pods of Google maps. So, follow the steps for installing the pods of Google maps on developers.google.com 1. Create the pod file as on the site. 2. In Podfile add the pod of Alamofire and SwiftyJSON. 3. Save the pod file.      pod 'GoogleMaps'     pod 'GooglePlaces'     pod 'Alamofire' , '~> 4.2.0'     pod 'SwiftyJSON' 4. Install the pods. Here is the code for route. import UIKit import GoogleMaps import GooglePlaces import Alamofire import SwiftyJSON class GoogleViewController: UIViewController , GMSMapViewDelegate {     @IBOutlet weak var googleView: GMSMapView !          // AIzaSyC907BQBnrZK0UjA2zARtE6Mq7L__yqw5Q     override func viewDidLoad() {         super . viewDidLoad ()         GMSServices . provideAPIKey ( "AIzaSyC907BQBnrZK0UjA2zARtE6Mq7L__yqw5Q" )         GMSPlacesClient . pr

Cancellable Task with Dispatch Work Item | iOS | Swift

In some scenarios, we all want that the task we want to perform should be cancellable later on. For this kind of behaviour, we already have OperationQueue but the use of It seems difficult for beginners. Most of us didn't use OperationQueue so frequently and were only familiar with Grand Central Dispatch (GCD) . by performing UI operations in the main thread, Dispatch Group, etc. By the use of DispatachWorkItem , we can create some tasks that can be cancelled later on. Here is the example, let workItem = DispatchWorkItem {     // Here is our task     debugPrint ( "Task is to print some text..." ) } This is DispatchWorkItem containing a task to print something. To perform this task, we need to make use of DispatchQueue like this by adding delay if required. DispatchQueue . main . asyncAfter (deadline: . now () + . seconds ( 1 ), execute: workItem ) Here is the basic example to add a task and perform it using DispatchQueue. Now to cancel that we need to keep the referen