Snippets Collections
Entrepreneurs choose crypto exchange scripts because they offer a fast, cost-effective, and customizable way to launch a cryptocurrency trading platform. These ready-made solutions come with essential features like trading engines, wallet integration, security modules, and admin dashboards—helping startups avoid the complexity of building from scratch. With reduced development time, lower investment costs, and scalable architecture, crypto exchange scripts are the ideal choice for entrepreneurs looking to enter the crypto market quickly and efficiently.

Dreaming of launching a cryptocurrency exchange? With Opris Cryptocurrency Exchange Development Services, you can bring that dream to life with a secure, scalable, and fully customizable platform that stands out in the crypto world.

🔹 Centralized & Decentralized Exchange Development
🔹 P2P & OTC Trading Solutions
🔹 Seamless Wallet Integration & Multi-Currency Support
🔹 High-Speed Order Matching Engine
🔹 Advanced Security Features – Protect Your Users
🔹 Regulatory Compliance – Expand Globally

Your exchange, your rules. Don’t miss out on the next big thing in crypto! 💡
With a massive $14B+ weekly trading volume and a 58.04% growth surge, PancakeSwap has officially overtaken Uniswap as the leading decentralized exchange!

What’s driving its success? High liquidity & smooth trading Low fees & ultra-fast transactions Strong community-driven ecosystem

Looking to build a decentralized exchange like PancakeSwap? Contact Opris Decentralized Exchange Development Company and launch your own DEX today!
Dappfort specializes in BRC20 wallet development, providing businesses with a secure, scalable, and budget-friendly solution for managing BRC-20 tokens. Our development process focuses on optimizing costs while ensuring high security, seamless user experience, and robust functionality.

Key Features:

Affordable Development – Cost-effective solutions tailored to your business needs. 
Secure Asset Management – Advanced encryption and multi-signature security. 
Seamless Transactions – Fast and efficient token transfers on the Bitcoin blockchain. 
User-Friendly Interface – Intuitive design for hassle-free access. 
Scalability & Customization – Adaptable to evolving market demands.

At Dappfort, we ensure your BRC20 wallet is built with cutting-edge technology while keeping development costs under control.

Get in touch to develop a cost-effective BRC20 wallet today!

Instant Reach Experts: 
Visit us : https://www.dappfort.com/cryptocurrency-wallet-development-company/ 
Contact : +91 8838534884 
Mail : sales@dappfort.com
import Subsonic
import SwiftUI

struct ContentView: View {
    let names = ["Jingle", "Mathys"]
    
    var body: some View {
        NavigationView {
            ScrollView{
                
                    ForEach(names, id: \.self) {name in
                        Button {
                            play(sound: "\(name).m4a")
                        } label: {
                            Image(name)
                                .resizable()
                                .scaledToFit()
                                .cornerRadius(25)
                                .padding(.horizontal)
                        }
                        
                    }
            }
            .navigationTitle("Friend Smile")
        }
        .navigationViewStyle(.stack)
    }
}
URLSession.shared
    .dataTaskPublisher(for: URL(string: "https://picsum.photos/300/600")!)
    .map(\.data)
    .compactMap(UIImage.init)

    /// Schedule to receive the sink closure on the
    /// main dispatch queue.
    .receive(on: DispatchQueue.main, options: nil)
    
    .sink { _ in
        print("Image loading completed")
    } receiveValue: { image in
        self.image = image
    }.store(in: &cancellables)
Purchases.shared.delegate = self

extension YourClass: PurchasesDelegate {
    func purchases(_ purchases: Purchases, receivedUpdated customerInfo: Purchases.CustomerInfo) {
        if let entitlement = customerInfo.entitlements["your_entitlement_id"] {
            if entitlement.isActive == false {
                // subscription has expired
                print("Subscription has expired")
            } else {
                // subscription is active
                print("Subscription is active")
            }
        }
    }
}
let fetchRequest: NSFetchRequest<UserModel_CD> = UserModel_CD.fetchRequest()
//Query on which basic data will be found from coreData
fetchRequest.predicate = NSPredicate(format: "email == %@ && password == %@", email, password)  

//This query in SQl looks like -
//SELECT * FROM Users WHERE email = 'user@example.com' AND password = 'password123';
        
do {
	let fetchedData = try viewContext.fetch(fetchRequest)
	return fetchedData.count > 0
} catch {
	return false
}
//'weak' must not be applied to non-class-bound 'any ListNotesDelegate'; consider adding a protocol conformance that has a class bound

//Whenever we want to create a weak reference the parent of object must conform to a class like AnyObject or UILabel etc.

//Example - 1

@IBOutlet weak private var titleLbl: UILabel!  //Here UILabel is a class
  
//Example - 2

protocol ListNotesDelegate {
    func refreshNotes()
    func deleteNote(with id: UUID)
}  

var delegate: ListNotesDelegate?  //You cannot assign this as weak var 
  
//To define it as weak -

protocol ListNotesDelegate:AnyObject {//Here AnyObject is a type alias for multiple classes
    func refreshNotes()
    func deleteNote(with id: UUID)
}  

weak var delegate: ListNotesDelegate?
// Create a data model file
// -> Create entity and attributes
// -> Set the Codegen property of Entity as Manual/None
// -> Select the Entity, Under Editor -> Create NSManagedObject Classes

//Create a CoreDataManager file

import Foundation
import CoreData

final class CoreDataManager{
    
    static let shared = CoreDataManager(modelName: "UserModel_CD")
    let persistentContainer: NSPersistentContainer
    var viewContext: NSManagedObjectContext{
        return persistentContainer.viewContext
    }
    
    init (modelName: String){
        persistentContainer = NSPersistentContainer(name: modelName)
    }
    
    func load(completion: (() -> Void)? = nil) {
        persistentContainer.loadPersistentStores { (description, error) in
            guard error == nil else {
                fatalError(error!.localizedDescription)
            }
            completion?()
        }
    }
    
    func save(){
        if viewContext.hasChanges{
            do{
                try viewContext.save()
            }catch{
                print("Error While Saving Data !!!")
            }
        }
    }
    
}

//Inside App delegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch
  
        CoreDataManager.shared.load()
  
        return true
}

// Extension that is application specific !!! here the changes are made
extension CoreDataManager{
    //Perform Your CRUD Here !!!
    
    func createUser(with email: String, and password: String){
        let user = UserModel_CD(context: viewContext)
        user.email = email
        user.password = password
        
        do{
            try viewContext.save()
        }catch{
            print(error.localizedDescription)
        }
        
    }
    
    func getAllUser() -> [UserModel_CD]{
        
        do{
            return try viewContext.fetch(UserModel_CD.fetchRequest())
        }catch{
            print(error.localizedDescription)
            return []
        }
        
    }
    
    func updateUser(user: UserModel_CD, updatedUser: UserModel_CD){
        
        user.email = updatedUser.email
        user.password = updatedUser.password
        
        do{
            try viewContext.save()
        }catch{
            print(error.localizedDescription)
        }
        
    }
    
    func deleteUser(user: UserModel_CD){
        viewContext.delete(user)
    }
    
}

//access this method like - CoreDataManager.shared.create()
//Here is signleton - that means you can create an object of a class outside it

class singleton{
  
  static let shared = singleton()
  init(){} //(Optional to do it or not)
  
  let temp = 5

}

//Usage

viewDidLoad(){
  let num = singleton.shared.temp
  
  //but also you can create object
  let obj = singleton()
  let num = obj.temp
}


//Here is Signleton - that means you cannot create an object of a class outside it

class Singleton{
  
  static let shared = singleton()
  private init(){} //(Optional to do it or not)
  
  let temp = 5

}

//Usage

viewDidLoad(){
  let num = singleton.shared.temp
  
  //but you cannot create object
  //let obj = singleton()
  //let num = obj.temp
}
import StoreKit

//inside viewController
let productId = "your_product_id"


//Action where you want to trigger the purchase
@IBAction func btn_OneTimeButtonClicked(_ sender: UIButton) {
	if SKPaymentQueue.canMakePayments(){
		let paymentRequest = SKMutablePayment()
		paymentRequest.productIdentifier = productId
		SKPaymentQueue.default().add(paymentRequest)
	}
}

//extension to handle the transaction states

extension your_View_Controller: SKPaymentTransactionObserver{
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        transactions.forEach { transaction in
            switch transaction.transactionState{
            case .purchasing:
                print("purchasing now ...")
            case .purchased:
                print("purchase successful !!!")
            case .failed:
                print("purchase failed !!!")
            case .restored:
                print("purchase restored !!!")
            case .deferred:
                print("purchase deferred !!!")
            @unknown default:
                print("Unknown error")
            }
        }
    }
}

// don't forgot to add storekit configuration file in your app if you are testing your app in simulator

import UIKit

struct Utility{
    
    static func setCornerRadius(to anyObject: AnyObject,_ cornerRadius: CGFloat, _ borderWidth: CGFloat, _ borderColor: UIColor){
        anyObject.layer.cornerRadius = cornerRadius
        anyObject.layer.borderWidth = borderWidth
        anyObject.layer.borderColor = borderColor.cgColor
    }
    
}
File -> Workspace Setting -> Derived Data
import UIKit
import PDFKit
import SVProgressHUD

class PdfViewController: UIViewController {
    
    @IBOutlet weak var dummyPdfView: UIView!
    
    @IBOutlet weak var courseLAbel: UILabel!
    
    var pdfView : PDFView!
    
    var pdfString = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setPDF()
    }
    
    func setPDF() {
        
        SVProgressHUD.show(withStatus: "Loading...")

        DispatchQueue.global(qos: .background).async {
            if let pdfURL = URL(string: self.pdfString), let pdfDocument = PDFDocument(url: pdfURL) {
                DispatchQueue.main.async {
                    // Create and configure the PDFView on the main thread
                    let newPDFView = PDFView(frame: self.dummyPdfView.bounds)
                    newPDFView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                    self.dummyPdfView.addSubview(newPDFView)
                    
                    // Set properties and assign document to PDFView
                    newPDFView.autoScales = true
                    newPDFView.displayDirection = .vertical
                    newPDFView.displayMode = .singlePageContinuous
                    newPDFView.document = pdfDocument
                    
                    SVProgressHUD.dismiss()
                }
            } else {
                DispatchQueue.main.async {
                    SVProgressHUD.showError(withStatus: "Failed to load PDF")
                }
            }
        }
    }
    
    @IBAction func backButtonPressed(_ sender: Any) {
        SVProgressHUD.dismiss()
        self.dismiss(animated: true)
    }
}
import AVFoundation
var bombSoundEffect: AVAudioPlayer?

