Snippets Collections
//
//  ViewController.swift
//  PushNotifications
//
//  Created by Apple on 17/10/2023.

import UIKit
import FirebaseMessaging
import FirebaseAuth

class ViewController: UIViewController  {

    @IBOutlet weak var notificationLabel: UILabel!
    var fcmToken = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        getFcmToken()
        
    }
    
    @IBAction func sendNotificationPressed(_ sender: Any) {
        sendNotification(fcmToken)
    }
    
    func getFcmToken() {
          if let token = Messaging.messaging().fcmToken {
              print("fcm : ", token)
              fcmToken = token
              self.notificationLabel.text = "Token Found : \(token)"
          } else {
              print("no token")
              self.notificationLabel.text = "no token"
          }
      }
    
    class func instantiateVC() -> ViewController
      {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier:"ViewController") as! ViewController
        return controller
      }

    @objc func didReceivePushNotification(_ notification: Notification) {
        if let userInfo = notification.userInfo, let message = userInfo["message"] as? String {
            // Update the UI with the received message
            notificationLabel.text = message
        }
    }

    deinit {
        // Remove the observer when the view controller is deallocated
        NotificationCenter.default.removeObserver(self)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        if let aps = userInfo["aps"] as? [String: Any], let message = aps["alert"] as? String {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PushNotificationReceived"), object: nil, userInfo: ["message": message])
        }
    }
    
    func sendNotification(_ token : String) {
        // Define the FCM server URL
        let fcmURL = URL(string: "https://fcm.googleapis.com/fcm/send")!

        // Prepare the notification payload
        let notificationBody: [String: Any] = [
            "notification": [
                "title": "New Notification",
                "body": "Notfication Received",
            ],
            "to": token, // Replace with the target device token or topic
        ]

        // Convert the payload to JSON data
        guard let jsonData = try? JSONSerialization.data(withJSONObject: notificationBody) else {
            print("Error creating JSON data")
            return
        }

        // Create an HTTP request
        var request = URLRequest(url: fcmURL)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=AAAAu-cOuBM:APA91bGgioW1_SBuSGDRVT-iDaPdvDARJCADKdJLbQIo9NmwEXmHx4wA_NcpB9fV6iZWOWrxPN3jWHIfkXYmVwRqi6xsZH_SfVphkxHU9xTrbIZM_gZDmjc9TRrz8vigBPhG5IRUjQa2", forHTTPHeaderField: "Authorization") // Replace with your FCM server key

        // Set the request body with the JSON data
        request.httpBody = jsonData

        // Perform the request
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error sending notification: \(error)")
                return
            }

            if let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) {
                print("Notification sent successfully")
            } else {
                print("Failed to send notification. Status code: \((response as? HTTPURLResponse)?.statusCode ?? -1)")
            }
        }

        task.resume()
    }
}



import UIKit
import UserNotifications
import Firebase
import FirebaseCore
import FirebaseMessaging

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    
    let gcmMessageIDKey: String = "gcm.message_id"
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
   
        FirebaseApp.configure()

        Thread.sleep(forTimeInterval: 0)
        self.registerForNotifications(application: application)
        UIApplication.shared.applicationIconBadgeNumber = 0
        let uid = Auth.auth().currentUser?.uid ?? ""
        print("user ID :" ,uid)
        
        return true
    }
    
    public static func segueViewController(viewController: UIViewController, identifier: String) {
        viewController.performSegue(withIdentifier: identifier, sender: viewController)
    }
    
    public static func newViewController(identifier: String) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let mainViewController = storyboard.instantiateViewController(withIdentifier: identifier)
        mainViewController.modalPresentationStyle = .popover
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window!.rootViewController = mainViewController
        appDelegate.window!.makeKeyAndVisible()
    }
 
    public static func embed(_ viewController: UIViewController, inParent controller: UIViewController, inView view: UIView){
        viewController.willMove(toParent: controller)
        view.addSubview(viewController.view)
        controller.addChild(viewController)
        viewController.didMove(toParent: controller)
    }

    func registerForNotifications(application: UIApplication) {
        //    application.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
        //remote Notifications
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (isGranted, err) in
                if err != nil {
                    print("Error notification : ", err!)
                }
                else {
                    print("no error in registerForNotifications")
                    UNUserNotificationCenter.current().delegate = self
                    Messaging.messaging().delegate = self
                    DispatchQueue.main.async {
                        application.registerForRemoteNotifications()
                        if let token = Messaging.messaging().fcmToken {
                            print("fcm : ", token)
                            
                            
                        } else {
                            print("no token")
                           // self.notificationLabel.text = "no token"
                        }
                    }
                }
            }
        }
        
        if #available(iOS 10, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.badge,.sound,.alert], completionHandler: { (granted, error) in
                DispatchQueue.main.async {
                    UNUserNotificationCenter.current().delegate = self
                    Messaging.messaging().delegate = self
                    application.registerForRemoteNotifications()
                }
            })
        } else {
            let notificationSettings = UIUserNotificationSettings(types: [.badge,.sound,.alert], categories: nil)
            DispatchQueue.main.async {
                UNUserNotificationCenter.current().delegate = self
                Messaging.messaging().delegate = self
                application.registerUserNotificationSettings(notificationSettings)
                application.registerForRemoteNotifications()
            }
        }
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
       let controller = ViewController.instantiateVC()
       self.window?.rootViewController = controller
       self.window?.makeKeyAndVisible()
       Messaging.messaging().appDidReceiveMessage(userInfo)
       completionHandler(.noData)
     }
    
     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
         
         print("Yay! Got a device token \(deviceToken)")
        // Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
         
       Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
       Messaging.messaging().setAPNSToken(deviceToken, type: .prod)
       Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
     }
   }

