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()
     }
   }


class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        stones = [-s for s in stones] 
        heapq.heapify(stones)
        
        while len(stones) > 1: 
            first = abs(heapq.heappop(stones)) #linear time for python 
            second = abs(heapq.heappop(stones))
            
            
            if first > second: 
                heapq.heappush(stones, second - first) #remember that since it's a minHeap we need negative numbers so it's second - first 
        
        #edge case to account if stones is empty whether originally or after smashing 
        stones.append(0)
        
        return abs(stones[0])
//Useful for background tasks, uploading resources, print/task 
 
//Can be impleneted with array (use push/shift or unshift/pop) or queue class 
//Again any time you use shift/unshift, you have O(N)
//FIFO 

class Node: 
  def __init__(self, value, next=None): 
    self.value = value 
    self.next = next 
  
class Queue: 
  def __init__(self, first=None, last=None, size=0): 
    self.first = first 
    self.last = last 
    self.size = size 
  
  #add to end of queue (similar to append or push) and returns size 
  def enqueue(self, value): 
    new_node = Node(value) 
    
    if self.first == None: 
      self.first = new_node 
      self.last = new_node 
    else: 
      self.last.next = new_node
      self.last = new_node 
    
    self.size += 1
    return self.size 
  
  #remove from beginning of queue 
  def dequeue(self): 
    if self.first == None: 
      return None 
    
    temp = self.first 
    if self.first == self.last: 
      self.last = None 
    #set 1st property to be original first's next 
    self.first = self.first.next 
    self.size -= 1 
    
    return temp.value 
    
  #useful to visualize any other function works 
  def print_queue_to_list(self): 
    result = []
    current = self.first 
    while current: 
      result.append(current.value)
      current = current.next 
    print(result)

s = Queue() 
s.enqueue(1) 
s.enqueue(2)
s.enqueue(3)
s.print_queue_to_list() >> [1, 2, 3]
s.dequeue() 
s.print_queue_to_list() >> [2, 3]

// Big O: 
// Insertion and Removal: O(1) **this is mainly what stacks are good for 
// Access and Search: O(N) 
//Recall with array implenetation, insertion and removal is not constant 
# //Used in call stack, undo/redo, routing 
 
# //Array implenentation (just use pop/push or shift/unshift) 
# //Recall that pop/push is more efficient than shift/unshift 
# //Indexes take up memory so linked list implenetation will be better 
 
# //Single linked implenetation of stack:

class Node: 
  def __init__(self, value, next=None): 
    self.value = value 
    self.next = next 

class Stack: 
  def __init__(self, first=None, last=None, size=0): 
    self.first = first
    self.last = last 
    self.size = size 
  
  #Similar to shift or insert(0, value). Adds to stack and returns size. Recall stack is LIFO  
  def push(self, value): 
    new_node = Node(value) 
    if self.first == None: 
      self.first = new_node 
      self.last = new_node 
    else: 
      #stores current 1st property on stack 
      temp = self.first 
      #reset 1st property to be newly created one 
      self.first = new_node 
      #set new next property 
      self.first.next = temp 
    #increment stack 
    self.size += 1  
    return self.size 
  
  #in python, this would be pop(0). Similar to unshift. Removes first element on stack  
  def pop(self): 
    #special case if stakc is empty 
    if self.first == None: 
      return None 
      
    temp = self.first 
    #if there is only 1 node, set 1st node and last property to be None 
    if self.first == self.last: 
      self.last = None
      #self.first = None will be set in next line 
    
    #for all scenarios except empty stack 
    self.first = self.first.next 
    self.size -= 1 
    return temp.value 
    
    #useful to visualize reverse() or any other function works 
  def print_stack_to_list(self): 
    result = []
    current = self.first 
    while current: 
      result.append(current.value)
      current = current.next 
    print(result)


s = Stack() 
s.push(1) 
s.push(2)
s.push(3)
s.print_stack_to_list() # [3, 2, 1]
s.pop()
s.print_stack_to_list() #[2, 1]



# //these methods deal with 1st node bc thats what stacks do (LIFO) 
# // Big O: 
# // Insertion and Removal: O(1) **this is mainly what stacks are good for 
# // Access and Search: O(N) 
      
star

Tue Aug 16 2022 06:14:12 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/last-stone-weight/

#python #neetcode #minheap #maxheap #pop #push #heapify

Save snippets that work with our extensions

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