func playSound(note: String) {
        let path = Bundle.main.path(forResource: note+".wav", ofType:nil)!
        let url = URL(fileURLWithPath: path)

        do {
            bombSoundEffect = try AVAudioPlayer(contentsOf: url)
            bombSoundEffect?.play()
        } catch {
            // couldn't load file :(
        }
    }
// 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 SwiftUI

struct ContentView: View {
    private let userDefaults = UserDefaults.standard
    private let COLOR_KEY = "COLOR_KEY"
    @State var selectedColor: Color = .purple
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                RoundedRectangle(cornerRadius: 20)
                    .fill(selectedColor)
                    .frame(height: 240)
                    .overlay {
                        Text("Red")
                            .font(.system(.title))
                            .foregroundColor(.white)
                    }
                
                Button {
                    saveColor(color: selectedColor)
                } label: {
                    Text("Save Color")
                        .frame(maxWidth: .infinity)
                        .font(.system(.headline, design: .rounded))
                }
                .padding()
                .frame(maxWidth: .infinity)
                .foregroundColor(.white)
                .background(selectedColor)
                .cornerRadius(10)
                
                Spacer()
            }
            .padding()
            .navigationBarTitle("Save Color", displayMode: .inline)
            .navigationBarItems(trailing: ColorPicker("", selection: $selectedColor))
            .onAppear {
                selectedColor = loadColor()
            }
        }
    }
    
    // Save Color
    func saveColor(color: Color) {
        let color = UIColor(color).cgColor
        
        if let components = color.components {
            userDefaults.set(components, forKey: COLOR_KEY)
            print("Save Color: \(components)")
        }
    }
    
    // Load Color
    func loadColor() -> Color {
        guard let array = userDefaults.object(forKey: COLOR_KEY) as? [CGFloat] else {
            return Color.purple
        }
        print("Load Color: \(array)")
        
        let color = Color(.sRGB, red: array[0], green: array[1], blue: array[2], opacity: array[3])
        return color
    }
}
import SwiftUI

struct ThreeColorView: View {
    static let red_x: CGFloat = UIScreen.main.bounds.width/2
    static let red_y: CGFloat = UIScreen.main.bounds.height/3
    
    @State private var redPosition: CGPoint = .init(x: red_x, y: red_y)
    
    @State private var greenPosition: CGPoint = .init(x: red_x - 30, y: red_y + 60)
    
    @State private var bluePosition: CGPoint = .init(x: red_x + 30, y: red_y + 60)
    
    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()
            
            Circle()
                .fill(Color(.systemRed))
                .frame(width: 200, height: 200)
                .position(redPosition)
                .gesture(
                    DragGesture()
                        .onChanged({ value in
                            redPosition = value.location
                        })
                )
            Circle()
                .fill(Color(.systemGreen))
                .frame(width: 200, height: 200)
                .position(greenPosition)
                .gesture(
                    DragGesture()
                        .onChanged({ value in
                            greenPosition = value.location
                        })
                )
                .blendMode(.lighten)
            
            Circle()
                .fill(Color(.systemBlue))
                .frame(width: 200, height: 200)
                .position(bluePosition)
                .gesture(
                    DragGesture()
                        .onChanged({ value in
                            bluePosition = value.location
                        })
                )
                .blendMode(.lighten)
        }
    }
}
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)
    }
let context = UICollectionViewFlowLayoutInvalidationContext()
context.invalidateSupplementaryElements(ofKind: UICollectionView.elementKindSectionHeader, at: [IndexPath(row: 0, section: 0)])
friendsListTableView.collectionViewLayout.invalidateLayout(with: context)
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
    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
    }
}
ScrollViewReader { proxy in
    ScrollView(.horizontal, showsIndicators: false) {
        HStack { // or LazyHStack
            ForEach(0..<items.count) { index in
                Text(items[index].title)
                    .id(index)
                    .onTapGesture {
                        print("tapped \(index)")
                    }
            }
        }
        .onAppear {
            DispatchQueue.main.async { 
                proxy.scrollTo(selectedIndex, anchor: .center)
            }
        }
    }
}
  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
        }
// Capítulo 5: Actualización y eliminación de datos en CoreData

// Para actualizar y eliminar objetos en CoreData utilizando SwiftUI, podemos utilizar el contexto de CoreData. A continuación se muestra:

Button("Update") {
    let request: NSFetchRequest<Product> = Product.fetchRequest()
    request.predicate = NSPredicate(format: "name == %@", "iPhone")
    
    do {
        let products = try context.fetch(request)
        if let product = products.first {
            product.price = 899.99
            try context.save()
        }
    } catch {
        print(error.localizedDescription)
    }
}

Button("Delete") {
    let request: NSFetchRequest<Product> = Product.fetchRequest()
    request.predicate = NSPredicate(format: "name == %@", "iPhone")
    
    do {
        let products = try context.fetch(request)
        if let product = products.first {
            context.delete(product)
            try context.save()
        }
    } catch {
        print(error.localizedDescription)
    }
}
//Para crear nuevas instancias de objetos y guardarlas. en la base de datos, podemos utilizar el contexto de CoreData. A continuación  se muestra un ejemplo de como crear una nueva instancia de objetos y guardarla en la base de datos:
Button("Save") {
     let product = Product(context: context)
     product.name = "iPhone"
     product.price = 999.99
           do {
               try! context.save() //guardar los datos en la base de datos de forma permanente...
            } catch {
                        print(error.localizedDescription)
         }
}
//Capítulo 4: Uso de CoreData con SwiftUI
//Para recuperar y mostrar datos utilizando las vistas de SwiftUI, podemos utilizar la clase FetchRequest. A continuación se muestra un ejemplo de cómo utilizar FetchRequest para recuperar datos de CoreData:
struct ProductList: View {
          @Environment(\.managedObjectContext) var context
          @FetchRequest(entity: Product.entity(), sortDescriptors: [])
          var products: FetchedResults<Product>
          var body: some View {
                  List(products, id: \.self) { product in
                                Text(product.name)
                      }
              }
      }
/*A continuación, debemos agregar nuestro modelo de datos a ese contenedor. A continuación se muestra un ejemplo de cómo agregar un modelo de datos a un contenedor de persistencia:*/
let container = NSPersistentContainer(name: "MyApp")
let description = NSPersistentStoreDescription()
description.type = NSInMemoryStoreType
container.persistentStoreDescriptions = [description]
try! container.loadPersistentStores()
//Por último, debemos inicializar el almacén de datos. A continuación se muestra un ejemplo de cómo inicializar el almacén de datos:    
let context = persistentContainer.viewContext
/*Capítulo 3: Configuración de CoreData
Para configurar CoreData, primero debemos crear un contenedor de persistencia. A continuación se muestra un ejemplo de cómo crear un contenedor de persistencia en un archivo AppDelegate.swift:*/

lazy var persistentContainer: NSPersistentContainer = {
          let container = NSPersistentContainer(name: "MyApp")
       container.loadPersistentStores(completionHandler: { (storeDescription, error) in
       if let error = error as NSError? {
                              fatalError("Unresolved error \(error), \(error.userInfo)")
                     }
           })
                       return container
  }()
//También podemos crear nuestro modelo de datos mediante código. A continuación, se muestra un ejemplo de cómo crear una clase modelo de entidad de CoreData mediante código:

import CoreData

class Product: NSManagedObject {
    @NSManaged var name: String
    @NSManaged var price: Double
}

let productEntity = NSEntityDescription.entity(forEntityName: "Product", in: context)!
let product = Product(entity: productEntity, insertInto: context)
product.name = "iPhone"
product.price = 999.99
//Capítulo 2: Diseño de modelo de datos en CoreData

//Podemos crear nuestro modelo de datos utilizando el editor de modelo visual de Xcode. A continuación se muestra un ejemplo de cómo se ve una clase modelo de entidad de CoreData en el editor de modelo visual:

class Product: NSManagedObject {
    @NSManaged var name: String
    @NSManaged var price: Double
}
// Install via Swift Package Manager:
// dependencies: [
//   .package(url: "https://github.com/transloadit/TransloaditKit", .upToNextMajor(from: "3.0.0"))
// ]}

// Auth
let credentials = Credentials(key: "YOUR_TRANSLOADIT_KEY")

// Init
let transloadit = Transloadit(credentials: credentials, session: "URLSession.shared")

// Add files to upload
let filesToUpload: [URL] = ...

// Execute
let assembly = transloadit.assembly(steps: [_originalStep, resizedStep, optimizeStep, exportedStep], andUpload: filesToUpload) { result in
  switch result {
  case .success(let assembly):
    print("Retrieved (assembly)")
  case .failure(let error):
    print("Assembly error (error)")
  }
}.pollAssemblyStatus { result in
  switch result {
  case .success(let assemblyStatus):
    print("Received assemblystatus (assemblyStatus)")
  case .failure(let error):
    print("Caught polling error (error)")
  }
    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)"
        }
    }
//
//  SearchableDemo.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/2/17.
//

import SwiftUI

struct NavigtionViewDemo: View {
    var body: some View {
        NavigationStack {
            List {
                NavigationLink("我的组件") {
                    MyCompView()
                }
                
                NavigationLink("我的API") {
                    MyApiView()
                }
            }
            .navigationTitle("配置中心")
            .navigationBarTitleDisplayMode(.inline)
            .listStyle(PlainListStyle())
        }
    }
}

struct MyCompView: View {
    
    var body: some View {
        NavigationStack {
            List {
                NavigationLink(destination: ArticleCompView()) {
                    Text("文章组件")
                }
                NavigationLink(destination: PhotoCompView()) {
                    Text("图片组件")
                }
                NavigationLink(destination: ChartCompView()) {
                    Text("报表组件")
                }
            }
            .listStyle(PlainListStyle())
            .navigationBarTitle("我的组件", displayMode: .inline)
            .navigationBarItems(trailing: AddCompButtonView())
        }
    }
}

struct MyApiView: View {
    
    var body: some View {
        NavigationStack {
            List {
                NavigationLink(destination: ArticleApiView()) {
                    Text("文章API")
                }
                NavigationLink(destination: PhotoApiView()) {
                    Text("图片API")
                }
                NavigationLink(destination: ChartApiView()) {
                    Text("报表API")
                }
            }
            .listStyle(PlainListStyle())
            .navigationBarTitle("我的API", displayMode: .inline)
            .navigationBarItems(trailing: AddApiButtonView())
        }
    }
}

struct ArticleCompView: View {
    var body: some View {
        NavigationStack {
            Text("文章组件信息")
                .navigationTitle("文章组件信息")
        }
    }
}

struct PhotoCompView: View {
    var body: some View {
        NavigationStack {
            Text("照片组件信息")
                .navigationTitle("照片组件信息")
        }
    }
}

struct ChartCompView: View {
    var body: some View {
        NavigationStack {
            Text("报表组件信息")
                .navigationTitle("报表组件信息")
        }
    }
}

struct ArticleApiView: View {
    var body: some View {
        NavigationStack {
            Text("文章API")
                .navigationTitle("文章API")
        }
    }
}

struct PhotoApiView: View {
    var body: some View {
        NavigationStack {
            Text("照片API")
                .navigationTitle("照片API")
        }
    }
}

struct ChartApiView: View {
    var body: some View {
        NavigationStack {
            Text("报表API")
                .navigationTitle("报表API")
        }
    }
}

struct AddCompButtonView: View {
    var body: some View {
        NavigationStack {
            NavigationLink(destination: AddCompView()) {
                Image(systemName: "plus")
            }
        }
    }
}

struct AddApiButtonView: View {
    var body: some View {
        NavigationStack {
            NavigationLink(destination: AddApiView()) {
                Image(systemName: "plus")
            }
        }
    }
}

struct AddCompView: View {
    var body: some View {
        NavigationStack {
            ZStack {
                Color.orange
                Text("创建组件页面")
            }
            .navigationTitle("创建组件页面")
        }
    }
}

struct AddApiView: View {
    var body: some View {
        ZStack {
            Color.purple
            Text("创建API页面")
        }
    }
}

struct SearchableDemo_Previews: PreviewProvider {
    static var previews: some View {
        NavigtionViewDemo()
    }
}
//
//  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")
        }
    }
//
//  DragView.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/2/12.
//

import SwiftUI

struct DragView: View {
    @State private var location: CGPoint = CGPoint(x: 50, y: 50)
    @GestureState private var fingerLocation: CGPoint? = nil
    @GestureState private var startLocation: CGPoint? = nil // 1
    
    var simpleDrag: some Gesture {
        DragGesture()
            .onChanged { value in
                var newLocation = startLocation ?? location // 3
                newLocation.x += value.translation.width
                newLocation.y += value.translation.height
                self.location = newLocation
            }.updating($startLocation) { (value, startLocation, transaction) in
                startLocation = startLocation ?? location // 2
            }
    }
    
    var fingerDrag: some Gesture {
        DragGesture()
            .updating($fingerLocation) { (value, fingerLocation, transaction) in
                fingerLocation = value.location
            }
    }
    
    var body: some View {
        VStack {
            ZStack {
                RoundedRectangle(cornerRadius: 10)
                    .foregroundColor(.pink)
                    .frame(width: 100, height: 100)
                    .position(location)
                    .gesture(
                        simpleDrag.simultaneously(with: fingerDrag)
                    )
                if let fingerLocation = fingerLocation {
                    Circle()
                        .stroke(Color.green, lineWidth: 2)
                        .frame(width: 44, height: 44)
                        .position(fingerLocation)
                }
            }
            HStack {
                Text("X:\(String(format: "%0.f", location.x))")
                    .foregroundColor(.indigo)
                    .font(.system(.largeTitle, design: .rounded))
                Text("Y:\(String(format: "%0.f", location.y))")
                    .foregroundColor(.indigo)
                    .font(.system(.largeTitle, design: .rounded))
            }
        }
    }
}

struct DragView_Previews: PreviewProvider {
    static var previews: some View {
        DragView()
    }
}
//
//  DeviceInfoView.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/2/12.
//

import SwiftUI

struct DeviceInfoView: View {
    let screenSize: CGSize = UIScreen.main.bounds.size
    let device: UIDevice = UIDevice.current
    
    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("屏幕宽度:\(screenSize.width)")    // 屏幕宽度:430.000000
            Text("屏幕高度:\(screenSize.height)")   // 屏幕高度:932.000000
            Text("设备名称:\(device.name)")         // 设备名称:iPhone 14 Pro Max
            Text("系统名称:\(device.systemName)")   // 系统名称:iOS
            Text("系统版本:\(device.systemVersion)")// 系统版本:16.2
            Text("设备型号:\(device.model)")        // 设备型号:iPhone
        }
        .padding()
        .background(.orange)
        .cornerRadius(10)
    }
}

struct DeviceInfoView_Previews: PreviewProvider {
    static var previews: some View {
        DeviceInfoView()
    }
}
//
//  SwiftUIDemoApp.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/1/29.
//

import SwiftUI

@main
struct LifeCycleApp: App {
    // 场景阶段环境变量
    @Environment(\.scenePhase) var scenePhase
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase) { phase in
            switch phase {
            case .background:
                // 应用在后台运行状态
                print("background")
            case .inactive:
                // 应用处于不活动状态
                print("inactive")
            case .active:
                // 应用处于活动状态
                print("active")
            @unknown default:
                // 应用处于默认状态
                print("default")
            }
        }
    }
}
//
//  RotationTextViewDemo.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/2/9.
//

import SwiftUI

struct SealViewDemo: View {
    let textArr: [String] = "北京百度网讯科技有限公司".map({String($0)})
    @State var textSize: Double = 30.0
    @State var circleLineWidth: Double = 7.0
    @State var circleRadius: CGFloat = 233
    @State var textCircleRadius: CGFloat = 90
    @State var starSize: Double = 50.0
    @State var rotationDegress: Double = 20
    @State var firstTextPox: Double = 110
    
    init() {
        // 每个字的旋转角度 = 第一个字的旋转角度的两倍/文字个数
        self.rotationDegress = 110*2.0/Double(textArr.count)
    }
    
    var body: some View {
        ZStack {
            Color.white.edgesIgnoringSafeArea(.all)
            
            VStack {
                ZStack {
                    Circle()
                        .stroke(.red, lineWidth: circleLineWidth)
                        .frame(width: circleRadius)
                    
                    ForEach(0..<textArr.count) { index in
                        RoundTextView(
                            text: textArr[index],
                            foregroundColor: .red,
                            degrees: getDegress(firstTextPox: firstTextPox,
                                                rotationDegress: rotationDegress,
                                                index: index),
                            textSize: $textSize,
                            textCircleRadius: $textCircleRadius)
                    }
                    
                    Image(systemName: "star.fill")
                        .resizable()
                        .frame(width: starSize, height: starSize)
                        .foregroundColor(.red)
                }
                
                
                VStack(alignment: .leading) {
                    VStack(alignment: .leading) {
                        Text("文字大小:\(String(format: "%.2f", textSize))")
                            .font(.system(.headline))
                        Slider(value: $textSize, in: 20...50, step: 1)
                        
                        Text("圆环宽度:\(String(format: "%.2f", circleLineWidth))")
                            .font(.system(.headline))
                        Slider(value: $circleLineWidth, in: 1...30, step: 1)
                        
                        Text("圆环半径:\(String(format: "%.2f", circleRadius))")
                            .font(.system(.headline))
                        Slider(value: $circleRadius, in: 200...300, step: 1)
                        Text("文字圆环半径:\(String(format: "%.2f", textCircleRadius))")
                            .font(.system(.headline))
                        Slider(value: $textCircleRadius, in: 50...150, step: 1)
                    }
                    
                    VStack(alignment: .leading) {
                        Text("五角星大小:\(String(format: "%.2f", starSize))")
                            .font(.system(.headline))
                        Slider(value: $starSize, in: 20...80, step: 1)
                        
                        Text("文字间距:\(String(format: "%.2f", rotationDegress))")
                            .font(.system(.headline))
                        Slider(value: $rotationDegress, in: 15...60, step: 1)
                        
                        Text("首字位置:\(String(format: "%.2f", firstTextPox))")
                            .font(.system(.headline))
                        Slider(value: $firstTextPox, in: 90...150, step: 1)
                    }
                    
                }
            }
            .padding()
        }
    }
}

struct RotationTextViewDemo_Previews: PreviewProvider {
    static var previews: some View {
        SealViewDemo()
    }
}

// 获取当前文字的旋转角度
func getDegress(firstTextPox: Double, rotationDegress: Double, index: Int) -> Double {
    // 首字旋转角度 + 该字的索引 * 每个字的旋转角度
    return -firstTextPox + Double(index) * rotationDegress
}

struct RoundTextView: View {
    var text: String
    var foregroundColor: Color
    var degrees: Double
    @Binding var textSize: Double
    @Binding var textCircleRadius: CGFloat
    
    var body: some View {
        Text(text)
            .font(.system(size: textSize))
            .offset(y: -textCircleRadius)
            .foregroundColor(foregroundColor)
            .rotationEffect(Angle(degrees: degrees))
    }
}
//
//  MeasureSizeView.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/2/8.
//

import SwiftUI

// 获取视图的尺寸
struct MeasureSizeView: View {
    // 视图的宽度
    @State private var viewWidth: Double = 0
    
    var body: some View {
        VStack {
            // 获取文本视图的宽度
            Text("Hello, World!")
                .measureSize { size in
                    viewWidth = size.width
                }
            // 展示文本视图的宽度
            Text(viewWidth, format: .number)
        }
    }
}

struct MeasureSizeView_Previews: PreviewProvider {
    static var previews: some View {
        MeasureSizeView()
    }
}

// 自定义视图尺寸修改器
struct MeasureSizeModifer: ViewModifier {
    let callback: (CGSize) -> Void
    
    func body(content: Content) -> some View {
        content
            .background {
                // 通过几何阅读器获取视图的尺寸
                GeometryReader { proxy in
                    Color.clear
                        .onAppear {
                            callback(proxy.size)
                        }
                }
            }
    }
}

extension View {
    // 自定义获取视图尺寸的修饰符
    func measureSize(_ callback: @escaping (CGSize) -> Void) -> some View {
        modifier(MeasureSizeModifer(callback: callback))
    }
}
//
//  SelectBackgroundColorView.swift
//  ApiBox
//
//  Created by shiyanjun on 2023/2/6.
//

import SwiftUI

// 视图模型类
class SelectColorViewModel: ObservableObject {
    // 记录当前用户选中的颜色,默认值白色
    @Published var selectColor: Color = .white
}

struct SelectBackgroundColorView: View {
    // 是否显示滑窗,默认不显示
    @State var showSheet: Bool = false
    // 注入视图模型实例
    @EnvironmentObject var vm: SelectColorViewModel
    
    var body: some View {
        ZStack {
            // 用户设置的背景色
            vm.selectColor
            VStack {
                Spacer()
                Button {
                    // 点击按钮展示滑窗让用户选择颜色
                    showSheet.toggle()
                } label: {
                    Text("设置背景色")
                        .frame(maxWidth: .infinity)
                        .frame(height: 45)
                        .foregroundColor(.white)
                        .background(.black)
                        .cornerRadius(10)
                }
                .sheet(isPresented: $showSheet) {
                    SheetView()
                }
                Spacer()
            }
            .padding()
        }
        .edgesIgnoringSafeArea(.all)
    }
}

// 底部滑窗
struct SheetView: View {
    // 注入视图模型实例
    @EnvironmentObject var vm: SelectColorViewModel
    // 用于关闭滑窗
    @Environment(\.presentationMode) private var presentationMode
    
    // 可供用户选择的颜色数组
    private let colors: [Color] = [.red, .green, .blue, .purple, .orange, .pink, .brown, .cyan, .teal]
    
    var body: some View {
        VStack {
            Text("请选择一种颜色")
                .font(.headline)
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .frame(height: 100)
            HStack {
                // 循环展示所有颜色供用户选择
                ForEach(colors, id: \.self) { color in
                    Button {
                        // 记住用户选中的颜色
                        vm.selectColor = color
                        // 关闭滑窗
                        presentationMode.wrappedValue.dismiss()
                    } label: {
                        Circle()
                            .frame(width: 30, height: 30)
                            .foregroundColor(color)
                            .overlay {
                                Circle()
                                // 用描边标识用户选中了该颜色
                                .stroke(.white, lineWidth: vm.selectColor == color ? 1 : 0)
                                // 用放大效果突出用户选的颜色
                                    .scaleEffect(vm.selectColor == color ? 1.2 : 1)
                            }
                    }
                }
            }
            Spacer()
        }
        .background(.black)
    }
}

struct SelectBackgroundColorView_Previews: PreviewProvider {
    static var previews: some View {
        SelectBackgroundColorView()
            .environmentObject(SelectColorViewModel())
    }
}
import UIKit
class PlaceHolderTextView:UITextView, UITextViewDelegate{
var placeholderText = "placeholderText"

override func willMove(toSuperview newSuperview: UIView?) {
    textColor = .lightText
    delegate = self
}

func textViewDidBeginEditing(_ textView: UITextView) {
    if textView.text == placeholderText{
        placeholderText = textView.text
        textView.text = ""
        textView.textColor = .darkText
    }
}

func textViewDidEndEditing(_ textView: UITextView) {
    if textView.text == ""{
        textView.text = placeholderText
        textColor = .lightText
    }
}    
}
SharedClass.sharedInstance.alert(view: self, title: "Your title here", message: "Your message here")
import UIKit
class SharedClass: NSObject {//This is shared class
static let sharedInstance = SharedClass()

    //Show alert
    func alert(view: UIViewController, title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        alert.addAction(defaultAction)
        DispatchQueue.main.async(execute: {
            view.present(alert, animated: true)
        })
    }

    private override init() {
    }
}
    @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"
        ]
        AppDelegate.signUpUrl = "https://vital-server.herokuapp.com/signup"
        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()
            }
    }

class RegistrationAPI: Codable {
    var message: String = ""
    var token: String = ""
    
    private enum CodingKeys: String, CodingKey {
        case token
        case message
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let token = try container.decodeIfPresent(String.self, forKey: .token) {
            self.token = token
        }
        if let message = try container.decodeIfPresent(String.self, forKey: .message) {
            self.message = message
        }
    }
}
//
//  ButtonText.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/2/1.
//

import SwiftUI

struct ButtonText: View {
    var body: some View {
        VStack {
            // 给文本设置圆角矩形背景
            Text("Hello!Hello!Hello!")
                .foregroundColor(.primary)
                .padding()
                .background(
                    Rectangle()
                        .fill(
                            // 线性渐变
                            LinearGradient(
                                gradient: Gradient(colors: [.red, .orange]),
                                startPoint: .leading,
                                endPoint: .trailing)
                        )
                        .cornerRadius(10)
                )
            // 给文本设置胶囊背景
            Text("Hello!Hello!Hello!")
                .foregroundColor(.primary)
                .padding()
                .background(
                    Capsule()
                        .fill(
                            // 角度渐变
                            AngularGradient(
                                gradient: Gradient(colors: [.red, .orange]),
                                center: .bottom
                            )
                        )
                        .cornerRadius(10)
                )
            // 给文本设置圆形背景
            Text("Hello!Hello!Hello!Hello!")
                .frame(width: 50, height: 50)
                .foregroundColor(.primary)
                .padding()
                .background(
                    Circle()
                        .fill(
                            // 角度渐变
                            AngularGradient(
                                gradient: Gradient(colors: [.red, .orange]),
                                center: .bottom,
                                angle: Angle(degrees: 0))
                        )
                        .cornerRadius(10)
                )
            
            
        }
    }
}

struct ButtonText_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            ButtonText()
        }
        .environment(\.colorScheme, .light)
    }
}
//
//  ButtonText.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/2/1.
//

import SwiftUI

struct ButtonText: View {
    var body: some View {
        VStack{
            // 给文本设置圆角矩形背景
            Text("Hello!Hello!Hello!")
                .foregroundColor(.primary)
                .padding()
                .background(
                    Rectangle()
                        .foregroundColor(Color.purple)
                        .cornerRadius(10)
                )
            // 给文本设置胶囊背景
            Text("Hello!Hello!Hello!")
                .foregroundColor(.primary)
                .padding()
                .background(
                    Capsule()
                        .foregroundColor(Color.purple)
                        .cornerRadius(10)
                )
            // 给文本设置圆形背景
            Text("Hello!Hello!Hello!Hello!")
                .frame(width: 50, height: 50)
                .foregroundColor(.primary)
                .padding()
                .background(
                    Circle()
                        .foregroundColor(Color.purple)
                        .cornerRadius(10)
                )
        }
    }
}

struct ButtonText_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            ButtonText()
        }
        .environment(\.colorScheme, .light)
    }
}
// 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)
    }
//
//  ContentView.swift
//  CoreDataMVVM
//
//  Created by shiyanjun on 2023/1/26.
//

import SwiftUI
import CoreData

// CoreData视图模型类,负责CoreData的增删改查
class CorDataViewModel: ObservableObject {
    // CoreData持久化容器对象
    let container: NSPersistentContainer
    // 存放水果的数组,用于展示水果列表
    @Published var savedEntitys: [FruitEntity] = []
    
    // 初始化
    init() {
        // 初始化CoreData持久化容器示例
        container = NSPersistentContainer(name: "FruitsContainer")
        container.loadPersistentStores { descreption, error in
            if let error = error {
                print("ERROR LOADING CORE DATA. \(error)")
            } else {
                print("Successfully loaded core data!")
            }
        }
        fetchFruits()
    }
    
    // 从CoreData数据库中加载水果列表
    func fetchFruits() {
        let request = NSFetchRequest<FruitEntity>(entityName: "FruitEntity")
        
        do {
            savedEntitys = try container.viewContext.fetch(request)
        } catch let error {
            print("Error fetching. \(error)")
        }
        
    }
    
    // 添加水果
    func addFruit(text: String) {
        let newFruit = FruitEntity(context: container.viewContext)
        newFruit.name = text
        saveData()
    }
    
    // 更新水果
    func updateFruit(entity: FruitEntity) {
        let currentName = entity.name ?? ""
        let newName = currentName + "!"
        entity.name = newName
        saveData()
    }
    
    // 删除水果
    func deleteFruit(indexSet: IndexSet) {
        guard let index = indexSet.first else { return }
        let entity = savedEntitys[index]
        container.viewContext.delete(entity)
        saveData()
    }
    
    // 公用保存方法
    func saveData() {
        do {
            try container.viewContext.save()
            fetchFruits()
        } catch let error {
            print("Error saving. \(error)")
        }
    }
}

// 应用的主页面
struct ContentView: View {
    // 创建CoreData视图模型实例
    @StateObject var vm = CorDataViewModel()
    // 记录用户输入的水果名称
    @State var textFieldText: String = ""
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                // 水果名称输入框
                TextField("Add fruit here...", text: $textFieldText)
                    .font(.headline)
                    .padding(.leading)
                    .frame(height: 55)
                    .background(Color(.gray).opacity(0.1))
                    .cornerRadius(10)
                    .padding(.horizontal)
                
                // 添加水果的按钮
                Button {
                    guard !textFieldText.isEmpty else { return }
                    vm.addFruit(text: textFieldText)
                    textFieldText = ""
                } label: {
                    Text("Submit")
                        .font(.headline)
                        .foregroundColor(.white)
                        .frame(height: 55)
                        .frame(maxWidth: .infinity)
                        .background(.pink)
                        .cornerRadius(10)
                }
                .padding(.horizontal)
                
