Snippets Collections
// you need apple developer account for this
// Start by watching these CodeWithChris videos and skip Revenue cat. Link: https://youtu.be/Ecxucvej1Dc
// i have to add code for in app subscription later *.

//Log in to your Apple connect account //https://appstoreconnect.apple.com/.

//Access Users and Access:

//In iTunes Connect, navigate to "Users and Access."
//Click on "Sandbox Testers" under the "People" section.
//Add a New Sandbox Tester:

//Click the "+" button to add a new sandbox tester.
//Fill in the tester's details, such as first name, last name, and dummy email address.


import Foundation
import StoreKit


protocol SubscriptionManagerDelegate: AnyObject {
    func transactionDidUpdate(state: SKPaymentTransactionState)
}

class SubscriptionManager: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
    
     var delegate: SubscriptionManagerDelegate?
    
    static let shared = SubscriptionManager()
    
    private var productIdentifier = "com.InAppSubscription.Demo.MonthlySubscription"
    private var product: SKProduct?
    private var completionBlock: ((SKProduct?) -> Void)?
    
    override init() {
        super.init()
        SKPaymentQueue.default().add(self)
    }
    
    func requestProductInfo1(myProductIentifier : String, completion: @escaping (SKProduct?) -> Void) {
        productIdentifier = myProductIentifier
        let productIdentifiers: Set<String> = [productIdentifier]
        let request = SKProductsRequest(productIdentifiers: productIdentifiers)
        request.delegate = self
        request.start()
        
        self.completionBlock = completion
    }
    
    func purchaseProduct() {
        if SKPaymentQueue.canMakePayments() {
            if let product = self.product {
                let payment = SKPayment(product: product)
                SKPaymentQueue.default().add(payment)
            } else {
                print("Product not available")
            }
        }
    }
    
    func restorePurchases() {
        SKPaymentQueue.default().restoreCompletedTransactions()
    }
    
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        if let product = response.products.first {
            self.product = product
            
            completionBlock?(product)
        }
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case .purchased:
                delegate?.transactionDidUpdate(state: .purchased)
                SKPaymentQueue.default().finishTransaction(transaction)
            case .failed:
                delegate?.transactionDidUpdate(state: .failed)
                SKPaymentQueue.default().finishTransaction(transaction)
            case .restored:
                delegate?.transactionDidUpdate(state: .restored)
                SKPaymentQueue.default().finishTransaction(transaction)
                
                
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
                
                if let date = transaction.transactionDate {
                    
                    let formattedDate = dateFormatter.string(from: date)
                    print("Status Check: Restored: \(transaction.payment.productIdentifier), \(formattedDate)")
                }
                
            default:
                break
            }
        }
    }
}


import UIKit
import StoreKit

class SubscriptionViewController: UIViewController, SubscriptionManagerDelegate {
    let productInfoLabel = UILabel()
    let transactionStatusLabel = UILabel()

    var product: SKProduct?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        SubscriptionManager.shared.delegate = self
        requestProductInfo()
    }

        func setupUI() {
            // Product Info Label
            productInfoLabel.text = "Product Information:\nLine 1 of product info\nLine 2 of product info"
            productInfoLabel.numberOfLines = 0 // 0 means unlimited lines
            productInfoLabel.frame = CGRect(x: 20, y: 100, width: 300, height: 100)
            view.addSubview(productInfoLabel)
    
            // Transaction Status Label
            transactionStatusLabel.text = "Transaction Status: "
            transactionStatusLabel.frame = CGRect(x: 20, y: 210, width: 300, height: 30)
            view.addSubview(transactionStatusLabel)
    
            // Request Product Button
            let requestProductButton = UIButton(type: .system)
            requestProductButton.setTitle("Request Product Info", for: .normal)
            requestProductButton.contentHorizontalAlignment = .left
            requestProductButton.frame = CGRect(x: 20, y: 280, width: 200, height: 30)
            requestProductButton.addTarget(self, action: #selector(requestProductInfo), for: .touchUpInside)
            view.addSubview(requestProductButton)
    
            // Purchase Button
            let purchaseButton = UIButton(type: .system)
            purchaseButton.setTitle("Purchase", for: .normal)
            purchaseButton.contentHorizontalAlignment = .left
            purchaseButton.frame = CGRect(x: 20, y: 320, width: 200, height: 30)
            purchaseButton.addTarget(self, action: #selector(purchaseProduct), for: .touchUpInside)
            view.addSubview(purchaseButton)
    
            // Restore Purchases Button
            let restorePurchasesButton = UIButton(type: .system)
            restorePurchasesButton.setTitle("Restore Purchases", for: .normal)
            restorePurchasesButton.contentHorizontalAlignment = .left
            restorePurchasesButton.frame = CGRect(x: 20, y: 350, width: 200, height: 30)
            restorePurchasesButton.addTarget(self, action: #selector(restorePurchases), for: .touchUpInside)
            view.addSubview(restorePurchasesButton)
        }

    @objc func requestProductInfo() {
        SubscriptionManager.shared.requestProductInfo1(myProductIentifier: "com.InAppSubscription.Demo.MonthlySubscription") { [weak self] product in
            if let product = product {
                self?.setValue("Product Information: \(product.localizedTitle), Price: \(product.price)")
            } else {
                self?.productInfoLabel.text = "Product Information not available."
            }
        }
    }

    @objc func purchaseProduct() {
        SubscriptionManager.shared.purchaseProduct()
    }

    @objc func restorePurchases() {
        SubscriptionManager.shared.restorePurchases()
    }
    
    @IBAction func showStatus(_ sender: Any) {
        SubscriptionManager.shared.restorePurchases()
    }
    
    func setValue(_ value : String) {
           DispatchQueue.main.async {
               self.productInfoLabel.text = value
           }
       }
    
    func transactionDidUpdate(state: SKPaymentTransactionState) {
          DispatchQueue.main.async {
              switch state {
              case .purchased:
                  self.transactionStatusLabel.text = "Transaction Status: Purchased"
              case .failed:
                  self.transactionStatusLabel.text = "Transaction Status: Failed"
              case .restored:
                  self.transactionStatusLabel.text = "Transaction Status: Restored"
              default:
                  print("Transaction state Empty")
                  break
              }
          }
      }
}
//
//  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()
     }
   }


    override func viewDidLoad() {
        super.viewDidLoad()
      
      setTermsAndConditionsLabel()
    }

  @IBAction func checkButtonPressed(_ sender: Any) {
        if check {
            checkImageView.isHidden = true
            uncheckImageView.isHidden = false
            check = false
        } else {
            checkImageView.isHidden = false
            uncheckImageView.isHidden = true
            check = true
        }
    }

@objc func tappedTermsAndConditions(_ sender: UITapGestureRecognizer) {
        if let link = URL(string: "https://www.google.com") {
            UIApplication.shared.open(link)
        }
    }
    
    func setTermsAndConditionsLabel() {
        
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tappedTermsAndConditions))
        termsAndConditionsLabel.isUserInteractionEnabled = true
        termsAndConditionsLabel.addGestureRecognizer(tapGestureRecognizer)
        
        let fullText = "I agree to the Terms and Conditions"
        let attributedString = NSMutableAttributedString(string: fullText)

        let grayAttributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.gray,
        ]
        
        let boldAttributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.boldSystemFont(ofSize: 17), // Replace with your desired font size
        ]

        let blueAttributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: hexStringToUIColor(hex: "2563EB"),
            .underlineStyle: NSUnderlineStyle.single.rawValue,
            .link: "termsAndConditionsURL", // Replace with your actual URL
        ]

        let grayRange = (fullText as NSString).range(of: "I agree to the")
        attributedString.addAttributes(grayAttributes, range: grayRange)

        let blueRange = (fullText as NSString).range(of: "Terms and Conditions")
        attributedString.addAttributes(blueAttributes, range: blueRange)
        
        let boldRange = (fullText as NSString).range(of: "Terms and Conditions")
        attributedString.addAttributes(boldAttributes, range: boldRange)

        termsAndConditionsLabel.attributedText = attributedString
    }
    @IBAction func loginPressed(_ sender: Any) {
        
        let email = emailTextField.text ?? ""
        let password = passwordTextField.text ?? ""
        var message = ""
        
        if email == "" {
            message = AppDelegate.selectedLanguage == "en" ? "Please enter email" : "الرجاء ادخال البريد الإلكتروني"
        } else if password == "" {
            message = AppDelegate.selectedLanguage == "en" ? "Please enter password" : "الرجاء ادخال كلمتك السريه"
        } else if !isValidEmail(email) {
            message = AppDelegate.selectedLanguage == "en" ? "please_enter_a_valid_email" : "الرجاء ادخال بريد إلكتروني صالح"
        }
        
        if message != "" {
            self.showToast(message: message)
            return
        }
        
        Auth.auth().signIn(withEmail: emailTextField.text ?? "", password: passwordTextField.text ?? "") { [weak self] authResult, error in
            if error != nil {
                let message = AppDelegate.selectedLanguage == "en" ? "Entered email or password is not correct" : "البريد الإلكتروني أو كلمة المرور المدخلة غير صحيحة"
                self?.showToast(message: message)
                return
            }
            self?.getUserData()
        }
    }
  override func viewDidLoad() {
        super.viewDidLoad()
        setSwipeGesture()
}

func setSwipeGesture() {
        let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
        if AppDelegate.selectedLanguage == "en" {
            swipeRightGesture.direction = .right
        } else {
            swipeRightGesture.direction = .left
        }
              view.addGestureRecognizer(swipeRightGesture)
    }
    
    @objc func handleSwipe(_ gesture: UISwipeGestureRecognizer) {
            if gesture.direction == .right && isOpen == false && AppDelegate.selectedLanguage == "en" {
                toggleSideMenu()
            }  else if gesture.direction == .left && isOpen == false && AppDelegate.selectedLanguage == "ar" {
                toggleSideMenu()
            }
        
     }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isOpen && AppDelegate.selectedLanguage == "en" {
             if let touch = touches.first {
                 let location = touch.location(in: view)
                 if location.x < 50 { // Adjust the threshold as needed
                     toggleSideMenu()
                 }
             } else if isOpen && AppDelegate.selectedLanguage == "ar" {
            
                         if let touch = touches.first {
                             let location = touch.location(in: view)
                             if location.x > view.frame.size.width - 50 { // Adjust the threshold as needed
                                 toggleSideMenu()
                             }
                         }
             }
         }
     }
    
    func toggleSideMenu() {
        if AppDelegate.selectedLanguage == "en" {
            UIView.animate(withDuration: 0.15) {
                if self.isOpen {
                    self.sideMenuView.frame.origin.x = -self.sideMenuView.frame.size.width
                    self.isOpen = false
                    
                } else {
                    self.sideMenuView.frame.origin.x = 0
                    self.isOpen = true
                }
            }
        } else {
                UIView.animate(withDuration: 0.15) {
                     if self.isOpen {
                         self.sideMenuView.frame.origin.x = self.view.frame.size.width // Slide it to the right side
                         self.isOpen = false
                     } else {
                         self.sideMenuView.frame.origin.x = self.view.frame.size.width - self.sideMenuView.frame.size.width // Slide it to the left side
                         self.isOpen = true
                     }
                 }
        }
    }
    
    func shareLinkOnSocialMedia(link: URL, viewController: UIViewController) {
        let activityViewController = UIActivityViewController(activityItems: [link], applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = viewController.view
        viewController.present(activityViewController, animated: true, completion: nil)
    }
    
    @IBAction func menuPressed(_ sender: Any) {
        toggleSideMenu()
    }

@IBAction func backMenuButton1Pressed(_ sender: Any) {
        toggleSideMenu()
    }
//
//  File.swift
//  Service Provider
//
//  Created by Mac HD on 13 Sep, 2023.
//

import Foundation
import UIKit

import ObjectiveC

extension Encodable {
    func toDictionary() -> [String: Any] {
        let mirror = Mirror(reflecting: self)
        var dictionary = [String: Any]()
        for child in mirror.children {
            guard let label = child.label else {
                continue
            }
            dictionary[label] = child.value
        }
        return dictionary
    }
}

extension UIButton {
    private struct AssociatedKeys {
        static var idKey = "idKey"
    }

    var id: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.idKey) as? String
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.idKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

extension UIViewController {
    

    func nextVC(identifier: String) {
        
        var storyboard : UIStoryboard
        
        if AppDelegate.selectedLanguage == "en" {
            storyboard = UIStoryboard(name: "Main", bundle: nil)
        } else {
            storyboard = UIStoryboard(name: "arabic", bundle: nil)
        }

            let vc = storyboard.instantiateViewController(withIdentifier: identifier)
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: false, completion: nil)
    }
    
    // MARK: - Toast
    
    func showToast(message : String) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.view.backgroundColor = UIColor.lightGray
        alert.view.alpha = 0.3
        alert.view.tintColor = .blue
        alert.view.tintColor = hexStringToUIColor(hex: "FEDA22")
        alert.view.layer.cornerRadius = alert.view.layer.frame.height/3
        
        self.present(alert, animated: true)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
            alert.dismiss(animated: true)
        }
    }
    
    func setToast(message : String, seconds: Double = 1.0) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.view.backgroundColor = UIColor.white
        alert.view.alpha = 0.3
        alert.view.tintColor = .blue
        alert.view.tintColor = hexStringToUIColor(hex: "FEDA22")
        alert.view.layer.cornerRadius = alert.view.layer.frame.height/3
        
        self.present(alert, animated: true)
       
        DispatchQueue.main.asyncAfter(deadline:  DispatchTime.now() + seconds) {
            alert.dismiss(animated: true)
        }
    }
    
    // MARK: - Color
    
    func hexStringToUIColor (hex:String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if (cString.hasPrefix("#")) {
            cString.remove(at: cString.startIndex)
        }

        if ((cString.count) != 6) {
            return UIColor.gray
        }

        var rgbValue:UInt64 = 0
        Scanner(string: cString).scanHexInt64(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
    
    // MARK: - DateTime
    
    func getCurrentTimeStamp() -> String {
        let time = Double(NSDate().timeIntervalSince1970)
        let timeStamp = String(Int(time * 1000))
        return timeStamp
    }
    
    func getDateTime(timeStamp : String, format: String) -> String {
            var t1 = Int(timeStamp) ?? 1
            t1 = t1/1000
            let date = NSDate(timeIntervalSince1970: TimeInterval(t1))
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = format
            let dateString = dateFormatter.string(from: date as Date)
            print("Date = \(dateString)")
            return dateString
        }
    
    func getDateTimeInArabic(timestamp: TimeInterval, format: String) -> String? {
        // Create a DateFormatter instance with Arabic locale settings
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "ar")
        dateFormatter.dateFormat = "dd MMM, yyyy HH:mm a"

        // Convert the timestamp to a Date object
        let date = Date(timeIntervalSince1970: timestamp)

        // Format the Date as an Arabic datetime string
        let arabicDateTime = dateFormatter.string(from: date)
        
        return arabicDateTime
    }
    
    func getDifference(recent: Date, previous: Date) -> (month: Int?, day: Int?, hour: Int?, minute: Int?, second: Int?) {
          let day = Calendar.current.dateComponents([.day], from: previous, to: recent).day
          let month = Calendar.current.dateComponents([.month], from: previous, to: recent).month
          let hour = Calendar.current.dateComponents([.hour], from: previous, to: recent).hour
          let minute = Calendar.current.dateComponents([.minute], from: previous, to: recent).minute
          let second = Calendar.current.dateComponents([.second], from: previous, to: recent).second

          return (month: month, day: day, hour: hour, minute: minute, second: second)
      }
 
    // MARK: - Validation
    
        func isValidName(testName:String) -> Bool {
            guard testName.count > 2, testName.count < 16 else { return false }

            let predicateTest = NSPredicate(format: "SELF MATCHES %@", "^(([^ ]?)(^[a-zA-Z].*[a-zA-Z]$)([^ ]?))$")
            return predicateTest.evaluate(with: testName)
        }
    
        func isValidEmail(_ email: String) -> Bool {
            let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
            let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
            return emailPred.evaluate(with: email)
        }
    
        func isValidPhone(_ mobilenumber: String) -> Bool {
            // optional plus sign
            let phoneRegex = "^[0-9+]{0,1}+[0-9]{5,16}$"
            let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
            return phoneTest.evaluate(with: mobilenumber)
        }
    
        func isValidPhoneNumber(_ phoneNumber: String) -> Bool {
            // must add plus sign
            let regEx = "^\\+(?:[0-9]?){6,14}[0-9]$"
            let phoneCheck = NSPredicate(format: "SELF MATCHES[c] %@", regEx)
            return phoneCheck.evaluate(with: phoneNumber)
        }
    
    func isValidPassword() {
        
    }
}

// MARK: - UIviews

extension UIView {
    
    func addshadow(top: Bool,
                  left: Bool,
                  bottom: Bool,
                  right: Bool,
                  shadowRadius: CGFloat) {
//            self.backgroundColor = UIColor.white
            self.layer.masksToBounds = false
            self.layer.cornerRadius = 8
            self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
            self.layer.shadowRadius = shadowRadius
        self.layer.shadowOpacity = 0.6
            self.layer.shadowColor = UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1.0).cgColor
            let path = UIBezierPath()
            var x: CGFloat = 0
            var y: CGFloat = 0
            var viewWidth = self.frame.width
            var viewHeight = self.frame.height
            // here x, y, viewWidth, and viewHeight can be changed in
            // order to play around with the shadow paths.
            if (!top) {
              y+=(shadowRadius+1)
            }
            if (!bottom) {
              viewHeight-=(shadowRadius+1)
            }
            if (!left) {
              x+=(shadowRadius+1)
            }
            if (!right) {
              viewWidth-=(shadowRadius+1)
            }
            // selecting top most point
            path.move(to: CGPoint(x: x, y: y))
            path.addLine(to: CGPoint(x: x, y: viewHeight))
            path.addLine(to: CGPoint(x: viewWidth, y: viewHeight))
            path.addLine(to: CGPoint(x: viewWidth, y: y))
            path.close()
            self.layer.shadowPath = path.cgPath
          }

       func roundCorners(corners: UIRectCorner, radius: CGFloat) {
            let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            layer.mask = mask
        }
}

// MARK: - Image

extension UIImageView {
  func setImageColor(color: UIColor) {
    let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
    self.image = templateImage
    self.tintColor = color
  }
}
extension Encodable {
    func toDictionary() -> [String: Any]? {
        do {
            let encoder = JSONEncoder()
            let data = try encoder.encode(self)
            let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
            return dictionary
        } catch {
            print("Error converting to dictionary:", error)
            return nil
        }
    }
}
import Foundation

struct CommentsModel {
    
  var comment = ""
  var gameId = ""
  var timestamp = 0
  var userId = ""
  var userModel = UserModel(user: [:])
    
    init(comment: [String: Any]) {
        
        self.comment = comment["comment"] as? String ?? ""
        self.gameId = comment["gameId"] as? String ?? ""
        self.timestamp = comment["timestamp"] as? Int ?? 0
        self.userId = comment["userId"] as? String ?? ""
        
        if let userDict = comment["userModel"] as? [String: Any] {
            self.userModel = UserModel(user: userDict)
         }
    }
}
//MARK: - Location


 var locationManager = CLLocationManager()
    var currentLatitude = ""
    var currentLongitude = ""
    var cityName = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.delegate = self
        
        getLocation()
    }

extension LocationViewController: CLLocationManagerDelegate {
    
    func navigateToMaps() {
        
        let address = bookingModel.addressModel
        let lat = address["locationLat"] as? String ?? ""
        let longitude = address["locationLng"] as? String ?? ""
        //let title = address["location"] as? String ?? ""
        
        let destinationLatitude = Double(longitude) ?? 0.0 // Replace with the destination latitude
        let destinationLongitude: Double = Double(lat) ?? 0.0 // Replace with the destination longitude
        
        if UIApplication.shared.canOpenURL(URL(string: "http://maps.apple.com/")!) {
            // Open Apple Maps with the specified source and destination coordinates
            let mapsURL = URL(string: "http://maps.apple.com/?saddr=\(Double(currentLatitude) ?? 0.0),\(Double(currentLongitude) ?? 0.0)&daddr=\(destinationLatitude),\(destinationLongitude)")!
            UIApplication.shared.open(mapsURL, options: [:], completionHandler: nil)
        } else {
            // Handle the case where Apple Maps app is not available
            print("Apple Maps is not available")
        }
    }
    
    func getLocation () {
        
        if #available(iOS 14.0, *) {
            switch locationManager.authorizationStatus {
            case .notDetermined:
                locationManager.requestWhenInUseAuthorization()
                locationManager.requestLocation()
                break
            case .authorizedWhenInUse :
                locationManager.requestWhenInUseAuthorization()
                locationManager.requestLocation()
                break
                
            default:
                print("status : ", locationManager.authorizationStatus)
                break
            }
        } else {
            print("Error894")
            // Fallback on earlier versions
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("Got Location Data")
        if let location = locations.last {
            let lat = String(location.coordinate.latitude)
            let lng = String(location.coordinate.longitude)
            
            print("Lat : ", lat)
            print("lng : ", lng)
            
            getAddressFromLatLon(pdblLatitude: String(location.coordinate.latitude), withLongitude: String(location.coordinate.longitude))
        } else {
            print("error 120")
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error121 : ", error)
    }
    
    func getAddressFromLatLon(pdblLatitude: String, withLongitude pdblLongitude: String) {
        // SVProgressHUD.show()
        var center : CLLocationCoordinate2D = CLLocationCoordinate2D()
        let lat: Double = Double("\(pdblLatitude)")!
        //21.228124
        
        let lon: Double = Double("\(pdblLongitude)")!
        //72.833770
        let ceo: CLGeocoder = CLGeocoder()
        center.latitude = lat
        center.longitude = lon
        
        let loc: CLLocation = CLLocation(latitude:center.latitude, longitude: center.longitude)
        
        ceo.reverseGeocodeLocation(loc, completionHandler:
                                    {(placemarks, error) in
            if (error != nil)
            {
                print("reverse geodcode fail: \(error!.localizedDescription)")
                SVProgressHUD.dismiss()
                return
            }
            let pm = placemarks! as [CLPlacemark]
            
            for p in pm {
                print(" p :: ", p)
            }
            
            if pm.count > 0 {
                let pm = placemarks![0]
                let cityName = pm.locality ?? ""
                let timeZone : String = pm.timeZone?.identifier ?? ""
                
                print("timeZone : ", timeZone)
                print("country : ",pm.country ?? "")
                print("city : ", cityName)
                print("locLat : ", pdblLatitude)
                print("locLng : ", pdblLongitude)
                self.currentLatitude = pdblLatitude
                self.currentLongitude = pdblLongitude
                self.cityName = cityName
                self.getBookingCoordinates()
            }
            SVProgressHUD.dismiss()
        })
    }
}
import UIKit

class CustomTableViewCell: UITableViewCell {
    var labelStackView: UIStackView!
    var innerView: UIView!
    var label: UILabel!

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupInnerView()
        setupLabelStackView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupInnerView()
        setupLabelStackView()
    }
    