extension AppDelegate: MessagingDelegate {
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    let dataDict:[String:String] = ["token": fcmToken ?? ""]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    print("Firebase Notification Token: \(fcmToken ?? "")")
  }
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: userInfo)
        //Messaging.messaging().shouldEstablishDirectChannel = true
        print("Notification Received")
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Firebase Notification Message yes: \(messageID)")
            print("User Info: \(userInfo)")
        }
        completionHandler([.alert, .badge, .sound])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
      //If notification is tapped
      let userInfo = response.notification.request.content.userInfo
      // Print message ID.
      if let messageID = userInfo[gcmMessageIDKey] {
       print("Firebase Notification Message 2: \(messageID)")
      }
       //print(userInfo["title"]) //"body"
      let controller = ViewController.instantiateVC()
      self.window?.rootViewController = controller
      self.window?.makeKeyAndVisible()
      print(userInfo)
      Messaging.messaging().appDidReceiveMessage(userInfo)
      completionHandler()
     }
   }


//
//  NotificationViewController.swift
//  Service Provider
//
//  Created by Mac HD on 01/02/2023.
//

import UIKit
import Firebase
import FirebaseFirestore
import FirebaseAuth
import SVProgressHUD

class NotificationViewController: UIViewController {

    @IBOutlet weak var notificationsTableView: UITableView!
    
    @IBOutlet weak var noNotificationsView: UIImageView!
    
    var notifications = [NotificationModel]()
    var arrangedNotifications = [NotificationModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        notificationsTableView.delegate = self
        notificationsTableView.dataSource = self
        
        getNotifications()
    }
    
    func getNotifications() {
        
        let uid = Auth.auth().currentUser?.uid ?? ""
        
        let db = Firestore.firestore()
        db.collection("Notifications")
            .whereField("receiverId", isEqualTo: uid)
            .order(by: "timestamp", descending: true).addSnapshotListener { querySnapShot, error in
                if error != nil {
                    print("Error : ", error as Any)
                    return
                }
                
                self.notifications.removeAll()
                
                var previousDate = ""
                var count = 0
                
                for document in querySnapShot!.documents {
                    
                    count += 1
                    var n = NotificationModel()
                        
                    let date = document.get("timestamp") as? Int ?? 0
                    let d = String(date)
                    let newDate = self.getDateTime(d, "d MMM, yyyy")
                        
                        if newDate != previousDate {
                            let notification = NotificationModel()
                            notification.date = newDate
                           previousDate = newDate
                           self.notifications.append(notification)
                            
                            n.date = ""
                            n.title = document.get("title") as? String ?? ""
                            n.body = document.get("body") as? String ?? ""
                           // notification.time = document.documentID
                            self.notifications.append(n)
                        } else {
                            n.title = document.get("title") as? String ?? ""
                            n.body = document.get("body") as? String ?? ""
                            self.notifications.append(n)
                        }
                }
                if self.notifications.count == 0 {
                    self.noNotificationsView.isHidden = false
                } else {
                    self.noNotificationsView.isHidden = true
                }
                print("an count3 : ", self.notifications.count)
                self.notificationsTableView.reloadData()
                
            }
    }
}


//MARK: - TableView

extension NotificationViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("an count453 : ", arrangedNotifications.count)
        return notifications.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let notification = notifications[indexPath.row]
        let notificationDate = notifications[indexPath.row].date
    
        print("n date :", notificationDate)
       
        if notification.date == "" {
            let cell = notificationsTableView.dequeueReusableCell(withIdentifier: "NotificationTableViewCell", for: indexPath) as! NotificationTableViewCell
            cell.selectionStyle = .none
            cell.title.text = notification.title
            cell.bodyLabel.text = notification.body
//            cell.notificationLabel.sizeToFit()
            print("doc34 id : ", notification.date)
            return cell
        } else {
            let cell = notificationsTableView.dequeueReusableCell(withIdentifier: "DateTableViewCell", for: indexPath) as! DateTableViewCell
            cell.dateLabel.text = notification.date
            cell.selectionStyle = .none
            print("date423 : ", notification.date)
            return cell
        }
    }
}
import Foundation

class NotificationModel {
    
    var body = ""
    var senderId = ""
    var receiverId = ""
    var notificationId = ""
    var serviceProviderId = ""
    var timestamp = 0
    var title = ""
    var date = ""
    
    init(notification : [String:Any]) {
        
        self.body = notification["body"] as? String ?? ""
        self.senderId = notification["senderId"] as? String ?? ""
        self.receiverId = notification["receiverId"] as? String ?? ""
        self.notificationId = notification["notificationId"] as? String ?? ""
        self.serviceProviderId = notification["serviceProviderId"] as? String ?? ""
        self.title = notification["title"] as? String ?? ""
        self.date = notification["date"] as? String ?? ""
        self.timestamp = notification["timestamp"] as? Int ?? 0
    }
}
function showToast(message, duration) {
  // Create a new div element for the toast message
  const toast = document.createElement('div');
  toast.classList.add('toast');

  // Add the message content to the toast
  toast.innerHTML = message;

  // Add the toast to the container element
  const container = document.getElementById('toast-container');
  container.appendChild(toast);

  // Use a timer to remove the toast after the specified duration
  setTimeout(() => {
    container.removeChild(toast);
  }, duration);
}
star

Fri Jul 07 2023 10:16:45 GMT+0000 (Coordinated Universal Time)

#ios #swift #notification #viewcontroller #controller
star

Fri Jul 07 2023 10:15:32 GMT+0000 (Coordinated Universal Time)

#ios #swift #notification #model

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension