Snippets Collections
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

class VideoPlayerViewController: UIViewController, AVPlayerViewControllerDelegate {

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

        // Do any additional setup after loading the view.
    }
  
@IBAction func btnPressed(_ sender: Any) {
       guard let url = URL(string: "https://firebasestorage.googleapis.com/v0/b/kreative-app.appspot.com/o/FileMessage%2F1661341223.mp4?alt=media&token=e8ca21b2-8ea9-44bc-a28f-85598395081c")else {return}
        let player = AVPlayer(url: url)
        
        playerController = AVPlayerViewController()
     
        playerController.player = player
        playerController.allowsPictureInPicturePlayback = true
        playerController.delegate = self
        playerController.player?.play()
    self.present(playerController , animated: true, completion: nil)
    }
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'
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
    override func viewDidAppear(_ animated: Bool) {
        
        self.profileImageView.frame.size = CGSize(width: self.profileImageView.frame.height,
                                                  height: self.profileImageView.frame.height)
        self.profileImageView.center.x = self.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" }

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

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
            present(imagePicker, animated: true, completion: nil)
        }
        else {
            print("No NO")
        }
    }

extension SignupViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            
            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
}
@IBAction func doSomething()
@IBAction func doSomething(sender: UIButton)
@IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)
[[NSProcessInfo processInfo] operatingSystemVersion]
// Preferred status bar style lightContent to use on dark background.
// Swift 3
override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}
star

Mon Oct 31 2022 06:03:39 GMT+0000 (UTC) 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 (UTC) https://stackoverflow.com/questions/61355475/swiftui-get-coordinates-of-textfield-or-any-view

#swift
star

Thu Sep 15 2022 13:00:15 GMT+0000 (UTC) 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 (UTC) 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 (UTC)

#ios #swift #gradient #gradent
star

Sun Sep 04 2022 19:23:27 GMT+0000 (UTC)

#swift
star

Sun Sep 04 2022 19:09:23 GMT+0000 (UTC)

#swift
star

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

#swift
star

Tue Aug 30 2022 07:54:18 GMT+0000 (UTC)

#ios #swift #video #player
star

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

#swift
star

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

#swift
star

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

#swift
star

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

#swift
star

Sat Jul 09 2022 12:10:01 GMT+0000 (UTC) undefined

#swift
star

Mon Jun 27 2022 10:53:43 GMT+0000 (UTC) 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 (UTC)

#ios #swift #file #pdf #png
star

Thu Jun 23 2022 08:13:46 GMT+0000 (UTC)

#ios #swift #wait #await
star

Tue Jun 21 2022 09:57:38 GMT+0000 (UTC)

#swift
star

Wed Jun 15 2022 07:10:53 GMT+0000 (UTC)

#ios #swift #closure
star

Mon Jun 13 2022 06:32:37 GMT+0000 (UTC)

#ios #swift #day #daypicker #picker
star

Fri Jun 10 2022 20:24:09 GMT+0000 (UTC) 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 (UTC)

#ios #swift #closure #return
star

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

#swift
star

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

#swift
star

Wed Jun 01 2022 07:44:59 GMT+0000 (UTC)

#ios #swift #languages #language
star

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

#swift
star

Tue May 31 2022 10:53:22 GMT+0000 (UTC)

#ios #swift #pods #pod #cocoapods
star

Mon May 30 2022 12:30:28 GMT+0000 (UTC)

#ios #swift #textview #text
star

Fri May 13 2022 11:08:14 GMT+0000 (UTC)

#ios #swift #row #reloadrow #tableview
star

Fri Apr 22 2022 05:32:05 GMT+0000 (UTC)

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

Tue Apr 19 2022 09:04:53 GMT+0000 (UTC)

#swift
star

Tue Apr 19 2022 09:04:00 GMT+0000 (UTC)

#swift
star

Tue Apr 19 2022 09:03:07 GMT+0000 (UTC)

#swift
star

Tue Apr 19 2022 09:02:10 GMT+0000 (UTC)

#swift
star

Tue Apr 19 2022 09:01:15 GMT+0000 (UTC)

#swift
star

Tue Apr 19 2022 09:00:06 GMT+0000 (UTC)

#swift
star

Sat Apr 09 2022 05:29:56 GMT+0000 (UTC)

#swift
star

Sat Apr 02 2022 04:49:10 GMT+0000 (UTC)

#ios #swift #return #completion
star

Wed Mar 30 2022 11:45:41 GMT+0000 (UTC)

#ios #swift #createbutton
star

Wed Mar 30 2022 07:50:10 GMT+0000 (UTC)

#ios #swift #url #geturl
star

Tue Mar 29 2022 07:49:14 GMT+0000 (UTC)

#ios #swift #stripe
star

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

#swift
star

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

#swift
star

Wed Mar 23 2022 09:21:04 GMT+0000 (UTC)

#swift
star

Sat Mar 19 2022 10:09:10 GMT+0000 (UTC)

#ios #swift #toast #tost
star

Wed Mar 16 2022 11:20:40 GMT+0000 (UTC)

#ios #swift #view #setview
star

Tue Mar 15 2022 04:14:56 GMT+0000 (UTC)

#ios #swift #shadow
star

Wed Mar 09 2022 08:36:25 GMT+0000 (UTC) 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 (UTC)

#swift
star

Sat Mar 05 2022 07:51:17 GMT+0000 (UTC) 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 (UTC)

#ios #swift #day #date #difference
star

Mon Jan 31 2022 17:00:47 GMT+0000 (UTC)

#swift
star

Tue Jan 18 2022 12:41:24 GMT+0000 (UTC)

#ios #swift #scroll
star

Tue Jan 18 2022 10:48:29 GMT+0000 (UTC)

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

Mon Jan 17 2022 10:01:54 GMT+0000 (UTC)

#ios #swift #dispatchqueue #dispatch #queue
star

Thu Jan 13 2022 12:10:26 GMT+0000 (UTC)

#ios #swift #query
star

Thu Jan 13 2022 10:58:19 GMT+0000 (UTC) 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 (UTC)

#ios #swift #update #updatedata #data
star

Tue Nov 30 2021 08:02:43 GMT+0000 (UTC)

#swift
star

Tue Nov 30 2021 08:01:58 GMT+0000 (UTC)

#swift
star

Tue Nov 30 2021 08:01:05 GMT+0000 (UTC)

#swift
star

Tue Nov 30 2021 07:59:47 GMT+0000 (UTC)

#swift
star

Tue Nov 30 2021 07:55:28 GMT+0000 (UTC)

#swift
star

Tue Nov 30 2021 07:54:29 GMT+0000 (UTC)

#swift
star

Tue Nov 30 2021 07:52:36 GMT+0000 (UTC)

#swift
star

Tue Nov 30 2021 07:51:33 GMT+0000 (UTC)

#swift
star

Tue Nov 30 2021 07:50:00 GMT+0000 (UTC)

#swift
star

Sun Aug 22 2021 23:11:07 GMT+0000 (UTC)

#swift
star

Wed Jul 14 2021 16:45:27 GMT+0000 (UTC)

#swift
star

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

#swift
star

Thu Jul 01 2021 20:43:40 GMT+0000 (UTC)

#swift
star

Thu Feb 25 2021 09:56:10 GMT+0000 (UTC)

#swift
star

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

#swift
star

Sun Jan 12 2020 17:30:26 GMT+0000 (UTC) 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 (UTC) 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 (UTC) 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 (UTC) 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 (UTC) https://gist.github.com/artemnovichkov/de5bd4daf64441c724a429d1a9b1e26e

#ios #swift
star

Wed Dec 25 2019 19:31:47 GMT+0000 (UTC) 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 (UTC) https://stackoverflow.com/questions/24007518/how-can-i-use-timer-formerly-nstimer-in-swift

#ios #swift #apps #howto
star

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

#ios #swift
star

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

#ios #swift
star

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

#ios #swift

Save snippets that work with our extensions

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