    private func setupInnerView() {
        
            innerView = UIView()
            innerView.translatesAutoresizingMaskIntoConstraints = false
            innerView.layer.borderWidth = 1.0 // 1-point border width
            innerView.layer.borderColor = UIColor.lightGray.cgColor // Border color
            
            contentView.addSubview(innerView)

            NSLayoutConstraint.activate([
                innerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10), // 8-point spacing from the left
                innerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 6), // 8-point spacing from the top
                innerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10), // 8-point spacing from the right
                innerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -6) // 8-point spacing from the bottom
            ])
        
        innerView.layer.cornerRadius = 13
        innerView.layer.borderColor = self.hexStringToUIColor(hex: "DCD8D8").cgColor
    }
    
    private func setupLabelStackView() {
        labelStackView = UIStackView()
        labelStackView.translatesAutoresizingMaskIntoConstraints = false
        labelStackView.axis = .vertical
        labelStackView.spacing = 8 // Adjust the vertical spacing between labels
        contentView.addSubview(labelStackView)

        NSLayoutConstraint.activate([
            labelStackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            labelStackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16),
            labelStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            labelStackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -16)
        ])
    }
    
    func setupLabels(labelData: [(String, UIImage, Int)]) -> ([UILabel], [UIImageView], [Int]) {
        
        var labels: [UILabel] = []
        var imageViews: [UIImageView] = []
        var tags: [Int] = []

        for (labelText, image, tag) in labelData {
            print("tagfkj : ", tag)
            let stackView = UIStackView()
            stackView.axis = .horizontal
            stackView.spacing = 8

            let imageView = UIImageView(image: image)
            imageView.contentMode = .scaleAspectFit
            imageView.widthAnchor.constraint(equalToConstant: 23).isActive = true
            imageView.heightAnchor.constraint(equalToConstant: 23).isActive = true
            imageView.tag = tag
            imageView.accessibilityIdentifier = "sewer"
            
            let label = UILabel()
            label.translatesAutoresizingMaskIntoConstraints = false
            label.text = labelText
            label.tag = tag
            
            stackView.addArrangedSubview(imageView)
            stackView.addArrangedSubview(label)

            labelStackView.addArrangedSubview(stackView)

            labels.append(label)
            imageViews.append(imageView)
            tags.append(tag)
        }

        return (labels, imageViews, tags)
    }
    
    func hexStringToUIColor (hex:String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if (cString.hasPrefix("#")) {
            cString.remove(at: cString.startIndex)
        }

        if ((cString.count) != 6) {
            return UIColor.gray
        }

        var rgbValue:UInt64 = 0
        Scanner(string: cString).scanHexInt64(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
}






func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

  var imagesArray = ["circle_complete_icon", "circle_unsel"]()
            var textArray = ["jfdsk", "dfs"]()
            var tag = indexpath.row
            var idsArray = ["1","2"]()

      tag = indexPath.row
            print("tag43 : \(indexPath.row) ", tag)
            
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
            cell.selectionStyle = .none
            
            for subview in cell.labelStackView.arrangedSubviews {
                cell.labelStackView.removeArrangedSubview(subview)
                subview.removeFromSuperview()
            }
            
            var count = 0
            let labelsAndImagesForCell = textArray.enumerated().map { (index, labelText) -> (String, UIImage, Int) in
                let imageName = imagesArray[count]
                count += 1
                let image = UIImage(named: imageName) ?? UIImage()
                
                // Replace "UIImage()" with your default image if needed
                print("chk378: ", indexPath.row)
                return (labelText, image, tag)
            }
            
            let (labels, imageViews, tags) = cell.setupLabels(labelData: labelsAndImagesForCell)
            
            // Access and configure each label and image view individually
            var c = 0
            for (index, label) in (labels).enumerated() {
                label.text = labelsAndImagesForCell[index].0
                let labelTapGesture = UITapGestureRecognizer(target: self, action: #selector(subCategoryPressed(tagGesture: )))
                label.tag = tags[c]
                label.accessibilityIdentifier = idsArray[c]
                c += 1
                label.isUserInteractionEnabled = true
                label.addGestureRecognizer(labelTapGesture)
            }
            
            var c1 = 0
            for (index, imageView) in imageViews.enumerated() {
                imageView.image = labelsAndImagesForCell[index].1
                
                let tapGesture = UITapGestureRecognizer(target: self, action: #selector(subCategoryPressed(tagGesture: )))
                imageView.tag = tags[c1]
                imageView.accessibilityIdentifier = idsArray[c1]
                c1 += 1
                imageView.isUserInteractionEnabled = true
                imageView.addGestureRecognizer(tapGesture)
            }
            
            imagesArray = []
            textArray = []
            
            return cell
            
        }

//
//  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
    }
}
@IBAction func eyeButtonPressed(_ sender: Any) {
        if passwordTextField.isSecureTextEntry == false {
            passwordTextField.isSecureTextEntry = true
            eyeImageView.image = UIImage(systemName: "eye.slash")
        } else {
            passwordTextField.isSecureTextEntry = false
            eyeImageView.image = UIImage(systemName: "eye")
        }
        eyeImageView.setImageColor(color: UIColor.gray)
    }
Make sure to add encodable like this 

struct modelName : Encodsble

let categories = categoriesArray.map{ $0.toDictionary()  }

extension Encodable {
    func toDictionary() -> [String: Any] {
        let mirror = Mirror(reflecting: self)
        var dictionary = [String: Any]()
        for child in mirror.children {
            guard let label = child.label else {
                continue
            }
            dictionary[label] = child.value
        }
        return dictionary
    }
}
extension ServiceProviderProfileViewController : UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return categories.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = categoryCollectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCollectionViewCell", for: indexPath) as! CategoryCollectionViewCell

            cell.categoryLabel.text = categories[indexPath.row]
        
            if indexPath.row == selectedCellIndex {
                cell.categoryView.layer.borderColor = UIColor.blue.cgColor
                cell.categoryLabel.textColor = UIColor.blue
            } else {
                cell.categoryView.layer.borderColor = UIColor.lightGray.cgColor
                cell.categoryLabel.textColor = UIColor.gray
            }
            return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedCellIndex = indexPath.row
        self.categoryCollectionView.reloadData()
    }
    
}
ERROR:  While executing gem ... (Gem::FilePermissionError)

    You don't have write permissions for the /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/gems/2.6.0 directory.




Hi Guys, My solution (on Big Sur 11.6.2):

Step 1:

Install brew

1. curl -fsSL -o install.sh https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh
 Save
2. /bin/bash install.sh
 Save
Step 2:

brew install chruby ruby-install
 Save
Step 3:

brew install cocoapods
 Save
Step 4: (Check your cocoapods version):

brew upgrade cocoapods
 Save
Képernyőfotó 2022-01-17 - 16.18.41.png

Need Xcode Command Line Tools, if not installed then run this command: sudo xcode-select --install
{
  "categories": [
    {
      "name": "Social Media",
      "apps": [
        {
          "name": "Facebook",
          "icon": "base64-encoded-icon",
          "urlScheme": "fb://"
        },
        {
          "name": "Twitter",
          "icon": "base64-encoded-icon",
          "urlScheme": "twitter://"
        },
        {
          "name": "Instagram",
          "icon": "base64-encoded-icon",
          "urlScheme": "instagram://"
        }
      ]
    },
    {
      "name": "Entertainment",
      "apps": [
        {
          "name": "Netflix",
          "icon": "base64-encoded-icon",
          "urlScheme": "netflix://"
        },
        {
          "name": "YouTube",
          "icon": "base64-encoded-icon",
          "urlScheme": "youtube://"
        },
        {
          "name": "Spotify",
          "icon": "base64-encoded-icon",
          "urlScheme": "spotify://"
        }
      ]
    }
  ]
}
    func addPonits(_ fieldName : String, _ points : Int,_ message : String) {
        
        let data = [
            fieldName : FieldValue.increment(Int64(points))
        ]
        
        let db = Firestore.firestore()
        let docRef = db.collection("Games").document(gameID)
        docRef.updateData(data) { error in
            if let error = error {
                print("Error updating document: \(error.localizedDescription)")
            } else {
                print("Document successfully updated")
                self.showToast(message: message)
            }
        }
    }
struct Person : Encodable {
    var name: String
    var age: Int
    var address: String?
}
    
    
let person = Person(name: "John Smith", age: 30, address: nil)
let dictionary = person.toDictionary()
print(dictionary) // Output: ["name": "John Smith", "age": 30]
    
    
    extension Encodable {
    func toDictionary() -> [String: Any]? {
        let mirror = Mirror(reflecting: self)
        var dictionary = [String: Any]()
        for child in mirror.children {
            guard let label = child.label else {
                continue
            }
            dictionary[label] = child.value
        }
        return dictionary
    }
}
  if let presentingViewController = self.presentingViewController?.presentingViewController {
            presentingViewController.dismiss(animated: false) {
                BottomBarViewController.BottomBarVC.embedFavoritesVC()
            }
        }
     let currentSelectedCell = playersTableView.cellForRow(at: indexPath) as! PlayerDetailsTableViewCell
        
        if selectedRow == -1 {
            currentSelectedCell.playerDetailsView.layer.borderColor = hexStringToUIColor(hex: "F34141").cgColor
            currentSelectedCell.playerDetailsView.layer.borderWidth = 1
            selectedRow = indexPath.row
        } else if indexPath.row == selectedRow {
            currentSelectedCell.playerDetailsView.layer.borderWidth = 0
            selectedRow = -1
        } else {
            currentSelectedCell.playerDetailsView.layer.borderColor = hexStringToUIColor(hex: "F34141").cgColor
            currentSelectedCell.playerDetailsView.layer.borderWidth = 1
            
            let newIndexPath = IndexPath(item: selectedRow, section: 0)
            if let cell = playersTableView.cellForRow(at: newIndexPath) as? PlayerDetailsTableViewCell {
                cell.playerDetailsView.layer.borderWidth = 0
            }
            selectedRow = indexPath.row
        }
    func timeAgoDisplay(previousTime : Int) -> String {
        
        let cTime = Int(NSDate().timeIntervalSince1970)
        let pTime = previousTime/1000
        
        let secondsAgo = cTime - pTime
        
        let minute = 60
        let hour = 60 * minute
        let day = 24 * hour
        let week = 7 * day
        let month = day * 30
        let year = month * 12
        
        
        
        if secondsAgo < minute {
            var txt = ""
            if secondsAgo == 1 {
                txt = "second ago"
            } else {
                txt = "seconds ago"
            }
            return "\(secondsAgo) \(txt)"
        } else if secondsAgo < hour {
            var txt = ""
            let minutes = secondsAgo / minute
            if minutes == 1 {
                txt = "minute ago"
            } else {
                txt = "minutes ago"
            }
            return "\(minutes) \(txt)"
        } else if secondsAgo < day {
            var txt = ""
            let hours = secondsAgo / hour
            if hours == 1 {
                txt = "hour ago"
            } else {
                txt = "hours ago"
            }
            return "\(hours) \(txt)"
        } else if secondsAgo < week {
            var txt = ""
            let days = secondsAgo / day
            if days == 1 {
                txt = "day ago"
            } else {
                txt = "days ago"
            }
            return "\(days) \(txt)"
        } else if secondsAgo < month {
            var txt = ""
            let weeks = secondsAgo / week
            if weeks == 1 {
                txt = "week ago"
            } else {
                txt = "weeks ago"
            }
            return "\(weeks) \(txt)"
        } else if secondsAgo < year {
            var txt = ""
            let months = secondsAgo / month
            if months == 1 {
                txt = "month ago"
            } else {
                txt = "months ago"
            }
            return "\(months) \(txt)"
        } else {
            var txt = ""
            let years = secondsAgo / year
            if years == 1 {
                txt = "year ago"
            } else {
                txt = "years ago"
            }
            return "\(years) \(txt)"
        }
    }
//
//  Reachability.swift
//  Vital
//
//  Created by Mac HD on 30/01/2023.
//

import SystemConfiguration

public class Reachability {

    class func isConnectedToNetwork() -> Bool {

        var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
            return false
        }

        /* Only Working for WIFI
        let isReachable = flags == .reachable
        let needsConnection = flags == .connectionRequired

        return isReachable && !needsConnection
        */

        // Working for Cellular and WIFI
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        let ret = (isReachable && !needsConnection)

        return ret

    }
}
    func checkInternetConnection() {
        
        let internetConnected = Reachability.isConnectedToNetwork()
        
        if !internetConnected {
            print("no internet")
            self.showToast(message: "no internet")
        }
    }
    @IBAction func signUpPressed(_ sender: Any) {
        
        if nameTextField.text == "" {
            self.showToast(message: "Please enter your name")
            return
        } else if emailTextField.text == "" {
            self.showToast(message: "Please enter your email")
            return
        } else if passwordTextField.text == "" {
            self.showToast(message: "Please enter password")
            return
        }
        
        let parameters: [String: Any] = [
            "name" : nameTextField.text ?? "",
            "email" : emailTextField.text ?? "",
            "password" : passwordTextField.text ?? "",
            "fcmToken" : "asfnasdbhj",
            "osType" : "iPhone"
        ]
        
        print("url : ", AppDelegate.signUpUrl)
        SVProgressHUD.show()
        AF.request(AppDelegate.signUpUrl , method: .post, parameters: parameters, encoding: JSONEncoding.default)
            .responseDecodable(of: RegistrationAPI.self) { (response) in
                print("resp : ", response)
                switch response.result {
                case .success(let response):
                    print("Success :: ", response.message)
                    if response.message == "Password is invalid" {
                        self.showToast(message: "Please enter a valid password")
                    } else if response.message == "Account already registered with this email" {
                        self.showToast(message: response.message)
                    } else {
                        print("Get token and continue")
                        UserDefaults.standard.set(response.token, forKey: "token")
                    }
                             
                    break
              case .failure(let error):
                    // Handle error
                    print("Failure : ", error)
                }
                
                SVProgressHUD.dismiss()
            }
    }
// Remove item from array

let db = Firestore.firestore()
            db.collection("Products").document("").updateData(["" : FieldValue.arrayRemove(["89024"])])

// increment value             
            db.collection("Products").document("").updateData([
                "field_name" : FieldValue.increment(Int64(3))
                    ])
                    
// union array
                    
            db.collection("collection_name").document("document_id")
            documentRef.updateData([
              "field_name": FieldValue.arrayUnion(["element1", "element2", "element3"])
            ])
// MARK: - Table View

topPlayersTableView.delgate = self
topPlayersTableView.dataSource = self


extension HomeViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = topPlayersTableView.dequeueReusableCell(withIdentifier: "TopPlayerTableViewCell") as! TopPlayerTableViewCell
        return cell
    }
}
   func setView() {
     
        [emailView, passwordView].forEach { (view) in
            if let view = view {
                view.layer.borderWidth = 2
                view.layer.borderColor = hexStringToUIColor(hex: "E9E9E9").cgColor
                view.layer.cornerRadius = view.layer.frame.height/3
            }
        }
    }