                // 展示水果列表
                List {
                    ForEach(vm.savedEntitys) { entity in
                        Text(entity.name ?? "NO NAME")
                            .onTapGesture {
                                vm.updateFruit(entity: entity)
                            }
                    }
                    .onDelete(perform: vm.deleteFruit)
                }
                .listStyle(PlainListStyle())
            }
            .navigationTitle("Fruits")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
    func setScrollView() {
        let contentWidth = topPlayersTableView.layer.frame.width + 20
        scrollView.contentSize = CGSize(width: contentWidth, height: scrollView.frame.height)
        scrollView.isPagingEnabled = true
    }
//
//  ContentView.swift
//  SwiftUIDemo
//
//  Created by shiyanjun on 2023/1/21.
//

import SwiftUI

struct ContentView: View {
    let url = URL(string: "https://picsum.photos/300")
    
    var body: some View {
        VStack {
            // 异步加载图片
            AsyncImage(url: url) { phase in
                switch phase {
                case .empty:
                    ProgressView()
                        .frame(width: 300, height: 300)
                case .success(let image):
                    image
                        .resizable()
                        .scaledToFit()
                        .frame(width: 300, height: 300)
                        .cornerRadius(150)
                        .overlay {
                            Circle()
                                .stroke(lineWidth: 4)
                                .foregroundColor(.white)
                        }
                        .shadow(color: .black.opacity(0.2), radius: 2, x: 2, y: 2)
                case .failure:
                    Image(systemName: "questionmark")
                        .font(.headline)
                default:
                    Image(systemName: "questionmark")
                        .font(.headline)
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
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
    }
let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

let action = UIAlertAction(title: "OK", style: .default, handler: nil)

let imgTitle = UIImage(named:"imgTitle.png")
let imgViewTitle = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
imgViewTitle.image = imgTitle

alert.view.addSubview(imgViewTitle)
alert.addAction(action)

self.present(alert, animated: true, completion: nil)
                        .background(GeometryReader { gp -> Color in
                            let rect = gp.frame(in: .named("OuterV")) // < in specific container
                            // let rect = gp.frame(in: .global) // < in window
                            // let rect = gp.frame(in: .local) // < own bounds
                            print("Origin: \(rect.origin)")
                            return Color.clear
                        })
let value1 = try? data.toDictionary()
let value2 = try? data.to(type: [String: Any].self)
let value3 = try? data.to(type: [String: String].self)
let value4 = try? string.asJSONToDictionary()
let value5 = try? string.asJSON(to: [String: String].self)
import Foundation

// MARK: - CastingError

struct CastingError: Error {
    let fromType: Any.Type
    let toType: Any.Type
    init<FromType, ToType>(fromType: FromType.Type, toType: ToType.Type) {
        self.fromType = fromType
        self.toType = toType
    }
}

extension CastingError: LocalizedError {
    var localizedDescription: String { return "Can not cast from \(fromType) to \(toType)" }
}

extension CastingError: CustomStringConvertible { var description: String { return localizedDescription } }

// MARK: - Data cast extensions

extension Data {
    func toDictionary(options: JSONSerialization.ReadingOptions = []) throws -> [String: Any] {
        return try to(type: [String: Any].self, options: options)
    }

    func to<T>(type: T.Type, options: JSONSerialization.ReadingOptions = []) throws -> T {
        guard let result = try JSONSerialization.jsonObject(with: self, options: options) as? T else {
            throw CastingError(fromType: type, toType: T.self)
        }
        return result
    }
}

// MARK: - String cast extensions

extension String {
    func asJSON<T>(to type: T.Type, using encoding: String.Encoding = .utf8) throws -> T {
        guard let data = data(using: encoding) else { throw CastingError(fromType: type, toType: T.self) }
        return try data.to(type: T.self)
    }

    func asJSONToDictionary(using encoding: String.Encoding = .utf8) throws -> [String: Any] {
        return try asJSON(to: [String: Any].self, using: encoding)
    }
}

// MARK: - Dictionary cast extensions

extension Dictionary {
    func toData(options: JSONSerialization.WritingOptions = []) throws -> Data {
        return try JSONSerialization.data(withJSONObject: self, options: options)
    }
}
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)
        )
    }

import Foundation
import SwiftUI

class AirConditionerViewModel: ObservableObject {
    
    enum AirConditionerMode: String, CaseIterable, Identifiable {
        case cool = "Cool"
        case heat = "Heat"
        var id: Self { self }
    }
    
    enum FanSpeed: String, CaseIterable, Identifiable {
        case low = "Low"
        case medium = "Medium"
        case high = "High"
        var id: Self { self }
    }
    
    let minTemperature = 60.0
    let maxTemperature = 100.0
    
    @Published var airConditionerIsOn = false
    @Published var airConditionerMode: AirConditionerMode = .cool
    @Published var currentTemperature = 75.0
    @Published var desiredTemperature = 80.0
    @Published var fanIsOn = false
    @Published var fanSpeed: FanSpeed = .low
    
}
import SwiftUI

struct AirConditionerView: View {
    
    @ObservedObject var viewModel: AirConditionerViewModel
    @FocusState var tempTextFieldIsFocused: Bool
    
    var body: some View {
        VStack(spacing: 15) {
            // MARK: - 1. Power Toggle
            Toggle("Power", isOn: $viewModel.airConditionerIsOn)
            
            // MARK: - 2. AC Mode picker
            HStack {
                Text("Mode")
                Picker("Mode", selection: $viewModel.airConditionerMode) {
                    ForEach(AirConditionerViewModel.AirConditionerMode.allCases) { mode in
                        Text(mode.rawValue)
                    }
                }.pickerStyle(.segmented)
            }.disabled(!viewModel.airConditionerIsOn)
            
            // MARK: - 3. Temperature text field
            HStack {
                Text("Temperature")
                TextField("", value: $viewModel.desiredTemperature, formatter: NumberFormatter())
                    .padding(.leading)
                    .border(.primary)
                    .focused($tempTextFieldIsFocused)
            }.disabled(!viewModel.airConditionerIsOn)
            
            // MARK: - 4. Temperature slider
            Slider(value: $viewModel.desiredTemperature,
                   in: viewModel.minTemperature...viewModel.maxTemperature,
                   onEditingChanged: { editing in
                if editing {
                    tempTextFieldIsFocused = false
                }
            }).disabled(!viewModel.airConditionerIsOn)
            
            // MARK: - 5. Fan power toggle
            Toggle("Fan", isOn: $viewModel.fanIsOn)
                .disabled(!viewModel.airConditionerIsOn)
            
            // MARK: - 6. Fan speed picker
            HStack {
                Text("Fan Speed")
                Spacer()
            }.disabled(!viewModel.airConditionerIsOn)
            Picker("Mode", selection: $viewModel.fanSpeed) {
                ForEach(AirConditionerViewModel.FanSpeed.allCases) { speed in
                    Text(speed.rawValue)
                }
            }
                .pickerStyle(.segmented)
                .disabled(!viewModel.airConditionerIsOn)
            
            // MARK: - 7. AC status Images
            HStack {
                switch viewModel.airConditionerMode {
                case .cool:
                    Image("snowflake")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 150, height: 150)
                case .heat:
                    Image("heating")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 150, height: 150)
                }
                
                if viewModel.fanIsOn {
                    VStack {
                        Image("fan")
                            .resizable()
                            .scaledToFit()
                            .frame(width: 100, height: 100)
                        switch viewModel.fanSpeed {
                        case .low:
                            Text("1x")
                        case .medium:
                            Text("2x")
                        case .high:
                            Text("3x")
                        }
                    }
                    .frame(width: 150, height: 150)
                } else {
                    Rectangle()
                        .foregroundColor(.clear)
                        .frame(width: 150, height: 150)
                }
            }
            
            // MARK: - 8. Progress Bar
            HStack {
                VStack {
                    Text("Current")
                    Text(String(format: "%.2f", viewModel.currentTemperature))
                        .frame(width: 50, height: 5)
                }
                
                ProgressView(value: viewModel.currentTemperature, total: viewModel.desiredTemperature)
                    .scaleEffect(x: 1, y: 5, anchor: .center)
                
                VStack {
                    Text("Goal")
                    Text(String(format: "%.2f", viewModel.desiredTemperature))
                        .frame(width: 50, height: 5)
                }
            }
        }
    }
}
// MARK: - UNUserNotificationCenterDelegate

extension AppDelegate: UNUserNotificationCenterDelegate {
  func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
  ) {
    // 1
    let userInfo = response.notification.request.content.userInfo
    
    // 2
    if 
      let aps = userInfo["aps"] as? [String: AnyObject],
      let newsItem = NewsItem.makeNewsItem(aps) {
      (window?.rootViewController as? UITabBarController)?.selectedIndex = 1
      
      // 3
      if response.actionIdentifier == Identifiers.viewAction,
        let url = URL(string: newsItem.link) {
        let safari = SFSafariViewController(url: url)
        window?.rootViewController?
          .present(safari, animated: true, completion: nil)
      }
    }
    
    // 4
    completionHandler()
  }
}
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()
    }
override func viewDidLoad() {
    super.viewDidLoad()

    myTbleView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    myTbleView.removeObserver(self, forKeyPath: "contentSize")
    super.viewWillDisappear(true)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if(keyPath == "contentSize"){
        if let newvalue = change?[.newKey]
        {
            let newsize  = newvalue as! CGSize
           tableViewHeightConstraint.constant = newsize.height
        }
    }
}
extension NSMutableAttributedString {
    var fontSize:CGFloat { return 14 }
    var boldFont:UIFont { return UIFont(name: "AvenirNext-Bold", size: fontSize) ?? UIFont.boldSystemFont(ofSize: fontSize) }
    var normalFont:UIFont { return UIFont(name: "AvenirNext-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)}
    
    func bold(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font : boldFont
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
    
    func normal(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font : normalFont,
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
    /* Other styling methods */
    func orangeHighlight(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font :  normalFont,
            .foregroundColor : UIColor.white,
            .backgroundColor : UIColor.orange
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
    
    func blackHighlight(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font :  normalFont,
            .foregroundColor : UIColor.white,
            .backgroundColor : UIColor.black
            
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
    
    func underlined(_ value:String) -> NSMutableAttributedString {
        
        let attributes:[NSAttributedString.Key : Any] = [
            .font :  normalFont,
            .underlineStyle : NSUnderlineStyle.single.rawValue
            
        ]
        
        self.append(NSAttributedString(string: value, attributes:attributes))
        return self
    }
}
func loadImage(index: Int) async -> UIImage {
    let imageURL = URL(string: "https://picsum.photos/200/300")!
    let request = URLRequest(url: imageURL)
    let (data, _) = try! await URLSession.shared.data(for: request, delegate: nil)
    print("Finished loading image \(index)")
    return UIImage(data: data)!
}
func loadImages() {
    Task {
        let firstImage = await loadImage(index: 1)
        let secondImage = await loadImage(index: 2)
        let thirdImage = await loadImage(index: 3)
        let images = [firstImage, secondImage, thirdImage]
    }
}
//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]
        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)
            }
let timer = 1

DispatchQueue.main.asyncAfter(deadline: .now() + timer) {
    // code to execute after 1 second
}
   
 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))
    }
}
// UIImage+Alpha.swift

extension UIImage {  

    func alpha(_ value:CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(at: CGPoint.zero, blendMode: .normal, alpha: value)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!   
    }
}
// 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 publisherE = PassthroughSubject<String, Never>()
let publisherF = PassthroughSubject<String, Never>()

let publishers = PassthroughSubject<PassthroughSubject<String, Never>,Never>()

publishers.switchToLatest().sink {
    print($0)
}

publishers.send(publisherE)
publisherE.send("Publisher E - Value 1") //Publisher E - Value 1
publisherE.send("Publisher E - Value 2") //Publisher E - Value 2

publishers.send(publisherF) // switching to publisher 2
publisherF.send("Publisher F - Value 1") //Publisher F - Value 1
publisherE.send("Publisher E - Value 3") //
var hasChangedPublisher: AnyPublisher<Void, Never> {
  preferences.publisher
    .merge(state.$permissionStatus)
    .map({ _ in
      return () // transform to Void
    })
    .eraseToAnyPublisher()
}
        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")
                }
        }
    }
}
struct ContentView : View {
    var body: some View {
        VStack {
            Text("Test")
            Text("Test2")

        }
    }
}

var child = UIHostingController(rootView: ContentView())
  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")
            }
        }
ErrorHandler.showCommonEmptyView(on: error, in: self) { [unowned self] in
		refreshCart()
}
profileButton.publisher(for: .touchUpInside)
		.sink { [unowned self] _ in showProfile() }
		.store(in: &cancellables)
DispatchQueue.main.async { [weak self] in
		self?.showMatchDetail(with: deepLinkValue.itemId)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 4) { [weak self] in
		print(self?.greetingValue ?? "Hello World")
}
UIView.animate(withDuration: 0.2) {
		self.collectionView.contentInset.bottom = self.collectionViewBottomInset
}
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
		print(self.greetingValue)
}
func application(
  _ application: UIApplication,
  ontinue userActivity: NSUserActivity,
  restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
	) -> Bool {
      deepLinkManager.application(application, continue: userActivity, restorationHandler: restorationHandler)
}
        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)
                }
            }
    }
Section(header: Text("Attendees")) {
                ForEach(data.attendees) { attendee in
                    Text(attendee.name)
                }
                .onDelete { indices in
                    data.attendees.remove(atOffsets: indices)
                }
            }
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
let firstDate = formatter.date(from: "8/08/2017")
let secondDate = formatter.date(from: "10/08/2017")

if firstDate?.compare(secondDate!) == .orderedAscending {
    print("First Date is smaller then second date")
}
extension Season {
    static var current: Season {
        let calendar = Calendar.current
        let date = Date()
        
        let dateComponents = calendar.dateComponents([.year], from: date)
        return dateComponents.year!
    }
    
    static var all: [Season] {
        let current: Season = .current
        return Array(1950...current).reversed()
    }
}
 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)
}
var closureOne = {
  print("I can do it")
}()
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()
        }
    }
    func flagTapped(_ number: Int){
        
        if number == correctAnswer{
            scoreTitle = "Correct!"
            totalScores += 2
        }else{
            scoreTitle = "Wrong!"
        }
        questionTries += 1
        if questionTries < 8{
            showingScore = true
        }else{
            gameOver = true
        }
    }
   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
    }
case .showSecondViewController(let animated):
	let secondViewController = AboutAppCoordinator().start()
  guard let secondViewController = secondViewController else {
		return .none
	}
	return .present(secondViewController, .automatic)
//
//  AboutAppCoordinator.swift
//  CoordinatorArticle
//
//  Created by Andrej Jasso on 27/09/2021.
//

import UIKit

// MARK: - Steps

final class AboutAppCoordinator: Coordinator<AppStep> {


    // MARK: - Overrides

    override func navigate(to step: AppStep) -> StepAction {
        switch step {
        default:
            return .none
        }
    }

    @discardableResult
    override func start() -> UIViewController? {
        super.start()

        let controller = UIViewController()
        let navigationController = UINavigationController()
        navigationController.viewControllers = [controller]
        controller.view.backgroundColor = .green

        return navigationController
    }
    

}
import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    private var appCoordinator: AppCoordinator!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let appCoordinator = AppCoordinator()
        self.appCoordinator = appCoordinator
        appCoordinator.start()
        appCoordinator.step = .showFirstViewController
        appCoordinator.step = .showSecondViewController
        return true
    }

}
override func navigate(to step: AppStep) -> StepAction {
        switch step {
        case .showFirstViewController(let animated):
            let firstViewController = DocumentBrowserViewController(forOpeningFilesWithContentTypes: ["two", "one"])
            return .push(firstViewController)

        case .showSecondViewController(let animated):
            let secondViewController = DocumentBrowserViewController(forOpeningFilesWithContentTypes: ["hone", "two"])
            return .push(secondViewController)

        default:
            return .none
        }

    }
import Foundation
import UIKit
import Combine


// MARK: - Navigation & Initializers

final class AppCoordinator: Coordinator<AppStep> {

    // MARK: - Properties

    private let appWindow: UIWindow

    // MARK: - Init

    override init() {
        appWindow = UIWindow()
        appWindow.frame = UIScreen.main.bounds
    }

    // MARK: - Overrides

    @discardableResult
    override func start() -> UIViewController? {
        super.start()

        let navigationController = UINavigationController()
        self.navigationController = navigationController
        appWindow.rootViewController = navigationController
        appWindow.makeKeyAndVisible()

        return navigationController
    }

}
enum AppStep {

    case showFirstViewController
    case showSecondViewController

}
@discardableResult
    func navigate(to stepper: Step) -> StepAction {
        return .none
    }

    private func navigate(flowAction: StepAction) {
        switch flowAction {
        case .dismiss:
            if let presentedViewController = navigationController?.presentedViewController {
                presentedViewController.dismiss(animated: true, completion: nil)
            } else {
                navigationController?.topViewController?.dismiss(animated: true, completion: nil)
            }

        case .push(let controller):
            navigationController?.pushViewController(controller, animated: true)

        case .pop:
            navigationController?.popViewController(animated: true)

        case .present(let controller, let style):
            controller.modalPresentationStyle = style

            if let presentedViewController = navigationController?.presentedViewController {
                presentedViewController.present(controller, animated: true, completion: nil)
            } else {
                navigationController?.topViewController?.present(
                    controller,
                    animated: true,
                    completion: nil
                )
            }

        case .none:
            break
        }
    }

    @discardableResult
    public func start() -> UIViewController? {
        $step
            .compactMap { $0 }
            .sink { [weak self] in
                guard let self = self else { return }

                self.navigate(flowAction: self.navigate(to: $0))
            }
        .store(in: &cancellables)

        return navigationController
    }
class Coordinator<Step> {

    weak var navigationController: UINavigationController?
    var cancellables: Set<AnyCancellable> = Set()
    @Published var step: Step?

}
import Combine
import UIKit

enum StepAction {

    case push(UIViewController)
    case present(UIViewController, UIModalPresentationStyle)
    case dismiss
    case pop
    case none

}
//
//  ContentView.swift
//  Dyana
//
//  Created by Zach Wadzinski on 3/29/21.
//
// Copyright Dyana Inc.

import SwiftUI
import Firebase

struct LoginView: View {
    @State var email = ""
    @State var password = ""
    @State var isFocused = false
    @State var showAlert = false
    @State var alertMessage = "Something went wrong."
    @State var isLoading = false
    @State var isSuccessful = false
    @EnvironmentObject var user: UserStore
    @State var signupToggle = false