// 1st method

if let storyboard = self.storyboard {
            let vc = storyboard.instantiateViewController(withIdentifier: "ForgotPasswordViewController") as! ForgotPasswordViewController
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: false, completion: nil)
        }

// 2nd method

    func nextVC(identifier: String) {
        if let storyboard = self.storyboard {
            let vc = storyboard.instantiateViewController(withIdentifier: identifier)
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: false, completion: nil)
        }
    }
// install pod :: AlignedCollectionViewFlowLayout
// also assign class AlignedCollectionViewFlowLayout in storyboard

func setLayout() {

        let alignedFlowLayout = AlignedCollectionViewFlowLayout(horizontalAlignment: .justified, verticalAlignment: .center)

        statsCollectionView.collectionViewLayout = alignedFlowLayout

        statsCollectionView.delegate = self
        statsCollectionView.dataSource = self

    }
    
}

// MARK: - Collection View

extension GameStatsViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        print("sec :", section)

        return UIEdgeInsets(top: 0.0, left: 0, bottom: 0.0, right: 0)//here your custom value for spacing
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        var widthPerItem : CGFloat = 0
        var heightPerItem : CGFloat = 0

        widthPerItem = collectionView.frame.width / 3 - 7
        heightPerItem = widthPerItem + 5

        return CGSize(width:widthPerItem, height: heightPerItem)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return namesArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = statsCollectionView.dequeueReusableCell(withReuseIdentifier: "GameStatsCollectionViewCell", for: indexPath) as! GameStatsCollectionViewCell
        cell.name.text = namesArray[indexPath.row]
        cell.points.text = numbers[indexPath.row]
        
        return cell
    }
}
Issue: place parentview at top of all views, buttons, labels

    
    public static var BottomBarVC: BottomBarViewController!
    public static var parentViewHeight: CGFloat = 0
    
    var homeVC : HomeViewController!
    var favoriteVC : FavouriteItemsViewController!
    var profileVC : ProfileViewController!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        BottomBarViewController.BottomBarVC = self
        BottomBarViewController.parentViewHeight = self.parentView.frame.height
        
        assignViewControllers()
//        setScanImage()
    }
    
    func assignViewControllers() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        homeVC = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController
        favoriteVC = storyboard.instantiateViewController(withIdentifier: "FavouriteItemsViewController") as? FavouriteItemsViewController
        profileVC = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as? ProfileViewController
        
        embedHomeVC()
    }
    
    func embedHomeVC() {
        AppDelegate.embed(self.homeVC, inParent: self, inView: self.parentView)
    }
    
    @IBAction func homeButtonPressed(_ sender: Any) {
      // C59104
      // 9A9A9A
        
        homeImageView.image = UIImage(named: "home_sel")
        homeLabel.textColor = hexStringToUIColor(hex: "C59104")
        
        favoriteImageView.image = UIImage(named: "favorite_unsel")
        favoriteLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        shoppingImageView.image = UIImage(named: "shopping_unsel")
        shoppingLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        profileImageView.image = UIImage(named: "profile_unsel")
        profileLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        AppDelegate.embed(self.homeVC, inParent: self, inView: self.parentView)
    }
    
    @IBAction func favoriteButtonPressed(_ sender: Any) {
      
        homeImageView.image = UIImage(named: "home_unsel")
        homeLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        favoriteImageView.image = UIImage(named: "favorite_sel")
        favoriteLabel.textColor = hexStringToUIColor(hex: "C59104")
        
        shoppingImageView.image = UIImage(named: "shopping_unsel")
        shoppingLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        profileImageView.image = UIImage(named: "profile_unsel")
        profileLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        AppDelegate.embed(self.favoriteVC, inParent: self, inView: self.parentView)
    }
    
    @IBAction func shoppingButtonPressed(_ sender: Any) {
      
        homeImageView.image = UIImage(named: "home_unsel")
        homeLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        favoriteImageView.image = UIImage(named: "favorite_unsel")
        favoriteLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        shoppingImageView.image = UIImage(named: "shopping_sel")
        shoppingLabel.textColor = hexStringToUIColor(hex: "C59104")
        
        profileImageView.image = UIImage(named: "profile_unsel")
        profileLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
    }
    
    @IBAction func profileButtonPressed(_ sender: Any) {
      
        homeImageView.image = UIImage(named: "home_unsel")
        homeLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        favoriteImageView.image = UIImage(named: "favorite_unsel")
        favoriteLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        shoppingImageView.image = UIImage(named: "shopping_unsel")
        shoppingLabel.textColor = hexStringToUIColor(hex: "9A9A9A")
        
        profileImageView.image = UIImage(named: "profile_sel")
        profileLabel.textColor = hexStringToUIColor(hex: "C59104")
        
        AppDelegate.embed(self.profileVC, inParent: self, inView: self.parentView)
    }
    func setScrollView() {
        let contentWidth = topPlayersTableView.layer.frame.width + 20
        scrollView.contentSize = CGSize(width: contentWidth, height: scrollView.frame.height)
        scrollView.isPagingEnabled = true
    }
import Stripe
import Alamofire

func alertResult(_ yesPressed: Bool) {
        if yesPressed {
       
            let stripCard = STPCardParams()
            stripCard.number = "4242424242424242"
            stripCard.name = "Jane Doe"
            stripCard.cvc = "123"
            stripCard.expYear = UInt(27)
            stripCard.expMonth = UInt(12)
            
            STPAPIClient.shared.createToken(withCard: stripCard) { (token: STPToken?, error: Error?) in
                    print("Printing Strip response:\(String(describing: token?.allResponseFields))\n\n")
                    print("Printing Strip Token:\(String(describing: token?.tokenId))")
                    if error != nil {
                        print(error as Any)
                        print(error?.localizedDescription ?? "")
                    }
                
                    if let token = token {
                        print("Token:",token.tokenId)
                        //self.jdk(token: token)
                        self.handlePayment(token: token)
                    }
                }
        }
    }
    
    func handlePayment(token: STPToken) {
        let url = "https://api.stripe.com/v1/charges" + "?key=" + "paste api key here"
        
        let headers: HTTPHeaders = ["Authorization": "paste api key here", "Content-Type": "application/x-www-form-urlencoded"]
        
        let amount = Int(topUpAmountTextField.text ?? "") ?? 100
        
        let parameters: Parameters = ["amount": amount, "currency": AppDelegate.balanceType, "source": token.tokenId]
        
        AF.request(url, method: .post, parameters: parameters, headers: headers).responseDecodable(of: Charge.self) { (response) in
            print("resp : ", response)
            switch response.result {
                
            case .success(let charge):
                // Handle successful charge
                print("Success :: ", charge.status)
                print("Amount :: ", charge.amount)
                
                self.updateBalance(amount : Double(charge.amount))
                break
            case .failure(let error):
                // Handle error
                print("Failure : ", error)
                self.showToast(message: "Top-up unsuccessfull")
            }
        }
    }

    struct Charge : Decodable {
      let status : String
      let amount : Int
    }

   func getFcmToken() {
        if let token = Messaging.messaging().fcmToken {
            print("fcm : ", token)
            fcmToken = token
        }
    }
  @IBOutlet weak var barChartView: BarChartView!

 var productTypes = ["Aluminum Cans", "Plastic Bottles", "Paper Waste"]
 var productsCountArray = [Int]()

// viewDidLoad

   setBarChartView()   

// MARK: Chart View

extension FootPrintViewController {
 
    func setBarChartView() {
        productsCountArray.append(HomeViewController.aluminumItemRecycled)
        productsCountArray.append(HomeViewController.plasticBottleRecycled)
        productsCountArray.append(HomeViewController.otherItemsCount)
        
        
        barChartView.gridBackgroundColor = UIColor.clear
//        productsCountArray = [10, 12, 9]
        
        barChartView.drawValueAboveBarEnabled = true
        barChartView.animate(yAxisDuration: 1)
        
        barChartView.xAxis.granularity = 1
        barChartView.pinchZoomEnabled = true
        barChartView.drawBarShadowEnabled = false
        barChartView.drawBordersEnabled = false
        barChartView.doubleTapToZoomEnabled = false
        barChartView.drawGridBackgroundEnabled = true
        
        setBarChartData()
    }
    
    func setBarChartData() {
        barChartView.noDataText = "No Data available for Chart"
        
        barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values:productTypes)

        barChartView.leftAxis.granularity = 1
        barChartView.rightAxis.granularity = 1

        var dataEntries: [BarChartDataEntry] = []
        for i in 0..<productTypes.count {
           let dataEntry = BarChartDataEntry(x: Double(i), y: Double(productsCountArray[i]))
           dataEntries.append(dataEntry)
        }
        
        
        let chartDataSet = BarChartDataSet(entries: dataEntries, label: "Bar Chart")
        chartDataSet.colors = [.systemGreen, .red , .systemBlue]
        
        
        
        let chartData = BarChartData(dataSet: chartDataSet)
        barChartView.data = chartData
    }
}
    let datePicker =  UIDatePicker()
    let toolBar = UIToolbar()
    
    var pickedDate = ""
    var dobTimeStamp = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
      
        createDatePicker()
    }


// MARK: - Date Picker

extension SignUpViewController {
    
    func createDatePicker() {
        toolBar.sizeToFit()
     //   toolBar.layer.frame.size = CGSize(width: 414, height: 500)
        
        let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
        toolBar.setItems([doneBtn], animated: true)
        datePicker.preferredDatePickerStyle = .wheels
        datePicker.datePickerMode = .date
    }
    
    @objc func donePressed() {
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd MMM,yyyy"
        pickedDate = dateFormatter.string(from: datePicker.date)
        print("picked Date : ", pickedDate)
        let myTimeStamp = Int(self.datePicker.date.timeIntervalSince1970)
        dobTimeStamp = String(myTimeStamp * 1000)
        self.view.endEditing(true)
    }
}

// MARK: Text Field

extension SignUpViewController: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        if textField.tag == 4 {
            textField.inputAccessoryView = toolBar
            textField.inputView = datePicker
            datePicker.maximumDate = Date()
        }
    }
}
Auth.auth().currentUser?.sendEmailVerification()
  func setCardView() {
        cardView.backgroundColor = .white

        cardView.layer.cornerRadius = 10.0

        cardView.layer.shadowColor = UIColor.gray.cgColor

        cardView.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)

        cardView.layer.shadowRadius = 6.0
        cardView.layer.shadowOpacity = 0.7
    }
https://medium.com/swlh/how-to-create-a-custom-gradient-in-swift-with-cagradientlayer-ios-swift-guide-190941cb3db2

lazy var gradient: CAGradientLayer = {
        let gradient = CAGradientLayer()
        gradient.type = .axial
        gradient.colors = [
            
            hexStringToUIColor(hex: "468d01"),
            hexStringToUIColor(hex: "acdc08")
        ]
        
        gradient.locations = [0,0.95]
        return gradient
    }()


func views() {
              gradient.frame = logInView.bounds
            logInView.layer.addSublayer(gradient)
            
            let x = logInView.frame.origin.x
            let y = logInView.frame.origin.y
            
            print("x = ", x)
            print("y = ", y)
            
            gradient.startPoint = CGPoint(x: 0, y: y)
            gradient.endPoint = CGPoint(x: 1, y: y)

}


    func hexStringToUIColor (hex:String) -> CGColor {
        var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if (cString.hasPrefix("#")) {
            cString.remove(at: cString.startIndex)
        }

        if ((cString.count) != 6) {
            return UIColor.gray.cgColor
        }

        var rgbValue:UInt64 = 0
        Scanner(string: cString).scanHexInt64(&rgbValue)

        return CGColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }

call video play code on action , not on viewdidload

import AVFoundation
import AVKit

 var playerController = AVPlayerViewController()
 var player: AVPlayer?
 var playerItem: AVPlayerItem?
 var playerObserver: Any?

class VideoPlayerViewController: UIViewController, AVPlayerViewControllerDelegate {

    var playerController = AVPlayerViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }
  
  func playVideo(url: URL) {
        player = AVPlayer(url: url)
        playerItem = player?.currentItem

        // Observe the player's current time to detect playback start
        playerObserver = player?.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.001, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: .main) { [weak self] time in
            guard let self = self else { return }

            if let currentItem = self.playerItem {
                let currentTime = currentItem.currentTime().seconds
                 
                if currentTime > 0.001 { // Adjust the threshold as needed
                    SVProgressHUD.dismiss()

                    // Pause the player and remove the observer
                   // self.player?.pause()
                    self.player?.removeTimeObserver(self.playerObserver!)

                    // Present AVPlayerViewController now that playback has started
                    self.present(self.playerController, animated: true) {
                        self.playerController.player = self.player
                        self.playerController.player?.play()
                    }
                }
            }
        }

        SVProgressHUD.show()
        player?.play()
    }
import SwiftUI
import UIKit

extension Color {
    func toHex() -> String? {
        let uic = UIColor(self)
        guard let components = uic.cgColor.components, components.count >= 3 else {
            return nil
        }
        let r = Float(components[0])
        let g = Float(components[1])
        let b = Float(components[2])
        var a = Float(1.0)

        if components.count >= 4 {
            a = Float(components[3])
        }

        if a != Float(1.0) {
            return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
        } else {
            return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
        }
    }
}
//MARK: - Document Picker

// From your project's capabilities, enable both the iCloud and the Key-Sharing.

@IBAction func pickDocumentPressed(_ sender: Any) {
       presentDocumentPicker()
    }

extension OffersReceivedViewController : UIDocumentPickerDelegate,UINavigationControllerDelegate {
    
    func presentDocumentPicker() {
        let sTypes = getSupportedTypes()
        let documentPickerController = UIDocumentPickerViewController(
            forOpeningContentTypes: sTypes)
        
        documentPickerController.delegate = self
        documentPickerController.allowsMultipleSelection = false
        SVProgressHUD.show()
        self.present(documentPickerController, animated: true) {
            SVProgressHUD.dismiss()
        }
    }
    
    public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let myURL = urls.first else {
            return
        }
        print("import result : \(myURL)")
        print("get Image Url")
        fileUrl = myURL
    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        print("view was cancelled")
        dismiss(animated: true, completion: nil)
    }
    
    func getSupportedTypes() -> [UTType] {
        let supportedTypes : [UTType] = [UTType.utf8TabSeparatedText, UTType.rtf,    UTType.pdf, UTType.webArchive, UTType.image, UTType.jpeg,    UTType.tiff, UTType.gif, UTType.png, UTType.bmp, UTType.ico,    UTType.rawImage, UTType.svg, UTType.livePhoto, UTType.movie,    UTType.video, UTType.audio, UTType.quickTimeMovie, UTType.mpeg,    UTType.mpeg2Video, UTType.mpeg2TransportStream, UTType.mp3,    UTType.mpeg4Movie, UTType.mpeg4Audio, UTType.avi, UTType.aiff,    UTType.wav, UTType.midi, UTType.archive, UTType.gzip, UTType.bz2,    UTType.zip, UTType.appleArchive, UTType.spreadsheet, UTType.epub]
        return supportedTypes
    }
}
let supportedTypes : [UTType] = [UTType.utf8TabSeparatedText, UTType.rtf,    UTType.pdf, UTType.webArchive, UTType.image, UTType.jpeg,    UTType.tiff, UTType.gif, UTType.png, UTType.bmp, UTType.ico,    UTType.rawImage, UTType.svg, UTType.livePhoto, UTType.movie,    UTType.video, UTType.audio, UTType.quickTimeMovie, UTType.mpeg,    UTType.mpeg2Video, UTType.mpeg2TransportStream, UTType.mp3,    UTType.mpeg4Movie, UTType.mpeg4Audio, UTType.avi, UTType.aiff,    UTType.wav, UTType.midi, UTType.archive, UTType.gzip, UTType.bz2,    UTType.zip, UTType.appleArchive, UTType.spreadsheet, UTType.epub]
<dict>
+  <key>NSCameraUsageDescription</key>
+  <string>To be able to scan barcodes</string>
</dict>
        var a = 0
        var b = 0
        let group = DispatchGroup()
            group.enter()

            DispatchQueue.main.async {
                FireStore.getDocument("Users", "") { (doc, v) in
                    a = 1
                    group.leave()
                }
            }
        group.enter()
           DispatchQueue.main.async {
            FireStore.getDocument("Users", "") { (doc, v) in
                b = 1
                group.leave()
            }
          }
        
            group.notify(queue: .main) {
                print("a = ", a)
                print("b = ", b)
            }
   
 StructureName.getDocument("Users", "") { (document, gotDocument) in
    
            if gotDocument {
                print("Success")
            } else {
                print("Error while getting Document")
            }
        }

    public static func getDocument(_ collectionName: String, _ documentId : String, completion: @escaping(_ documentSnapShot : DocumentSnapshot,_ success : Bool) -> Void) {
        
            SVProgressHUD.show()
            let User = Auth.auth().currentUser
            guard let user = User else {
                SVProgressHUD.dismiss()
                return
            }
     
        var docID = ""
        if documentId == "" {
            docID = user.uid
        } else {
            docID = documentId
        }

            let db = Firestore.firestore()
        db.collection(collectionName).document(docID).addSnapshotListener { (document, error) in
                if error != nil {
                    print("Error :", error as Any)
                    SVProgressHUD.dismiss()
                    return
                }
                
                guard let document = document else {
                    print("Error While Getting Document")
                    SVProgressHUD.dismiss()
                    return
                }
                completion(document, true)
            }
    }
   
 FireStore.getDocument("Users", "") { (document, gotDocument) in
    
            if gotDocument {
                print("Success")
            } else {
                print("Error while getting Document")
            }
        }

    public static func getDocument(_ collectionName: String, _ documentId : String, completion: @escaping(_ documentSnapShot : DocumentSnapshot,_ success : Bool) -> Void) {
        
            SVProgressHUD.show()
            let User = Auth.auth().currentUser
            guard let user = User else {
                SVProgressHUD.dismiss()
                return
            }
     
        var docID = ""
        if documentId == "" {
            docID = user.uid
        } else {
            docID = documentId
        }

            let db = Firestore.firestore()
            db.collection(collectionName).document(docID).getDocument { (document, error) in
                
                if error != nil {
                    print("Error :", error as Any)
                    SVProgressHUD.dismiss()
                    return
                }
                
                
                guard let document = document else {
                    print("Error While Getting Document")
                    SVProgressHUD.dismiss()
                    return
                }
                completion(document, true)
            }
    }
// calling    
        StrutName.updateDocument("Users", "", dataToUpdate) { (isUpdated) in
            if isUpdated {
                    print("Success")
            } else {
                print("Found Error While Updating")
            }
        }

    public static func updateDocument (_ collectionName: String, _ documentId : String, _ dataToUpdate: [String: Any], completionHandler:@escaping (_ success:Bool) -> Void) {
        
        var documentID = ""
        
        SVProgressHUD.show()
        let User = Auth.auth().currentUser
        guard let user = User else {
            SVProgressHUD.dismiss()
            completionHandler(false)
            return
        }
        
        if documentId == "" {
            documentID = user.uid
        } else {
            documentID = documentId
        }
        
        let db = Firestore.firestore()
        db.collection(collectionName).document(documentID).setData(dataToUpdate, merge: true) { (error) in
            
            if error != nil {
                completionHandler(false)
                SVProgressHUD.dismiss()
                return
            }
            print("updated321")
            completionHandler(true)
            SVProgressHUD.dismiss()
        }
    }
// calling      
UpdateProfileData(dataToUpdate) { (isUpdated) in
            if isUpdated {
                self.aboutTableView.reloadData()
                print("updatedd")
            }
        }

func UpdateProfileData (_ dateToUpdate: [String: Any], completionHandler:@escaping (_ success:Bool) -> Void) {
        
        SVProgressHUD.show()
        let User = Auth.auth().currentUser
        guard let user = User else {
            print("Error45")
            SVProgressHUD.dismiss()
            return
        }
        let db = Firestore.firestore()
        db.collection("Users").document(user.uid).setData(dateToUpdate, merge: true) { (error) in
            if error != nil {
                print("Error99")
                SVProgressHUD.dismiss()
                return
            }
            print("updated")
            completionHandler(true)
            SVProgressHUD.dismiss()
        }
    }
        let dataToUpdate = [
            "certificationsList" : FieldValue.arrayUnion (
                [[ "company": certificate.company,
                   "title" : certificate.title,
                   "startDate" : startDate1,
                   "endDate" : endDate1
                ]])
              ]
        let dataToUpdate = [
            "languagesList" : FieldValue.arrayUnion(
                [[ "languageLevel": language.language_Level,
                "languageTitle" : language.language_Title  ]])
                                                    ]
@IBOutlet weak var dayPicker: UIPickerView!
     
var pickerData: [Int]!

  viewDidLoad(){
  setDayPicker()
  dayPicker.delegate = self
  dayPicker.dataSource = self
}
  
//MARK: - Day Picker

extension PostRequestViewController : UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        print("\(pickerData[row])")
            return "\(pickerData[row])"
        }
    
    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        let attributedString = NSAttributedString(string: String(pickerData[row]), attributes: [NSAttributedString.Key.foregroundColor : pickerView.hexStringToUIColor(hex: "FEDA22")])
        return attributedString
    }
    
    func setDayPicker () {
        let minDay = 1
              let maxDay = 90
              pickerData = Array(stride(from: minDay, to: maxDay + 1, by: 1))
    }
}
// calling 
    getProfileMode { (mode) in
            print("Mode : ", mode)
        }

func getProfileMode(completion: @escaping (String) -> Void) {
           // write firestore code here
            completion("true")
        }
    let add = { (n1 : Int, n2: Int) -> (String) in
            
            return String(n1 + n2)
        }
        let result = add(5, 3)
        print("result = ", result)
        let xPosition = payPalSingleClickView.frame.origin.x
            let yPosition = payPalSingleClickView.frame.origin.y // Slide Up - 20px

            let width = payPalSingleClickView.frame.size.width
            let height = payPalSingleClickView.frame.size.height

        UIView.animate(withDuration: 0.0, animations: {
            self.personalBalanceView.frame = CGRect(x: xPosition, y: yPosition, width: width, height: height)
            })
    let languages = ["Afrikaans","Arabic","Bengali","Bulgarian","Catalan","Cantonese","Croatian","Czech","Danish","Dutch","Lithuanian","Malay","Malayalam","Panjabi","Tamil","English","Finnish","French","German","Greek","Hebrew","Hindi","Hungarian","Indonesian","Italian","Japanese","Javanese","Korean","Norwegian","Polish","Portuguese","Romanian","Russian","Serbian","Slovak","Slovene","Spanish","Swedish","Telugu","Thai","Turkish","Ukrainian","Vietnamese","Welsh","Algerian","Aramaic","Armenian","Berber","Burmese","Bosnian","Brazilian","Bulgarian","Cypriot","Corsica","Creole","Scottish","Egyptian","Esperanto","Estonian","Finn","Flemish","Georgian","Hawaiian","Indonesian","Inuit","Irish","Icelandic","Latin","Mandarin","Nepalese","Sanskrit","Urdu","Tagalog","Tahitian","Tibetan","Gypsy","Wu"
    ]
var arrData = [String]() // This is your data array
var arrSelectedIndex = [IndexPath]() // This is selected cell Index array
var selectedSkills = [String]() // This is selected cell data array

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrData.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
          if selectedSkills.contains(arrData[indexPath.row]) {
            cell.skillsView.backgroundColor = cell.skillsView.hexStringToUIColor(hex: "FEDA22")
        }
      return cell
    }
  
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
        
            if let cell = collectionView.cellForItem(at: indexPath) as? SkillsCollectionViewCell {

                let selectedCategory = subCategoriesPopUpArray[indexPath.item]

                if selectedSubCategories.contains(selectedCategory) {
                    cell.skillsView.backgroundColor = cell.skillsView.hexStringToUIColor(hex: "F0F0F0")
                    selectedSubCategories = selectedSubCategories.filter {
                        $0 != selectedCategory
                    }
                } else {
                    selectedSubCategories.append(selectedCategory)
                    cell.skillsView.backgroundColor = cell.skillsView.hexStringToUIColor(hex: "FEDA22")
                }
        }
    }
}
  pod "AlignedCollectionViewFlowLayout"
  pod 'iOSDropDown'
  pod 'KYDrawerController'
  pod 'Firebase/Database'
  pod 'Firebase/Core'
  pod 'FirebaseAuth'
  pod 'GoogleSignIn'
  pod 'Firebase/Storage'
  pod 'Firebase/Firestore'
  pod 'SDWebImage', '~>5.0'
  pod 'IQKeyboardManagerSwift', '~>6.5.0'
  pod 'SwiftQRScanner', :git => 'https://github.com/vinodiOS/SwiftQRScanner'
  pod 'FacebookCore'
  pod 'FacebookLogin'
  pod 'FBSDKCoreKit'
  pod 'FBSDKLoginKit'
  pod 'SVProgressHUD'
  pod 'SwiftyJSON'
  pod 'FacebookSDK'
  pod 'FacebookSDK/LoginKit'
  pod 'FacebookSDK/ShareKit'
  pod 'FacebookSDK/PlacesKit'
  pod 'ADCountryPicker'
  pod 'Stripe'
  pod 'Alamofire'
  pod "FINNBottomSheet", git: "https://github.com/finn-no/BottomSheet.git"
  pod "MBCircularProgressBar"
  pod 'ImageSlideshow'
  pod 'SVPinView'
  pod 'LMGaugeViewSwift' // circle
extension UIImageView {
  func setImageColor(color: UIColor) {
    let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
    self.image = templateImage
    self.tintColor = color
  }
}
extension SendOfferVC : UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.text == "Add a Description to your Offer" {
            textView.text = ""
            textView.textColor = UIColor.darkGray
        }
    }
    func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        if textView.text == "" {
            textView.text = "Add a Description to your Offer"
            textView.textColor = UIColor.lightGray
        }
         return true
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if(text == "\n") {
                  textView.resignFirstResponder()
                  return false
              }
              return true
    }
}
    func setBalanceLabel(_ balance: String) {
        let height = balanceLabel.layer.frame.height
        balanceLabel.text = "  " + balance + "  "
        balanceLabel.sizeToFit()
        balanceLabel.layer.frame.size.height = height
        balanceLabel.layer.cornerRadius = balanceLabel.layer.frame.height/2
    }
  override func viewDidLoad() {
        super.viewDidLoad()
    
           let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
            let width = UIScreen.main.bounds.width
            layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
            layout.itemSize = CGSize(width: width / 2 - 20, height: width / 2)
            layout.minimumInteritemSpacing = 0
            layout.minimumLineSpacing = 0
            popularServicesCollectionView!.collectionViewLayout = layout
  }

  myCartTableView.reloadRows(at: [IndexPath(row: imgView.tag, section: 0)], with: .none)
    func hexStringToUIColor (hex:String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if (cString.hasPrefix("#")) {
            cString.remove(at: cString.startIndex)
        }

        if ((cString.count) != 6) {
            return UIColor.gray
        }

        var rgbValue:UInt64 = 0
        Scanner(string: cString).scanHexInt64(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
  @objc func addToCartTaped(tapGesture: UITapGestureRecognizer) {
        let imgView = tapGesture.view as! UIImageView
  
    }

# Paste in cell
cell.addToCartImageView.tag = indexPath.row
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(addToCartTaped(tapGesture:)))
            cell.addToCartImageView.isUserInteractionEnabled = true
            cell.addToCartImageView.addGestureRecognizer(tapGesture)
sellerRecomendRating = star.tag
        
        var count = 0
        [star1, star2, star3, star4, star5].forEach { star in
            count += 1
            if count <= sellerRecomendRating {
                star?.image = UIImage(named: "star_sel")
            } else {
                star?.image = UIImage(named: "star_unsel")
            }
        }
        let parameters: [String:Any] = [
            "country" : "US",
            "type" : "custom",
            "capabilities": ["card_payments": ["requested": "true"], "transfers": ["requested": "true"]]]
            //"business_type": "individual",
//            "business_profile[url]": "https://google.com"]
        
        let url = "https://api.stripe.com/v1/accounts"
        let api_key = ""
        let loginData = api_key.data(using: String.Encoding.utf8)
        let base64LoginString = loginData?.base64EncodedString()
        print("key : ", (base64LoginString ?? "") as String)
        let headers: HTTPHeaders = ["Authorization": "Basic \(base64LoginString!)", "Content-Type": "application/x-www-form-urlencoded", "Accept": "*/*"]
        AF.request(url, method: .post, parameters: parameters, headers: headers)
            .responseJSON(completionHandler: { (response) in
                do {
                    let json = try JSON(data: response.data!)
                    print(json["id"])
                }
                catch let error {
                    print(error.localizedDescription)
                }
            })
    override func viewDidLoad() {
        // function calling
        querySomething { (completed) in
              print("completed :", completed)
        }
    }
    
    func querySomething(completion: @escaping (Bool) -> Void) {
        let db = Firestore.firestore()
        db.collection("collectionName").document().addSnapshotListener { (documentSnapshot, error) in
            if error != nil {
                completion(false)
                return
            }
            completion(true)
        }
    }
var number = "73-84-4"
cardNumber1 = number.filter { $0 != "-" }
print("card 122", number)
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL"
let nameOfMonth = dateFormatter.string(from: now)
    func createBackButton() {
        let image = UIImage(named: "left-arrow") as UIImage?
        let button = UIButton(type: UIButton.ButtonType.custom) as UIButton
        let screenSize: CGRect = UIScreen.main.bounds
            let screenWidth = screenSize.width
            let screenHeight = screenSize.height
        
        button.frame = CGRect(x: screenWidth * 0.05, y: screenHeight * 0.05, width: screenWidth * 0.05, height: screenWidth * 0.03) // (X, Y, Height, Width)
        button.setImage(image, for: .normal)
        button.addTarget(self, action: #selector(customGoBack(sender:)), for: UIControl.Event.touchUpInside)
            self.view.addSubview(button)
    }
    
    @objc func customGoBack(sender: UIButton) {
        if self.webView.canGoBack {
            print("Can go back")
            self.webView.goBack()
            self.webView.reload()
        } else {
            print("Can't go back")
        }
    }
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    var webView: WKWebView!

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "https://www.google.com")!
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
    }
    
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
            if(navigationAction.navigationType == .other) {
                if let redirectedUrl = navigationAction.request.url {
                    //do what you need with url
                    //self.delegate?.openURL(url: redirectedUrl)
                }
                decisionHandler(.cancel)
                return
            }
            decisionHandler(.allow)
        }
}
    func createStripeConnectAccount() {
        let parameters: [String:Any] = [
            "type" : "express",
            "country" : "US",
//            "capabilities": [["card_payments"]["requested"],
//            "capabilities[transfers][requested]": true,
//            "business_type": "individual",
            "business_profile[url]": "https://google.com"]
        
        let url = "https://api.stripe.com/v1/accounts"
        let api_key = "add test api key here"
        let loginData = api_key.data(using: String.Encoding.utf8)
        let base64LoginString = loginData?.base64EncodedString()
        print("key : ", (base64LoginString ?? "") as String)
        let headers: HTTPHeaders = ["Authorization": "Basic \(base64LoginString!)", "Content-Type": "application/x-www-form-urlencoded", "Accept": "*/*"]
        AF.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers)
            .responseDecodable(of: DecodableType.self)
            { response in
                switch response.result {
                case .success(let dict):
                    print("success ", response.result, dict)
                    let res = dict.id
                    print("ID1 : ", res)
                case .failure(let error):
                    print("Failure : ", error)
                }
            }
    }
 static func showToast(message : String,view:UIView) {

    let toastContainer = UIView(frame: CGRect())
                toastContainer.backgroundColor = UIColor.black.withAlphaComponent(0.6)
                toastContainer.alpha = 0.0
                toastContainer.layer.cornerRadius = 25;
                toastContainer.clipsToBounds  =  true

                let toastLabel = UILabel(frame: CGRect())
                toastLabel.textColor = UIColor.white
                toastLabel.textAlignment = .center;
                toastLabel.font.withSize(12.0)
                toastLabel.text = message
                toastLabel.clipsToBounds  =  true
                toastLabel.numberOfLines = 0

                toastContainer.addSubview(toastLabel)
                view.addSubview(toastContainer)

                toastLabel.translatesAutoresizingMaskIntoConstraints = false
                toastContainer.translatesAutoresizingMaskIntoConstraints = false

                let a1 = NSLayoutConstraint(item: toastLabel, attribute: .leading, relatedBy: .equal, toItem: toastContainer, attribute: .leading, multiplier: 1, constant: 15)
                let a2 = NSLayoutConstraint(item: toastLabel, attribute: .trailing, relatedBy: .equal, toItem: toastContainer, attribute: .trailing, multiplier: 1, constant: -15)
                let a3 = NSLayoutConstraint(item: toastLabel, attribute: .bottom, relatedBy: .equal, toItem: toastContainer, attribute: .bottom, multiplier: 1, constant: -15)
                let a4 = NSLayoutConstraint(item: toastLabel, attribute: .top, relatedBy: .equal, toItem: toastContainer, attribute: .top, multiplier: 1, constant: 15)
                toastContainer.addConstraints([a1, a2, a3, a4])

                let c1 = NSLayoutConstraint(item: toastContainer, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 65)
                let c2 = NSLayoutConstraint(item: toastContainer, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: -65)
                let c3 = NSLayoutConstraint(item: toastContainer, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: -75)
            view.addConstraints([c1, c2, c3])

                UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseIn, animations: {
                    toastContainer.alpha = 1.0
                }, completion: { _ in
                    UIView.animate(withDuration: 0.5, delay: 1.5, options: .curveEaseOut, animations: {
                        toastContainer.alpha = 0.0
                    }, completion: {_ in
                        toastContainer.removeFromSuperview()
                    })
                })
    }
    func setEditButtonPosition() {
               let x1 = profileImageView.frame.maxX - profileImageView.layer.frame.height/4.5
        let y1 = profileImageView.frame.maxY - profileImageView.layer.frame.height/4.5
        
               statusImageView.frame.origin = CGPoint(x: x1, y: y1)

    }
        nameImageView.layer.cornerRadius = nameImageView.frame.height/2
        nameImageView.layer.borderWidth = 0.75
        nameImageView.layer.borderColor = UIColor.lightGray.cgColor
   func setProfileImage() {
        profileImageView.frame.size = CGSize(width: profileImageView.frame.height,
                                                  height: profileImageView.frame.height)
        profileImageView.layer.cornerRadius = profileImageView.layer.frame.height/2
        profileImageView.center.x = view.center.x
    }
func addshadow(top: Bool,
              left: Bool,
              bottom: Bool,
              right: Bool,
              shadowRadius: CGFloat) {
        self.backgroundColor = UIColor.white
        self.layer.masksToBounds = false
        self.layer.cornerRadius = 8
        self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
        self.layer.shadowRadius = shadowRadius
        self.layer.shadowOpacity = 0.4
        self.layer.shadowColor = UIColor(red: 6.0/255, green: 141.0/255, blue: 144.0/255, alpha: 1.0).cgColor
        let path = UIBezierPath()
        var x: CGFloat = 0
        var y: CGFloat = 0
        var viewWidth = self.frame.width
        var viewHeight = self.frame.height
        // here x, y, viewWidth, and viewHeight can be changed in
        // order to play around with the shadow paths.
        if (!top) {
          y+=(shadowRadius+1)
        }
        if (!bottom) {
          viewHeight-=(shadowRadius+1)
        }
        if (!left) {
          x+=(shadowRadius+1)
        }
        if (!right) {
          viewWidth-=(shadowRadius+1)
        }
        // selecting top most point
        path.move(to: CGPoint(x: x, y: y))
        // Move to the Bottom Left Corner, this will cover left edges
        /*
         |☐
         */
        path.addLine(to: CGPoint(x: x, y: viewHeight))
        // Move to the Bottom Right Corner, this will cover bottom edge
        /*
         ☐
         -
         */
        path.addLine(to: CGPoint(x: viewWidth, y: viewHeight))
        // Move to the Top Right Corner, this will cover right edge
        /*
         ☐|
         */
        path.addLine(to: CGPoint(x: viewWidth, y: y))
        // Move back to the initial point, this will cover the top edge
        /*
         _
         ☐
         */
        path.close()
        self.layer.shadowPath = path.cgPath
      }
func isValid(testStr:String) -> Bool {
    guard testStr.count > 7, testStr.count < 18 else { return false }

    let predicateTest = NSPredicate(format: "SELF MATCHES %@", "^(([^ ]?)(^[a-zA-Z].*[a-zA-Z]$)([^ ]?))$")
    return predicateTest.evaluate(with: testStr)
}
extension MerchantTabBarViewController: QRScannerCodeDelegate {
    
    func presentQRView(){
        let activityView = activityIndicatorView()
        activityView.startAnimating()
        let scanner = QRCodeScannerController()
        scanner.delegate = self
        scanner.modalTransitionStyle = .coverVertical
        self.present(scanner, animated: true) {
            activityView.stopAnimating()
        }
    }
    
    func qrScanner(_ controller: UIViewController, scanDidComplete result: String) {
        print("result:\(result)")
    }

    func qrScannerDidFail(_ controller: UIViewController, error: String) {
        print("error:\(error)")
    }
    
    func qrScannerDidCancel(_ controller: UIViewController) {
        print("SwiftQRScanner did cancel")
    }
}
let refreshAlert = UIAlertController(title: "Offer Sent", message: "Your offer has been sent Successfully", preferredStyle: UIAlertController.Style.alert)

                refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
                    self.dismiss(animated: true, completion: nil)
                  print("Handle Ok logic here")
                  }))
                
                refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in
                    self.dismiss(animated: true, completion: nil)
                  print("Handle Cancel logic here")
                  }))

                self.present(refreshAlert, animated: true, completion: nil)

func isDayEnded(recent: Date, previous: Date) -> Bool {
    let day:Int = Calendar.current.dateComponents([.day], from: previous, to: recent).day ?? 0
    if day >= 1 {
        return true
    } else {
        return false
    }
}
let previous = NSDate(timeIntervalSince1970: 1645601459)
let recent = NSDate(timeIntervalSince1970:   1648020659)
let dayEnded = isDayEnded(recent: recent as Date, previous: previous as Date)
print("Day = \(dayEnded)")
let age = calcAge(birthday: "789089362000") // pass timeStamp in mili seconds
print("Age = \(age)")

func calcAge(birthday: String) -> Int {
    let seconds = (Int(birthday)!/1000) as NSNumber?
    let timeStampDate = Date(timeIntervalSince1970: seconds!.doubleValue)
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
    let now = Date()
    let calcAge = calendar.components(.year, from: timeStampDate, to: now, options: [])
    let age = calcAge.year
    return age!
  }
override func layoutSubviews() {
    super.layoutSubviews()
    roundCorners(corners: [.topLeft, .topRight], radius: 3.0)
}

extension UIView {
   func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
}
UIApplication.shared.open(URL(string: "http://www.google.com")!, options: [:], completionHandler: nil)
var secondsRemaining = 60    
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
        if secondsRemaining > 0 {
            print ("\(self.secondsRemaining) seconds")
            secondsRemaining -= 1
        } else {
            Timer.invalidate()
        }
    }
   let User = Auth.auth().currentUser
        if let user = User{
            let db = Firestore.firestore()
            db.collection("Appointments").whereField("patient_id", isEqualTo: user.uid).getDocuments { [self] (document, error) in
                guard let data = document?.documents else {
                    return
                }
                      for d in data{
                    self.chatStatus = d.get("chat_status") as? String ?? ""
                    self.startTime = d.get("start_time") as? String ?? ""
                }
                      //updating data
                    let document = document!.documents.first
                    document?.reference.updateData([
                                   "chat_status": "Started"
                               ])
func scrollToBottom(){
    DispatchQueue.main.async {
        let indexPath = IndexPath(row: self.dataArray.count-1, section: 0)
        self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
    }
}
self.postModel = self.postModel.sorted(by: { $0.time_stamp > $1.time_stamp
100% scale use CTRL+1 or CMD+1
75% scale use CTRL+2 or CMD+2
50% scale use CTRL+3 or CMD+3
33% scale use CTRL+4 or CMD+4
25% scale use CTRL+5 or CMD+5
   DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: {
            self.profileImageView.makeCircle()
        })
db.collection("Groups").whereField("group_members", arrayContains: userId ?? "324").getDocuments() {(groups, error) in
                if error != nil {
                    print("Error getting documents: \(error!)")
                } else { }
To Filter Model Array:

var filteredItems = unfilteredItems.filter { $0.cat == "garden" }

Arrange :

self.chatModelArray = self.chatModelArray.sorted { $0.time == $1.time }

To Filter name : 

var filteredItems = unfilteredItems.filter { $0.name.localizedCaseInsensitiveContains(textField.text ?? "") }

To Filter an Array:

let result = arr.filter {$0.contains("ali")}
@IBAction func saveChangesPressed(_ sender: UIButton) {
        
        let user = Auth.auth().currentUser
        if let user = user {
            let db = Firestore.firestore()
            let docRef = db.collection("Users").document(user.uid)
            docRef.updateData(["Name": self.nameField.text ?? "User","Email": self.emailField.text ?? "a@gmail.com", "MobileNumber": self.phoneNumberField.text ?? "123"])
        }
    }
func getImageUrl(){
    print("get Image Url")
    guard let imageData = postPictureImageView.image?.jpegData(compressionQuality: 0.5) else { return }
    let timeStamp = Int(Date().timeIntervalSince1970)
    let storageRef = Storage.storage().reference().child("Posted Images/\(timeStamp).jpg")
    storageRef.putData(imageData, metadata: nil) { (metadata, error) in
        if error != nil {
            print("error")
        } else {
            storageRef.downloadURL { (url, error) in
                if let url =  url?.absoluteString {
                    Url = String(url)
                    }
                }
            }
        }
    }
}
var imagePicker = UIImagePickerController()
var imagePicked = false


    @IBAction func updateProfilePressed(_ sender: Any) {
        let email = emailTextField.text ?? ""
        let phone = phoneNumberTextField.text ?? ""
        
        if nameTextField.text == "" {
            self.showToast(message: "Please enter name")
            return
        } else if !isValidPhone(phone) {
            self.showToast(message: "Please enter a valid phone number")
            return
        }
        
        if imagePicked {
            DB.getImageUrl(profileImageView) { imageUrl in
               let data = [
                    "profileUrl" : imageUrl,
                    "name" : self.nameTextField.text ?? "",
                    "phoneNumber": self.phoneNumberTextField.text ?? "",
                ]
                self.saveData(data)
            }
        } else {
           let data = [
                "name" : self.nameTextField.text ?? "",
                "phoneNumber": self.phoneNumberTextField.text ?? "",
            ]
            self.saveData(data)
        }
    }
    
    func saveData(_ data : [String:Any]) {
        
        let userId = Auth.auth().currentUser?.uid ?? ""
        
        DB.updateDocument("ServiceProviders", userId, data, merge: true) { success in
            if success {
                self.showToast(message: "Profile Updated!")
            }
        }
    }


// MARK: - Image Picker

extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func enableImageViewTapGesture()
        {
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(profileImageTapped(tapGesturerecognizer:)))
            profileImageView.isUserInteractionEnabled = true
            profileImageView.addGestureRecognizer(tapGestureRecognizer)
        }
    
    @objc func profileImageTapped(tapGesturerecognizer: UITapGestureRecognizer){
        
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
            print("Button capture")
            imagePicker.delegate = self
            imagePicker.sourceType = .savedPhotosAlbum
            imagePicker.allowsEditing = true
            
            SVProgressHUD.show()
            present(imagePicker, animated: true) {
                SVProgressHUD.dismiss()
            }
        }
        else {
            print("No")
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            imagePicked = true
            profileImageView.layer.cornerRadius = profileImageView.bounds.width/2
            profileImageView.image = pickedImage
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
        dismiss(animated: true, completion:nil)
    }
}
    func getDateTime(_ timeStamp : String,_ format: String) -> String {
        var t1 = Int(timeStamp) ?? 1
         t1 = t1/1000
        let date = NSDate(timeIntervalSince1970: TimeInterval(t1))
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        let dateString = dateFormatter.string(from: date as Date)
        print("Date = \(dateString)")
        return dateString
    }
function aaa(a, b){
return a+b;
}
let url = URL(string: image.url)
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
imageView.image = UIImage(data: data!)
#include <iostream>
#include "unordered_set"
#include "basicActions.h"
using namespace std;

void createLoop(Node *head)
{
    Node *p = head;

    while (p->next != nullptr)
    {
        p = p->next;
    }
    p->next = head;
    return;
}

bool detectLoop(Node *head)
{
    unordered_set<Node *> s;
    Node *p = head;

    while (p != nullptr)
    {
        if (s.find(p) != s.end())
            return true;

        s.insert(p);
        p = p->next;
    }
    return false;
}

int main()
{
    Node *head = nullptr;
    insertAtEnd(head, 1);
    insertAtEnd(head, 2);
    insertAtEnd(head, 3);
    insertAtEnd(head, 4);
    insertAtEnd(head, 5);

    createLoop(head);

    detectLoop(head) ? cout << "Loop Detected.." << '\n' : cout << "No Loop Detected.." << '\n';
}
#include <iostream>
using namespace std;

struct hashing
{
    int value;
    int key;
};


void put(int value, hashing hash[],int n) {
    hash[value % n].value = value;
    hash[value % n].key = (value % n);
}

int get(int key, hashing hash[]) {
    return hash[key].value;
}

int main()
{
    int n;
    
    struct hashing hash[n];
    cin >> n;
    for (int t=0;t<n;t++) {
        put(t+1,hash,n);
        cout << "Inserted : " << (t+1) << endl;
    }
    int temp;
    cin >> temp;
    cout << get(temp,hash) << endl;
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>IDECodeSnippetCompletionPrefix</key>
	<string>snippetAlert</string>
	<key>IDECodeSnippetCompletionScopes</key>
	<array>
		<string>All</string>
	</array>
	<key>IDECodeSnippetContents</key>
	<string>let alertController = UIAlertController(title: &lt;#T##String?#&gt;, message: &lt;#T##String?#&gt;, preferredStyle: &lt;#T##UIAlertController.Style#&gt;)
let firstAction = UIAlertAction(title: &lt;#T##String?#&gt;, style: .default, handler: &lt;#T##((UIAlertAction) -&gt; Void)?##((UIAlertAction) -&gt; Void)?##(UIAlertAction) -&gt; Void#&gt;)
let cancelAction = UIAlertAction(title: &lt;#T##String?#&gt;, style: .cancel, handler: nil)

alertController.addAction(firstAction)
alertController.addAction(cancelAction)
present(alertController, animated: true)</string>
	<key>IDECodeSnippetIdentifier</key>
	<string>8C458AD7-C631-457B-85CC-D2501E425D59</string>
	<key>IDECodeSnippetLanguage</key>
	<string>Xcode.SourceCodeLanguage.Swift</string>
	<key>IDECodeSnippetSummary</key>
	<string></string>
	<key>IDECodeSnippetTitle</key>
	<string>UIAlertController</string>
	<key>IDECodeSnippetUserSnippet</key>
	<true/>
	<key>IDECodeSnippetVersion</key>
	<integer>2</integer>
</dict>
</plist>
import 'package:flutter/material.dart';

void main() {
  runApp(
    new MaterialApp(
      title: 'Hello World App',
      home: new myApp(),
    )
  );
}

class myApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Hello World App'),
      ),
      body: new Center(
        child: new Text(
          'Hello, world!'
        ),
      ),
    );
  }
}
import UIKit

extension UITableView {
    
    func dequeueReusableCell<T: UITableViewCell>() -> T {
        return dequeueReusableCell(withIdentifier: NSStringFromClass(T.self)) as! T
    }
}

//using: let cell: ExampleTableViewCell = tableView.dequeueReusableCell()
// MARK: - Properties

// MARK: - IBOutlets

// MARK: - Life cycle

// MARK: - Set up

// MARK: - IBActions

// MARK: - Navigation

// MARK: - Network Manager calls

// MARK: - Extensions
override func viewDidLoad() {
    super.viewDidLoad()
    // Swift block syntax (iOS 10+)
    let timer = Timer(timeInterval: 0.4, repeats: true) { _ in print("Done!") }
    // Swift >=3 selector syntax
    let timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
    // Swift 2.2 selector syntax
    let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
    // Swift <2.2 selector syntax
    let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
}

// must be internal or public. 
@objc func update() {
    // Something cool
}
@IBAction func doSomething()
@IBAction func doSomething(sender: UIButton)
@IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)
[[NSProcessInfo processInfo] operatingSystemVersion]
// Preferred status bar style lightContent to use on dark background.
// Swift 3
override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}
star

Mon Oct 23 2023 06:41:18 GMT+0000 (Coordinated Universal Time)

#ios #swift #inapp #subscription #purchase #appstore
star

Mon Oct 09 2023 10:47:40 GMT+0000 (Coordinated Universal Time)

#ios #swift #menu #slide #slidemenu #slider #slideview
star

Mon Oct 09 2023 07:52:02 GMT+0000 (Coordinated Universal Time)

#ios #swift #menu #slide #slidemenu #slider #slideview
star

Fri Sep 08 2023 05:23:34 GMT+0000 (Coordinated Universal Time)

#ios #swift #file #extension
star

Thu Aug 10 2023 05:53:22 GMT+0000 (Coordinated Universal Time)

#ios #swift #model #comment #comments
star

Wed Aug 09 2023 06:34:24 GMT+0000 (Coordinated Universal Time)

#ios #swift #location
star

Wed Aug 02 2023 07:18:27 GMT+0000 (Coordinated Universal Time)

#ios #swift #cell #custom #customcell
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
star

Wed Jul 05 2023 05:32:27 GMT+0000 (Coordinated Universal Time)

#ios #swift #eye #password #hide #show
star

Fri Jun 23 2023 08:10:31 GMT+0000 (Coordinated Universal Time)

#ios #swift #dic #dict #model #modelarray #dictonary
star

Tue May 16 2023 11:27:12 GMT+0000 (Coordinated Universal Time)

#ios #swift #pod #permission
star

Wed Apr 26 2023 04:43:12 GMT+0000 (Coordinated Universal Time) https://pastebox.io/

#json #ios
star

Fri Mar 31 2023 07:07:52 GMT+0000 (Coordinated Universal Time)

#ios #swift #increment
star

Fri Mar 31 2023 06:42:39 GMT+0000 (Coordinated Universal Time)