    func hideKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }

    func login() {
        self.hideKeyboard()
        self.isFocused = false
        self.isLoading = true

        Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
            self.isLoading = false

            if error != nil {
                self.alertMessage = error?.localizedDescription ?? ""
                self.showAlert = true
            } else {
                self.isSuccessful = true
                self.user.isLogged = true
                UserDefaults.standard.set(true, forKey: "isLogged")

                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    self.isSuccessful = false
                    self.email = ""
                    self.password = ""
                    self.user.showLogin = false
            }
        }
        }
    }


    var body: some View {
        ZStack {
            MainPageView()
            Color(#colorLiteral(red: 0.9787462354, green: 0.9567045569, blue: 0.9562209249, alpha: 1)).edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)

            LoginLogo()
                .padding(.top)


            VStack {


                VinesView()
                    .padding(.vertical, 30)

                LoginTextView()
                    .padding(.vertical, 40)

                GoogleSignInView()

                //EmailLoginView(email: $email, password: $password, isFocused: $isFocused)
                VStack {
                    ZStack {
                        RoundedRectangle(cornerRadius: 8)
                            .fill(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)))
                            .frame(width: .infinity, height: 46)

                        HStack {
                            VStack(alignment: .leading) {
                                TextField("User Email", text: $email, onEditingChanged: { (changed) in
                                        print("Suggestion onEditingChanged - \(changed)")
                                })
                                {
                                        print("Suggestion onCommit")
                                    }.font(.system(size: 14)).foregroundColor(Color(#colorLiteral(red: 0.82, green: 0.82, blue: 0.82, alpha: 1)))


                            }.keyboardType(.emailAddress)
                            .onTapGesture {
                                self.isFocused = true
                            }

                            Spacer()
                        }.padding(.leading)

                    }.padding(.horizontal, 70)

                ZStack {
                    RoundedRectangle(cornerRadius: 8)
                        .fill(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)))
                        .frame(width: .infinity, height: 46)

                    HStack {
                        VStack(alignment: .leading) {
                            TextField("Password", text: $password, onEditingChanged: { (changed) in
                                    print("Suggestion onEditingChanged - \(changed)")
                                }) {
                                    print("Suggestion onCommit")
                                }.font(.system(size: 14)).foregroundColor(Color(#colorLiteral(red: 0.82, green: 0.82, blue: 0.82, alpha: 1)))
                        }.onTapGesture {
                            self.isFocused = true
                        }
                        Spacer()
                    }.padding(.leading)

                }.padding(.horizontal, 70)
                }

                NavigationLink(destination: NameInput()){
                    Text("Forgot Password?").font(.custom("Lato Medium", size: 12)).foregroundColor(Color(#colorLiteral(red: 0.09, green: 0.78, blue: 0.6, alpha: 1))).multilineTextAlignment(.center)
                        .frame(width: nil, height: 15)
                        //.padding(.bottom)
                }

                Button(action: {
                    self.login()
                })
                {
                    SendLoginView()
                        .padding(.top,20)
                        .alert(isPresented: $showAlert) {
                            Alert(title: Text("Error"), message: Text(self.alertMessage), dismissButton: .default(Text("OK")))
                }
                }
                VStack {
                    Button(action: {
                        self.signupToggle.toggle()
                    }) {
                    Text("New to Dyana? Create an account.").font(.custom("Lato Medium", size: 12)).foregroundColor(Color(#colorLiteral(red: 0.09, green: 0.78, blue: 0.6, alpha: 1))).multilineTextAlignment(.center)
                        .frame(width: .infinity, height: 15)
                        .padding(.bottom)
                    }
                }

            }

            ShapesView()

            if isLoading {
                LoadingView()
            }
            if isSuccessful {
                MainPageView()
            }
        }.offset(y: isFocused ? -300 : 0)
        .animation(.easeInOut)
        .onTapGesture {
            self.isFocused = false
            self.hideKeyboard()
        }


    }
}



struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        LoginView()
    }
}


struct LoginLogo: View {
    var body: some View {
        VStack {
            Image("LoginLogo")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: 134, height: 45)
                .clipped()
                .frame(width: 134, height: 45)
            Spacer()
        }
    }
}

struct VinesView: View {
    var body: some View {
        VStack {
            //VINES
            Image("LoginVines")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: 500, height: 70)
                .clipped()
                .frame(width: .infinity, height: 45)
        }
    }
}

struct LoginTextView: View {
    var body: some View {
        VStack {
            Text("Log In").font(.system(size: 26)).fontWeight(.heavy).foregroundColor(Color(#colorLiteral(red: 0.1, green: 0.27, blue: 0.42, alpha: 1))).multilineTextAlignment(.center)
        }
    }
}

struct GoogleSignInView: View {
    var body: some View {
            ZStack {
                //GOOGLE SIGN IN
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)))
                    .frame(width: .infinity, height: 46)

                RoundedRectangle(cornerRadius: 8)
                    .strokeBorder(Color(#colorLiteral(red: 0.08627451211214066, green: 0.7803921699523926, blue: 0.6039215922355652, alpha: 1)), lineWidth: 1)
                    .frame(width: .infinity, height: 46)

                HStack {
                    //googlelogo 1
                    Image("LoginGoogleLogo")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 29, height: 29)
                        .clipped()
                        .frame(width: 29, height: 29)
                        .padding(.leading, 40)
                    Spacer()

                    //Continue with Google
                    Text("Continue with Google").font(.system(size: 14)).foregroundColor(Color(#colorLiteral(red: 0.09, green: 0.78, blue: 0.6, alpha: 1))).multilineTextAlignment(.center)
                        .padding(.trailing, 90)
                }
            }.padding(.horizontal, 70)


    }
}
//  Converted by Storyboard to SwiftUI Converter - https://swiftify.com/#/converter/storyboard2swiftui

import SwiftUI

// --------------------------------------------------------------------------------
// UIViewController
// --------------------------------------------------------------------------------
struct View1: View {
    var body: some View {
        ZStack(alignment: .topLeading) {
            GeometryReader { geometry in
                Text("Hello SwiftUI!")
                    .frame(dynamicWidth: 126.5, dynamicHeight: 28.5)
                    .font(.custom("ChalkboardSE-Regular", size: 20))
                    .offset(dyanmicX: 124.5, dynamicY: 319.5)
            }
        }
        .frame(dynamicWidth: 375, dynamicHeight: 667)
        .background(Color(.systemBackground))
        .edgesIgnoringSafeArea(.all)
    }
}

// --------------------------------------------------------------------------------
// Dynamic Size Helper
// --------------------------------------------------------------------------------
struct DynamicSize {
    static private let baseViewWidth: CGFloat = 320.0
    static private let baseViewHeight: CGFloat = 568.0

    static func getHeight(_ height: CGFloat) -> CGFloat {
        return (height / baseViewHeight) * UIScreen.main.bounds.height
    }

    static func getWidth(_ width: CGFloat) -> CGFloat {
        return (width / baseViewWidth) * UIScreen.main.bounds.width
    }

    static func getOffsetX(_ x: CGFloat) -> CGFloat {
        return (x / baseViewWidth) * UIScreen.main.bounds.width
    }

    static func getOffsetY(_ y: CGFloat) -> CGFloat {
        return (y / baseViewHeight) * UIScreen.main.bounds.height
    }
}

struct View1_Previews: PreviewProvider {
    static var previews: some View {
        View1()
    }
}


// --------------------------------------------------------------------------------
// Frame and Offset Helper
// --------------------------------------------------------------------------------
extension View {
    func frame(dynamicWidth: CGFloat? = nil, dynamicHeight: CGFloat? = nil) -> some View {
        self.frame(width: DynamicSize.getWidth(dynamicWidth ?? 0), height: DynamicSize.getHeight(dynamicHeight ?? 0))
    }
    
    func offset(dyanmicX: CGFloat = 0, dynamicY: CGFloat = 0) -> some View {
        self.offset(x: DynamicSize.getOffsetX(dyanmicX), y: DynamicSize.getOffsetY(dynamicY))
    }
}
extension View {
    
    /// Hide or show the view based on a boolean value.
    ///
    /// Example for visibility:
    ///
    ///     Text("Label")
    ///         .isHidden(true)
    ///
    /// Example for complete removal:
    ///
    ///     Text("Label")
    ///         .isHidden(true, remove: true)
    ///
    /// - Parameters:
    ///   - hidden: Set to `false` to show the view. Set to `true` to hide the view.
    ///   - remove: Boolean value indicating whether or not to remove the view.
    @ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View {
        if hidden {
            if !remove {
                self.hidden()
            }
        } else {
            self
        }
    }
}
struct ToggleView: View {
    @State private var toggleValue: Bool = true
    
    var body: some View {
        Toggle(isOn: $toggleValue, label: {})
            .toggleStyle(SwitchToggleStyle(tint: Color(red: 1.0, green: 0.5696961, blue: 0.9999913)))
            .introspectSwitch(customize: { (toggle) in
                toggle.thumbTintColor = UIColor.purple
            })
            .background(Color(red: 0.9529412, green: 0.9529412, blue: 0.18431373))
            .frame(width: DynamicSizeHelper.getWidth(322), height: DynamicSizeHelper.getHeight(31), alignment: .topLeading)
            .aspectRatio(contentMode: .fill)
            .labelsHidden()
    }
}
private func deviceTokenDataToString(_ deviceToken: Data) -> String {
        let tokenChars = (deviceToken as NSData).bytes.assumingMemoryBound(to: CChar.self)
        var tokenString = ""

        for i in 0..<deviceToken.count {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }

        return tokenString
    }

   func updateDeviceToken() {
        guard let deviceToken: Data = dataStorageService.value(for: .pushDeviceToken),
            deviceToken.isEmpty == false else {
                return
        }
        let stringPushToken = deviceTokenDataToString(deviceToken)
        mixpanel?.track(event: "Push Token Updated", properties: ["token": stringPushToken])
        peopleObject?.people.set(properties: ["$ios_devices": [stringPushToken]]
        mixpanel?.flush()
    }
//
//  GoogleSignInButtonView.swift
//
//  Created by Ivan Schaab on 11/09/2019.
//  Copyright © 2019 Ivan Schaab. All rights reserved.
//
import GoogleSignIn
import SwiftUI

struct GoogleSignInButtonView: View {

    @EnvironmentObject var lvm: LoginViewModel

    var body: some View {
        HStack {
            Spacer()
            GoogleButtonViewControllerRepresentable { (token, user) in
                // Google Login Success
                // Now do Backend Validations
                self.lvm.loginOauth(token: token, user: user)
            }
            Spacer()
        }.frame(alignment: .center)
    }
}

class GoogleButtonUIKitViewController: UIViewController {

    var signInButton = GIDSignInButton()

    override func viewDidLoad() {
        super.viewDidLoad()

        GIDSignIn.sharedInstance().clientID = Constants.GOOGLE_CLIENT_ID
        self.view.addSubview(signInButton)

        GIDSignIn.sharedInstance()?.presentingViewController = self

        // Automatically sign in the user.
        GIDSignIn.sharedInstance()?.restorePreviousSignIn()
    }
}

struct GoogleButtonViewControllerRepresentable: UIViewControllerRepresentable
{
    let vc = GoogleButtonUIKitViewController()
    var googleResponse: (String, User) -> Void

    func makeUIViewController(context: Context) -> GoogleButtonUIKitViewController {
        return vc
    }
    func updateUIViewController(_ uiViewController: GoogleButtonUIKitViewController, context: Context) {}
    func makeCoordinator() -> Coordinator {
        Coordinator(vc: vc, googleResponse: googleResponse)
    }

    static func dismantleUIViewController(_ uiViewController: GoogleButtonUIKitViewController, coordinator: GoogleButtonViewControllerRepresentable.Coordinator) {
        print("DISMANTLE")
    }

    class Coordinator: NSObject, GIDSignInDelegate  {
        var foo: (String, User) -> Void
        init(vc: GoogleButtonUIKitViewController, googleResponse: @escaping (String, User) -> Void) {
            self.foo = googleResponse
            super.init()
            GIDSignIn.sharedInstance()?.delegate = self
        }

        func sign(_ signIn: GIDSignIn!, didSignInFor googleUser: GIDGoogleUser!, withError error: Error!) {
            if let error = error {
                if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
                    print("The user has not signed in before or they have since signed out.")
                } else {
                    print("\(error.localizedDescription)")
                }
                return
            }
//            let userId = googleUser.userID                  // For client-side use only!
            let idToken = googleUser.authentication.idToken // Safe to send to the server
            let email = googleUser.profile.email

            if googleUser.profile.hasImage{
                let imageUrl = googleUser.profile.imageURL(withDimension: 120)
                print(" image url: ", imageUrl?.absoluteString ?? "NO URL")
            }

            let user : User = User(id: 1, name: googleUser.profile.givenName, surname: googleUser.profile.familyName, imgName: ""  , email: googleUser.profile.email)

            print("email: ",email ?? "NO EMAIL")

            foo(idToken! , user)
        }
    }
}



#if DEBUG
struct SomeRepView_Previews: PreviewProvider {
    static var previews: some View {
        GoogleSignInButtonView().environmentObject(LoginViewModel())
    }
}
#endif
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 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
}
// Preferred status bar style lightContent to use on dark background.
// Swift 3
override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}
[[NSProcessInfo processInfo] operatingSystemVersion]
@IBAction func doSomething()
@IBAction func doSomething(sender: UIButton)
@IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)
star