#ios #swift #dict #model #dictionary
star

Thu Mar 02 2023 10:45:29 GMT+0000 (Coordinated Universal Time)

#ios #swift #vc #dismis #dismiss #dissmis
star

Wed Mar 01 2023 08:01:14 GMT+0000 (Coordinated Universal Time)

#ios #swift #cell #select #selection #single
star

Thu Feb 23 2023 19:17:31 GMT+0000 (Coordinated Universal Time)

#ios #swift #time #date #chat
star

Mon Feb 20 2023 06:20:42 GMT+0000 (Coordinated Universal Time)

#ios #swift #check #internet #network #connection #connect
star

Mon Feb 20 2023 06:19:26 GMT+0000 (Coordinated Universal Time)

#ios #swift #check #internet #connection #connect #network
star

Tue Feb 07 2023 05:39:59 GMT+0000 (Coordinated Universal Time)

#ios #swift #remove #increment #union
star

Fri Jan 27 2023 17:21:38 GMT+0000 (Coordinated Universal Time)

#ios #swift #table #tableview #snippet
star

Fri Jan 27 2023 17:17:47 GMT+0000 (Coordinated Universal Time)

#ios #swift #view #snippet
star

Fri Jan 27 2023 17:13:07 GMT+0000 (Coordinated Universal Time)

#ios #swift #vc #next #nextvc #snippet
star

Fri Jan 27 2023 17:08:22 GMT+0000 (Coordinated Universal Time)

#ios #swift #collectionview #collection #cv
star

Fri Jan 27 2023 17:06:39 GMT+0000 (Coordinated Universal Time)

#ios #swift #bottombar #bottom #tab #tabbar #snippet #snipet #snipit #code
star

Wed Jan 25 2023 15:36:09 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/chat/07129f0f-4c3a-4dc4-892c-f0353b6ad551

#ios #swift #scroll #horizontal #snippet
star

Sun Jan 22 2023 08:20:36 GMT+0000 (Coordinated Universal Time)

#ios #swift #stripe #stripeconnect
star

Thu Jan 05 2023 05:58:35 GMT+0000 (Coordinated Universal Time)

#ios #swift #fcm
star

Tue Jan 03 2023 06:16:48 GMT+0000 (Coordinated Universal Time)

#ios #swift #barchart #bar #chart
star

Sat Dec 31 2022 04:27:45 GMT+0000 (Coordinated Universal Time)

#ios #swift #date #picker
star

Tue Dec 27 2022 12:22:59 GMT+0000 (Coordinated Universal Time)

#ios #swift #email #verify
star

Fri Dec 16 2022 12:24:19 GMT+0000 (Coordinated Universal Time)

#ios #swift #card #view #cardview
star

Fri Sep 09 2022 07:26:02 GMT+0000 (Coordinated Universal Time)

#ios #swift #gradient #gradent
star

Tue Aug 30 2022 07:54:18 GMT+0000 (Coordinated Universal Time)

#ios #swift #video #player
star

Wed Aug 10 2022 08:11:11 GMT+0000 (Coordinated Universal Time) https://blog.eidinger.info/from-hex-to-color-and-back-in-swiftui

#ios #swiftui
star

Mon Jun 27 2022 10:53:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/37296929/implement-document-picker-in-swift-ios

#ios #swift #file #pdf #doc #document #picker #mp3 #mp4 #video #audio
star

Mon Jun 27 2022 08:05:49 GMT+0000 (Coordinated Universal Time)

#ios #swift #file #pdf #png
star

Thu Jun 23 2022 08:13:46 GMT+0000 (Coordinated Universal Time)

#ios #swift #wait #await
star

Wed Jun 15 2022 10:51:10 GMT+0000 (Coordinated Universal Time)

#ios #swift #closure #document #get
star

Wed Jun 15 2022 10:50:25 GMT+0000 (Coordinated Universal Time)

#ios #swift #closure #document #get
star

Wed Jun 15 2022 07:24:22 GMT+0000 (Coordinated Universal Time)

#ios #swift #closure #update #document
star

Wed Jun 15 2022 07:10:53 GMT+0000 (Coordinated Universal Time)

#ios #swift #closure
star

Wed Jun 15 2022 05:17:16 GMT+0000 (Coordinated Universal Time)

#ios #swift #update #dictionary #array
star

Tue Jun 14 2022 09:49:00 GMT+0000 (Coordinated Universal Time)

#ios #swift #update #dictionary #array
star

Mon Jun 13 2022 06:32:37 GMT+0000 (Coordinated Universal Time)

#ios #swift #day #daypicker #picker
star

Thu Jun 09 2022 10:49:22 GMT+0000 (Coordinated Universal Time)

#ios #swift #closure #return
star

Wed Jun 08 2022 05:35:30 GMT+0000 (Coordinated Universal Time)

#ios #swift #view #change #animate
star

Fri Jun 03 2022 11:39:59 GMT+0000 (Coordinated Universal Time)

#ios #swift #view #change #animate
star

Wed Jun 01 2022 07:44:59 GMT+0000 (Coordinated Universal Time)

#ios #swift #languages #language
star

Tue May 31 2022 10:53:22 GMT+0000 (Coordinated Universal Time)

#ios #swift #pods #pod #cocoapods
star

Tue May 31 2022 05:47:57 GMT+0000 (Coordinated Universal Time)

#ios #swift #image #imagecolor #imagecolour #changeimagecolour
star

Mon May 30 2022 12:30:28 GMT+0000 (Coordinated Universal Time)

#ios #swift #textview #text
star

Tue May 24 2022 10:32:06 GMT+0000 (Coordinated Universal Time)

#ios #swift #label #layout #width #labelwidth
star

Mon May 23 2022 05:09:17 GMT+0000 (Coordinated Universal Time)

#ios #swift #collectionview #collection #flow #flowlayout
star

Fri May 13 2022 11:08:14 GMT+0000 (Coordinated Universal Time)

#ios #swift #row #reloadrow #tableview
star

Fri May 13 2022 10:33:12 GMT+0000 (Coordinated Universal Time)

#ios #swift #color #colour #hex
star

Fri Apr 22 2022 07:10:23 GMT+0000 (Coordinated Universal Time)

#ios #swift #tap #taped #imagetaped
star

Fri Apr 22 2022 05:32:05 GMT+0000 (Coordinated Universal Time)

#ios #swift #rating #review #star #rate
star

Tue Apr 05 2022 07:14:32 GMT+0000 (Coordinated Universal Time)

#ios #swift #custom #stripe #stripeconnect
star

Sat Apr 02 2022 04:49:10 GMT+0000 (Coordinated Universal Time)

#ios #swift #return #completion
star

Fri Apr 01 2022 12:12:44 GMT+0000 (Coordinated Universal Time)

#ios #swift #remove #removecharacters #char #characters #string
star

Fri Apr 01 2022 05:39:35 GMT+0000 (Coordinated Universal Time)

#ios #swift #createbutton #currentmonth #date #year
star

Wed Mar 30 2022 11:45:41 GMT+0000 (Coordinated Universal Time)

#ios #swift #createbutton
star

Wed Mar 30 2022 07:50:10 GMT+0000 (Coordinated Universal Time)

#ios #swift #url #geturl
star

Tue Mar 29 2022 07:49:14 GMT+0000 (Coordinated Universal Time)

#ios #swift #stripe
star

Sat Mar 19 2022 10:09:10 GMT+0000 (Coordinated Universal Time)

#ios #swift #toast #tost
star

Thu Mar 17 2022 06:21:49 GMT+0000 (Coordinated Universal Time)

#ios #swift #set #setbutton #setimageview #image #button
star

Wed Mar 16 2022 11:20:40 GMT+0000 (Coordinated Universal Time)

#ios #swift #view #setview
star

Tue Mar 15 2022 11:50:41 GMT+0000 (Coordinated Universal Time)

#ios #swift #profileimage #image #profile #snippet
star

Tue Mar 15 2022 04:14:56 GMT+0000 (Coordinated Universal Time)

#ios #swift #shadow
star

Wed Mar 09 2022 08:36:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/55181606/how-to-have-a-firstname-validation-in-ios-swift4

#ios #swift #name #validation #validate
star

Tue Mar 08 2022 10:09:08 GMT+0000 (Coordinated Universal Time)

#ios #swift #qr #qr #qr #qrcode #qrcode
star

Sat Mar 05 2022 07:51:17 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/25511945/swift-alert-view-with-ok-and-cancel-which-button-tapped

#alert #ios #swift
star

Thu Feb 24 2022 07:51:11 GMT+0000 (Coordinated Universal Time)

#ios #swift #day #date #difference
star

Sat Feb 19 2022 04:44:50 GMT+0000 (Coordinated Universal Time)

#ios #swift #calculate #age
star

Thu Feb 17 2022 04:21:17 GMT+0000 (Coordinated Universal Time) https://flaviocopes.com/react-native-fix-iphoneos-cannot-be-located/

#react #ios
star

Mon Feb 07 2022 07:41:03 GMT+0000 (Coordinated Universal Time)

#ios #swift #round #corner #view #viewround
star

Thu Feb 03 2022 12:20:28 GMT+0000 (Coordinated Universal Time)

#ios #swift #webpage #page #web #url #link
star

Tue Feb 01 2022 07:12:29 GMT+0000 (Coordinated Universal Time)

#ios #swift #timer #counter #count #countdown
star

Thu Jan 27 2022 08:01:04 GMT+0000 (Coordinated Universal Time)

#ios #swift #getandupdate #data #getandupdatedata
star

Tue Jan 18 2022 12:41:24 GMT+0000 (Coordinated Universal Time)

#ios #swift #scroll
star

Tue Jan 18 2022 10:48:29 GMT+0000 (Coordinated Universal Time)

#ios #swift #xcode #sort #array #sortarray
star

Mon Jan 17 2022 10:24:31 GMT+0000 (Coordinated Universal Time)

#ios #swift #xcode #simulator #size
star

Mon Jan 17 2022 10:01:54 GMT+0000 (Coordinated Universal Time)

#ios #swift #dispatchqueue #dispatch #queue
star

Thu Jan 13 2022 12:10:26 GMT+0000 (Coordinated Universal Time)

#ios #swift #query
star

Thu Jan 13 2022 10:58:19 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/48467867/adding-a-filter-to-an-array-in-swift-4

#swift #filter #array #ios
star

Mon Jan 10 2022 06:37:19 GMT+0000 (Coordinated Universal Time)

#ios #swift #update #updatedata #data
star

Sat Jan 08 2022 09:45:11 GMT+0000 (Coordinated Universal Time)

#ios #swift #image
star

Sat Jan 08 2022 09:39:33 GMT+0000 (Coordinated Universal Time)

#ios #swift #date #time #datetime
star

Mon Dec 06 2021 11:15:02 GMT+0000 (Coordinated Universal Time)

#ios #imporant #ddd
star

Thu May 06 2021 17:15:22 GMT+0000 (Coordinated Universal Time)

#ios #imporant #ddd
star

Sun Jan 12 2020 17:30:26 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift

#ios #swift #swift4
star

Fri Jan 03 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://github.com/manosriram/Data-Structures/blob/master/linkedLists/detectLoop.cpp

#ios #swift #apps #loops
star

Fri Jan 03 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://github.com/manosriram/Data-Structures/blob/master/Hashing/basicHash.cpp

#ios #swift #apps #hash #security
star

Sun Dec 29 2019 19:53:43 GMT+0000 (Coordinated Universal Time) https://github.com/mjurfest/ios-xcode-snippets/blob/master/8C458AD7-C631-457B-85CC-D2501E425D59.codesnippet

#ios #swift #howto #appdevelopment #apps
star

Sun Dec 29 2019 19:42:22 GMT+0000 (Coordinated Universal Time) https://kodestat.gitbook.io/flutter/flutter-hello-world

#android #dart #flutter #ios #helloworld
star

Fri Dec 27 2019 10:53:20 GMT+0000 (Coordinated Universal Time) https://gist.github.com/artemnovichkov/de5bd4daf64441c724a429d1a9b1e26e

#ios #swift
star

Wed Dec 25 2019 19:31:47 GMT+0000 (Coordinated Universal Time) https://medium.com/better-programming/helpful-code-snippets-for-ios-21aa5ef894de

#ios #swift #question #apps #makethisbetter
star

Wed Dec 25 2019 19:27:50 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/24007518/how-can-i-use-timer-formerly-nstimer-in-swift

#ios #swift #apps #howto
star

https://developer.apple.com/documentation/uikit/uibutton

#ios #swift
star

https://stackoverflow.com/questions/3339722/how-to-check-ios-version

#ios #swift
star

https://stackoverflow.com/questions/17678881/how-to-change-status-bar-text-color-in-ios

#ios #swift

Save snippets that work with our extensions

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