Mon Jan 27 2025 05:20:19 GMT+0000 (Coordinated Universal Time)

#swift
star

Sat Jan 18 2025 12:28:51 GMT+0000 (Coordinated Universal Time) https://www.avanderlee.com/combine/runloop-main-vs-dispatchqueue-main/

#swift
star

Fri Apr 12 2024 14:08:58 GMT+0000 (Coordinated Universal Time)

#swift #inapppurchase
star

Fri Apr 12 2024 12:07:04 GMT+0000 (Coordinated Universal Time)

#swift #coredata
star

Fri Apr 12 2024 06:37:48 GMT+0000 (Coordinated Universal Time)

#swift #retailcycle
star

Fri Apr 12 2024 06:27:34 GMT+0000 (Coordinated Universal Time)

#swift #coredata
star

Tue Apr 09 2024 07:24:08 GMT+0000 (Coordinated Universal Time)

#swift #inapppurchase
star

Mon Apr 08 2024 11:48:34 GMT+0000 (Coordinated Universal Time)

#swift #inapppurchase
star

Sun Apr 07 2024 05:59:48 GMT+0000 (Coordinated Universal Time)

#swift
star

Sat Apr 06 2024 07:21:54 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Mar 19 2024 05:26:56 GMT+0000 (Coordinated Universal Time)

#pdf #ios #swift
star

Fri Feb 09 2024 21:39:39 GMT+0000 (Coordinated Universal Time)

#swift
star

Mon Dec 18 2023 06:33:06 GMT+0000 (Coordinated Universal Time) https://www.dappfort.com/

#swift #javascript #kotlin #mysql
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

Fri Aug 04 2023 13:13:30 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Fri Aug 04 2023 08:56:30 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
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

Mon Jun 26 2023 04:13:17 GMT+0000 (Coordinated Universal Time)

#swift
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

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

Mon Mar 20 2023 13:30:08 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/69279513/swiftui-scroll-to-horizontal-list-item

#swift #swiftui
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

Mon Feb 27 2023 00:59:39 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Mon Feb 27 2023 00:53:00 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Mon Feb 27 2023 00:50:31 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Mon Feb 27 2023 00:45:35 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Mon Feb 27 2023 00:37:29 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Mon Feb 27 2023 00:31:33 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Sun Feb 26 2023 23:59:50 GMT+0000 (Coordinated Universal Time) https://app-designer2.de

#swift #swiftui
star

Sat Feb 25 2023 13:33:18 GMT+0000 (Coordinated Universal Time) https://transloadit.com/demos/image-manipulation/resize-to-wallpaper-for-apple-iphone-11-pro-max/

#swift
star

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

#ios #swift #time #date #chat
star

Wed Feb 22 2023 05:12:56 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
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

Sun Feb 12 2023 09:44:09 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Sun Feb 12 2023 08:32:54 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Sun Feb 12 2023 04:55:56 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Fri Feb 10 2023 05:54:54 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Wed Feb 08 2023 11:54:17 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Tue Feb 07 2023 12:09:14 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Tue Feb 07 2023 11:45:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/27652227/add-placeholder-text-inside-uitextview-in-swift

#swift
star

Tue Feb 07 2023 06:27:52 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/24022479/how-would-i-create-a-uialertview-in-swift

#swift
star

Tue Feb 07 2023 06:27:42 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/24022479/how-would-i-create-a-uialertview-in-swift

#swift
star

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

#ios #swift #api #signup
star

Wed Feb 01 2023 06:23:59 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
star

Wed Feb 01 2023 05:47:27 GMT+0000 (Coordinated Universal Time)

#swift #swiftui
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

Thu Jan 26 2023 08:57:46 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=MCLiPW2ns2w

#swift
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

Wed Jan 25 2023 14:02:05 GMT+0000 (Coordinated Universal Time)

#swift
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

Mon Oct 31 2022 06:03:39 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42478380/add-image-in-alert-message-box-title-with-swift-3

#swift
star

Mon Oct 10 2022 14:49:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/61355475/swiftui-get-coordinates-of-textfield-or-any-view

#swift
star

Thu Sep 15 2022 13:00:15 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary

#swift
star

Thu Sep 15 2022 13:00:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary

#swift
star

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

#ios #swift #gradient #gradent
star

Sun Sep 04 2022 19:23:27 GMT+0000 (Coordinated Universal Time)

#swift
star

Sun Sep 04 2022 19:09:23 GMT+0000 (Coordinated Universal Time)

#swift
star

Thu Sep 01 2022 09:54:55 GMT+0000 (Coordinated Universal Time) https://www.raywenderlich.com/11395893-push-notifications-tutorial-getting-started#toc-anchor-012

#swift
star

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

#ios #swift #video #player
star

Mon Aug 29 2022 12:11:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38035346/get-height-of-table-contents-in-swift

#swift
star

Sun Aug 14 2022 11:43:38 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/28496093/making-text-bold-using-attributed-string-in-swift

#swift
star

Sat Jul 09 2022 12:10:16 GMT+0000 (Coordinated Universal Time) https://www.avanderlee.com/swift/async-let-asynchronous-functions-in-parallel/

#swift
star

Sat Jul 09 2022 12:10:13 GMT+0000 (Coordinated Universal Time) https://www.avanderlee.com/swift/async-let-asynchronous-functions-in-parallel/

#swift
star

Sat Jul 09 2022 12:10:01 GMT+0000 (Coordinated Universal Time) undefined

#swift
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

Tue Jun 21 2022 09:57:38 GMT+0000 (Coordinated Universal Time)

#swift
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

Fri Jun 10 2022 20:24:09 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/28517866/how-to-set-the-alpha-of-an-uiimage-in-swift-programmatically

#swift
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

Sun Jun 05 2022 22:15:33 GMT+0000 (Coordinated Universal Time) https://www.createwithswift.com/reference-combine-combining-operators/

#swift
star

Sun Jun 05 2022 06:56:37 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/62253436/how-to-combine-2-publishers-and-erase-values-to-void

#swift
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

Wed Jun 01 2022 05:05:49 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/56631892/addsubview-swiftui-view-to-uikit-uiview-in-swift

#swift
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 19 2022 09:04:53 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Apr 19 2022 09:04:00 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Apr 19 2022 09:03:07 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Apr 19 2022 09:02:10 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Apr 19 2022 09:01:15 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Apr 19 2022 09:00:06 GMT+0000 (Coordinated Universal Time)

#swift
star

Sat Apr 09 2022 05:29:56 GMT+0000 (Coordinated Universal Time)

#swift
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

Tue Mar 29 2022 00:24:33 GMT+0000 (Coordinated Universal Time) https://developer.apple.com/tutorials/app-dev-training/updating-app-data

#swift
star

Thu Mar 24 2022 00:05:49 GMT+0000 (Coordinated Universal Time) https://iostutorialjunction.com/2017/10/compare-two-dates-using-swift-in-ios.html

#swift
star

Wed Mar 23 2022 09:21:04 GMT+0000 (Coordinated Universal Time)

#swift
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

Wed Mar 09 2022 00:49:08 GMT+0000 (Coordinated Universal Time)

#swift
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

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

Mon Jan 31 2022 17:00:47 GMT+0000 (Coordinated Universal Time)

#swift
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

Tue Nov 30 2021 08:02:43 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Nov 30 2021 08:01:58 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Nov 30 2021 08:01:05 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Nov 30 2021 07:59:47 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Nov 30 2021 07:55:28 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Nov 30 2021 07:54:29 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Nov 30 2021 07:52:36 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Nov 30 2021 07:51:33 GMT+0000 (Coordinated Universal Time)

#swift
star

Tue Nov 30 2021 07:50:00 GMT+0000 (Coordinated Universal Time)

#swift
star

Sun Aug 22 2021 23:11:07 GMT+0000 (Coordinated Universal Time)

#swift
star

Wed Jul 14 2021 16:45:27 GMT+0000 (Coordinated Universal Time)

#swift
star

Wed Jul 14 2021 16:35:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/a/59228385/

#swift
star

Thu Jul 01 2021 20:43:40 GMT+0000 (Coordinated Universal Time)

#swift
star

Thu Feb 25 2021 09:56:10 GMT+0000 (Coordinated Universal Time)

#swift
star

Sat Sep 12 2020 12:59:37 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57924768/add-google-sign-in-with-swiftui

#swift
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

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://stackoverflow.com/questions/17678881/how-to-change-status-bar-text-color-in-ios

#ios #swift
star

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

#ios #swift
star

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

#ios #swift

Save snippets that work with our extensions

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