text
stringlengths 8
1.32M
|
|---|
//
// HealthyTableViewController.swift
// CafeApp2
//
// Created by Austin Patton on 10/26/17.
// Copyright © 2017 Austin Patton. All rights reserved.
//
import Foundation
import UIKit
import Firebase
import FirebaseDatabase
class healthyMenuCell: UITableViewCell{
@IBOutlet weak var healthyTextView: UITextView!
}
struct drinkStruct{
let name : String!
let price : Double!
}
struct DBConfigured {
static var configuredBool: Bool = false //Needed to make it a struct so its global. Otherwise, when you go back to the table view controller after already being it it, it gets configured twice and crashes the program
}
struct menuItemStruct{
var name = ""
var calories = 0
var carbohydrate = 0
var cholesterol = 0
var description = ""
var fat = 0
var price = 0.0
var protein = 0
var sodium = 0
var pic = ""
init(name: String, calories: Int, carbohydrate: Int, cholesterol: Int, description: String, fat: Int, price: Double, protein: Int, sodium: Int, pic: String) {
self.name = name
self.calories = calories
self.carbohydrate = carbohydrate
self.cholesterol = cholesterol
self.description = description
self.fat = fat
self.price = price
self.protein = protein
self.sodium = sodium
self.pic = pic
}
init(name: String, price: Double, pic: String) {
self.name = name
self.price = price
self.pic = pic
}
}
class HealthyTableViewController: UITableViewController {
var drinks = [drinkStruct]()
private var menuItems = [menuItemStruct]()
var arrayIndex = Int()
var ref:DatabaseReference?
//var dictionaryArray = [[String: AnyObject]]()
let section = ["Soups and Salads", "Sides", "Wraps", "Sandwiches", "Grill"]
let foodItems = [[loadSoupsSalads], [loadSides], [loadWraps], [loadSandwiches], [loadGrill]]
//checked w/ print statement and it loads as "[[(Function)], [(Function)]...etc]
//need to figure out a way to grab the items from each function rather than just calling the whole function
override func viewDidLoad() {
super.viewDidLoad()
if(DBConfigured.configuredBool == false){
FirebaseApp.configure()
DBConfigured.configuredBool = true
}
self.title = "Cafe Eckles Menu"//self.pop to root navigation controller
self.loadDrinks(completionHandler: { items in
self.menuItems += items
self.loadSoupsSalads(completionHandler: { items in
self.menuItems += items
self.loadSides(completionHandler: { items in
self.menuItems += items
self.loadWraps(completionHandler: { items in
self.menuItems += items
self.loadSandwiches(completionHandler: { items in
self.menuItems += items
self.loadGrill(completionHandler: { items in
self.menuItems += items
self.loadOther(completionHandler: { items in
self.menuItems += items
self.tableView.reloadData()
})
})
})
})
})
})
})
/*loadSoupsSalads(completionHandler: { items in
self.menuItems += items
})*/
/*loadSides(completionHandler: { items in
self.menuItems += items
})*/
//printArray(completion:loadSandwiches()) //dont understand why im getting an error here. It returns void and has void parameters
//loadDrinks()
//loadSides()You can load all of the items this way without completion handlers. However, they will be randomly ordered
//loadGrill()
//loadWraps()
//loadSandwiches()
//loadSoupsSalads()
//printArray()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
//post ()
}
func post(){
let title = "Title"
let message = "Message"
let post : [String : AnyObject] = ["title" : title as AnyObject, "message" : message as AnyObject]
let databaseRef = Database.database().reference()
databaseRef.child("Posts").childByAutoId().setValue(post)
}
func printArray(completion: ()->()){
completion()
print("THIS IS THE ARRAYS CONTENTS --------------\n\n")//this is for an in progress way to add sections to the device
for menuItemStruct in menuItems{
print(menuItemStruct)
}
}
func loadDrinks (completionHandler: @escaping ([menuItemStruct]) -> Void){//<--------------------Once the database is fixed, take out coffee so it reads the drinks category
ref = Database.database().reference()
var items: [menuItemStruct] = []
ref?.child("menu_items").child("Drinks").observeSingleEvent(of: .value, with: {(snapshot) in
print (snapshot)
for (key, dict) in snapshot.value as? NSDictionary ?? [:] {
let dict = dict as? NSDictionary
let calories = dict!["calories"] as? Int, carbohydrate = dict!["carbohydrate"] as? Int, cholesterol = dict!["cholesterol"] as? Int, description = dict!["description"] as? String, fat = dict!["fat"] as? Int, name = dict!["name"] as? String, price = dict!["price"] as? Double, protein = dict!["protein"] as? Int, sodium = dict!["sodium"] as? Int, pic = dict?["pic"] as? String
items.append(menuItemStruct(name: name!, price: price!, pic: pic!))//snapshot will read in calories and the other values that arent included in this one as nil since they're not in the database. That's why there's another initializer which is specifically only for drinks since it only initializes name, price, and pic while everything else is set to zero or " "
//self.arrayIndex += 1
}
//let name = snapshot.value!["name"]
completionHandler(items)
print("------------------------------------------------------")
self.tableView.reloadData()
})
}
func loadSandwiches(completionHandler: @escaping ([menuItemStruct]) -> Void){//ALL OF THE MENU ITEMS HAVE THE SAME LOADING FUNCTIONS MINUS DRINKS (they just access a different child dictionary) WHICH IS WHY EACH DICTIONARY HAS TO HAVE ITS OWN FUNCTION
ref = Database.database().reference()
var items: [menuItemStruct] = []
ref?.child("menu_items").child("sandwiches").observeSingleEvent(of: .value, with: {(snapshot) in
print (snapshot)
for (key, dict) in snapshot.value as? NSDictionary ?? [:] {
let dict = dict as? NSDictionary
let calories = dict!["calories"] as? Int, carbohydrate = dict!["carbohydrate"] as? Int, cholesterol = dict!["cholesterol"] as? Int, description = dict!["description"] as? String, fat = dict!["fat"] as? Int, name = dict!["name"] as? String, price = dict!["price"] as? Double, protein = dict!["protein"] as? Int, sodium = dict!["sodium"] as? Int, pic = dict?["pic"] as? String
items.append(menuItemStruct(name: name!, calories: calories!, carbohydrate: carbohydrate!, cholesterol: cholesterol!, description: description!, fat: fat!, price: price!, protein: protein!, sodium: sodium!, pic: pic! ))
//self.arrayIndex += 1
}
//let name = snapshot.value!["name"]
completionHandler(items)
print("------------------------------------------------------")
self.tableView.reloadData()
})
}
func loadWraps(completionHandler: @escaping ([menuItemStruct]) -> Void){
ref = Database.database().reference()
var items: [menuItemStruct] = []
ref?.child("menu_items").child("Wraps").observeSingleEvent(of: .value, with: {(snapshot) in
print (snapshot)
for (key, dict) in snapshot.value as? NSDictionary ?? [:] {
let dict = dict as? NSDictionary
let calories = dict!["calories"] as? Int, carbohydrate = dict!["carbohydrate"] as? Int, cholesterol = dict!["cholesterol"] as? Int, description = dict!["description"] as? String, fat = dict!["fat"] as? Int, name = dict!["name"] as? String, price = dict!["price"] as? Double, protein = dict!["protein"] as? Int, sodium = dict!["sodium"] as? Int, pic = dict!["pic"] as? String
items.append(menuItemStruct(name: name!, calories: calories!, carbohydrate: carbohydrate!, cholesterol: cholesterol!, description: description!, fat: fat!, price: price!, protein: protein!, sodium: sodium!, pic: pic! ))
//self.arrayIndex += 1
}
//let name = snapshot.value!["name"]
completionHandler(items)
print("------------------------------------------------------")
self.tableView.reloadData()
})
}
func loadGrill(completionHandler: @escaping ([menuItemStruct]) -> Void){
ref = Database.database().reference()
var items: [menuItemStruct] = []
ref?.child("menu_items").child("grill").observeSingleEvent(of: .value, with: {(snapshot) in
print (snapshot)
for (key, dict) in snapshot.value as? NSDictionary ?? [:] {
let dict = dict as? NSDictionary
let calories = dict!["calories"] as? Int, carbohydrate = dict!["carbohydrate"] as? Int, cholesterol = dict!["cholesterol"] as? Int, description = dict!["description"] as? String, fat = dict!["fat"] as? Int, name = dict!["name"] as? String, price = dict!["price"] as? Double, protein = dict!["protein"] as? Int, sodium = dict!["sodium"] as? Int, pic = dict!["pic"] as? String
items.append(menuItemStruct(name: name!, calories: calories!, carbohydrate: carbohydrate!, cholesterol: cholesterol!, description: description!, fat: fat!, price: price!, protein: protein!, sodium: sodium!, pic: pic! ))
//self.arrayIndex += 1
}
//let name = snapshot.value!["name"]
completionHandler(items)
print("------------------------------------------------------")
self.tableView.reloadData()
})
}
func loadSoupsSalads(completionHandler: @escaping ([menuItemStruct]) -> Void){
ref = Database.database().reference()
var items: [menuItemStruct] = []
ref?.child("menu_items").child("soups_salads").observeSingleEvent(of: .value, with: {(snapshot) in
print (snapshot)
for (key, dict) in snapshot.value as? NSDictionary ?? [:] {
let dict = dict as? NSDictionary
let calories = dict!["calories"] as? Int, carbohydrate = dict!["carbohydrate"] as? Int, cholesterol = dict!["cholesterol"] as? Int, description = dict!["description"] as? String, fat = dict!["fat"] as? Int, name = dict!["name"] as? String, price = dict!["price"] as? Double, protein = dict!["protein"] as? Int, sodium = dict!["sodium"] as? Int, pic = dict?["pic"] as? String
items.append(menuItemStruct(name: name!, calories: calories!, carbohydrate: carbohydrate!, cholesterol: cholesterol!, description: description!, fat: fat!, price: price!, protein: protein!, sodium: sodium!, pic: (pic)! ))
//self.arrayIndex += 1
}
//let name = snapshot.value!["name"]
completionHandler(items)
print("------------------------------------------------------")
self.tableView.reloadData()
})
}
func loadSides(completionHandler: @escaping ([menuItemStruct]) -> Void){
ref = Database.database().reference()
var items: [menuItemStruct] = []
ref?.child("menu_items").child("Sides").observeSingleEvent(of: .value, with: {(snapshot) in
print (snapshot)
for (key, dict) in snapshot.value as? NSDictionary ?? [:] {
let dict = dict as? NSDictionary
let calories = dict!["calories"] as? Int, carbohydrate = dict!["carbohydrate"] as? Int, cholesterol = dict!["cholesterol"] as? Int, description = dict!["description"] as? String, fat = dict!["fat"] as? Int, name = dict!["name"] as? String, price = dict!["price"] as? Double, protein = dict!["protein"] as? Int, sodium = dict!["sodium"] as? Int, pic = dict!["pic"] as? String
items.append(menuItemStruct(name: name!, calories: calories!, carbohydrate: carbohydrate!, cholesterol: cholesterol!, description: description!, fat: fat!, price: price!, protein: protein!, sodium: sodium!, pic: pic! ))
//self.arrayIndex += 1
}
//let name = snapshot.value!["name"]
completionHandler(items)
print("------------------------------------------------------")
self.tableView.reloadData()
})
}
func loadOther(completionHandler: @escaping ([menuItemStruct]) -> Void){
ref = Database.database().reference()
var items: [menuItemStruct] = []
ref?.child("menu_items").child("Other").observeSingleEvent(of: .value, with: {(snapshot) in
print (snapshot)
for (key, dict) in snapshot.value as? NSDictionary ?? [:] {
let dict = dict as? NSDictionary
let calories = dict!["calories"] as? Int, carbohydrate = dict!["carbohydrate"] as? Int, cholesterol = dict!["cholesterol"] as? Int, description = dict!["description"] as? String, fat = dict!["fat"] as? Int, name = dict!["name"] as? String, price = dict!["price"] as? Double, protein = dict!["protein"] as? Int, sodium = dict!["sodium"] as? Int, pic = dict!["pic"] as? String
items.append(menuItemStruct(name: name!, calories: calories!, carbohydrate: carbohydrate!, cholesterol: cholesterol!, description: description!, fat: fat!, price: price!, protein: protein!, sodium: sodium!, pic: pic! ))
//self.arrayIndex += 1
}
//let name = snapshot.value!["name"]
completionHandler(items)
print("------------------------------------------------------")
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
/* if section == 1 {
return 3
}
else if section == 2 {
return 3
}
else if section == 3 {
return 2
}
else if section == 4 {
return 4
}
else if section == 5{
return 3
}
else if section == 6{
return 1
}
else {
return 0
}*/
return menuItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "healthyMenuChoiceCell", for: indexPath) as! healthyMenuCell
cell.healthyTextView.isEditable = false
cell.healthyTextView?.text = menuItems[indexPath.row].name + " \n$ " + menuItems[indexPath.row].price.description
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UITableViewCell
let indexPath = self.tableView.indexPath(for: cell)
let viewController = segue.destination as! HealthyViewController
//viewController.testText = drinks[indexPath!.row].name + "\n$ " + drinks[indexPath!.row].price.description
viewController.testText = "Name: " + menuItems[indexPath!.row].name + "\nPrice: $" + menuItems[indexPath!.row].price.description + "\nDescription: " + menuItems[indexPath!.row].description + "\nCalories: " + menuItems[indexPath!.row].calories.description + "\nCarbohydrates: " + menuItems[indexPath!.row].carbohydrate.description + " grams\nFat: " + menuItems[indexPath!.row].fat.description + " grams\nCholesterol: " + menuItems[indexPath!.row].cholesterol.description + " grams\nSodium: " + menuItems[indexPath!.row].sodium.description + " grams\nProtein: " + menuItems[indexPath!.row].protein.description + " grams"
viewController.testFood = menuItems[indexPath!.row].name
viewController.testDescription = menuItems[indexPath!.row].description
viewController.testPrice = menuItems[indexPath!.row].price.description
viewController.testCalories = menuItems[indexPath!.row].calories.description
viewController.testCarbohydrates = menuItems[indexPath!.row].carbohydrate.description
viewController.testFats = menuItems[indexPath!.row].fat.description
viewController.testCholesteral = menuItems[indexPath!.row].cholesterol.description
viewController.testSodium = menuItems[indexPath!.row].sodium.description
viewController.testProtein = menuItems[indexPath!.row].protein.description
viewController.testPic = menuItems[indexPath!.row].pic
//labels for switch between textbox to label controls
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
|
//
// AppDelegate.swift
// quizzy
//
// Created by Kristen Chen on 11/29/20.
//
import Foundation
import UIKit
import Firebase
import Resolver
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
}
|
//
// RegistrationTVC.swift
// StartUp
//
// Created by Saleh on 31/1/17.
// Copyright © 2017 Rokomari (https://www.rokomari.com/policy). All rights reserved.
//
import UIKit
class RegistrationTVC: UITableViewController {
@IBOutlet weak var emailContainerView: UIView!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordContainerView: UIView!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var signUpButton: UIButton!
//
@IBOutlet weak var fullNameContainerView: UIView!
@IBOutlet weak var phoneContainerView: UIView!
@IBOutlet weak var fullNameTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var maleSwitch: UISwitch!
@IBOutlet weak var femaleSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// self.navigationController?.navigationBarHidden = true
self.title = "Sign Up"
setUpUI()
}
func setUpUI()
{
self.tableView.separatorColor = UIColor.clear
self.emailContainerView.layer.cornerRadius = 2.0
self.emailContainerView.layer.borderColor = UIColor.lightGray.cgColor
self.emailContainerView.layer.borderWidth = 1.0
self.passwordContainerView.layer.cornerRadius = 2.0
self.passwordContainerView.layer.borderColor = UIColor.lightGray.cgColor
self.passwordContainerView.layer.borderWidth = 1.0
self.fullNameContainerView.layer.cornerRadius = 2.0
self.fullNameContainerView.layer.borderColor = UIColor.lightGray.cgColor
self.fullNameContainerView.layer.borderWidth = 1.0
self.phoneContainerView.layer.cornerRadius = 2.0
self.phoneContainerView.layer.borderColor = UIColor.lightGray.cgColor
self.phoneContainerView.layer.borderWidth = 1.0
self.signUpButton.layer.cornerRadius = 2.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func signInButtonAction(_ sender: UIButton) {
let _ = self.navigationController?.popViewController(animated: true)
}
@IBAction func facebookButtonAction(_ sender: AnyObject) {
print("facebook button tapped")
}
@IBAction func gmailButtonAction(_ sender: AnyObject) {
print("gmial button tapped")
}
@IBAction func signUpButtonAction(_ sender: AnyObject) {
print("signup button tapped")
}
//
@IBAction func maleSwitchAction(_ sender: AnyObject) {
print("male switch pressed")
}
@IBAction func femaleSwitchAction(_ sender: AnyObject) {
print("female switch pressed")
}
}
|
//
// MapViewController.swift
// ShopSearch
//
// Created by Kanako Kobayashi on 2017/01/14.
// Copyright © 2017年 Swift-Beginners. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
// 緯度情報
var latitude: Double = 0.0
// 経度情報
var longitude: Double = 0.0
// 店舗情報
var shop_info: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// 位置情報を設定
let coordinate = CLLocationCoordinate2DMake(latitude, longitude)
// 表示領域を設定
let span = MKCoordinateSpanMake(0.005, 0.005)
let region = MKCoordinateRegionMake(coordinate, span)
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude)
// 店舗情報をセット
annotation.title = shop_info
// ピンを立てる
self.dispMap.setRegion(region, animated:true)
self.dispMap.addAnnotation(annotation)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var dispMap: MKMapView!
}
|
//
// ViewController.swift
// AppleNewsFeed
//
// Created by karlis.kazulis on 12/02/2021.
//
import UIKit
class NewsFeedViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Apple news"
}
@IBAction func getDataTapped(_ sender: Any) {
}
func handleGetData(){
}
}
|
//
// ProfileViewController.swift
// macro-tracker
//
// Created by Felix on 2020-03-10.
// Copyright © 2020 Felix. All rights reserved.
//
import UIKit
import CoreData
protocol ProfileViewControllerDelegate: AnyObject {
func showProfileEdit()
}
class ProfileViewController: UIViewController {
weak var delegate: ProfileViewControllerDelegate?
private let viewModel = ProfileViewModel()
private let scrollView = UIScrollView()
private let resultsLabel = MTLabel()
private let bodyInfoLabel = MTLabel()
private let editTableAction = UIButton()
private var bmrIcon = UIImageView(image: UIImage(named: "fire"))
private let bmrValue = MTLabel()
private let bmrLabel = MTLabel()
private let bmiIcon = UIImageView(image: UIImage(named: "bmi"))
private let bmiValue = MTLabel()
private let bmiLabel = MTLabel()
private let waterIcon = UIImageView(image: UIImage(named: "water"))
private let waterValue = MTLabel()
private let waterLabel = MTLabel()
private let resultsView = ContainerCardView()
private let bodyInfoTableContainer = ContainerCardView()
private let bodyInfoTable = UITableView()
init() {
super.init(nibName: nil, bundle: nil)
title = "Profile"
let icon = UIImage(named: "person.ios")
tabBarItem = UITabBarItem(title: "Profile", image: icon, selectedImage: icon)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupConstraints()
}
func setupView() {
scrollView.contentSize.height = 700
scrollView.alwaysBounceVertical = true
scrollView.showsVerticalScrollIndicator = false
scrollView.backgroundColor = .clear
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
resultsLabel.text = "Calculated Results"
resultsLabel.font = UIFont.systemFont(ofSize: 25)
resultsLabel.textAlignment = .center
scrollView.addSubview(resultsLabel)
resultsView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(resultsView)
bmrValue.text = viewModel.getBMRAsString()
bmrValue.textColor = .black
bmrValue.font = UIFont.systemFont(ofSize: 25)
bmrValue.translatesAutoresizingMaskIntoConstraints = false
resultsView.addSubview(bmrValue)
bmrLabel.text = "Basal Metabolic Rate"
bmrLabel.font = UIFont.systemFont(ofSize: 15)
resultsView.addSubview(bmrLabel)
bmrIcon.translatesAutoresizingMaskIntoConstraints = false
resultsView.addSubview(bmrIcon)
bmiValue.text = viewModel.getBMIAsString()
bmiValue.font = UIFont.systemFont(ofSize: 25)
resultsView.addSubview(bmiValue)
bmiLabel.text = "Body Mass Index"
bmiLabel.font = UIFont.systemFont(ofSize: 15)
resultsView.addSubview(bmiLabel)
bmiIcon.translatesAutoresizingMaskIntoConstraints = false
resultsView.addSubview(bmiIcon)
waterValue.text = viewModel.getWaterRequirementAsString()
waterValue.font = UIFont.systemFont(ofSize: 25)
resultsView.addSubview(waterValue)
waterLabel.text = "Daily Water Requirement"
waterLabel.font = UIFont.systemFont(ofSize: 15)
resultsView.addSubview(waterLabel)
waterIcon.translatesAutoresizingMaskIntoConstraints = false
resultsView.addSubview(waterIcon)
bodyInfoLabel.text = "User Information"
bodyInfoLabel.font = UIFont.systemFont(ofSize: 25)
bodyInfoLabel.textAlignment = .center
scrollView.addSubview(bodyInfoLabel)
editTableAction.addTarget(self, action: #selector(showEditAction), for: .touchUpInside)
editTableAction.setImage(UIImage(named: "edit"), for: .normal)
editTableAction.tintColor = .black
editTableAction.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(editTableAction)
bodyInfoTableContainer.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(bodyInfoTableContainer)
bodyInfoTable.enableRoundedCorners()
bodyInfoTable.delegate = self
bodyInfoTable.dataSource = self
bodyInfoTable.backgroundColor = .white
bodyInfoTable.isScrollEnabled = false
bodyInfoTable.allowsSelection = false
bodyInfoTable.register(ProfileTableViewCell.self, forCellReuseIdentifier: "cell")
bodyInfoTable.translatesAutoresizingMaskIntoConstraints = false
bodyInfoTableContainer.addSubview(bodyInfoTable)
}
func setupConstraints() {
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor),
resultsLabel.topAnchor.constraint(equalTo: scrollView.topAnchor),
resultsLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: Constants.profileSidePadding),
resultsView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
resultsView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 0.96),
resultsView.heightAnchor.constraint(equalToConstant: 230),
resultsView.topAnchor.constraint(equalTo: resultsLabel.bottomAnchor, constant: 10),
bmrIcon.topAnchor.constraint(equalTo: resultsView.topAnchor, constant: 20),
bmrIcon.leadingAnchor.constraint(equalTo: resultsView.leadingAnchor, constant: 30),
bmrValue.centerXAnchor.constraint(equalTo: resultsView.centerXAnchor),
bmrValue.topAnchor.constraint(equalTo: resultsView.topAnchor, constant: 20),
bmrLabel.centerXAnchor.constraint(equalTo: resultsView.centerXAnchor),
bmrLabel.topAnchor.constraint(equalTo: bmrValue.bottomAnchor),
bmiIcon.topAnchor.constraint(equalTo: bmrIcon.bottomAnchor, constant: 20),
bmiIcon.leadingAnchor.constraint(equalTo: resultsView.leadingAnchor, constant: 30),
bmiValue.centerXAnchor.constraint(equalTo: resultsView.centerXAnchor),
bmiValue.topAnchor.constraint(equalTo: bmrLabel.bottomAnchor, constant: 20),
bmiLabel.centerXAnchor.constraint(equalTo: resultsView.centerXAnchor),
bmiLabel.topAnchor.constraint(equalTo: bmiValue.bottomAnchor),
waterIcon.topAnchor.constraint(equalTo: bmiIcon.bottomAnchor, constant: 20),
waterIcon.leadingAnchor.constraint(equalTo: resultsView.leadingAnchor, constant: 30),
waterValue.centerXAnchor.constraint(equalTo: resultsView.centerXAnchor),
waterValue.topAnchor.constraint(equalTo: bmiLabel.bottomAnchor, constant: 20),
waterLabel.centerXAnchor.constraint(equalTo: resultsView.centerXAnchor),
waterLabel.topAnchor.constraint(equalTo: waterValue.bottomAnchor),
bodyInfoLabel.topAnchor.constraint(equalTo: resultsView.bottomAnchor, constant: 30),
bodyInfoLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: Constants.profileSidePadding),
editTableAction.topAnchor.constraint(equalTo: resultsView.bottomAnchor, constant: 35),
editTableAction.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -Constants.profileSidePadding - 5),
bodyInfoTableContainer.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 0.96),
bodyInfoTableContainer.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
bodyInfoTableContainer.topAnchor.constraint(equalTo: bodyInfoLabel.bottomAnchor, constant: 10),
bodyInfoTableContainer.heightAnchor.constraint(equalToConstant: 299),
bodyInfoTable.widthAnchor.constraint(equalTo: bodyInfoTableContainer.widthAnchor),
bodyInfoTable.heightAnchor.constraint(equalTo: bodyInfoTableContainer.heightAnchor)
])
}
@objc func showEditAction() {
delegate?.showProfileEdit()
}
}
extension ProfileViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ProfileTableViewCell
let cellTypes = viewModel.cellTypes
let profileData = viewModel.dataAsString
cell.backgroundColor = .clear
cell.textLabel?.textColor = .black
cell.titleLabel.text = cellTypes[indexPath.row].rawValue
cell.infoLabel.text = profileData[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
50
}
}
|
//
// PersonCollectionViewCell.swift
// Film
//
// Created by Tomas Vosicky on 26.11.16.
// Copyright © 2016 Tomas Vosicky. All rights reserved.
//
import UIKit
class PersonCollectionViewCell: UICollectionViewCell {
weak var faceImage: UIImageView!
weak var titleLabel: UILabel!
weak var characterLabel: UILabel!
var person: Person? {
didSet {
titleLabel.text = person?.name
characterLabel.text = person?.character
if (person?.profilePath != nil) {
faceImage.image = nil
faceImage.loadImage(usingUrl: TMDBRequest.getImage(for: person!))
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.snp.makeConstraints { (make) in
make.width.equalTo(95)
}
let faceImage = UIImageView()
faceImage.contentMode = .scaleAspectFill
faceImage.layer.cornerRadius = 45
faceImage.layer.masksToBounds = true
faceImage.backgroundColor = .gray
addSubview(faceImage)
faceImage.snp.makeConstraints({ (make) in
make.width.height.equalTo(90)
make.top.centerX.equalTo(self)
})
let titleLabel = UILabel()
titleLabel.textAlignment = .center
titleLabel.textColor = .white
// titleLabel.backgroundColor = .blue
titleLabel.numberOfLines = 2
titleLabel.font = UIFont.systemFont(ofSize: 13)
addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(faceImage.snp.bottom).offset(7)
make.centerX.equalTo(faceImage.snp.centerX)
make.width.equalTo(self)
}
let characterLabel = UILabel()
characterLabel.textAlignment = .center
characterLabel.textColor = .gray
// characterLabel.backgroundColor = .green
characterLabel.numberOfLines = 1
characterLabel.font = UIFont.systemFont(ofSize: 12)
addSubview(characterLabel)
characterLabel.snp.makeConstraints { (make) in
make.top.equalTo(titleLabel.snp.bottom).offset(4)
make.centerX.equalTo(faceImage.snp.centerX)
make.width.equalTo(self)
}
self.faceImage = faceImage
self.titleLabel = titleLabel
self.characterLabel = characterLabel
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// Origin.swift
// TFT companion app
//
// Created by Sam Wayne on 7/5/19.
// Copyright © 2019 Sam Wayne. All rights reserved.
//
import Foundation
struct Origin : Decodable {
let name: String
let description: String?
// let bonuses: [Bonus]
let accentChampionImage: String
}
//struct Bonus : Decodable {
// let needed: Int
// let effect: String
//
//}
|
//
// NSErrorExtensions.swift
// CTFS_Wallet
//
// Created by Subba Nelakudhiti on 9/29/17.
// Copyright © 2017 Subba Nelakudhiti. All rights reserved.
//
import UIKit
//MARK: Error Codes
enum NetworkStatusCode:Int {
case REQUEST_SUCCESS = 200
case REQUEST_TIMEOUT = -1001
}
//MARK: Error Message
enum ErrorManager:Error
{
case NoInternetAvaialble
case NoBaseUrlAvailable
case NoApiResponse
case JsonParsingError
case HttpError(statusCode:Int)
case UnkonwnError
var descrption : String
{
switch self {
case .NoInternetAvaialble:
return "Its seems to be Offline"
case .NoBaseUrlAvailable:
return "Api basr url not "
case .JsonParsingError:
return "Not valid Json"
case .HttpError(let statusCode):
return generateHttpErrorMessage(statusCode: statusCode)
default:
return "Unknown Error"
}
}
}
// MARK: Create Http Error Message based on Status Code
func generateHttpErrorMessage(statusCode:Int) -> String
{
switch statusCode {
case NetworkStatusCode.REQUEST_SUCCESS.rawValue:
return "Network Call Success"
case NetworkStatusCode.REQUEST_TIMEOUT.rawValue:
return "Request Time Out For Api Calls"
default:
return "Unknown Error"
}
}
|
import Cocoa
/**
* Callback signature
*/
extension FileWatcher {
public typealias CallBack = (_ fileWatcherEvent: FileWatcherEvent) -> Void
}
|
//
// MainTableViewController.swift
// YACTA
//
// Created by MAC on 25/11/2019.
// Copyright © 2019 Gera Volobuev. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController {
let defaults = UserDefaults.standard
let sharedDefaults = UserDefaults(suiteName:
"group.todayExtensionYACTA")
var remindersArray = [String]() {
didSet {
sharedDefaults?.setValue(remindersArray, forKey: "newEntry")
defaults.setValue(remindersArray, forKey: "oldArray")
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "YADLA"
registerLocal()
// custom table view
self.registerTableViewCells()
self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
// :NAVIGATION BAR BUTTONS //
// try using SF symbol for add button
if #available(iOS 13.0, *) {
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "plus"), style: .plain, target: self, action: #selector(pushDateEdit))
} else {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(pushDateEdit))
}
// check if user stored any data previously and insert it
let data = defaults.value(forKey: "oldArray")
if data != nil {
remindersArray = data as! Array
}
NotificationCenter.default.addObserver(self, selector: #selector(appBecomeActive), name: UIApplication.willEnterForegroundNotification, object: nil )
}
@objc func appBecomeActive() {
tableView.reloadData()
}
// push to next view for adding reminder
@objc func pushDateEdit() {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Date") as? DateViewController {
vc.delegate = self
navigationController?.pushViewController(vc, animated: true)
}
}
// add new entry to array
func addDate(newDate: String) {
remindersArray.append(newDate)
tableView.reloadData()
let splittedDate = newDate.components(separatedBy: "\n")
// let date = String(daysLeft(days: splittedDate[1]))
scheduleLocal(title: splittedDate[0], body: splittedDate[1])
}
// edit existing array entry
func editDate(newDate: String, oldDate: String) {
if let row = remindersArray.firstIndex(where: {$0 == oldDate}) {
remindersArray[row] = newDate
tableView.reloadData()
}
}
// register custom table cell
func registerTableViewCells() {
let customCell = UINib(nibName: "CustomTableViewCell", bundle: nil)
self.tableView.register(customCell, forCellReuseIdentifier: "CustomTableViewCell")
}
// calculate number of days left from reminer's date entry
func daysLeft(days: String) -> Int {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy"
guard let date = dateFormatter.date(from: days) else { return 0 }
let now = Date()
let calendar = Calendar.current
let date1 = calendar.startOfDay(for: now)
let date2 = calendar.startOfDay(for: date)
let components = calendar.dateComponents([.day], from: date1, to: date2)
return components.day!
}
// MARK: - Notifications
@objc func registerLocal() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("Yay")
} else {
print("Douh")
}
}
}
@objc func scheduleLocal(title: String, body: String) {
let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.categoryIdentifier = "alarm"
content.sound = .default
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy"
let date = dateFormatter.date(from: body)
let calendar = NSCalendar.current
let components = calendar.dateComponents([.day, .month, .year], from: date!)
var dateComponets = DateComponents()
dateComponets.hour = 19
dateComponets.minute = 30
dateComponets.year = components.year
dateComponets.month = components.month
dateComponets.day = components.day
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponets, repeats: true)
// let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false) // for debuging
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return remindersArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as? CustomTableViewCell else { fatalError("Unable to dequeue cell") }
// Get user date+reminder as item
let date = remindersArray[indexPath.row]
// split item array in two seperating it by new line
let splittedDate = date.components(separatedBy: "\n")
// use daysLeft() on item date and place it in detailLabel
cell.daysLeftLabel?.text = String(daysLeft(days: splittedDate[1]))
cell.dateLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
// Color the reminder title
let headerColor = date
let footerColor = splittedDate[0]
let range = (headerColor as NSString).range(of: footerColor)
let coloredResult = NSMutableAttributedString.init(string: headerColor)
coloredResult.addAttribute(NSAttributedString.Key.foregroundColor, value: #colorLiteral(red: 0.9960784314, green: 0.3764705882, blue: 0.3254901961, alpha: 1), range: range)
cell.dateLabel?.attributedText = coloredResult
return cell
}
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, complete in
self.remindersArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
complete(true)
}
UIButton.appearance().setTitleColor(#colorLiteral(red: 0.9960784314, green: 0.3764705882, blue: 0.3254901961, alpha: 1), for: UIControl.State.normal)
deleteAction.title = "DELETE"
deleteAction.backgroundColor = .white
let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
configuration.performsFirstActionWithFullSwipe = true
return configuration
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let DVC = storyboard?.instantiateViewController(withIdentifier: "Date") as? DateViewController {
DVC.delegate = self
navigationController?.pushViewController(DVC, animated: true)
DVC.cellForEdit.append(remindersArray[indexPath.row])
DVC.cellForEdit.append(String(indexPath.row))
}
}
}
|
//
// WikiConstants.swift
// Travel Companion
//
// Created by Stefan Jaindl on 26.08.18.
// Copyright © 2018 Stefan Jaindl. All rights reserved.
//
import Foundation
struct WikiConstants {
struct UrlComponents {
static let urlProtocol = "https"
static let domainWikipedia = "en.wikipedia.org"
static let domainWikiVoyage = "en.wikivoyage.org"
static let path = "/w/api.php"
}
struct ParameterKeys {
static let action = "action"
static let format = "format"
static let titles = "titles"
static let prop = "prop"
static let inprop = "inprop"
}
struct ParameterValues {
static let query = "query"
static let responseFormat = "json"
static let propInfo = "info"
static let inprop = "url"
}
struct ResponseKeys {
static let fullUrl = "fullurl"
}
}
|
//
// NewTopicController.swift
// rush00
//
// Created by Audran DITSCH on 1/13/18.
// Copyright © 2018 Charles LANIER. All rights reserved.
//
import UIKit
class NewTopicController: UIViewController, UITextViewDelegate {
@IBOutlet weak var topicTitle: UITextField!
@IBOutlet weak var topicContent: UITextView!
@IBOutlet weak var sendButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let myColor = UIColor.lightGray
topicContent.delegate = self
topicContent.text = "Enter your comment here..."
topicContent.textColor = .lightGray
topicContent.layer.borderColor = myColor.cgColor
topicContent.layer.borderWidth = 0.3
topicContent.layer.cornerRadius = 5.0
}
func textViewDidBeginEditing(_ textView: UITextView)
{
if (textView.text == "Enter your comment here...")
{
textView.text = ""
textView.textColor = .black
}
textView.becomeFirstResponder() //Optional
}
func textViewDidEndEditing(_ textView: UITextView)
{
if (textView.text == "")
{
textView.text = "Enter your comment here..."
textView.textColor = .lightGray
}
textView.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// NeopixelModuleManager.swift
// Bluefruit Connect
//
// Created by Antonio García on 24/02/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import Foundation
import CoreImage
class NeopixelModuleManager: NSObject {
// Constants
private static let kSketchVersion = "Neopixel v2."
//
enum Components: CaseIterable {
case rgb
case rbg
case grb
case gbr
case brg
case bgr
case wrgb
case wrbg
case wgrb
case wgbr
case wbrg
case wbgr
case rwgb
case rwbg
case rgwb
case rgbw
case rbwg
case rbgw
case gwrb
case gwbr
case grwb
case grbw
case gbwr
case gbrw
case bwrg
case bwgr
case brwg
case brgw
case bgwr
case bgrw
var value: UInt8 {
switch self {
// Offset: W R G B
case .rgb: return ((0 << 6) | (0 << 4) | (1 << 2) | (2))
case .rbg: return ((0 << 6) | (0 << 4) | (2 << 2) | (1))
case .grb: return ((1 << 6) | (1 << 4) | (0 << 2) | (2))
case .gbr: return ((2 << 6) | (2 << 4) | (0 << 2) | (1))
case .brg: return ((1 << 6) | (1 << 4) | (2 << 2) | (0))
case .bgr: return ((2 << 6) | (2 << 4) | (1 << 2) | (0))
// RGBW NeoPixel permutations; all 4 offsets are distinct
// Offset: W R G B
case .wrgb: return ((0 << 6) | (1 << 4) | (2 << 2) | (3))
case .wrbg: return ((0 << 6) | (1 << 4) | (3 << 2) | (2))
case .wgrb: return ((0 << 6) | (2 << 4) | (1 << 2) | (3))
case .wgbr: return ((0 << 6) | (3 << 4) | (1 << 2) | (2))
case .wbrg: return ((0 << 6) | (2 << 4) | (3 << 2) | (1))
case .wbgr: return ((0 << 6) | (3 << 4) | (2 << 2) | (1))
case .rwgb: return ((1 << 6) | (0 << 4) | (2 << 2) | (3))
case .rwbg: return ((1 << 6) | (0 << 4) | (3 << 2) | (2))
case .rgwb: return ((2 << 6) | (0 << 4) | (1 << 2) | (3))
case .rgbw: return ((3 << 6) | (0 << 4) | (1 << 2) | (2))
case .rbwg: return ((2 << 6) | (0 << 4) | (3 << 2) | (1))
case .rbgw: return ((3 << 6) | (0 << 4) | (2 << 2) | (1))
case .gwrb: return ((1 << 6) | (2 << 4) | (0 << 2) | (3))
case .gwbr: return ((1 << 6) | (3 << 4) | (0 << 2) | (2))
case .grwb: return ((2 << 6) | (1 << 4) | (0 << 2) | (3))
case .grbw: return ((3 << 6) | (1 << 4) | (0 << 2) | (2))
case .gbwr: return ((2 << 6) | (3 << 4) | (0 << 2) | (1))
case .gbrw: return ((3 << 6) | (2 << 4) | (0 << 2) | (1))
case .bwrg: return ((1 << 6) | (2 << 4) | (3 << 2) | (0))
case .bwgr: return ((1 << 6) | (3 << 4) | (2 << 2) | (0))
case .brwg: return ((2 << 6) | (1 << 4) | (3 << 2) | (0))
case .brgw: return ((3 << 6) | (1 << 4) | (2 << 2) | (0))
case .bgwr: return ((2 << 6) | (3 << 4) | (1 << 2) | (0))
case .bgrw: return ((3 << 6) | (2 << 4) | (1 << 2) | (0))
}
}
var numComponents: Int {
switch self {
case .rgb, .rbg, .grb, .gbr, .brg, .bgr: return 3
default: return 4
}
}
var name: String {
switch self {
case .rgb: return "RGB"
case .rbg: return "RBG"
case .grb: return "GRB"
case .gbr: return "GBR"
case .brg: return "BRG"
case .bgr: return "BGR"
case .wrgb: return "WRGB"
case .wrbg: return "WRBG"
case .wgrb: return "WGRB"
case .wgbr: return "WGBR"
case .wbrg: return "WBRG"
case .wbgr: return "WBGR"
case .rwgb: return "RWGB"
case .rwbg: return "RWBG"
case .rgwb: return "RGWB"
case .rgbw: return "RGBW"
case .rbwg: return "RBWG"
case .rbgw: return "RBGW"
case .gwrb: return "GWRB"
case .gwbr: return "GWBR"
case .grwb: return "GRWB"
case .grbw: return "GRBW"
case .gbwr: return "GBWR"
case .gbrw: return "GBRW"
case .bwrg: return "BWRG"
case .bwgr: return "BWGR"
case .brwg: return "BRWG"
case .brgw: return "BRGW"
case .bgwr: return "BGWR"
case .bgrw: return "BGRW"
}
}
static func fromValue(_ value: UInt8) -> Components? {
return Components.allCases.first(where: {$0.value == value})
}
}
struct Board {
var name = "<No name>"
var width: UInt8 = 0, height: UInt8 = 0
var stride: UInt8 = 0
static func loadStandardBoard(_ standardIndex: Int) -> Board? {
let path = Bundle.main.path(forResource: "NeopixelBoards", ofType: "plist")!
guard let boards = NSArray(contentsOfFile: path) as? [[String: AnyObject]] else { DLog("Error: cannot load boards"); return nil }
let boardData = boards[standardIndex]
let name = boardData["name"] as! String
let width = UInt8((boardData["width"] as! NSNumber).intValue)
let height = UInt8((boardData["height"] as! NSNumber).intValue)
let stride = UInt8((boardData["stride"] as! NSNumber).intValue)
let board = NeopixelModuleManager.Board(name: name, width: width, height: height, stride: stride)
return board
}
}
// Bluetooth Uart
private var uartManager: UartPacketManager!
private var blePeripheral: BlePeripheral
// Neopixel
var isSketchDetected: Bool?
public private(set) var board: Board?
private var components = Components.grb
private var is400KhzEnabled = false
init(blePeripheral: BlePeripheral) {
self.blePeripheral = blePeripheral
super.init()
// Init Uart
uartManager = UartPacketManager(delegate: nil, isPacketCacheEnabled: false, isMqttEnabled: false)
}
deinit {
DLog("neopixel deinit")
stop()
}
// MARK: - Start / Stop
func start(uartReadyCompletion:@escaping ((Error?) -> Void)) {
DLog("neopixel start")
// Enable Uart
blePeripheral.uartEnable(uartRxHandler: uartManager.rxPacketReceived) { error in
uartReadyCompletion(error)
}
}
func stop() {
DLog("neopixel stop")
blePeripheral.reset()
}
func isReady() -> Bool {
return blePeripheral.isUartEnabled()
}
func isBoardConfigured() -> Bool {
return board != nil
}
func connectNeopixel(completion: @escaping ((Bool) -> Void)) {
self.checkNeopixelSketch(completion: completion)
}
// MARK: - Neopixel Commands
private func checkNeopixelSketch(completion: @escaping ((Bool) -> (Void))) {
// Send version command and check if returns a valid response
DLog("Command: get Version")
let command: [UInt8] = [0x56] // V
let data = Data(bytes: command, count: command.count)
isSketchDetected = nil // Reset status
uartManager.sendAndWaitReply(blePeripheral: blePeripheral, data: data) { (data, error) in
var isSketchDetected = false
if let data = data as? Data, error == nil, let result = String(data: data, encoding: .utf8) {
if result.hasPrefix(NeopixelModuleManager.kSketchVersion) {
isSketchDetected = true
} else {
DLog("Error: sketch wrong version: \(result). Expecting: \(NeopixelModuleManager.kSketchVersion)")
}
} else if let error = error {
DLog("Error: checkNeopixelSketch: \(error)")
}
DLog("isNeopixelAvailable: \(isSketchDetected)")
self.isSketchDetected = isSketchDetected
completion(isSketchDetected)
}
}
func setupNeopixel(board device: Board, components: Components, is400HzEnabled: Bool, completion: @escaping ((Bool) -> Void)) {
DLog("Command: Setup")
// let pinNumber: UInt8 = 6 // TODO: ask user
let command: [UInt8] = [0x53, device.width, device.height, device.stride, components.value, is400HzEnabled ? 1:0] // Command: 'S'
let data = Data(bytes: command, count: command.count)
uartManager.sendAndWaitReply(blePeripheral: blePeripheral, data: data) { [weak self] (data, error) in
guard let context = self else { completion(false); return }
var success = false
if let error = error {
DLog("Error: setupNeopixel: \(error)")
}
else if let data = data as? Data, let result = String(data: data, encoding: .utf8) {
success = result.hasPrefix("OK")
}
DLog("setup success: \(success)")
if success {
context.board = device
context.components = components
context.is400KhzEnabled = is400HzEnabled
}
completion(success)
}
}
func resetBoard() {
board = nil
}
func setPixelColor(_ color: Color, colorW: Float, x: UInt8, y: UInt8, completion: ((Bool) -> Void)? = nil) {
DLog("Command: set Pixel")
let numComponents = components.numComponents
guard numComponents == 3 || numComponents == 4 else {
DLog("Error: unsupported numComponents: \(numComponents)");
completion?(false)
return
}
let rgb = colorComponents(color)
var command: [UInt8] = [0x50, x, y, rgb.red, rgb.green, rgb.blue ] // Command: 'P'
if components.numComponents == 4 {
let colorWValue = UInt8(colorW*255)
command.append(colorWValue)
}
sendCommand(command, completion: completion)
}
func clearBoard(color: Color, colorW: Float, completion: ((Bool) -> Void)? = nil) {
DLog("Command: Clear")
let numComponents = components.numComponents
guard numComponents == 3 || numComponents == 4 else {
DLog("Error: unsupported numComponents: \(components.numComponents)");
completion?(false)
return
}
let rgb = colorComponents(color)
var command: [UInt8] = [0x43, rgb.red, rgb.green, rgb.blue] // Command: 'C'
if numComponents == 4 {
let colorWValue = UInt8(colorW*255)
command.append(colorWValue)
}
sendCommand(command, completion: completion)
}
func setBrighness(_ brightness: Float, completion: ((Bool) -> Void)? = nil) {
DLog("Command: set Brightness: \(brightness)")
let brightnessValue = UInt8(brightness*255)
let command: [UInt8] = [0x42, brightnessValue ] // Command: 'B'
sendCommand(command, completion: completion)
}
private func colorComponents(_ color: Color) -> (red: UInt8, green: UInt8, blue: UInt8) {
let colorComponents = color.cgColor.components
let r = UInt8((colorComponents?[0])! * 255)
let g = UInt8((colorComponents?[1])! * 255)
let b = UInt8((colorComponents?[2])! * 255)
return (r, g, b)
}
func setImage(completion: ((Bool) -> Void)?) {
DLog("Command: set Image")
// TODO: implement
let width: UInt8 = 8
let height: UInt8 = 4
var command: [UInt8] = [0x49] // Command: 'I'
let redPixel: [UInt8] = [32, 1, 1 ]
let blackPixel: [UInt8] = [0, 0, 0 ]
var imageData: [UInt8] = []
let imageLength = width * height
for i in 0..<imageLength {
imageData.append(contentsOf: i%2==0 ? redPixel : blackPixel)
}
command.append(contentsOf: imageData)
sendCommand(command, completion: completion)
}
private func sendCommand(_ command: [UInt8], completion: ((Bool) -> Void)? = nil) {
let data = Data(bytes: command, count: command.count)
sendCommand(data: data, completion: completion)
}
private func sendCommand(data: Data, completion: ((Bool) -> Void)? = nil) {
guard board != nil else {
DLog("sendCommand: unknown board")
completion?(false)
return
}
uartManager.sendAndWaitReply(blePeripheral: blePeripheral, data: data) { (data, error) in
var success = false
if let data = data as? Data, error == nil, let result = String(data:data, encoding: .utf8) {
success = result.hasPrefix("OK")
} else if let error = error {
DLog("Error: sendDataToUart: \(error)")
}
DLog("result: \(success)")
completion?(success)
}
}
}
|
//
// MoviesViewController.swift
// RxPractice
//
//
import UIKit
// MVC - Model View Controller
// MODEL: API, Data from Server, DB, File
// VIEW: UIX
// Controller: Glue between Model & View
// MVVM - Model View(View Controller) View-Model
// MODEL: API, Data from Server, DB, File
// VIEW: UIX (View Controller)
// VIEW-Model:
class MoviesViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let moviesViewModel = MoviesViewModel()
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension MoviesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return moviesViewModel.dummyMoviesModel.movies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let index = indexPath.row
let movietitle = moviesViewModel.getTitleOfMovie(index)
let cell = UITableViewCell()
cell.textLabel?.text = movietitle
return cell
}
}
|
//
// Position.swift
// TG
//
// Created by Andrii Narinian on 8/7/17.
// Copyright © 2017 ROLIQUE. All rights reserved.
//
import Foundation
struct Position {
var x: Double
var y: Double
var z: Double
}
|
//
// DetailViewController.swift
// Table
//
// Created by 조주혁 on 2020/06/09.
// Copyright © 2020 Ju-Hyuk Cho. All rights reserved.
//
import UIKit
import Firebase
class DetailViewController: UIViewController {
var ref: DatabaseReference!
var itemName: String = ""
let uid: String = (Auth.auth().currentUser?.uid)!
@IBOutlet var lblItem: UILabel!
@IBOutlet var lblStartDate: UILabel!
@IBOutlet var lblFinishDate: UILabel!
@IBOutlet var lblPrice: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
ref = Database.database().reference()
}
func receiveItem() {
ref.child(uid).child(itemName).observeSingleEvent(of: .value) { snapshot in
let value = snapshot.value as? String ?? "errorItem"
self.lblItem.text = value
}
}
func receiveStartDate() {
ref.child(uid).child(itemName).child("start").observeSingleEvent(of: .value) { snapshot in
let value = snapshot.value as? String ?? "errorStartDate"
self.lblStartDate.text = value
}
}
func receiveFinishDate() {
ref.child(uid).child(itemName).child("finish").observeSingleEvent(of: .value) { snapshot in
let value = snapshot.value as? String ?? "errorFinishDate"
self.lblFinishDate.text = value
}
}
func receivePrice() {
ref.child(uid).child(itemName).child("price").observeSingleEvent(of: .value) { snapshot in
let value = snapshot.value as? String ?? "errorPrice"
self.lblPrice.text = value
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// MovieInput.swift
// MetalImage
//
// Created by Andrei-Sergiu Pițiș on 02/07/2017.
// Copyright © 2017 Andrei-Sergiu Pițiș. All rights reserved.
//
import Foundation
import AVFoundation
import Accelerate
//This will be passed by reference, but Swift structs are passed by value, hence the class qualifier.
private class AudioStructure {
var instance: MovieInput?
var audioFormat: AudioStreamBasicDescription?
}
public enum PlaybackOptions {
case none
case playAtactualSpeed
case playAtactualSpeedAndLoopIndefinetely
}
public class MovieInput: ImageSource {
public var targets: [ImageConsumer] = []
fileprivate(set) public var outputTexture: MTLTexture?
fileprivate var frameTime: CMTime = kCMTimeZero
private let asset: AVURLAsset
private var assetReader: AVAssetReader?
private let assetReaderQueue: DispatchQueue = DispatchQueue.global(qos: .background)
private let context: MetalContext
private let metalTextureCache: CVMetalTextureCache
//Used for playback at actual speed
private var endRecordingTime: CMTime = kCMTimeZero
private var playerItem: AVPlayerItem?
private var player: AVQueuePlayer?
private var itemVideoOutput: AVPlayerItemVideoOutput?
private let playbackOptions: PlaybackOptions
private lazy var displayLink = DisplayLink { (displayLink, timestamp) in
self.render(displayLink: displayLink, timestamp: timestamp)
}
private var completionCallback: (() -> Void)?
private(set) var isRunning: Bool = false
public weak var audioEncodingTarget: AudioEncodingTarget? {
didSet {
audioEncodingTarget?.enableAudio()
}
}
public init?(url: URL, playbackOptions: PlaybackOptions = .none, context: MetalContext) {
guard let textureCache = context.textureCache() else {
Logger.error("Could not create texture cache")
return nil
}
self.metalTextureCache = textureCache
self.context = context
asset = AVURLAsset(url: url)
self.playbackOptions = playbackOptions
let videoTracks = asset.tracks(withMediaType: .video)
let audioTracks = asset.tracks(withMediaType: .audio)
if playbackOptions != .none {
player = AVQueuePlayer()
playerItem = AVPlayerItem(asset: asset)
let attributes = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_32BGRA)]
itemVideoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: attributes)
playerItem?.add(itemVideoOutput!)
configureRealtimePlaybackAudio(audioTracks: audioTracks, playerItem: &playerItem!)
NotificationCenter.default.addObserver(self, selector: #selector(finishedItemPlayback(notification:)), name: .AVPlayerItemDidPlayToEndTime, object: playerItem)
player?.replaceCurrentItem(with: playerItem)
let itemCopy = playerItem?.copy() as! AVPlayerItem
player?.insert(itemCopy, after: playerItem!)
if playbackOptions == .playAtactualSpeedAndLoopIndefinetely {
player?.actionAtItemEnd = AVPlayerActionAtItemEnd.advance
} else {
player?.actionAtItemEnd = AVPlayerActionAtItemEnd.pause
}
} else {
do {
try assetReader = AVAssetReader(asset: asset)
} catch {
Logger.error("Could not create asset reader for asset")
return nil
}
setupAudio(audioTracks: audioTracks, for: assetReader!)
setupVideo(videoTracks: videoTracks, for: assetReader!)
}
}
deinit {
completionCallback = nil
NotificationCenter.default.removeObserver(self)
Logger.debug("Deinit Movie Input")
}
public func start(completion: (() -> Void)?) {
guard isRunning == false else {
Logger.warning("Movie reader is already running")
return
}
isRunning = true
if playbackOptions != .none {
completionCallback = completion
player?.play()
displayLink.start()
} else {
asset.loadValuesAsynchronously(forKeys: ["duration", "tracks"]) { [weak self] in
guard let strongSelf = self, let assetReader = strongSelf.assetReader else {
return
}
var videoOutput: AVAssetReaderOutput?
var audioOutput: AVAssetReaderOutput?
for output in assetReader.outputs {
if output.mediaType == AVMediaType.video.rawValue {
videoOutput = output
}
if output.mediaType == AVMediaType.audio.rawValue {
audioOutput = output
}
}
DispatchQueue.global(qos: .default).async {
var error: NSError?
guard strongSelf.asset.statusOfValue(forKey: "tracks", error: &error) == .loaded else {
Logger.error("Could not load tracks. Error = \(String(describing: error))")
return
}
guard assetReader.startReading() == true else {
Logger.error("Could not start asset reader")
return
}
reading: while assetReader.status == .reading {
autoreleasepool {
if let _ = strongSelf.audioEncodingTarget {
if let sampleBuffer = videoOutput?.copyNextSampleBuffer() {
strongSelf.readNextVideoFrame(sampleBuffer: sampleBuffer)
}
if let sampleBuffer = audioOutput?.copyNextSampleBuffer() {
strongSelf.readNextAudioFrame(sampleBuffer: sampleBuffer)
}
} else if let sampleBuffer = videoOutput?.copyNextSampleBuffer() {
strongSelf.readNextVideoFrame(sampleBuffer: sampleBuffer)
} else {
assetReader.cancelReading()
}
}
}
if assetReader.status == .completed || assetReader.status == .cancelled {
strongSelf.isRunning = false
assetReader.cancelReading()
completion?()
}
}
}
}
}
public func stop() {
guard isRunning == true else {
Logger.warning("Movie reader already stopped running")
return
}
isRunning = false
if playbackOptions != .none {
player?.pause()
displayLink.stop()
} else {
assetReader?.cancelReading()
}
}
//MTAudioProcessingTap implementation
private let tapInit: MTAudioProcessingTapInitCallback = {
(tap, clientInfo, tapStorageOut) in
guard let clientInfo = clientInfo else {
return
}
let pointerToSelf = Unmanaged<MovieInput>.fromOpaque(clientInfo)
let objectSelf = pointerToSelf.takeRetainedValue()
let audioStructurePointer = calloc(1, MemoryLayout<AudioStructure>.size)
audioStructurePointer?.initializeMemory(as: AudioStructure.self, to: AudioStructure())
var structure: AudioStructure? = audioStructurePointer?.bindMemory(to: AudioStructure.self, capacity: 1).pointee
structure?.instance = objectSelf
tapStorageOut.pointee = audioStructurePointer
}
private let tapFinalize: MTAudioProcessingTapFinalizeCallback = {
(tap) in
let storage = MTAudioProcessingTapGetStorage(tap)
free(storage)
Logger.info("Audio tap finalized")
}
private let tapPrepare: MTAudioProcessingTapPrepareCallback = {
(tap, itemCount, streamDescription) in
var structure: AudioStructure = MTAudioProcessingTapGetStorage(tap).bindMemory(to: AudioStructure.self, capacity: 1).pointee
structure.audioFormat = streamDescription.pointee
Logger.info("Audio tap prepared")
}
private var tapUnprepare: MTAudioProcessingTapUnprepareCallback = {
(tap) in
Logger.info("Audio tap unprepared")
}
private var tapProcess: MTAudioProcessingTapProcessCallback = {
(tap, numberFrames, flags, bufferListInOut, numberFramesOut, flagsOut) in
let status = MTAudioProcessingTapGetSourceAudio(tap, numberFrames, bufferListInOut, flagsOut, nil, numberFramesOut)
guard status == 0 else {
return
}
var structure: AudioStructure = MTAudioProcessingTapGetStorage(tap).bindMemory(to: AudioStructure.self, capacity: 1).pointee
if var format = structure.audioFormat, let object = structure.instance {
object.processAudioData(audioData: bufferListInOut, framesNumber: numberFrames, audioFormat: &format)
}
}
private func configureRealtimePlaybackAudio(audioTracks: [AVAssetTrack], playerItem: inout AVPlayerItem) {
let rawPointerSelf = Unmanaged.passUnretained(self).toOpaque()
var callbacks = MTAudioProcessingTapCallbacks(
version: kMTAudioProcessingTapCallbacksVersion_0,
clientInfo: rawPointerSelf,
init: tapInit,
finalize: tapFinalize,
prepare: tapPrepare,
unprepare: tapUnprepare,
process: tapProcess)
var tap: Unmanaged<MTAudioProcessingTap>?
let err = MTAudioProcessingTapCreate(kCFAllocatorDefault, &callbacks, kMTAudioProcessingTapCreationFlag_PostEffects, &tap)
if err == noErr {
}
var inputParameters: [AVMutableAudioMixInputParameters] = []
for track in audioTracks {
let parameter = AVMutableAudioMixInputParameters(track: track)
parameter.audioTapProcessor = tap?.takeUnretainedValue()
inputParameters.append(parameter)
}
let audioMix = AVMutableAudioMix()
audioMix.inputParameters = inputParameters
playerItem.audioMix = audioMix
_ = tap?.autorelease()
}
//MTAudioProcessingTap implementation end
@objc private func finishedItemPlayback(notification: Notification) {
guard let player = player, let lastItem = player.items().last else {
return
}
let itemCopy = lastItem.copy() as! AVPlayerItem
player.currentItem?.remove(itemVideoOutput!)
lastItem.add(itemVideoOutput!)
player.insert(itemCopy, after: lastItem)
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: playerItem)
NotificationCenter.default.addObserver(self, selector: #selector(finishedItemPlayback(notification:)), name: .AVPlayerItemDidPlayToEndTime, object: lastItem)
playerItem = lastItem
endRecordingTime = frameTime
if playbackOptions != .playAtactualSpeedAndLoopIndefinetely {
displayLink.stop()
player.advanceToNextItem()
isRunning = false
completionCallback?()
}
}
private func render(displayLink: MIDisplayLink, timestamp: MITimestamp) {
guard let videoOutput = itemVideoOutput else {
return
}
//TODO: Compare timestamps for iOS and OSX and figure out how to remove the OS checks
#if os(iOS)
let nextVsync: CFTimeInterval = timestamp + displayLink.duration
let currentTime = videoOutput.itemTime(forHostTime: nextVsync)
if videoOutput.hasNewPixelBuffer(forItemTime: currentTime), let pixelBuffer = videoOutput.copyPixelBuffer(forItemTime: currentTime, itemTimeForDisplay: nil) {
readNextImage(pixelBuffer: pixelBuffer, at: currentTime)
}
#elseif os(OSX)
var currentTime = kCMTimeInvalid
let nextVSync = timestamp
currentTime = videoOutput.itemTime(for: nextVSync)
frameTime = CMTimeAdd(currentTime, endRecordingTime)
if videoOutput.hasNewPixelBuffer(forItemTime: currentTime), let pixelBuffer = videoOutput.copyPixelBuffer(forItemTime: currentTime, itemTimeForDisplay: nil) {
readNextImage(pixelBuffer: pixelBuffer, at: frameTime)
}
#endif
}
private func readNextImage(pixelBuffer: CVImageBuffer, at frameTime: CMTime) {
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
var cvMetalTexture: CVMetalTexture?
let result = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, metalTextureCache, pixelBuffer, nil, .bgra8Unorm, width, height, 0, &cvMetalTexture)
guard result == kCVReturnSuccess else {
Logger.error("Failed to get Metal texture from pixel buffer")
return
}
let metalTexture = CVMetalTextureGetTexture(cvMetalTexture!)
outputTexture = metalTexture
autoreleasepool {
for var target in targets {
let commandBuffer = context.newCommandBuffer()
target.inputTexture = metalTexture
target.newFrameReady(at: frameTime, at: 0, using: commandBuffer)
}
}
}
private func readNextVideoFrame(sampleBuffer: CMSampleBuffer) {
assetReaderQueue.sync { [weak self] in
guard let strongSelf = self else {
return
}
guard let pixelBuffer: CVImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
Logger.error("Could not get pixel buffer.")
return
}
strongSelf.frameTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
strongSelf.readNextImage(pixelBuffer: pixelBuffer, at: strongSelf.frameTime)
}
}
private func readNextAudioFrame(sampleBuffer: CMSampleBuffer?) {
assetReaderQueue.sync {
audioEncodingTarget?.processAudio(sampleBuffer)
}
}
private func processAudioData(audioData: UnsafeMutablePointer<AudioBufferList>, framesNumber: CMItemCount, audioFormat: UnsafePointer<AudioStreamBasicDescription>) {
var sampleBuffer: CMSampleBuffer?
var status: OSStatus?
var format: CMFormatDescription?
status = CMAudioFormatDescriptionCreate(kCFAllocatorDefault, audioFormat, 0, nil, 0, nil, nil, &format)
if status != noErr {
Logger.error("Error CMAudioFormatDescriptionCreater :\(String(describing: status))")
return
}
var timing = CMSampleTimingInfo(duration: CMTimeMake(1, Int32(audioFormat.pointee.mSampleRate)), presentationTimeStamp: kCMTimeZero, decodeTimeStamp: kCMTimeInvalid)
status = CMSampleBufferCreate(kCFAllocatorDefault, nil, false, nil, nil, format, framesNumber, 1, &timing, 0, nil, &sampleBuffer)
if status != noErr {
Logger.error("Error CMSampleBufferCreate :\(String(describing: status))")
return
}
status = CMSampleBufferSetDataBufferFromAudioBufferList(sampleBuffer!, kCFAllocatorDefault , kCFAllocatorDefault, 0, audioData)
if status != noErr {
Logger.error("Error CMSampleBufferSetDataBufferFromAudioBufferList :\(String(describing: status))")
return
}
readNextAudioFrame(sampleBuffer: sampleBuffer)
}
private func setupAudio(audioTracks: [AVAssetTrack], for reader: AVAssetReader) {
guard audioTracks.count > 0 else {
Logger.info("The asset does not have any audio tracks")
return
}
let audioSettings: [String: Any] = [AVFormatIDKey: kAudioFormatLinearPCM]
let audioTrackOutput = AVAssetReaderAudioMixOutput(audioTracks: audioTracks, audioSettings: audioSettings)//AVAssetReaderTrackOutput(track: audioTrack, outputSettings: audioSettings)
audioTrackOutput.alwaysCopiesSampleData = false
if reader.canAdd(audioTrackOutput) {
reader.add(audioTrackOutput)
} else {
Logger.error("Could not add audio output to reader")
}
}
private func setupVideo(videoTracks: [AVAssetTrack], for reader: AVAssetReader) {
guard let videoTrack = videoTracks.first else {
Logger.info("The asset does not have any video tracks")
return
}
let videoSettings: [String: Any] = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]
let videoTrackOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: videoSettings)
videoTrackOutput.alwaysCopiesSampleData = false
if reader.canAdd(videoTrackOutput) {
reader.add(videoTrackOutput)
} else {
Logger.error("Could not add video output to reader")
}
}
}
|
//
// offerRideCellFile.swift
// ClassyDrives
//
// Created by Mindfull Junkies on 09/06/19.
// Copyright © 2019 Mindfull Junkies. All rights reserved.
//
import UIKit
class offerRideCellFile: UITableViewCell {
@IBOutlet var cellImg: UIImageView!
@IBOutlet var cellName: UITextField!
@IBOutlet var cellBtn: UIButton!
@IBOutlet var cellView: UIView!
var cellAtn:((offerRideCellFile)->Void)?
override func awakeFromNib() {
super.awakeFromNib()
cellView.setShadow()
cellBtn.addTarget(self, action: #selector(cellBtnAtn), for: .touchUpInside)
}
@objc func cellBtnAtn(){
cellAtn?(self)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// ContentView.swift
// Pixlation
//
// Created by Chelsie Eiden on 2/12/20.
// Copyright © 2020 Chelsie Eiden. All rights reserved.
//
import SwiftUI
struct CaptureImageView {
@Binding var isShown: Bool
@Binding var image: Image?
func makeCoordinator() -> Coordinator {
return Coordinator(isShown: $isShown, image: $image)
}
}
extension CaptureImageView: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<CaptureImageView>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
picker.sourceType = .camera
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController,
context: UIViewControllerRepresentableContext<CaptureImageView>) {
}
}
struct ContentView: View {
@State var image: Image? = nil
@State var showCaptureImageView: Bool = false
var body: some View {
VStack {
TabView {
//Photos Tab Content
ZStack {
VStack {
Button(action: {
self.showCaptureImageView.toggle()
}) {
Text("Take a photo")
}
image?.resizable()
// .frame(width: 250, height: 250)
// .clipShape(Circle())
// .overlay(Circle().stroke(Color.white, lineWidth: 4))
// .shadow(radius: 10)
}
if (showCaptureImageView) {
CaptureImageView(isShown: $showCaptureImageView, image: $image)
}
}//End photos tab content
//Style photos tab button
.tabItem {
Image(systemName: "1.circle")
Text("Photos")
}.tag(0)
//Start flashcards tab content
Text("Second View")
//Style flashcards tab button
.tabItem {
Image(systemName: "2.circle")
Text("Flashcards")
}.tag(1)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
import UIKit
class AlbumHeader: UIView {
init() {
super.init(frame: .zero)
backgroundColor = .systemGray6
setupLayout()
}
required init?(coder: NSCoder) { nil }
// MARK: - Subviews
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.image = UIImage(systemName: "arrow.up.arrow.down")?.withRenderingMode(.alwaysOriginal)
imageView.alpha = 0.3
return imageView
}()
// MARK: - Private
private func setupLayout() {
imageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(imageView)
NSLayoutConstraint.activate([
imageView.topAnchor.constraint(equalTo: topAnchor),
imageView.bottomAnchor.constraint(equalTo: bottomAnchor),
imageView.centerXAnchor.constraint(equalTo: centerXAnchor),
imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor),
])
}
}
|
//
// MovieDetailsRouter.swift
// MatchAnimation
//
// Created by Data Kondzhariia on 03.12.2020.
// Copyright (c) 2020 Data Kondzhariia. All rights reserved.
//
import UIKit
@objc protocol MovieDetailsRoutingLogic {
}
protocol MovieDetailsDataPassing {
var dataStore: MovieDetailsDataStore? { get }
}
class MovieDetailsRouter: NSObject {
weak var viewController: MovieDetailsViewController?
public var dataStore: MovieDetailsDataStore?
}
// MARK: - MovieDetails Routing Logic
extension MovieDetailsRouter: MovieDetailsRoutingLogic {
}
// MARK: - MovieDetails Data Passing
extension MovieDetailsRouter: MovieDetailsDataPassing {
}
|
import UIKit
import ThemeKit
import SnapKit
class ShortcutInputCell: UITableViewCell {
private let formValidatedView: FormValidatedView
private let inputStackView = InputStackView(singleLine: true)
private var shortcutViews = [InputSecondaryButtonWrapperView]()
private let deleteView = InputSecondaryCircleButtonWrapperView()
var onChangeText: ((String?) -> ())?
init() {
formValidatedView = FormValidatedView(contentView: inputStackView)
super.init(style: .default, reuseIdentifier: nil)
backgroundColor = .clear
selectionStyle = .none
contentView.addSubview(formValidatedView)
formValidatedView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
deleteView.button.set(image: UIImage(named: "trash_20"))
deleteView.onTapButton = { [weak self] in self?.onTapDelete() }
inputStackView.appendSubview(deleteView)
inputStackView.onChangeText = { [weak self] text in
self?.handleChange(text: text)
}
syncButtonStates()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func onTapDelete() {
inputStackView.text = nil
handleChange(text: nil)
}
private func handleChange(text: String?) {
onChangeText?(text)
syncButtonStates()
}
private func syncButtonStates() {
if let text = inputStackView.text, !text.isEmpty {
deleteView.isHidden = false
shortcutViews.forEach { view in view.isHidden = true }
} else {
deleteView.isHidden = true
shortcutViews.forEach { view in view.isHidden = false }
}
}
}
extension ShortcutInputCell {
var inputPlaceholder: String? {
get { inputStackView.placeholder }
set { inputStackView.placeholder = newValue }
}
var inputText: String? {
get { inputStackView.text }
set {
inputStackView.text = newValue
syncButtonStates()
}
}
var isEditable: Bool {
get { inputStackView.isUserInteractionEnabled }
set { inputStackView.isUserInteractionEnabled = newValue }
}
var keyboardType: UIKeyboardType {
get { inputStackView.keyboardType }
set { inputStackView.keyboardType = newValue }
}
var autocapitalizationType: UITextAutocapitalizationType {
get { inputStackView.autocapitalizationType }
set { inputStackView.autocapitalizationType = newValue }
}
var autocorrectionType: UITextAutocorrectionType {
get { inputStackView.autocorrectionType }
set { inputStackView.autocorrectionType = newValue }
}
func set(cautionType: CautionType?) {
formValidatedView.set(cautionType: cautionType)
}
func set(shortcuts: [InputShortcut]) {
shortcutViews = shortcuts.map { shortcut in
let view = InputSecondaryButtonWrapperView(style: .default)
view.button.setTitle(shortcut.title, for: .normal)
view.onTapButton = { [weak self] in
self?.inputStackView.text = shortcut.value
self?.handleChange(text: shortcut.value)
}
inputStackView.appendSubview(view)
return view
}
syncButtonStates()
}
var onChangeHeight: (() -> ())? {
get { formValidatedView.onChangeHeight }
set { formValidatedView.onChangeHeight = newValue }
}
var isValidText: ((String) -> Bool)? {
get { inputStackView.isValidText }
set { inputStackView.isValidText = newValue }
}
func height(containerWidth: CGFloat) -> CGFloat {
formValidatedView.height(containerWidth: containerWidth)
}
}
struct InputShortcut {
let title: String
let value: String
}
|
import MetalKit
class TextureArray: NSObject {
var texture: MTLTexture!
var width: Int = 0
var height: Int = 0
var arrayLength: Int = 0
private var _textureCollection: [Int32:MTLTexture] = [:]
init(arrayLength: Int = 1) {
self.arrayLength = arrayLength
}
private func generateTexture() {
let textureDescriptor = MTLTextureDescriptor()
textureDescriptor.textureType = .type2DArray
textureDescriptor.pixelFormat = GameSettings.MainPixelFormat
textureDescriptor.width = self.width
textureDescriptor.height = self.height
textureDescriptor.arrayLength = self.arrayLength
self.texture = Engine.Device.makeTexture(descriptor: textureDescriptor)
}
func setSlice(slice: Int32, tex: MTLTexture) {
if(width == 0 || height == 0){
width = tex.width
height = tex.height
generateTexture()
}else{
assert(tex.width == width, "The collection of textures needs to have the same size dimension")
}
//Add the texture to the collection for later use
_textureCollection.updateValue(tex, forKey: slice)
//Replace the slice region with the new texture
let rowBytes = width * 4
let length = rowBytes * height
let bgraBytes = [UInt8](repeating: 0, count: length)
tex.getBytes(UnsafeMutableRawPointer(mutating: bgraBytes),
bytesPerRow: rowBytes,
from: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0)
texture.replace(region: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0,
slice: Int(slice),
withBytes: bgraBytes,
bytesPerRow: rowBytes,
bytesPerImage: bgraBytes.count)
}
}
|
//
// CellEditingView.swift
// Habit Tracker
//
// Created by Michael Filippini on 7/8/18.
// Copyright © 2018 Michael Filippini. All rights reserved.
//
import UIKit
class CellEditingView: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var renameHabitTextField: UITextField!
@IBOutlet weak var renameDoneButton: UIButton!
@IBOutlet weak var timesPerDayLabel: UILabel!
@IBOutlet weak var timesCompletedTodayLabel: UILabel!
@IBOutlet weak var colorSelectEdit: UICollectionView!
@IBOutlet weak var saveChangesButton: UIButton!
@IBOutlet weak var deleteButton: UIButton!
var habitNamesArray: [String] = []
var timesCompleteArray: [Int] = []
var colorsArray: [UIColor] = []
var timesPerDayArray: [Int] = []
var indexOfEdit = NSIndexPath()
let colorDisplayArray = [Common.Global.purple,Common.Global.blue,Common.Global.green,Common.Global.yellow,Common.Global.orange,Common.Global.red]
var selectedColor = Common.Global.blue
var habitName = ""
var habitPerDay = 1
var habitCurrent = 1
var selectedColorLocation = 1
override func viewDidLoad() {
super.viewDidLoad()
updateWithCorrectValues()
colorSelectEdit.dataSource = self
colorSelectEdit.delegate = self
stylizeUIElements()
}
func stylizeUIElements(){
renameHabitTextField.layer.borderColor = Common.Global.lightGrey.cgColor
renameHabitTextField.layer.borderWidth = 2
renameHabitTextField.layer.cornerRadius = 10
renameHabitTextField.backgroundColor = Common.Global.darkGrey
saveChangesButton.layer.borderWidth = 2
saveChangesButton.layer.borderColor = Common.Global.lightGrey.cgColor
saveChangesButton.backgroundColor = Common.Global.darkGrey
saveChangesButton.layer.cornerRadius = 26
deleteButton.layer.borderWidth = 2
deleteButton.layer.borderColor = Common.Global.lightGrey.cgColor
deleteButton.backgroundColor = Common.Global.darkGrey
deleteButton.layer.cornerRadius = 26
renameDoneButton.layer.borderWidth = 2
renameDoneButton.layer.borderColor = Common.Global.lightGrey.cgColor
renameDoneButton.backgroundColor = Common.Global.darkGrey
renameDoneButton.layer.cornerRadius = 17
}
// manual select of color becuase UIColectionViews are annoying
override func viewDidAppear(_ animated: Bool) {
colorSelectEdit.cellForItem(at: NSIndexPath(item: selectedColorLocation, section: 0) as IndexPath)?.layer.borderWidth = 5
colorSelectEdit.cellForItem(at: NSIndexPath(item: selectedColorLocation, section: 0) as IndexPath)?.layer.borderColor = UIColor.white.cgColor
}
// fills edit scrren with correct data
func updateWithCorrectValues(){
selectedColor = colorsArray[indexOfEdit.item]
habitName = habitNamesArray[indexOfEdit.item]
habitPerDay = timesPerDayArray[indexOfEdit.item]
habitCurrent = timesCompleteArray[indexOfEdit.item]
renameHabitTextField.text = habitName
timesPerDayLabel.text = String(habitPerDay)
timesCompletedTodayLabel.text = String(habitCurrent)
selectedColorLocation = colorDisplayArray.index(of: selectedColor)!
renameDoneButton.setTitleColor(UIColor.white, for: .normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// setup collection view for color select
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colorDisplayArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = colorSelectEdit.dequeueReusableCell(withReuseIdentifier: "CellWithColor", for: indexPath) as! ColorCell
cell.viewForColor.backgroundColor = colorDisplayArray[indexPath.item]
return cell
}
// select of colletion view with extra code becuse collection views are mean
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
colorSelectEdit.cellForItem(at: NSIndexPath(item: selectedColorLocation, section: 0) as IndexPath)?.layer.borderWidth = 0.5
colorSelectEdit.cellForItem(at: NSIndexPath(item: selectedColorLocation, section: 0) as IndexPath)?.layer.borderColor = Common.Global.lightGrey.cgColor
cell?.layer.borderWidth = 5
cell?.layer.borderColor = UIColor.white.cgColor
selectedColor = colorDisplayArray[indexPath.item]
}
// deseleect collection view
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderWidth = 0.5
cell?.layer.borderColor = Common.Global.lightGrey.cgColor
}
// done button pulls text
@IBAction func pullNewText(_ sender: UITextField) {
if let nameText = renameHabitTextField.text{
habitName = nameText
}
}
// makes button look nice and update
@IBAction func updateDoneButton(_ sender: UITextField) {
if renameHabitTextField.text != ""{
renameDoneButton.setTitleColor(UIColor.white, for: .normal)
} else{
renameDoneButton.setTitleColor(Common.Global.lightGrey, for: .normal)
}
}
// tap scrren to close keyboard was conflicting with color select so this :(
@IBAction func finishCloseKeyboard(_ sender: UIButton) {
view.endEditing(true)
}
// makes buttons work and avoids people messing stuff up
@IBAction func subtractPerDay(_ sender: UIButton) {
let number = Int(timesPerDayLabel.text!)!
if number > 1{
timesPerDayLabel.text = String(number - 1)
habitPerDay -= 1
let numberToday = Int(timesCompletedTodayLabel.text!)!
if numberToday == number {
timesCompletedTodayLabel.text = String(number - 1)
habitCurrent -= 1
}
}
}
@IBAction func addPerDay(_ sender: UIButton) {
timesPerDayLabel.text = String(Int(timesPerDayLabel.text!)! + 1)
habitPerDay += 1
}
@IBAction func subtractToday(_ sender: UIButton) {
let number = Int(timesCompletedTodayLabel.text!)!
if number > 0{
timesCompletedTodayLabel.text = String(number - 1)
habitCurrent -= 1
}
}
@IBAction func addToday(_ sender: UIButton) {
let number = Int(timesCompletedTodayLabel.text!)!
if number < habitPerDay{
timesCompletedTodayLabel.text = String(number + 1)
habitCurrent += 1
}
}
// segue when delete clicked
@IBAction func deleteClicked(_ sender: Any) {
habitNamesArray.remove(at: indexOfEdit.item)
timesPerDayArray.remove(at: indexOfEdit.item)
timesCompleteArray.remove(at: indexOfEdit.item)
colorsArray.remove(at: indexOfEdit.item)
performSegue(withIdentifier: "unwindToInitialViewController2", sender: self)
}
// segue when save clicked
@IBAction func saveAndFinish(_ sender: UIButton) {
if habitName != ""{
habitNamesArray[indexOfEdit.item] = habitName
timesPerDayArray[indexOfEdit.item] = habitPerDay
timesCompleteArray[indexOfEdit.item] = habitCurrent
colorsArray[indexOfEdit.item] = selectedColor
performSegue(withIdentifier: "unwindToInitialViewController2", sender: self)
}
}
// data passed back to beginning
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let dvc = segue.destination as! ViewController
dvc.habitNamesArray = habitNamesArray
dvc.timesPerDayArray = timesPerDayArray
dvc.timesCompleteArray = timesCompleteArray
dvc.colorsArray = colorsArray
}
}
|
import UIKit
// MARK: - MainViewController
final class MainViewController: UIViewController {
private let tableView = UITableView()
private lazy var dataProvider: DataProviderProtocol? = {
let notepadDataStore = (UIApplication.shared.delegate as! AppDelegate).notepadDataStore
do {
try dataProvider = DataProvider(notepadDataStore, delegate: self)
return dataProvider
} catch {
showError("Данные недоступны.")
return nil
}
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupNavBar()
setupTableView()
}
private func setupNavBar() {
navigationController?.navigationBar.topItem?.title = "Блокнот"
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .automatic
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(didTapAddButton))
}
private func setupTableView() {
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
])
tableView.delegate = self
tableView.dataSource = self
}
@objc
private func didTapAddButton(_ sender: UIBarButtonItem) {
showNewRecordViewController()
}
private func showNewRecordViewController() {
let viewControllerToPresent = NewRecordViewController()
viewControllerToPresent.delegate = self
if let sheet = viewControllerToPresent.sheetPresentationController {
sheet.detents = [.medium()]
sheet.prefersGrabberVisible = true
sheet.preferredCornerRadius = 24
}
present(viewControllerToPresent, animated: true, completion: nil)
}
private func showError(_ message: String) {
let alert = UIAlertController(title: "Ошибка!", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in }))
present(alert, animated: true, completion: nil)
}
}
// MARK: - UITableViewDelegate
extension MainViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView,
editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
.delete
}
}
// MARK: - NewRecordViewControllerDelegate
extension MainViewController: NewRecordViewControllerDelegate {
func add(_ record: NotepadRecord) {
try? dataProvider?.addRecord(record)
dismiss(animated: true)
}
}
// MARK: - UITableViewDataSource
extension MainViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let record = dataProvider?.object(at: indexPath) else { return UITableViewCell() }
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "NotepadCell")
cell.textLabel?.text = record.title
cell.detailTextLabel?.text = record.body
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
dataProvider?.numberOfSections ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dataProvider?.numberOfRowsInSection(section) ?? 0
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
true
}
func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else { return }
try? dataProvider?.deleteRecord(at: indexPath)
}
}
// MARK: - DataProviderDelegate
extension MainViewController: DataProviderDelegate {
func didUpdate(_ update: NotepadStoreUpdate) {
tableView.performBatchUpdates {
let insertedIndexPaths = update.insertedIndexes.map { IndexPath(item: $0, section: 0) }
let deletedIndexPaths = update.deletedIndexes.map { IndexPath(item: $0, section: 0) }
tableView.insertRows(at: insertedIndexPaths, with: .automatic)
tableView.deleteRows(at: deletedIndexPaths, with: .fade)
}
}
}
|
//
// CellModel.swift
// PrediCiclo
//
// Created by Manuel Sanchez on 06/02/20.
// Copyright © 2020 Zublime. All rights reserved.
//
import Foundation
struct CellModel: Codable {
var id: Int
var image: String
var label: String
}
|
//
// NavigationView.swift
// Lendu
//
//
//
import UIKit
class NavigationView: UINavigationController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
//Required to maintain the support with iOS 12.4 (minimum version supported)
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad() {
super.viewDidLoad()
let background = UIImage(color: UIColor.white, size: CGSize(width: navigationBar.frame.width, height: 1))
navigationBar.setBackgroundImage(background, for: UIBarMetrics.default)
navigationBar.shadowImage = background
let backButton = UIImage(named: "backIcon")
navigationBar.tintColor = .black
navigationBar.backIndicatorImage = backButton
navigationBar.backIndicatorTransitionMaskImage = backButton
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
if let baseViewController = rootViewController as? BaseView, baseViewController.hasMenuButton {
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
super.pushViewController(viewController, animated: animated)
}
override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) {
if let baseViewController = viewControllers.first as? BaseView {
}
super.setViewControllers(viewControllers, animated: animated)
}
@objc func popCurrentViewController(_ animated: Bool)
{
self.popViewController(animated: true)
}
}
|
//
// ViewController.swift
// News App
//
// Created by Naveen Gaur on 22/12/18.
// Copyright © 2018 Naveen Gaur. All rights reserved.
//
import UIKit
import Moya
import WebKit
var country = "us"
var domain = "wsj.com"
var domain2 = "nytimes.com"
var apiKey = "4eddeca93e8d4594bc9a605f7ef49319"
class ViewController: UIViewController {
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let newsProvider = MoyaProvider<NewsService>()
newsProvider.request(.getNews(country: "us", category: ""), completion: { (result) in
switch result {
case .success(let response):
//let json = try! JSONSerialization.jsonObject(with: response.data, options: [])
let json = try! JSONDecoder().decode(News.self, from: response.data)
case .failure(let error):
print(error)
}
})
}
}
|
//
// ViewController.swift
// Book
//
// Created by cscoi028 on 2019. 8. 23..
// Copyright © 2019년 Korea University. All rights reserved.
//
import UIKit
import UserNotifications
import FirebaseDatabase
class ViewController: UIViewController {
var database : DatabaseReference!
var databaseHandler : DatabaseHandle!
var users : [String : [String : Any]]! = [:]
var writings : [String : [String : Any]]! = [:]
var userNames: [UserName] = []
var dataContents : [String] = []
// 주원 -(1) local notification
/* 출처: https://www.youtube.com/watch?v=JuqQUP0pnZY
https://medium.com/quick-code/local-notifications-with-swift-4-b32e7ad93c2 */
// @objc func datePickerChanged(_ datePicker:UIDatePicker) {
@objc func sendLocalNotification(_ notification: Notification) {
let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .sound /*, .badge*/]
center.requestAuthorization(options: options) {
(granted, error) in
if !granted {
print("User has declined notifications")
}
}
center.getNotificationSettings { (settings) in
if settings.authorizationStatus != .authorized {
print("Notifications not allowed")
}
}
for child in writings {
if let tempType : String = child.value["type"] as? String {
if tempType == "명언", let tempContent : String = child.value["contents"] as? String {
dataContents.append(tempContent)
}
}
}
let randomNum : Int = Int(arc4random_uniform(UInt32(dataContents.count - 1)))
let content = UNMutableNotificationContent()
content.title = "오늘의 문학이 배송되었습니다"
//content.body = "여기용" // 여기에 넣기
content.body = dataContents[randomNum]
content.sound = UNNotificationSound.default()
//content.badge = 1
UIApplication.shared.applicationIconBadgeNumber = 0
var date = DateComponents() //(timeIntervalSinceNow: 3600)
// if let savedTime = UserDefaults.standard.object(forKey: "defaultRemindTime") as? String {
//let hoursRange = savedTime.startIndex...savedTime.startIndex.advancedBy(1)
// let hoursRange = savedTime.startIndex...savedTime.index(savedTime.startIndex, offsetBy: 1)
//
// if let tempHour : Int = Int(savedTime[hoursRange]) {
// date.hour = tempHour
// print(type(of: date.hour))
// }
// //date.hour = Int(savedTime[hoursRange])
// let minutesRange = savedTime.index(savedTime.startIndex, offsetBy: 2)..<savedTime.endIndex
//
// if let tempMin : Int = Int(savedTime[minutesRange]) {
// date.minute = tempMin
// print(date.minute)
//let minutesRange = savedTime.startIndex.advancedBy(2)...savedTime.endIndex.predecessor()
//date.minute = Int(savedTime[minutesRange])
date.hour = 15
date.minute = 31
// let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)
center.add(request) { (error) in
if let error = error {
print("Error")
}
}
}
// 여기까지
override func viewDidLoad() {
super.viewDidLoad()
database = Database.database().reference()
decodeAndPopup()
// 주원 (2)
NotificationCenter.default.addObserver(self, selector: #selector(sendLocalNotification(_:)), name: .remindTimeChanged, object: nil)
// 여기까지
databaseHandler = database.child("writings")
.observe(.value, with: {(snapshot) -> Void in
guard let tempWritings = snapshot.value as? [String : [String : Any]]
else{
print("데이터 불러오기 실패")
return
}
self.writings = tempWritings
})
// sendLocalNotification()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func tapShorts(_ sender: UITapGestureRecognizer) {
let nextViewController = ContentsViewController()
navigationController?.pushViewController(nextViewController, animated: true)
}
@IBAction func tapLongs(_ sender: UITapGestureRecognizer) {
let nextViewController = ContentsViewController()
navigationController?.pushViewController(nextViewController, animated: true)
}
//초기에 사용자 받아오기
func decodeAndPopup() {
database = Database.database().reference()
database.child("users").observeSingleEvent(of: .value) { (snapshot) in
guard let tempUsers = snapshot.value as? [String : [String : Any]] else {
print("users 데이터 불러오기 실패")
return
}
self.users = tempUsers
//주원
let filePath = try! FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("userNames.json")
let jsonData: Data
do {
jsonData = try Data(contentsOf: filePath)
let decoder: JSONDecoder = JSONDecoder()
do {
self.userNames.removeAll()
self.userNames = try decoder.decode([UserName].self, from: jsonData)
if self.userNames.isEmpty == true {
return
} else {
//나연----------
let userName = self.userNames[0].userName
for child in self.users {
if let temp : String = child.value["name"] as? String {
if temp == userName {
currentUserKey = child.key
currentUser = child.value
if let tempLikeArray = currentUser["likes"] as? [String] {
likeArray = tempLikeArray
}
break
}
}
//값들 설정 필요
}
}
} catch {
print("decode json 실패" + error.localizedDescription)
}
} catch {
print("load data 실패" + error.localizedDescription)
return
}
}
}
}
// 주원
extension UIViewController {
func hideKeyboard() {
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(tapGesture)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
|
import Foundation
@objc(FetcherModule)
class FetcherModule: RCTEventEmitter {
override func supportedEvents() -> [String]! {
return ["progress"]
}
@objc
static override func requiresMainQueueSetup() -> Bool {
return false
}
@objc
func fetchAsync(_ fetchMap: NSDictionary, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
let expectedFetchCount = fetchMap.count
let collector = FetchResultCollector(
emitter: self,
expectedFetchCount: expectedFetchCount,
resolve: resolve, reject: reject
);
for (targetFilePath, url) in fetchMap {
fetchAsync(sourceUrl: String(describing: url), targetFilePath: String(describing: targetFilePath), collector: collector);
}
}
func fetchAsync(sourceUrl: String, targetFilePath: String, collector: FetchResultCollector) {
let targetFileURL = URL(fileURLWithPath: targetFilePath)
let fileManager = FileManager.default
if fileManager.fileExists(atPath: targetFileURL.path) {
collector.alreadyExists(url: sourceUrl, targetFile: targetFileURL);
return;
}
let encoded = sourceUrl.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)
if (encoded == nil) {
collector.failed(url: sourceUrl, targetFile: targetFileURL, message: "Failed to encode url!")
return
}
let url = URL(string: encoded!)
if (url == nil) {
collector.failed(url: sourceUrl, targetFile: targetFileURL, message: "Failed to create URL!")
return
}
let downloadTask = URLSession.shared.downloadTask(with: url!) {
(urlOrNil: URL?, responseOrNil: URLResponse?, errorOrNil: Error?) in
guard let fileURL = urlOrNil else {
let errorMessage = errorOrNil?.localizedDescription ?? "Failed to download because of unknown error!"
collector.failed(url: sourceUrl, targetFile: targetFileURL, message: errorMessage)
return
}
guard let response = responseOrNil else {
collector.failed(url: sourceUrl, targetFile: targetFileURL, message: "Failed to download because of unkown error!")
return
}
let statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1
if (statusCode != 200) {
let statusMessage = HTTPURLResponse.localizedString(forStatusCode: statusCode)
collector.failed(url: sourceUrl, targetFile: targetFileURL, message: "\(statusCode): \(statusMessage)")
return
}
do {
try fileManager.createDirectory(at: targetFileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
try fileManager.moveItem(at: fileURL, to: targetFileURL)
collector.fetched(url: sourceUrl, targetFile: targetFileURL)
} catch {
collector.failed(url: sourceUrl, targetFile: targetFileURL, message: error.localizedDescription)
}
}
downloadTask.resume()
}
}
|
//
// Vocab.swift
// Nihongo
//
// Created by Dang Nguyen Vu on 3/9/17.
// Copyright © 2017 Dang Nguyen Vu. All rights reserved.
//
import Foundation
import FirebaseDatabase
struct Vocab {
var jp: String?
var vi: String?
var sub: String?
var kanji: String?
var audioLink: String?
var imageLink: String?
var description: String?
var key: String
init(jp: String, vi: String, sub: String, kanji: String, audioLink: String, imageLink: String, description: String) {
self.jp = jp
self.vi = vi
self.sub = sub
self.kanji = kanji
self.audioLink = audioLink
self.imageLink = imageLink
self.description = description
self.key = ""
}
init(snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: String]
jp = snapshotValue["jp"]
vi = snapshotValue["vi"]
sub = snapshotValue["sub"]
kanji = snapshotValue["kanji"]
audioLink = snapshotValue["audioLink"]
imageLink = snapshotValue["imageLink"]
description = snapshotValue["description"]
key = snapshot.key
}
func toAnyObject() -> Any {
return ["jp": jp,
"vi": vi,
"sub": sub,
"kanji": kanji,
"audioLink": audioLink,
"imageLink": imageLink,
"description": description]
}
}
|
//
// LocationServices.swift
// SuCasa
//
// Created by Gabriela Resende on 28/11/19.
// Copyright © 2019 João Victor Batista. All rights reserved.
//
import Foundation
import MapKit
class LocationUtil {
static let shared = LocationUtil()
// singleton
private init() {
}
let locationManager = CLLocationManager()
var currentLocation = CLLocationCoordinate2D()
//gets users current location, if location isnt allowed shows an alert
func buildLocationAlert(completionHandler: @escaping (_ alert: UIAlertController?,_ place: CLPlacemark?) -> Void) {
var alertLoc: UIAlertController? = nil
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
locationManager.startUpdatingLocation()
if let location = locationManager.location?.coordinate{
convertLatLongToAddress(latitude: location.latitude, longitude: location.longitude) { (place) in
self.currentLocation = location
if let place = place {
completionHandler(nil, place)
}
}
}
}
else if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
else if CLLocationManager.authorizationStatus() == .denied {
let alertLoc = UIAlertController(title: "Permita acesso à sua localização" , message: "Você deve permitir acesso à sua localização ou colocar seus dados manualmente" , preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Abrir Ajustes", style: .default) { (_) -> Void in
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
}
alertLoc.addAction(UIAlertAction(title: "Cancelar", style: .default, handler: nil))
alertLoc.addAction(settingsAction)
completionHandler(alertLoc, nil)
}
}
//Func to convert lat and long to adress
func convertLatLongToAddress(latitude:Double,longitude:Double, completion: @escaping (_ place: CLPlacemark?) -> Void){
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: latitude, longitude: longitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
if let error = error {
completion(nil)
} else {
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
completion(placeMark)
}
})
}
//returns distance between 2 locations in meters
func distanceBetweenCoordinates(placeLoc:CLLocation) -> CLLocationDistance{
let getLat: CLLocationDegrees = currentLocation.latitude
let getLong: CLLocationDegrees = currentLocation.longitude
let currentLoc : CLLocation = CLLocation(latitude: getLat, longitude: getLong)
return currentLoc.distance(from: placeLoc)
}
static func getLocationFromString(forPlaceCalled name: String,
completion: @escaping(CLLocation?) -> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(name) { placemarks, error in
guard error == nil else {
print("*** Error in \(#function): \(error!.localizedDescription)")
completion(nil)
return
}
guard let placemark = placemarks?[0] else {
print("*** Error in \(#function): placemark is nil")
completion(nil)
return
}
guard let location = placemark.location else {
print("*** Error in \(#function): placemark is nil")
completion(nil)
return
}
completion(location)
}
}
}
|
//
// EmojiMemoryGameView.swift
// Memorize
//
// Created by Elina Mansurova on 2021-09-08.
//
import SwiftUI
struct EmojiMemoryGameView: View {
@ObservedObject var gameViewModel: EmojiMemoryGameViewModel
var body: some View {
AspectVGrid(items: gameViewModel.cards, aspectRatio: 2/3, content: { card in
if !card.isFaceUp && card.isMatched {
Rectangle().opacity(0)
} else {
CardView(card: card)
.padding(4)
.onTapGesture {
gameViewModel.choose(card)
}
}
})
.foregroundColor(.red)
.padding(.horizontal)
}
}
struct CardView: View {
let card: EmojiMemoryGameViewModel.Card
var body: some View {
GeometryReader { geometry in
ZStack {
let shape = RoundedRectangle(cornerRadius: DrawingConstants.cornerRadius)
if card.isFaceUp {
shape.fill().foregroundColor(.white)
shape.strokeBorder(lineWidth: DrawingConstants.lineWidth)
PieShape(startAngle: Angle(degrees: 0-90), endAngle: Angle(degrees: 110-90)).opacity(DrawingConstants.circleOpacity).padding(DrawingConstants.circlePadding)
Text(card.content).font(font(in: geometry.size))
} else if card.isMatched {
shape.opacity(0)
} else {
shape.fill()
}
}
}
}
private func font(in size: CGSize) -> Font {
Font.system(size: min(size.width, size.height) * DrawingConstants.fontScale)
}
private struct DrawingConstants {
static let cornerRadius: CGFloat = 10
static let lineWidth: CGFloat = 3
static let fontScale: CGFloat = 0.6
static let circleOpacity = 0.4
static let circlePadding: CGFloat = 5
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let game = EmojiMemoryGameViewModel()
EmojiMemoryGameView(gameViewModel: game)
}
}
|
//
// ProjectTableViewCell.swift
// Schematic Capture
//
// Created by Gi Pyo Kim on 2/7/20.
// Copyright © 2020 GIPGIP Studio. All rights reserved.
//
import UIKit
class ProjectTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var numbOfJobSheetLabel: UILabel!
var project: Project? {
didSet {
updateViews()
}
}
private func updateViews() {
guard let project = project else { return }
nameLabel.text = project.name
numbOfJobSheetLabel.text = project.jobSheets != nil ? "\(project.jobSheets!.count)" + (project.jobSheets!.count > 1 ? " jobs" : " job") : "0 Jobs"
}
}
|
//
// NewAccountInputTextField.swift
// WavesWallet-iOS
//
// Created by mefilt on 17.09.2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
final class InputTextField: UIView, NibOwnerLoadable {
enum Kind {
case password
case newPassword
case text
}
struct Model {
let title: String
let kind: Kind
let placeholder: String?
}
@IBOutlet private var titleLabel: UILabel!
@IBOutlet private var errorLabel: UILabel!
@IBOutlet private var textFieldValue: UITextField!
@IBOutlet private var eyeButton: UIButton!
@IBOutlet private var separatorView: SeparatorView!
private lazy var tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(handlerTapGesture(recognizer:)))
private var secureText: String?
var value: String? {
set {
textFieldValue.text = newValue
checkValidValue()
ifNeedPlaceholder()
}
get {
return textFieldValue.text
}
}
var text: String {
return textFieldValue.text ?? ""
}
var trimmingText: String {
return text.trimmingCharacters(in: CharacterSet.whitespaces)
}
var isEnabled: Bool {
set {
tapGesture.isEnabled = isEnabled
textFieldValue.isEnabled = isEnabled
textFieldValue.isUserInteractionEnabled = isEnabled
}
get {
return textFieldValue.isEnabled
}
}
private var isHiddenTitleLabel: Bool = true
private var isSecureTextEntry: Bool = false {
didSet {
textFieldValue.isSecureTextEntry = isSecureTextEntry
if #available(iOS 10.0, *) {
textFieldValue.textContentType = UITextContentType(rawValue: "")
}
if isSecureTextEntry {
eyeButton.setImage(Images.eyeopen24Basic500.image, for: .normal)
} else {
eyeButton.setImage(Images.eyeclsoe24Basic500.image, for: .normal)
}
}
}
private var externalError: String?
var valueValidator: ((String?) -> String?)?
var changedValue: ((Bool,String?) -> Void)?
var textFieldShouldReturn: ((InputTextField) -> Void)?
var rightView: UIView? {
didSet {
if let rightView = self.rightView {
rightView.translatesAutoresizingMaskIntoConstraints = true
textFieldValue.rightViewMode = .always
textFieldValue.rightView = rightView
} else {
textFieldValue.rightViewMode = .never
textFieldValue.rightView = nil
}
}
}
var clearButtonMode: UITextField.ViewMode? {
didSet {
textFieldValue.clearButtonMode = clearButtonMode ?? .never
}
}
var returnKey: UIReturnKeyType? {
didSet {
textFieldValue.returnKeyType = returnKey ?? .done
}
}
var autocapitalizationType: UITextAutocapitalizationType? {
didSet {
textFieldValue.autocapitalizationType = autocapitalizationType ?? .none
}
}
var keyboardType: UIKeyboardType? {
didSet {
textFieldValue.keyboardType = keyboardType ?? .default
}
}
private(set) var isValidValue: Bool = false
private var kind: Kind?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadNibContent()
}
override func awakeFromNib() {
super.awakeFromNib()
addGestureRecognizer(tapGesture)
textFieldValue.delegate = self
eyeButton.addTarget(self, action: #selector(tapEyeButton), for: .touchUpInside)
textFieldValue.addTarget(self, action: #selector(textFieldChanged), for: .editingChanged)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@discardableResult override func becomeFirstResponder() -> Bool {
return textFieldValue.becomeFirstResponder()
}
@objc private func handlerTapGesture(recognizer: UITapGestureRecognizer) {
if recognizer.state == .ended {
textFieldValue.becomeFirstResponder()
}
}
@objc func keyboardWillHide() {
checkValidValue()
}
@objc private func tapEyeButton() {
isSecureTextEntry = !isSecureTextEntry
}
@objc private func textFieldChanged() {
if isValidValue == false {
checkValidValue()
}
changedValue?(isValidValue, value)
ifNeedPlaceholder()
}
private func ifNeedPlaceholder() {
let isShow = text.count > 0
let isHiddenTitleLabel = !isShow
guard isHiddenTitleLabel != self.isHiddenTitleLabel else { return }
self.isHiddenTitleLabel = isHiddenTitleLabel
titleLabel.isHidden = isHiddenTitleLabel
if !self.isHiddenTitleLabel {
self.titleLabel.alpha = 0
} else {
self.titleLabel.alpha = 1
}
UIView.animate(withDuration: 0.24) {
if self.isHiddenTitleLabel {
self.titleLabel.alpha = 0
} else {
self.titleLabel.alpha = 1
}
}
}
private func checkValidValue() {
checkValidValue(value)
}
private func checkValidValue(_ value: String?) {
var error: String? = nil
var isValidValue: Bool = true
if let value = value, value.count > 0,
let validator = valueValidator,
let errorMessage = validator(value)
{
error = errorMessage
isValidValue = false
} else if let externalError = externalError {
error = externalError
isValidValue = false
} else {
isValidValue = (value?.count ?? 0) > 0
}
errorLabel.isHidden = isValidValue
errorLabel.text = error
self.isValidValue = isValidValue
}
var error: String? {
get {
return externalError ?? errorLabel.text
}
set {
externalError = newValue
checkValidValue()
}
}
}
// MARK: ViewConfiguration
extension InputTextField: ViewConfiguration {
func update(with model: InputTextField.Model) {
kind = model.kind
titleLabel.text = model.title
textFieldValue.placeholder = model.placeholder
titleLabel.isHidden = isHiddenTitleLabel
checkValidValue()
switch model.kind {
case .text:
isSecureTextEntry = false
eyeButton.isHidden = true
textFieldValue.autocorrectionType = .no
if #available(iOS 10.0, *) {
textFieldValue.textContentType = .name
}
case .password, .newPassword:
if #available(iOS 10.0, *) {
textFieldValue.textContentType = UITextContentType(rawValue: "")
}
self.rightView = eyeButton
isSecureTextEntry = true
eyeButton.isHidden = false
textFieldValue.autocorrectionType = .no
}
ifNeedPlaceholder()
}
}
// MARK: UITextFieldDelegate
extension InputTextField: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
DispatchQueue.main.async(execute: {
self.textFieldValue.selectedTextRange = self.textFieldValue.textRange(from: self.textFieldValue.endOfDocument,
to: self.textFieldValue.endOfDocument)
})
separatorView.backgroundColor = .submit400
}
func textFieldDidEndEditing(_ textField: UITextField) {
separatorView.backgroundColor = .accent100
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
checkValidValue()
if isValidValue {
textFieldShouldReturn?(self)
return true
}
return false
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var newString = string
if self.autocapitalizationType == .none {
newString = newString.lowercased()
}
if let text = textField.text,
let textRange = Range(range, in: text) {
let updatedText = text.replacingCharacters(in: textRange,
with: newString)
checkValidValue(updatedText)
}
return true
}
}
|
//
// SaveService.swift
// buroptima1
//
// Created by Nail Safin on 16.07.2020.
// Copyright © 2020 Nail Safin. All rights reserved.
//
import Foundation
enum BuroptimaFields: String {
case code
case accessToken
case personID
case orgID
}
final class BuroptimaSaveInUD {
private let provider: ServiceUD
init() {
provider = ServiceUD()
}
func save(fields: [BuroptimaFields: String] ) {
fields.forEach { key, value in
provider.set(to: key.rawValue, value: value)
}
}
func get(valueFromField field: BuroptimaFields)-> String {
provider.get(from: field.rawValue)
}
}
|
//
// CustomTextField.swift
// HISmartPhone
//
// Created by Huỳnh Công Thái on 1/14/18.
// Copyright © 2018 MACOS. All rights reserved.
//
import UIKit
protocol CustomTextFieldDelegate: class {
func editingBegin(customTextField: CustomTextField)
func editingDidEnd(customTextField: CustomTextField)
func editingChanged(customTextField: CustomTextField, text: String?)
}
// This class custom UITextField
class CustomTextField: BaseUIView {
// MARK: Define variables
weak var delegate: CustomTextFieldDelegate?
// MARK: Define controls
private var lineDivider: UIView = {
let viewConfig = UIView()
viewConfig.backgroundColor = Theme.shared.lineDeviderColor
return viewConfig
}()
private (set) lazy var textField: UITextField = {
let textfieldConfig = UITextField()
textfieldConfig.delegate = self
textfieldConfig.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
textfieldConfig.textColor = Theme.shared.primaryColor
return textfieldConfig
}()
// MARK: Init
init(placeholder: String, fontSize: CGFloat = Dimension.shared.bodyFontSize, keyboardType: UIKeyboardType = .default){
super.init(frame: CGRect.zero)
self.textField.placeholder = placeholder
self.textField.keyboardType = keyboardType
self.textField.font = UIFont.systemFont(ofSize: fontSize)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Setup UI
override func setupView() {
self.setupTextField()
self.setupLineDivider()
}
private func setupLineDivider() {
self.addSubview(self.lineDivider)
self.lineDivider.snp.makeConstraints { (make) in
make.left.right.equalTo(self)
make.top.equalTo(self.textField.snp.bottom).offset(Dimension.shared.smallHorizontalMargin)
make.height.equalTo(Dimension.shared.heightLineDivider)
make.bottom.equalToSuperview()
}
}
private func setupTextField() {
self.addSubview(self.textField)
self.textField.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.right.equalToSuperview().offset(-Dimension.shared.mediumHorizontalMargin)
make.left.equalToSuperview().offset(Dimension.shared.mediumHorizontalMargin)
}
self.textField.addTarget(self, action: #selector(CustomTextField.didSelectedTextfield), for: .editingDidBegin)
self.textField.addTarget(self, action: #selector(CustomTextField.didEndEditingTextfield), for: .editingDidEnd)
self.textField.addTarget(self, action: #selector(CustomTextField.editingChangedTextfield), for: .editingChanged)
}
@objc private func didSelectedTextfield() {
self.lineDivider.backgroundColor = Theme.shared.primaryColor
self.delegate?.editingBegin(customTextField: self)
}
@objc private func didEndEditingTextfield() {
self.lineDivider.backgroundColor = Theme.shared.lineDeviderColor
self.delegate?.editingDidEnd(customTextField: self)
}
@objc private func editingChangedTextfield() {
self.delegate?.editingChanged(customTextField: self, text: self.textField.text)
}
// Set value
func setValue(text: String) {
self.textField.text = text
}
}
//MARK: - UITextFieldDelegate
extension CustomTextField: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.endEditing(true)
return false
}
}
|
//
// HomeHeader.swift
// AccountBook
//
// Created by Mason Sun on 2019/11/20.
// Copyright © 2019 Mason Sun. All rights reserved.
//
import SwiftUI
struct HomeHeader: View {
var amount: Amount
var body: some View {
HStack() {
HStack {
VStack(alignment: .center, spacing: 4) {
Text("Income")
.font(.system(.headline))
Text(amount.income.getAmountString(with: .income))
.font(.system(.title))
}
.frame(maxWidth: .infinity)
}
HStack {
VStack(alignment: .center, spacing: 4) {
Text("Spending")
.font(.system(.headline))
Text(amount.spending.getAmountString(with: .spending))
.font(.system(.title))
}
.frame(maxWidth: .infinity)
}
}
}
struct Amount {
let income: Decimal
let spending: Decimal
static var defaultValue: Amount {
Amount(income: 100, spending: 200)
}
}
}
struct HomeHeader_Previews: PreviewProvider {
static var previews: some View {
HomeHeader(amount: .defaultValue)
.environmentObject(UserData())
.padding([ .leading, .trailing ], 16)
}
}
|
//
// SolitaryMainView.swift
// SwiftUIReference
//
// Created by David S Reich on 30/1/20.
// Copyright © 2020 Stellar Software Pty Ltd. All rights reserved.
//
import SwiftUI
/*
This is based on PlainMainView.
SwiftUI currently has problems with navigation which break some of the features in PlainMainView.
Avoid this problem altogether ...
Stay in one View and stack up the searches.
Pop them when the back button is pressed.
*/
struct SolitaryMainView: View {
@State var solitaryViewModel: SolitaryViewModel
@State private var imageModels = [ImageDataModelProtocolWrapper]()
@State private var nextImageTags = ""
@State private var showingSelectorView = false
@State private var showingSettingsView = false
@State private var settingsChanged = true
@State private var showingAlert = false
@State private var alertMessageString: String?
@State private var isLoading = false
// body used to be a lot more complicated, but still is helped by breaking it down into several funcs
var body: some View {
NavigationView {
ZStack {
GeometryReader { geometry in
self.mainView(geometry: geometry).opacity(self.isLoading ? 0.25 : 1.0)
}
Group {
if isLoading {
ActivityIndicatorView(style: .large)
}
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
.alert(isPresented: $showingAlert) {
if UserDefaultsManager.hasAPIKey() {
return Alert(title: Text("Something went wrong!"),
message: Text( alertMessageString ?? "Unknown error!!??!!"),
dismissButton: .default(Text("OK ... I guess")))
} else {
return Alert(title: Text("API Key is missing"),
message: Text("Go to Settings to enter an API Key"),
dismissButton: .default(Text("OK ... I guess")))
}
}
}
private func mainView(geometry: GeometryProxy) -> some View {
VStack {
baseListWithNavBarView(geometry: geometry)
.navigationBarTitle(Text(solitaryViewModel.title), displayMode: .inline)
.onAppear(perform: loadEverything)
}
}
private func baseListWithNavBarView(geometry: GeometryProxy) -> some View {
basicImageList()
.navigationBarItems(
leading: leadingNavigationItem(geometry: geometry),
trailing: trailingNavigationItem()
)
}
private func basicImageList() -> some View {
List(imageModels.indices, id: \.self) { index in
NavigationLink(destination: ImageView(imageModel: self.imageModels[index].imageModel)) {
ImageRowView(imageModel: self.imageModels[index].imageModel, showOnLeft: index.isMultiple(of: 2))
}
}
}
private func leadingNavigationItem(geometry: GeometryProxy) -> some View {
// swiftlint:disable multiple_closures_with_trailing_closure
Button(action: {
if self.solitaryViewModel.isBackButtonSettings {
self.settingsChanged = false
self.showingSettingsView = true
} else {
self.goBack(toTop: false)
}
}) {
//it appears that some of these settings are carried to the navigation title !!!
Text(solitaryViewModel.backButtonText).frame(width: geometry.size.width * 0.25).lineLimit(1)
}
.sheet(isPresented: $showingSettingsView, onDismiss: {
if self.settingsChanged {
self.solitaryViewModel.clearDataSource()
self.loadEverything()
}
}) {
SettingsView(isPresented: self.$showingSettingsView,
userSettings: self.$solitaryViewModel.userSettings,
tags: self.$solitaryViewModel.tagString,
settingsChanged: self.$settingsChanged)
}
}
private func trailingNavigationItem() -> some View {
Button(solitaryViewModel.rightButtonText) {
if self.solitaryViewModel.isRightButtonPickTags {
self.nextImageTags = ""
self.showingSelectorView = true
} else {
self.goBack(toTop: true)
}
}
.sheet(isPresented: $showingSelectorView, onDismiss: {
if !self.nextImageTags.isEmpty {
self.solitaryViewModel.tagString = self.nextImageTags
self.settingsChanged = true
self.loadEverything()
}
}) {
SelectorView(isPresented: self.$showingSelectorView,
selectedStrings: self.$nextImageTags,
allStrings: self.solitaryViewModel.tagsArray)
}
}
private func loadEverything() {
//use settingsChanged in case .onAppear is triggered more than once.
//we should not assume that we have a reliable SwiftUI View lifecycle model at this time
guard settingsChanged else {
return
}
settingsChanged = false
// reset
self.imageModels.removeAll()
isLoading = true
solitaryViewModel.populateDataSource(imageTags: solitaryViewModel.tagString) { referenceError in
self.isLoading = false
if let referenceError = referenceError {
//handle error
print("\(referenceError)")
self.alertMessageString = referenceError.errorDescription
self.showingAlert = true
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.imageModels = self.solitaryViewModel.imageModels
}
}
}
private func goBack(toTop: Bool) {
if toTop {
solitaryViewModel.goBackToTop()
} else {
solitaryViewModel.goBackOneLevel()
}
self.imageModels.removeAll()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.imageModels = self.solitaryViewModel.imageModels
}
}
}
struct SolitaryMainView_Previews: PreviewProvider {
static var previews: some View {
let solitaryViewModel = SolitaryViewModel(dataSource: DataSource(networkService: MockNetworkService()),
userSettings: UserDefaultsManager.getUserSettings())
return SolitaryMainView(solitaryViewModel: solitaryViewModel)
}
}
|
//
// SearchCoordinator.swift
// PodcastsKo
//
// Created by John Roque Jorillo on 7/26/20.
// Copyright © 2020 JohnRoque Inc. All rights reserved.
//
import UIKit
import PodcastKoCore
class SearchCoordinator: CoordinatorType {
var childCoordinators: [CoordinatorType] = []
// MARK: - Navigation
/// Root ViewController for SearchCoordinator flow
lazy var navigation: UINavigationController = {
let navigationVc = UINavigationController(rootViewController: searchVc)
return navigationVc
}()
// MARK: - Screens
lazy var searchVc: SearchViewController = {
let vc = SearchComposer.composeWith()
vc.coordinator = self
return vc
}()
/// Trigger to start SearchCoordinator Flow
func start() {
}
}
extension SearchCoordinator: SearchViewControllerDelegate {
func showEpisodes(_ vc: SearchViewController, podCast: Podcast) {
let episodesVc = EpisodesComposer.composeWith(podCast: podCast)
episodesVc.coordinator = self
self.navigation.pushViewController(episodesVc, animated: true)
}
}
extension SearchCoordinator: EpisodesViewControllerDelegate {
func back(_ vc: EpisodesViewController) {
self.navigation.popViewController(animated: true)
}
}
|
//
// ViewController.swift
// sqlTutorial
//
// Created by aanvi on 11/2/19.
// Copyright © 2019 aanvi. All rights reserved.
//
import UIKit
import SQLite3
class ViewController: UIViewController {
var db: OpaquePointer?
@IBOutlet weak var inputPennies: UITextField!
@IBOutlet weak var inputNickels: UITextField!
@IBOutlet weak var inputDimes: UITextField!
@IBOutlet weak var inputQuarters: UITextField!
@IBOutlet weak var inputFifties: UITextField!
@IBAction func insertCoinCount(_ sender: Any) {
let p = inputPennies.text?.trimmingCharacters(in: .whitespacesAndNewlines)
let n = inputNickels.text?.trimmingCharacters(in: .whitespacesAndNewlines)
let d = inputDimes.text?.trimmingCharacters(in: .whitespacesAndNewlines)
let q = inputQuarters.text?.trimmingCharacters(in: .whitespacesAndNewlines)
let f = inputFifties.text?.trimmingCharacters(in: .whitespacesAndNewlines)
if(p?.isEmpty)!{
print("empty pennies")
return;
}
if(n?.isEmpty)!{
print("empty nickels")
return
}
if(d?.isEmpty)!{
print("empty dimes")
return;
}
if(q?.isEmpty)!{
print("empty quarters")
return;
}
if(f?.isEmpty)!{
print("empty fifties")
return;
}
var statementInsert: OpaquePointer?
let insertCoinCount = "INSERT INTO countHistory (numPennies,numNickels,numDimes,numQuarters,numFifties) VALUES (?,?,?,?,?)"
if sqlite3_prepare(db,insertCoinCount,-1,&statementInsert,nil) != SQLITE_OK{
print("error binding query")
}
if sqlite3_bind_int(statementInsert,1,(p! as NSString).intValue) != SQLITE_OK{
print("error binding pennies")
}
if sqlite3_bind_int(statementInsert,2,(n! as NSString).intValue) != SQLITE_OK{
print("error binding nickels")
}
if sqlite3_bind_int(statementInsert,3,(d! as NSString).intValue) != SQLITE_OK{
print("error binding dimes")
}
if sqlite3_bind_int(statementInsert,4,(q! as NSString).intValue) != SQLITE_OK{
print("error binding quarters")
}
if sqlite3_bind_int(statementInsert,5,(f! as NSString).intValue) != SQLITE_OK{
print("error binding fifties")
}
if sqlite3_step(statementInsert) == SQLITE_DONE{
print("inserted successfully")
}
}
@IBAction func viewCT(_ sender: Any) {
let selectQuery = "SELECT * FROM countHistory"
var stmt: OpaquePointer?
if sqlite3_prepare(db,selectQuery,-1,&stmt,nil) == SQLITE_OK{
print("Query Result: ")
while sqlite3_step(stmt) == SQLITE_ROW{
let penny = sqlite3_column_int(stmt,1)
let nickel = sqlite3_column_int(stmt,2)
let dime = sqlite3_column_int(stmt,3)
let quarter = sqlite3_column_int(stmt,4)
let fifty = sqlite3_column_int(stmt,5)
print("\(penny) | \(nickel) | \(dime) | \(quarter) | \(fifty)")
}
}else{
print("error in preparing statement")
}
sqlite3_finalize(stmt)
}
override func viewDidLoad() {
super.viewDidLoad()
let fileUrl = try!
FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("CoinDB.sqlite")
if sqlite3_open(fileUrl.path,&db) != SQLITE_OK{
print("error opening db")
}
let createCTH = "CREATE TABLE IF NOT EXISTS countHistory (id INTEGER PRIMARY KEY AUTOINCREMENT, numPennies INTEGER, numNickels INTEGER, numDimes INTEGER, numQuarters INTEGER, numFifties INTEGER)"
if sqlite3_exec(db,createCTH,nil,nil,nil) != SQLITE_OK{
print("error creating count history table")
return
}
let createCET = "CREATE TABLE IF NOT EXISTS exchangeRates(code TEXT PRIMARY KEY UNIQUE, amtInDollar NUMERIC)"
if sqlite3_exec(db, createCET, nil, nil, nil) != SQLITE_OK{
print("error creating exchange rate table")
}
let insertEV = "INSERT INTO exchangeRates (code, amtInDollar) VALUES (EUR, 0.9),(GBP, 0.77), (MXN, 19.11)"
if sqlite3_exec(db, insertEV,nil,nil,nil) != SQLITE_OK{
print("error inserting exchange rate vals")
}
print("Everything is fine!")
}
}
|
//
// ToDoHeaderCell.swift
// BMKToDo
//
// Created by Bharat Khatke on 28/07/21.
//
import UIKit
//MARK:- You can code this calss in single file as well example in ToDoCell
class ToDoHeaderCell: UITableViewCell {
@IBOutlet weak var headerTitleLbl: UILabel!
@IBOutlet weak var addTaskBtn: UIButton!
func loadSectionData(_ sectionData: SectionModel) {
self.headerTitleLbl.text = sectionData.taskType
self.addTaskBtn.tag = sectionData.id
}
}
|
//
// RepoTableViewCell.swift
// GitRx
//
// Created by Михаил Нечаев on 21.12.2019.
// Copyright © 2019 Михаил Нечаев. All rights reserved.
//
import UIKit
import RxSwift
final class RepoTableViewCell: UITableViewCell {
// MARK: - Properties
lazy var avatarImageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
lazy var nameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 17, weight: .medium)
label.textColor = .darkText
return label
}()
lazy var descriptionLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .regular)
label.numberOfLines = 3
label.textColor = .lightGray
return label
}()
lazy var languageLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .regular)
label.textColor = .darkText
return label
}()
lazy var starsLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
label.textColor = .darkText
label.textAlignment = .right
return label
}()
lazy var forksLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
label.textColor = .darkText
label.textAlignment = .right
return label
}()
lazy var dateLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .regular)
label.textColor = .darkText
label.textAlignment = .right
return label
}()
// MARK: - Initializers
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Setup layout
private extension RepoTableViewCell {
func setupLayout() {
setupAvatarLayout()
setupNameLayout()
setupDescriptionLayout()
setupLanguageLayout()
setupStarsLayout()
setupForksLayout()
setupDateLayout()
}
func setupAvatarLayout() {
addSubview(avatarImageView)
avatarImageView.translatesAutoresizingMaskIntoConstraints = false
avatarImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16).isActive = true
avatarImageView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true
avatarImageView.heightAnchor.constraint(equalToConstant: 44).isActive = true
avatarImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true
}
func setupNameLayout() {
addSubview(nameLabel)
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 16).isActive = true
nameLabel.topAnchor.constraint(equalTo: topAnchor, constant: 6).isActive = true
}
func setupDescriptionLayout() {
addSubview(descriptionLabel)
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 16).isActive = true
descriptionLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 6).isActive = true
}
func setupLanguageLayout() {
addSubview(languageLabel)
languageLabel.translatesAutoresizingMaskIntoConstraints = false
languageLabel.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 16).isActive = true
languageLabel.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 6).isActive = true
languageLabel.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -8).isActive = true
}
func setupStarsLayout() {
addSubview(starsLabel)
starsLabel.translatesAutoresizingMaskIntoConstraints = false
starsLabel.leadingAnchor.constraint(equalTo: nameLabel.trailingAnchor, constant: 8).isActive = true
starsLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true
starsLabel.centerYAnchor.constraint(equalTo: nameLabel.centerYAnchor, constant: 0).isActive = true
starsLabel.widthAnchor.constraint(equalToConstant: 94).isActive = true
}
func setupForksLayout() {
addSubview(forksLabel)
forksLabel.translatesAutoresizingMaskIntoConstraints = false
forksLabel.leadingAnchor.constraint(equalTo: descriptionLabel.trailingAnchor, constant: 8).isActive = true
forksLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true
forksLabel.centerYAnchor.constraint(equalTo: descriptionLabel.centerYAnchor, constant: 0).isActive = true
forksLabel.widthAnchor.constraint(equalToConstant: 94).isActive = true
}
func setupDateLayout() {
addSubview(dateLabel)
dateLabel.translatesAutoresizingMaskIntoConstraints = false
dateLabel.leadingAnchor.constraint(equalTo: languageLabel.trailingAnchor, constant: 8).isActive = true
dateLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true
dateLabel.bottomAnchor.constraint(equalTo: languageLabel.bottomAnchor, constant: 0).isActive = true
dateLabel.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -8).isActive = true
}
}
|
import UIKit
class ViewController2: UIViewController, UICollectionViewDataSource {
@IBOutlet weak var collectionOfImages: UICollectionView!
@IBOutlet weak var im: UIImageView!
var pressedImages: [UIImage] = []
var shuffledImages: [UIImage] = []
var pressedButton = false
override func viewDidLoad() {
super.viewDidLoad()
collectionOfImages.dataSource = self
pressedImages = []
shuffledImages = roundImages.shuffled()
}
//Shows toast with number of tries left when you miss the round
func showToast(message : String) {
let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height/1.15, width: 150, height: 35))
toastLabel.textColor = UIColor.red
toastLabel.textAlignment = .center;
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.clipsToBounds = true
self.view.addSubview(toastLabel)
UIView.animate(withDuration: 1.5, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
//Creates the final number of cells
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return roundImages.count
}
//Creates each cell with id "ImageCell" inside the CollectionView, forcing it to change its data-type to ImageCell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let celda = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
//Adds an image to the background of the button contained in each cell
celda.imageButton.setBackgroundImage(shuffledImages[indexPath.row], for: UIControl.State.normal)
return celda
}
//Button that, when pressed, vanishes and adds the image inside to a new array to compare it with the original one and pass the actual round
@IBAction func imageButtonAction(_ sender: UIButton) {
pressedImages.append(sender.backgroundImage(for: UIControl.State.normal)!)
sender.alpha = 0.5
sender.isEnabled = false
}
//Resets array and shows images again
@IBAction func editAgainButton(_ sender: UIButton) {
pressedImages = []
for i in 0...roundImages.count - 1 {
let index = IndexPath(row: i, section: 0)
let cell = collectionOfImages.cellForItem(at: index) as! ImageCell
cell.imageButton.alpha = 1
cell.imageButton.isEnabled = true
}
}
//Button that checks if the arrays compared are equal or not to pass the round
@IBAction func confirmButton(_ sender: Any) {
if (pressedImages == roundImages) {
totalScore += 1
numberOfImages += 1
imageNumber = 0
if (numberOfImages == 10) {
self.performSegue(withIdentifier: "finalScreen", sender: nil)
}
else {
self.performSegue(withIdentifier: "backToFirst", sender: nil)
}
}
else if(pressedImages.count == roundImages.count && pressedImages != roundImages){
currentTries -= 1
if(currentTries > 1) {
self.showToast(message: "Error. \(currentTries) tries left")
}
else if(currentTries == 1) {
self.showToast(message: "Error. \(currentTries) try left")
}
else if(currentTries == 0) {
self.showToast(message: "You lost!")
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.performSegue(withIdentifier: "finalScreen", sender: nil)
}
}
}
else if(pressedImages.count != roundImages.count){
self.showToast(message: "Select all images!")
}
}
}
|
//
// MyCollectionViewCell.swift
// CollectioView
//
// Created by GaneshKumar Gunju on 24/04/18.
// Copyright © 2018 vaayooInc. All rights reserved.
//
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var secondList: UILabel!
}
|
//
// ContactStore.swift
// Contacts
//
// Created by Svetlio on 9.04.21.
//
import UIKit
class ContactStore {
var allContacts = [(Character, [Contact])]()
init() {
for _ in 1...10 {
createContact()
}
}
@discardableResult func createContact() -> Contact? {
let newContact = Contact(random: true)
guard let first = newContact.name.first else {
return nil
}
if let index = allContacts.firstIndex { $0.0 == first } {
allContacts[index].1.append(newContact)
allContacts[index].1.sort()
} else {
allContacts.append((first,[newContact]))
allContacts.sort { $0.0 < $1.0 }
}
return newContact
}
func getNumberOfRows(_ section: Int) -> Int {
allContacts[section].1.count
}
func getContact(section: Int, row: Int) -> Contact {
allContacts[section].1[row]
}
func getSectoinTittle(section: Int) -> String {
String(allContacts[section].0)
}
}
|
//
// CompanyReader.swift
// Jupiter
//
// Created by adulphan youngmod on 15/8/18.
// Copyright © 2018 goldbac. All rights reserved.
//
import Foundation
import CloudKit
extension Company: CompanyReader {}
protocol CompanyReader: SystemField {
var name: String? { get }
var modifiedLocal: Date? { get }
var identifier: UUID? { get }
var accounts: [Account] { get }
}
|
import BSON
import XCTest
@testable import AroundTheTable
class CoordinatesTests: XCTestCase {
static var allTests: [(String, (CoordinatesTests) -> () throws -> Void)] {
return [
("testEncode", testEncode),
("testDecode", testDecode),
("testDecodeNotADocument", testDecodeNotADocument),
("testDecodeMissingCoordinates", testDecodeMissingCoordinates),
("testDecodeInvalidCoordinates", testDecodeInvalidCoordinates)
]
}
func testEncode() {
let input = Coordinates(latitude: 50, longitude: 2)
let expected: Document = [
"type": "Point",
"coordinates": [ 2.0, 50.0 ]
]
XCTAssert(input.typeIdentifier == expected.typeIdentifier)
XCTAssert(Document(input.point.makePrimitive()) == expected)
}
func testDecode() throws {
let input: Document = [
"type": "Point",
"coordinates": [ 2.0, 50.0 ]
]
let result = try Coordinates(input)
let expected = Coordinates(latitude: 50, longitude: 2)
XCTAssert(result == expected)
}
func testDecodeNotADocument() throws {
let input: Primitive = "(50, 2)"
let result = try Coordinates(input)
XCTAssertNil(result)
}
func testDecodeMissingCoordinates() {
let input: Document = [
"type": "Point",
]
XCTAssertThrowsError(try Coordinates(input))
}
func testDecodeInvalidCoordinates() {
let input: Document = [
"type": "Point",
"coordinates": [ 2.0 ]
]
XCTAssertThrowsError(try Coordinates(input))
}
}
|
//
// Constants.swift
// MarvelCharacters
//
// Created by Osamu Chiba on 9/26/21.
// Copyright © 2021 Opix. All rights reserved.
//
import Foundation
import SwiftUI
let apiPublicKey = "MARVEL_PUBLIC_KEY"
let apiPrivateKey = "MARVEL_PRIVATE_KEY"
let apiHostKey = "MARVEL_HOST_KEY"
let marvelScheme = "https"
let marvelCharacterPath = "characters"
// Reference: https://developer.marvel.com/documentation/images
let thumbnailKey = "standard_small" // 65 x 45px
let largeImageKey = "landscape_large" // 190 x 140px
let kCornerRadius: CGFloat = 16
let kDefaultPadding: CGFloat = 16
let kHalfPadding: CGFloat = 8
let kQuaterPadding: CGFloat = 4
let kBorderLineWidth: CGFloat = 1.25
let kSelectedBorderLineWidth: CGFloat = 2.5
let kMaxDownload: Int = 100
let appPrimaryColor = Color.blue
let appFavroiteColor = Color.red
let appDarkGray = Color(red: 129 / 255, green: 129 / 255, blue: 129 / 255)
|
//
// ReminderViewController.swift
// mogo-apps-ios
//
// Created by Ellrica Jana on 06/04/21.
//
import UIKit
class ReminderViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var reminderTable: UITableView!
var reminders: [Reminder] = []
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Saving Reminder"
reminders = createArray()
// showMiracle()
}
@IBAction func unwindToFirstViewController(_ sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? addWithdrawViewController {
let newAmountString = sourceViewController.amountField.text!.components(separatedBy: " ")
let amount = Double(newAmountString[1])!
DispatchQueue.main.async {
if amount == 300000.0{
self.showMiracle(value: 0,descriptionDialog: "1 January 2022")
}else if amount == 200000.0{
self.showMiracle(value: 1,descriptionDialog: "IDR 312.500/month")
}else if amount == 500000.0{
self.showMiracle(value: 2,descriptionDialog: "5 December 2021")
}
}
}
}
func showMiracle(value :Int, descriptionDialog:String) {
let slideVC = OverlayView()
// Kirim data 0 - 4
slideVC.flag = value
slideVC.a = "Shoes"
slideVC.b = descriptionDialog
slideVC.c = "200.000"
slideVC.modalPresentationStyle = .custom
slideVC.transitioningDelegate = self
self.present(slideVC, animated: true, completion: nil)
}
func createArray() -> [Reminder] {
let reminder1 = Reminder(reminderTitle: "Shoes", reminderDetail: "Add Saving IDR 300.000")
return [reminder1]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return reminders.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 59.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reminder = reminders[indexPath.row]
let cell = (tableView.dequeueReusableCell(withIdentifier: "reminderCellIdentifier", for: indexPath) as? ReminderViewCell)!
cell.setReminder(reminder: reminder)
return cell
}
// func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// self.performSegue(withIdentifier: "segueAddWithdraw", sender: self)
// }
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableView.beginUpdates()
reminders.remove(at: indexPath.row)
//reminderDetailArray.remove(at: indexPath.row)
tableView.deleteRows(at: [IndexPath(row: indexPath.row, section: 0)], with: .fade)
tableView.endUpdates()
}
}
}
extension ReminderViewController: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
PresentationController(presentedViewController: presented, presenting: presenting)
}
}
|
//
// ConversationCell.swift
// ChatApp
//
// Created by L on 2021/9/26.
//
import UIKit
class ConversationCell: UITableViewCell {
// MARK: - Properties
var conversation: Conversation? {
didSet { configure() }
}
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.backgroundColor = .lightGray
return imageView
}()
let timestampLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.textColor = .darkGray
label.text = "1h"
return label
}()
let usernameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
return label
}()
let messageTextLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
return label
}()
// MARK: - Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(profileImageView)
profileImageView.snp.makeConstraints { make in
make.left.equalToSuperview().offset(12)
make.size.equalTo(50)
make.centerY.equalToSuperview()
profileImageView.layer.cornerRadius = 50 / 2
}
let stack = UIStackView(arrangedSubviews: [usernameLabel,messageTextLabel])
stack.axis = .vertical
stack.spacing = 5
addSubview(stack)
stack.snp.makeConstraints { make in
make.centerY.equalTo(profileImageView)
make.left.equalTo(profileImageView.snp.right).offset(12)
make.right.equalToSuperview().offset(-12)
}
addSubview(timestampLabel)
timestampLabel.snp.makeConstraints { make in
make.top.equalToSuperview().offset(20)
make.right.equalToSuperview().offset(-12)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Helpers
func configure() {
guard let conversation = conversation else { return }
let viewModel = ConversationViewModel(conversation: conversation)
usernameLabel.text = conversation.user.username
messageTextLabel.text = conversation.message.text
timestampLabel.text = viewModel.timestamp
profileImageView.kf.setImage(with: viewModel.profileImageUrl)
}
}
|
//
// SideViewController.swift
// PikaChat
//
// Created by Praveen Gowda I V on 7/25/16.
// Copyright © 2016 Gowda I V, Praveen. All rights reserved.
//
import UIKit
import FirebaseAuth
class SideViewController: UIViewController {
@IBOutlet weak var usernameLabel: UILabel!
override func viewDidLoad() {
usernameLabel.text = FIRAuth.auth()?.currentUser?.displayName
}
@IBAction func signoutUser() {
Utils.logoutUser()
dismissViewControllerAnimated(true, completion: nil)
}
}
|
//
// StudentLocationResponse.swift
// On the Map
//
// Created by Aditya Rana on 14.09.20.
// Copyright © 2020 Aditya Rana. All rights reserved.
//
import Foundation
struct StudentLocationResponse: Codable {
let results: [StudentLocation]
enum CodingKeys: String, CodingKey {
case results
}
}
class StudentsLocationData {
static var studentsData = [StudentLocation]()
}
|
//
// UIViewControllerExtensions.swift
// ImageFilter
//
// Created by Vladimir Gordienko on 08/12/2018.
// Copyright © 2018 Vladimir Gordienko. All rights reserved.
//
import UIKit
extension UIViewController: ShowAlert {
func showAlert(message: String) {
let alert = UIAlertController(title: "", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
extension UIViewController: PhotoLibraryPermissionsReachability {
func checkPhotoLibraryPermission() {
checkPhotoLibraryAuthorizationStatus { [weak self] (success) in
if !success {
self?.showAlert(message: "ImageFilter doesn't have permission to use the photo library, please change privacy settings")
}
}
}
}
extension UIViewController: CameraPermissionsReachability {
func checkCameraPermission() {
checkCameraAuthorizationStatus { [weak self] (success) in
if !success {
self?.showAlert(message: "ImageFilter doesn't have permission to use the camera, please change privacy settings")
}
}
}
}
|
//
// TableViewMain.swift
// CLEAN
//
// Created by eunji on 2018. 6. 21..
// Copyright © 2018년 clean. All rights reserved.
//
import Foundation
import UIKit
class CleanTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableview: UITableView!
var datas:Array<Dictionary<String, Any>> = []
override func viewDidLoad() {
super.viewDidLoad()
tableview.dataSource = self
tableview.delegate = self
CleanTableData.shared.data_setting()
CleanTableData.shared.data_debug()
//datas = CleanTableData.shared.data.data
//print(",,,,\ncount: \(datas.count)\n0000000")
//self.tableview.register(UITableViewCell.self,forCellReuseIdentifier: "cell")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
CleanTableData.shared.data_setting()
CleanTableData.shared.data_debug()
//datas = CleanTableData.shared.data.data
if let dataList:Array<Dictionary<String, Any>> = UserDefaults.standard.object(forKey: Constants.Database.data_name) as? Array<Dictionary<String, Any>> {
datas = dataList
}
print(",,,,\ncount: \(datas.count)\n0000000")
tableview.reloadData()
}
func viewInit() {
// tableview.backgroundColor = .white
// tableview.layer.masksToBounds = false
tableview.layer.shadowColor = UIColor.black.cgColor
tableview.layer.shadowOffset = CGSize.zero
tableview.layer.shadowOpacity = 0.3
tableview.layer.shadowRadius = 10
return
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return datas.count
}
//테이블뷰 셀 높이 지정
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 110
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// let quanx = datas[indexPath.row]
// let image = String(quanx.eid)
//
// cell.textLabel?.text = quanx.ename
// cell.detailTextLabel?.text = quanx.front_date
// cell.imageView?.image = UIImage(named: image)
// Configure the cell...
// getData["memo"] = get_data.memo
// getData["valid"] = get_data.valid
// getData["front_date"] = get_data.front_date
// getData["cycle"] = get_data.cycle
// getData["alarm"] = get_data.alarm
// getData["eid"] = get_data.eid
//수정본
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
let infoDic = datas[indexPath.row] as Dictionary<String, Any>
var image = ""
let eid = infoDic["eid"]
if eid as! Int == 00 {
image = "sofa"
} else if eid as! Int == 01 {
image = "floor2"
} else if eid as! Int == 10 {
image = "microwave"
} else if eid as! Int == 11 {
image = "floor"
} else if eid as! Int == 20 {
image = "bath"
} else if eid as! Int == 21 {
image = "basin"
} else if eid as! Int == 22 {
image = "floor"
} else if eid as! Int == 23 {
image = "toilet"
} else if eid as! Int == 30 {
image = "bed"
} else if eid as! Int == 31 {
image = "floor2"
} else if eid as! Int == 40 {
image = "bed"
} else if eid as! Int == 41 {
image = "floor2"
} else if eid as! Int == 50 {
image = "bed"
}else if eid as! Int == 51 {
image = "floor2"
} else if eid as! Int == 60 {
image = "closet"
} else if eid as! Int == 61 {
image = "floor2"
} else if eid as! Int == 70 {
image = "tv"
} else if eid as! Int == 71 {
image = "computer"
} else if eid as! Int == 72 {
image = "hairdry"
}
cell.imgView.image = UIImage(named: image)
cell.lblTitle.text = infoDic["ename"] as? String
cell.lblDays.text = infoDic["front_date"] as? String
return cell
}
}
|
//
// SetShowMessage.swift
// pizzino
//
// Created by PERSEO on 25/06/16.
// Copyright © 2016 Mattia Azzena. All rights reserved.
//
import UIKit
import SCLAlertView
class SetShowMessageController: UITableViewController {
//delegato dalla table al newmessage
var delegate: SetShowMessageDelegate?
//modifiche delegato
func whereTheChangesAreMade(data: String!) {
if let del = delegate {
//richiamo la funzione del protocollo che viene letta
del.aggiornaSetShowMessageDelegate(data)
}
}
var statoAttuale : String!
//lettura impostazione corrente
//al primo avvio letto dal proprieta segue
@IBOutlet var testoShowMessage: UILabel!
@IBOutlet var testoDescShowMessage: UITextView!
@IBOutlet var switchShowMessage: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
//impostazioni navbar
navigationItem.title = "SETSHOWDELETE".localized_con_commento("titolo princiaple")
//top bar
navigationController!.navigationBar.barStyle = UIBarStyle.BlackOpaque
navigationController!.navigationBar.barTintColor = myColor_verde
//colore font
navigationController!.navigationBar.tintColor = UIColor.whiteColor()
testoShowMessage.text = "SETSHOWMESSAGECELLA".localized_con_commento("Show deleted message")
testoDescShowMessage.text = "DESCSHOWMESSAGE".localized_con_commento("descrizione").uppercaseString
testoDescShowMessage.textColor = myColor_grigio3
testoDescShowMessage.font = .systemFontOfSize(12)
switchShowMessage.addTarget(self, action: #selector(SetShowMessageController.selezioneShowMessage(_:)), forControlEvents: UIControlEvents.ValueChanged)
aggiornaImpostazioni()
}
func aggiornaImpostazioni(){
if statoAttuale == "0" {
self.switchShowMessage.setOn(false, animated: true)
}
else{
self.switchShowMessage.setOn(true, animated: true)
}
}
func selezioneShowMessage(switchState: UISwitch) {
if switchShowMessage.on {
//selezinato on
self.statoAttuale = "1"
self.whereTheChangesAreMade(self.statoAttuale)
self.switchShowMessage.setOn(true, animated: true)
self.aggiornaImpostazioni()
}
//se swith off
else {
//clear
self.statoAttuale = "0"
self.whereTheChangesAreMade(self.statoAttuale)
self.aggiornaImpostazioni()
}
}
}
|
import Foundation
func sum() {
// aからnまでの総和を求める(for文)
print("aからnまでの総和を求めます。")
var a = Int(input("整数a:"))!
var b = Int(input("整数b:"))!
if a > b {
(a, b) = (b, a)
}
var sum = 0
for i in a...b {
sum += i // sumに1を加える
}
print("\(a)から\(b)までの総和は\(sum)です。")
}
|
//
// SectionRepresentable.swift
// DataSources
//
// Created by Sergey on 14.09.2018.
// Copyright © 2018 Sergey. All rights reserved.
//
import Foundation
public protocol SectionRepresentable {
var header: SectionHeaderRepresentable? { get }
var footer: SectionFooterRepresentable? { get }
var isEmpty: Bool { get }
func itemsCount() -> Int
func item<PresenterType>(at index: Int) -> PresenterType?
func headerTitle() -> String?
func footerTitle() -> String?
func append(with newItems: [PresenterType], handler: SectionChangeHandler?)
func append(with item: PresenterType, handler: SectionChangeHandler?)
func remove(itemsAt indices: [Int])
func remove(itemAt index: Int)
func removeAll(with handler: SectionChangeHandler?)
func insert(with newItems: [PresenterType], at index: Int, handler: SectionChangeHandler?)
func insert(with item: PresenterType, at index: Int)
func replace(itemAt index: Int, with item: PresenterType)
func reorderItems(at sourceIndex: Int, and destinationIndex: Int)
}
public extension SectionRepresentable {
// MARK: - Utils -
func headerTitle() -> String? {
return header?.headerTitle
}
func footerTitle() -> String? {
return footer?.footerTitle
}
// MARK: - Append -
func append(with item: PresenterType, handler: SectionChangeHandler?) {
append(with: [item], handler: handler)
}
// MARK: - Remove -
func remove(itemsAt indices: [Int]) {
indices.forEach({ remove(itemAt: $0) })
}
// MARK: - Insert -
func insert(with item: PresenterType, at index: Int) {
insert(with: [item], at: index, handler: nil)
}
}
|
// Generated using Sourcery 0.9.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
import UIKit
public func style<Object: UIBarButtonItem>() -> Lens<Object, UIBarButtonItem.Style> {
return Lens(
get: { $0.style },
setter: { $0.style = $1 }
)
}
public func width<Object: UIBarButtonItem>() -> Lens<Object, CGFloat> {
return Lens(
get: { $0.width },
setter: { $0.width = $1 }
)
}
public func possibleTitles<Object: UIBarButtonItem>() -> Lens<Object, Set<String>?> {
return Lens(
get: { $0.possibleTitles },
setter: { $0.possibleTitles = $1 }
)
}
public func customView<Object: UIBarButtonItem>() -> Lens<Object, UIView?> {
return Lens(
get: { $0.customView },
setter: { $0.customView = $1 }
)
}
public func action<Object: UIBarButtonItem>() -> Lens<Object, Selector?> {
return Lens(
get: { $0.action },
setter: { $0.action = $1 }
)
}
public func target<Object: UIBarButtonItem>() -> Lens<Object, AnyObject?> {
return Lens(
get: { $0.target },
setter: { $0.target = $1 }
)
}
public func tintColor<Object: UIBarButtonItem>() -> Lens<Object, UIColor?> {
return Lens(
get: { $0.tintColor },
setter: { $0.tintColor = $1 }
)
}
|
//: [Previous](@previous)
import Foundation
let remindersDataURL = URL(fileURLWithPath: "Reminders",
relativeTo: FileManager.documentDirectoryURL)
let stringURL = FileManager.documentDirectoryURL.appendingPathComponent("String").appendingPathExtension("txt")
stringURL.path
//challenge
let challengeString:String = "To Do List"
let challengeURL: URL = URL(fileURLWithPath: challengeString, relativeTo: FileManager.documentDirectoryURL).appendingPathExtension("txt")
challengeURL.lastPathComponent
//: [Next](@next)
|
//
// HuanHu_showDeliveryVC.swift
// CalculateAgent
//
// Created by Dongze Li on 4/6/18.
// Copyright © 2018 Dongze Li. All rights reserved.
//
import UIKit
class HuanHu_showDeliveryVC: UIViewController {
var data: DeliveryRecord = DeliveryRecord()
var titleLabel: UILabel!
var zone5Label: UILabel!
var zone2Label: UILabel!
// all the fields
var zone2Field: UILabel!
var zone5Field: UILabel!
var initY = 100
let offset = 40
let smallOffset = 25
let gap = 300
override func viewDidLoad() {
super.viewDidLoad()
titleLabel = UILabel(frame:CGRect(x: 20, y: initY, width: 320, height: 20))
self.view.addSubview(titleLabel)
initY += offset
initY += smallOffset
zone2Label = UILabel(frame: CGRect(x: 30, y: initY, width: 100, height: 20))
zone2Field = UILabel(frame: CGRect(x: gap, y: initY, width: 100, height: 20))
self.view.addSubview(zone2Label)
self.view.addSubview(zone2Field)
initY += offset
initY += offset
initY += offset
zone5Label = UILabel(frame: CGRect(x: 30, y: initY, width: 100, height: 20))
zone5Field = UILabel(frame: CGRect(x: gap, y: initY, width: 100, height: 20))
self.view.addSubview(zone5Label)
self.view.addSubview(zone5Field)
showDetails(record: self.data)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// assign numbers to the labels
func showDetails(record: DeliveryRecord) -> Void{
titleLabel.text = "\(record.date) \(record.hospital)送货记录📝"
zone2Label.text = "二病区"
zone5Label.text = "五病区"
for item in record.list {
switch item.key {
case "二病区": zone2Field.text = "\(item.value)套"; break
case "五病区": zone5Field.text = "\(item.value)套"; break
default: break
}
}
}
}
|
//
// VerifyEmailController.swift
// LoginTest2
//
// Created by Brendon Van on 7/6/19.
// Copyright © 2019 Brendon Van. All rights reserved.
//
//MARK: - Imports
import UIKit
import Firebase
class SignUpController: UITableViewController, UITextFieldDelegate {
//MARK: - Variables
var uid = ""
var email = ""
//MARK: - Prepare Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch identifier {
case "verifyEmailSegue":
let vc: VerifyEmailController = segue.destination as! VerifyEmailController
vc.uid = self.uid
vc.email = self.email
default:
return
}
}
}
//MARK: - Handle SignUp
// func handleRegister() {
//Checks if text field are used
// guard let firstName = firstNameTextField.text, let lastName = lastNameTextField.text, let phoneNum = phoneTextField.text, let password = passwordTextField.text, let passwordVerified = passwordVerifyTextField.text else {
// print("Form is not valid")
// return
// }
//
// //Creates User
// Auth.auth().createUser(withEmail: email, password: password, completion: {(user , error) in
// let user = Auth.auth().currentUser
// if error != nil {
// // If there is something wrong give user error
// let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertController.Style.alert)
//
// alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {(action) in
// alert.dismiss(animated: true, completion: nil)
// }))
//
// user?.delete(completion: nil)
// return self.present(alert, animated: true, completion: nil)
//
//
// } else if Check().ifPasswordIsValid(passwordStr: password) == false{
// // Checks if password is valid if not let user know
// let alert = UIAlertController(title: "Invalid Password", message: "Password must contain 6 characters, 1 Uppercase, and 1 digit", preferredStyle: UIAlertController.Style.alert)
//
// alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {(action) in
// alert.dismiss(animated: true, completion: nil)
// }))
//
// user?.delete(completion: nil)
// return self.present(alert, animated: true, completion: nil)
//
// } else if Check().ifPasswordVerifyIsValid(passwordStr: password, passwordVerifiedStr: passwordVerified) {
// // Checks if phone is valid if not let user know
// let alert = UIAlertController(title: "Passwords do not match", message: "Please check your password", preferredStyle: UIAlertController.Style.alert)
//
// alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {(action) in
// alert.dismiss(animated: true, completion: nil)
// }))
//
// user?.delete(completion: nil)
// return self.present(alert, animated: true, completion: nil)
//
// } else if Check().ifPhoneIsValid(phoneStr: phoneNum) == false {
// // Checks if phone is valid if not let user know
// let alert = UIAlertController(title: "Invalid Phone Number Format", message: "Format phone ###-###-####", preferredStyle: UIAlertController.Style.alert)
//
// alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {(action) in
// alert.dismiss(animated: true, completion: nil)
// }))
//
// user?.delete(completion: nil)
// return self.present(alert, animated: true, completion: nil)
//
// } else if user?.isEmailVerified == false {
// // Checks if email is verified if not let user know
//
// let uid = Auth.auth().currentUser!.uid
// let ref = Database.database().reference(fromURL: "https://theaterx-official.firebaseio.com/")
// let values = ["Type": "Customer", "First": firstName, "Last": lastName, "Phone": phoneNum, "Email": self.email]
// let usersReference = ref.child("users").child(uid)
// usersReference.updateChildValues(values, withCompletionBlock: {(error, ref) in
// if error != nil {
// print(error! )
// return
// }
//
// Auth.auth().currentUser?.sendEmailVerification(completion: nil)
// print("Saved user successfully into Firebase database")
//
// self.uid = uid
// //self.email = email
//
// self.performSegue(withIdentifier: "verifyEmailSegue", sender: nil)
//
// })
//
// }
//
// })
// }// HandleRegister()
//
//
}
|
//
// ViewController.swift
// SpeedReader
//
// Created by Kay Yin on 7/3/17.
// Copyright © 2017 Kay Yin. All rights reserved.
//
import Cocoa
class ArticleViewController: NSViewController, NSTextViewDelegate {
var article: Article?
var observer: NSKeyValueObservation?
@IBOutlet var contentTextView: NSTextView!
@IBOutlet weak var guidanceView: NSView!
@IBOutlet weak var outerTextScrollView: NSScrollView!
var detailWindow: ReadDetailWindow?
var allFontNames: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.view.wantsLayer = true
allFontNames = NSFontManager.shared.availableFontFamilies
observer = view.observe(\.effectiveAppearance) { [weak self] _, _ in
self?.updateAppearanceRelatedChanges()
}
contentTextView.textContainerInset = NSSize(width: 20.0, height: 20.0)
contentTextView.delegate = self
}
private func updateAppearanceRelatedChanges() {
if #available(OSX 10.14, *) {
switch view.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) {
case .aqua?: contentTextView.drawsBackground = true
case .darkAqua?: contentTextView.drawsBackground = false
default: contentTextView.drawsBackground = true
}
}
}
override var representedObject: Any? {
didSet {
}
}
func updateToReflectArticle() {
if article != nil {
self.contentTextView.string = article?.content ?? ""
self.contentTextView.scroll(CGPoint(x: 0, y: -50))
}
}
func textDidChange(_ notification: Notification) {
article?.content = contentTextView.string
(NSApplication.shared.delegate as? AppDelegate)?.saveAction(nil)
}
@IBAction func createArticle(_ sender: NSButton) {
if let vc = storyboard?.instantiateController(withIdentifier: "BlankDocument") as? NSViewController {
self.present(vc, asPopoverRelativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.maxY, behavior: .transient)
}
}
}
|
//
// UIView+Ex.swift
// TortyMozyrApp
//
// Created by Саша Капчук on 2.04.21.
//
import UIKit
extension UIView {
func addSubview(_ views: [UIView]) {
views.forEach {
self.addSubview($0)
}
}
}
|
//
// Contract.swift
// VelAll
//
// Created by Mohcine BELARREM on 04/08/2020.
// Copyright © 2020 Mohcine BELARREM. All rights reserved.
//
import Foundation
struct Contract : Decodable {
enum CodingKeys : String,CodingKey {
case name,cities
case commercialName = "commercial_name"
case countryCode = "country_code"
}
let name : String
let commercialName : String
let cities : [String]
let countryCode : String
init(from decoder : Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "No Name"
self.commercialName = try container.decodeIfPresent(String.self, forKey: .commercialName) ?? "No Commercial Name"
self.countryCode = try container.decodeIfPresent(String.self, forKey: .countryCode) ?? "No Country"
self.cities = try container.decodeIfPresent([String].self, forKey: .cities) ?? [String]()
}
var description : String {
return "Name : \(name)\n" +
"Commercial Name : \(commercialName)\n" +
"Country Code : \(countryCode)\n" +
"cities : \(cities)\n"
}
}
|
//
// Alamofire_SwiftyJSON.swift
// SwiftDemo
//
// Created by sam on 2019/4/24.
// Copyright © 2019 sam . All rights reserved.
//SwiftyJSON_HandyJson的使用
import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
import HandyJSON
// 相当于数据模型model
struct ItemsModel: HandyJSON {
var cover_image_url = ""
var title = ""
var likecount = ""
}
class SwiftyJSON_HandyJson_VC: UIViewController,UITableViewDelegate,UITableViewDataSource {
lazy var gifttableview: UITableView = {
let tableview: UITableView = UITableView(frame:self.view.bounds, style: .plain)
tableview.backgroundColor = .white
tableview.delegate = self
tableview.dataSource = self
tableview.rowHeight = 300
return tableview
}()
// 数据源
var dataArray = [ItemsModel]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "SwiftyJSON_HandyJson的使用"
self.view.addSubview(gifttableview)
self.AlamofireGetRequest()
//self.AlamofirePostRequest()
//注册cell
gifttableview.register(SamTableViewCell.self)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(with: SamTableViewCell.self, for: indexPath)
let model = self.dataArray[indexPath.row]
cell.iconImv.kf.setImage(with: URL(string: model.cover_image_url))
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
print(indexPath.row)
}
}
extension SwiftyJSON_HandyJson_VC{
func AlamofireGetRequest() {
NetworkManager.NetWorkRequest(.getPhotoList, completion: { (JSOnDictory) -> (Void) in//JSOnDictory 是Json类型
//print(json)
let dataARR = JSOnDictory["data"]["items"].arrayObject
if let arr = JSONDeserializer<ItemsModel>.deserializeModelArrayFrom(array: dataARR) {
let arr1 = arr.compactMap({$0})
self.dataArray = arr1
self.gifttableview.reloadData()
}
}) { (errorStr) -> (Void) in
print(errorStr)
}
}
}
|
//
// ViewController.swift
// FarkleRedo
//
// Created by Yemi Ajibola on 8/20/16.
// Copyright © 2016 Yemi Ajibola. All rights reserved.
//
import UIKit
class ViewController: UIViewController, DiceImageViewDelegate, ScoreLogicDelegate, PlayerDelegate {
@IBOutlet weak var diceOne: DiceImageView!
@IBOutlet weak var diceSix: DiceImageView!
@IBOutlet weak var diceFive: DiceImageView!
@IBOutlet weak var diceFour: DiceImageView!
@IBOutlet weak var diceThree: DiceImageView!
@IBOutlet weak var diceTwo: DiceImageView!
@IBOutlet weak var playerOneScoreLabel: UILabel!
@IBOutlet weak var playerTwoScoreLabel: UILabel!
@IBOutlet weak var roundScoreLabel: UILabel!
@IBOutlet weak var rollScoreLabel: UILabel!
@IBOutlet weak var gatherDiceLabel: UILabel!
@IBOutlet weak var rollButton: UIButton!
var playerOne: Player!
var playerTwo: Player!
var currentPlayer:Player!
//var players:[Player]!
var boardDice: [DiceImageView]!
var scoreLogic: ScoreLogic!
var animator: UIDynamicAnimator? = nil
override func viewDidLoad() {
super.viewDidLoad()
scoreLogic = ScoreLogic()
playerOne = Player(nameString: "Yemi")
playerTwo = Player()
currentPlayer = playerOne
playerOne.delegate = self
playerTwo.delegate = self
gatherDiceLabel.userInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.gatherDice))
gatherDiceLabel.addGestureRecognizer(tapGesture)
animator = UIDynamicAnimator(referenceView: view)
boardDice = [diceOne, diceTwo, diceThree, diceFour, diceFive, diceSix]
for die in boardDice {
die.delegate = self
}
scoreLogic.delegate = self
}
@IBAction func onRollButtonTapped(sender: UIButton) {
currentPlayer.selectedDice.removeAll(keepCapacity: true)
for die in boardDice {
die.roll()
}
scoreLogic.calculateScore(boardDice)
if checkForFarkle(boardDice) {
showMessage("Farkle!", message: "You farkled. You lose your round score.")
scoreLogic.roundScore = 0
reset()
switchPlayers()
}
rollButton.enabled = false
}
@IBAction func onBankButtonTapped(sender: UIButton) {
if currentPlayer == playerOne {
playerOne.score += scoreLogic.roundScore
} else {
playerTwo.score += scoreLogic.roundScore
}
scoreLogic.roundScore = 0
reset()
switchPlayers()
}
func showMessage(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(okAction)
presentViewController(alert, animated: true, completion: nil)
}
func diceImageViewTapped(die: DiceImageView) {
if !currentPlayer.selectedDice.contains(die) {
die.alpha = 0.35
boardDice.removeAtIndex(boardDice.indexOf(die)!)
currentPlayer.selectedDice.append(die)
} else {
die.alpha = 1.0
currentPlayer.selectedDice.removeAtIndex(currentPlayer.selectedDice.indexOf(die)!)
boardDice.append(die)
}
scoreLogic.calculateScore(currentPlayer.selectedDice)
if checkForHotDice() {
showMessage("Hot Dice!", message: "You get to roll again.")
scoreLogic.roundScore += scoreLogic.rollScore
reset()
}
}
func rollScoreWasUpdated() {
rollScoreLabel.text = "Roll score: \(scoreLogic.rollScore)"
}
func roundScoreWasUpdated() {
roundScoreLabel.text = "Round score: \(scoreLogic.roundScore)"
}
func playerScoreWasUpdated() {
if currentPlayer == playerOne {
playerOneScoreLabel.text = "Player One score: \(playerOne.score)"
} else {
playerTwoScoreLabel.text = "Player Two score: \(playerTwo.score)"
}
}
func gatherDice() {
scoreLogic.roundScore += scoreLogic.rollScore
for die in currentPlayer.selectedDice {
let snapBehavior = UISnapBehavior(item: die, snapToPoint: gatherDiceLabel.center)
animator?.addBehavior(snapBehavior)
}
rollButton.enabled = true
}
func checkForFarkle(diceHand: [DiceImageView]) -> Bool {
return (scoreLogic.rollScore == 0 && diceHand.count > 0) ? true : false
}
func checkForHotDice() -> Bool {
return boardDice.count == 0
}
func switchPlayers() {
if currentPlayer == playerTwo {
currentPlayer = playerOne
} else {
currentPlayer = playerTwo
}
}
func reset() {
boardDice = [diceOne, diceTwo, diceThree, diceFour, diceFive, diceSix]
currentPlayer.selectedDice.removeAll(keepCapacity: true)
for die in boardDice {
die.roll()
die.alpha = 1.0
die.userInteractionEnabled = true
}
scoreLogic.calculateScore(boardDice)
checkForFarkle(boardDice)
}
}
|
//
// File.swift
// ChatViewPrototype
//
// Created by Robin Malhotra on 06/01/17.
// Copyright © 2017 Robin Malhotra. All rights reserved.
//
import AsyncDisplayKit
protocol KeyboardToolbar {
var node: ASDisplayNode {get}
}
extension KeyboardToolbar where Self: UIViewController {
func setup() {
self.viewDidLayoutSubviews()
}
}
|
//
// MPComment.swift
// MessagePosting
//
// Created by Nicolas Flacco on 9/3/14.
// Copyright (c) 2014 Nicolas Flacco. All rights reserved.
//
import CoreData
class MPComment {
var id: String?
var text: String!
var createdAt: NSDate!
var updatedAt: NSDate!
var post:Post!
var pfPost:PFObject!
var pfComment:PFObject!
required init(text:String, post:Post, date:NSDate) {
self.text = text
self.createdAt = date
self.updatedAt = date
self.post = post
// Create pfComment
self.pfComment = PFObject(className:parseClassNameComment)
self.pfComment[parseKeyNameText] = self.text
// Add comment to post
self.pfPost = PFObject(withoutDataWithClassName: parseClassNamePost, objectId: post.id)
self.pfPost.incrementKey(parseKeyNameNumberComments)
self.pfPost.addObject(self.pfComment, forKey: parseKeyNameComments) // Add the comment to the post
self.pfComment[parseKeyNameParent] = self.pfPost
}
required init(obj: PFObject) {
if obj.parseClassName == parseClassNameComment {
self.id = obj.objectId
self.text = obj.objectForKey(parseKeyNameText) as String
self.createdAt = obj.createdAt as NSDate
self.updatedAt = obj.updatedAt as NSDate
} else {
assertionFailure(":(")
}
}
// MARK: - Core data
func saveToCoreData(post: Post) -> Comment? {
println("comment:saveToCoreData")
// 1. Does this post already exist in DB?
// 2. If so, has it been updated?
if let validId = self.id {
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
let entityDescripition = NSEntityDescription.entityForName(coreDataEntityComment, inManagedObjectContext: managedObjectContext!)
let comment = Comment(entity: entityDescripition!, insertIntoManagedObjectContext: managedObjectContext!)
comment.text = self.text
comment.createdAt = self.createdAt
comment.updatedAt = self.updatedAt
comment.id = validId
comment.post = post
var error:NSError?
managedObjectContext?.save(&error)
if let realError = error {
// TODO
println("TODO: fail!");
}
return comment
} else {
assertionFailure("This should not happen :(")
return nil
}
}
class func findCommentInCoreData(comment:MPComment, successBlock:(Comment) -> Void, failureBlock:(MPComment) -> Void, errorBlock:(NSError!) -> Void) {
dispatch_async(dispatch_get_main_queue(), {
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
var fetchRequest = NSFetchRequest(entityName: coreDataEntityComment)
fetchRequest.predicate = NSPredicate(format: "id == %@", comment.id!)
var error:NSError? = nil
var result = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error)
if result?.count == 1 {
let comment = result?.first as Comment
successBlock(comment)
} else if result?.count == 0 {
failureBlock(comment)
} else {
errorBlock(error)
}
})
}
// MARK: - Parse.com
class func getCommentsForPost(post:Post) {
var query = PFQuery(className: parseClassNameComment)
query.whereKey(parseKeyNameParent, equalTo:PFObject(withoutDataWithClassName: parseClassNamePost, objectId: post.id))
query.orderByAscending(parseKeyNameDate)
query.limit = 1000
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]!, error:NSError!) -> Void in
if let realError = error {
// Oh dear -> fire callback
} else {
// Stupendous -> fire callback
for obj in objects {
let pfObj = obj as PFObject
let comment = MPComment(obj: pfObj)
let successBlock = {(post coreDataComment:Comment) -> Void in
println("already exists")
}
let failureBlock = {(comment mpComment:MPComment) -> Void in
let coreDataComment = mpComment.saveToCoreData(post)
}
let errorBlock = {(error:NSError!) -> Void in
println("failure to fetch")
}
MPComment.findCommentInCoreData(comment, successBlock, failureBlock: failureBlock, errorBlock: errorBlock)
}
}
}
}
func saveToParse(successBlock:(String) -> Void, errorBlock:(NSError!) -> Void) {
// We save the post, because it automatically saves the comment
// NOTE: We only get the comment's objectId after the post has been saved to Parse.com (not at PFObject creation locally)
self.pfPost.saveInBackgroundWithBlock({
(success: Bool!, error:NSError!) -> Void in
println("comment:saveToParse:backgroundblock")
if success! {
self.id = self.pfComment.objectId // Save comment.objectId here!
// save the comment to core data
self.saveToCoreData(self.post)
trackComposeComment(self.text, self.createdAt)
// update the post
MPPost.update(self.post, date: self.updatedAt)
// fire success
successBlock(self.id!)
} else {
println("failure to upload")
errorBlock(error)
}
})
}
}
|
//
// StorageManager.swift
// EvaluationTestiOS
//
// Created by Денис Магильницкий on 16.01.2021.
// Copyright © 2021 Денис Магильницкий. All rights reserved.
//
import Foundation
public class StorageManager: StorageManagerProtocol {
var albumsArray = [Album]()
var tracksArray = [Track]()
func save<T>(description: FetchingDataType, data: [T]) {
switch description {
case .albums:
albumsArray = (data as! [Album]).sorted(by: { $0 < $1 })
case .tracks:
if data.count > 0 {
tracksArray = data as! [Track]
tracksArray.remove(at: 0)
}
}
}
func removeLastRequestData(description: FetchingDataType) {
switch description {
case .albums:
albumsArray.removeAll()
case .tracks:
tracksArray.removeAll()
}
}
func getSavedRequestData<T>(description: FetchingDataType, for indexPath: IndexPath) -> T {
switch description {
case .albums:
return albumsArray[indexPath.row] as! T
case .tracks:
if tracksArray.count > 0 {
return tracksArray[indexPath.row - 1] as! T
}
return tracksArray[indexPath.row] as! T
}
}
func getNumberOfElementsIn(description: FetchingDataType) -> Int {
switch description {
case .albums:
return albumsArray.count
case .tracks:
return tracksArray.count
}
}
// Get model by album ID for present in AlbumDetailViewController
func getModelById(_ id: Int) -> Album? {
for album in albumsArray {
if id == album.collectionId {
return album
}
}
return nil
}
// Convert date with format: "yyyy-MM-dEEEEEhh:mm:ssZZZ" to "MM dd yyyy"
func getDateFrom(_ model: Album) -> String {
let dateString = model.releaseDate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dEEEEEhh:mm:ssZZZ"
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM dd yyyy"
return dateFormatter.string(from: dateObj!)
}
}
|
//
// ArgumentParser.swift
// awwyiss
//
// Created by Jasdev Singh on 4/9/16.
//
//
import Foundation
/**
Represents an error in CLI argument parsing
- InvalidMessageLength: Message had an invalud length, must be in (0, 45)
*/
enum ArgumentParsingParseError: PrintableErrorProtocol {
case InvalidMessageLength
case InvalidArguments
}
// MARK: - CustomStringConvertible
extension ArgumentParsingParseError: CustomStringConvertible {
var description: String {
switch self {
case InvalidMessageLength:
return "Messages must be non-empty and less than 45 characters!"
case InvalidArguments:
return "Invalid arguments! See README.md for instructions."
}
}
}
struct ArgumentParser {
// Prevent initialization
private init() {}
private struct Constants {
static let maxMessageLength = 45
}
/**
Creates a message `Result` from CLI arguments
- parameter arguments: The arguments passed into the script
- returns: A `Result` with the message string or an error
*/
static func parseArguments(arguments: [String]) -> Result<(message: String, sfw: Bool)> {
let arguments = Array(arguments.dropFirst())
guard arguments.count > 1 else {
return .Failure(ArgumentParsingParseError.InvalidArguments)
}
let sfw = arguments[0] == "sfw"
// Ignore launch path
let finalMessage = arguments.suffix(from: sfw ? 1 : 0).joined(separator: " ")
guard case 1..<Constants.maxMessageLength = finalMessage.characters.count else {
return .Failure(ArgumentParsingParseError.InvalidMessageLength)
}
return .Success((message: finalMessage, sfw: sfw))
}
}
|
//
// CameraMultiImageViewController.swift
// Harvey
//
// Created by Sean Hart on 8/29/17.
// Copyright © 2017 TangoJ Labs, LLC. All rights reserved.
//
import AVFoundation
import GoogleMaps
import MapKit
import MobileCoreServices
import UIKit
protocol CameraViewControllerDelegate
{
func returnFromCamera(updatedRow: Int?)
}
class CameraMultiImageViewController: UIViewController, AVCaptureFileOutputRecordingDelegate, MKMapViewDelegate, AWSRequestDelegate
{
var cameraDelegate: CameraViewControllerDelegate?
// MARK: PROPERTIES
var loadingScreen: UIView!
var captureSession: AVCaptureSession!
var stillImageOutput: AVCaptureStillImageOutput?
var captureDeviceInput: AVCaptureDeviceInput!
var captureDevice: AVCaptureDevice!
var previewLayer: AVCaptureVideoPreviewLayer!
var imageRingView: UIView!
var actionButton: UIView!
var actionButtonLabel: UILabel!
var actionButtonTapView: UIView!
var loadingIndicator: UIActivityIndicatorView!
var switchCameraView: UIView!
var switchCameraLabel: UILabel!
var switchCameraTapView: UIView!
var exitCameraView: UIView!
var exitCameraImage: UIImageView!
var exitCameraTapView: UIView!
var mapViewSize: CGFloat = 100 //Constants.Dim.recordResponseEdgeSize
let imageRingDiameter: CGFloat = 300
var screenSize: CGRect!
var viewContainer: UIView!
var cameraView: UIView!
var mapViewContainer: UIView!
var mapView: MKMapView!
// var mapViewTapView1: UIView!
// var mapViewTapView2: UIView!
// var mapViewTapView3: UIView!
// The Google Maps Coordinate Object for the current center of the map and the default Camera
var mapCenter: CLLocationCoordinate2D!
var defaultCamera: GMSCameraPosition!
// Type of recording
var forSpot: Bool = false
var forRepair: Bool = false
var repairRow: Int?
// Item data
var spot: Spot?
var repair: Repair?
var previewViewArray = [UIView]()
var selectedIDs = [String]()
var useBackCamera = true
// MARK: INITIALIZING
// Do any additional setup after loading the view.
override func viewDidLoad()
{
super.viewDidLoad()
UIApplication.shared.isIdleTimerDisabled = true
UIApplication.shared.isStatusBarHidden = true
if self.navigationController != nil
{
self.navigationController!.isNavigationBarHidden = true
}
// Calculate the screenSize
screenSize = UIScreen.main.bounds
print("CVC - SCREEN SIZE: \(screenSize)")
print("CVC - VIEW SIZE: \(self.view.frame)")
// Add the loading screen, leaving NO room for the status bar at the top
loadingScreen = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))
loadingScreen.backgroundColor = UIColor.darkGray.withAlphaComponent(1.0)
self.view.addSubview(loadingScreen)
previewLayer = AVCaptureVideoPreviewLayer(layer: self.view.layer)
viewContainer = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
viewContainer.backgroundColor = UIColor.black
viewContainer.clipsToBounds = false
self.view.addSubview(viewContainer)
// The cameraView should be square, but centered and filling the viewContainer, so offset the left side off the screen to compensate
let leftOffset = (screenSize.height - screenSize.width) / 4
cameraView = UIView(frame: CGRect(x: 0 - leftOffset, y: 0, width: screenSize.height, height: screenSize.height))
cameraView.backgroundColor = UIColor.black
cameraView.clipsToBounds = false
viewContainer.addSubview(cameraView)
print("CAMERA VIEW FRAME: \(cameraView.frame)")
mapViewContainer = UIView(frame: CGRect(x: (viewContainer.frame.width / 2) - (mapViewSize / 2), y: viewContainer.frame.height - 5 - mapViewSize, width: mapViewSize, height: mapViewSize))
mapViewContainer.backgroundColor = UIColor.clear
mapViewContainer.layer.cornerRadius = mapViewSize / 2
mapViewContainer.clipsToBounds = true
viewContainer.addSubview(mapViewContainer)
let initialLocation = CLLocation(latitude: Constants.Settings.mapViewDefaultLat, longitude: Constants.Settings.mapViewDefaultLong)
let regionRadius: CLLocationDistance = 1000
let coordinateRegion = MKCoordinateRegionMakeWithDistance(initialLocation.coordinate, regionRadius * 2.0, regionRadius * 2.0)
mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: mapViewSize, height: mapViewSize))
mapView.delegate = self
mapView.showsUserLocation = true
mapView.showsCompass = false
mapView.showsScale = false
mapView.showsTraffic = false
mapView.showsPointsOfInterest = false
mapView.isUserInteractionEnabled = false
mapViewContainer.addSubview(mapView)
print("CVC - MV SET 1: TRACKING MODE: \(mapView.userTrackingMode.rawValue)")
mapView.setRegion(coordinateRegion, animated: true)
mapView.userTrackingMode = MKUserTrackingMode.followWithHeading
print("CVC - MV SET 2: TRACKING MODE: \(mapView.userTrackingMode.rawValue)")
for subview in mapView.subviews
{
print("CVC - MAP SUBVIEW: \(subview.description)")
}
// Add the Text Button and overlaid Tap View for more tap coverage
let actionButtonSize: CGFloat = 40
actionButton = UIView(frame: CGRect(x: (viewContainer.frame.width / 2) - (actionButtonSize / 2), y: (viewContainer.frame.height / 2) - (actionButtonSize / 2), width: actionButtonSize, height: actionButtonSize))
actionButton.layer.cornerRadius = 20
actionButton.backgroundColor = UIColor.white.withAlphaComponent(0.3)
actionButton.isHidden = true
viewContainer.addSubview(actionButton)
actionButtonLabel = UILabel(frame: CGRect(x: 5, y: 5, width: 30, height: 30))
actionButtonLabel.backgroundColor = UIColor.clear
actionButtonLabel.text = "\u{2713}" //"\u{1F5D1}"
actionButtonLabel.textAlignment = .center
actionButtonLabel.font = UIFont(name: "HelveticaNeue-UltraLight", size: 18)
actionButton.addSubview(actionButtonLabel)
actionButtonTapView = UIView(frame: CGRect(x: (viewContainer.frame.width / 2) - ((actionButtonSize + 20) / 2), y: (viewContainer.frame.height / 2) - ((actionButtonSize + 20) / 2), width: actionButtonSize + 20, height: actionButtonSize + 20))
actionButtonTapView.layer.cornerRadius = (actionButtonSize + 20) / 2
actionButtonTapView.backgroundColor = UIColor.clear
viewContainer.addSubview(actionButtonTapView)
loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: actionButton.frame.width, height: actionButton.frame.height))
loadingIndicator.color = Constants.Colors.colorTextLight
actionButton.addSubview(loadingIndicator)
// Add the Switch Camera Button and overlaid Tap View for more tap coverage
switchCameraView = UIView(frame: CGRect(x: viewContainer.frame.width - 60, y: viewContainer.frame.height - 60, width: 40, height: 40))
switchCameraView.layer.cornerRadius = 20
switchCameraView.backgroundColor = UIColor.white.withAlphaComponent(0.3)
// viewContainer.addSubview(switchCameraView)
switchCameraLabel = UILabel(frame: CGRect(x: 5, y: 5, width: 30, height: 30))
switchCameraLabel.backgroundColor = UIColor.clear
switchCameraLabel.text = "\u{21ba}"
switchCameraLabel.textAlignment = .center
switchCameraLabel.font = UIFont(name: "HelveticaNeue-UltraLight", size: 18)
switchCameraView.addSubview(switchCameraLabel)
switchCameraTapView = UIView(frame: CGRect(x: viewContainer.frame.width - 70, y: viewContainer.frame.height - 70, width: 60, height: 60))
switchCameraTapView.layer.cornerRadius = 30
switchCameraTapView.backgroundColor = UIColor.clear
// viewContainer.addSubview(switchCameraTapView)
// Add the Exit Camera Button and overlaid Tap View for more tap coverage
exitCameraView = UIView(frame: CGRect(x: 20, y: viewContainer.frame.height - 60, width: 40, height: 40))
exitCameraView.layer.cornerRadius = 20
exitCameraView.backgroundColor = UIColor.white.withAlphaComponent(0.3)
viewContainer.addSubview(exitCameraView)
// exitCameraLabel = UILabel(frame: CGRect(x: 5, y: 5, width: 30, height: 30))
// exitCameraLabel.backgroundColor = UIColor.clear
// exitCameraLabel.text = "\u{274c}"
// exitCameraLabel.textAlignment = .center
// exitCameraLabel.textColor = Constants.Colors.colorTextLight
// exitCameraLabel.font = UIFont(name: "HelveticaNeue-UltraLight", size: 18)
// exitCameraView.addSubview(exitCameraLabel)
exitCameraImage = UIImageView(frame: CGRect(x: 5, y: 5, width: 30, height: 30))
exitCameraImage.contentMode = UIViewContentMode.scaleAspectFit
exitCameraImage.clipsToBounds = true
exitCameraImage.image = UIImage(named: Constants.Strings.iconCloseOrange)
exitCameraView.addSubview(exitCameraImage)
exitCameraTapView = UIView(frame: CGRect(x: 10, y: viewContainer.frame.height - 70, width: 60, height: 60))
exitCameraTapView.layer.cornerRadius = 30
exitCameraTapView.backgroundColor = UIColor.clear
viewContainer.addSubview(exitCameraTapView)
// Add the overall circle for the ring view
// print("CVC - VC FRAME WIDTH: \(viewContainer.frame.width)")
// print("CVC - VC FRAME HEIGHT: \(viewContainer.frame.height)")
imageRingView = UIView(frame: CGRect(x: (viewContainer.frame.width / 2) - (imageRingDiameter / 2), y: (viewContainer.frame.height / 2) - (imageRingDiameter / 2), width: imageRingDiameter, height: imageRingDiameter))
imageRingView.layer.cornerRadius = imageRingDiameter / 2
imageRingView.backgroundColor = UIColor.white.withAlphaComponent(0.3)
imageRingView.isHidden = true
viewContainer.addSubview(imageRingView)
// Add the path and mask to only show the outer ring
let path = CGMutablePath()
path.addArc(center: CGPoint(x: imageRingDiameter / 2, y: imageRingDiameter / 2), radius: (imageRingDiameter / 2) - Constants.Dim.cameraViewImageCellSize, startAngle: 0.0, endAngle: 2 * 3.14, clockwise: false)
path.addRect(CGRect(x: 0, y: 0, width: imageRingDiameter, height: imageRingDiameter))
let maskLayer = CAShapeLayer()
maskLayer.path = path
maskLayer.fillRule = kCAFillRuleEvenOdd
imageRingView.layer.mask = maskLayer
imageRingView.clipsToBounds = true
adjustMapAttributionLabel()
// print("CAMERA VIEW: HIDE LOADING SCREEN")
self.view.sendSubview(toBack: self.loadingScreen)
// clearTmpDirectory()
// Request a random id -- NOT FOR REPAIRS - use the currently existing RepairID
if forSpot
{
AWSPrepRequest(requestToCall: AWSCreateRandomID(randomIdType: Constants.randomIdType.random_spot_id), delegate: self as AWSRequestDelegate).prepRequest()
}
refreshImageRing()
}
// Perform setup before the view loads
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(true)
// prepareSessionUseBackCamera(useBackCamera: true)
}
// These will occur after viewDidLoad
override func viewDidAppear(_ animated: Bool)
{
adjustMapAttributionLabel()
if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == AVAuthorizationStatus.authorized
{
print("CVC - CAMERA ALREADY AUTHORIZED")
self.prepareSessionUseBackCamera(useBackCamera: true)
}
else
{
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in
if granted == true
{
print("CVC - CAMERA NOW AUTHORIZED")
self.prepareSessionUseBackCamera(useBackCamera: true)
}
else
{
print("CVC - CAMERA NOT PERMISSIONED")
// Show the popup message instructing the user to change the phone camera settings for the app
let alertController = UIAlertController(title: "Camera Not Authorized", message: "Harveytown does not have permission to use your camera. Please go to your phone settings to allow access.", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default)
{ (result : UIAlertAction) -> Void in
print("CVC - POPUP CLOSE")
self.popViewController()
}
alertController.addAction(okAction)
alertController.show()
}
})
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func adjustMapAttributionLabel()
{
let attributionLabel: UIView = mapView.subviews[1]
let labelWidth = attributionLabel.frame.width
attributionLabel.frame = CGRect(x: (mapViewContainer.frame.width / 2) - (labelWidth / 2), y: attributionLabel.frame.minY, width: labelWidth, height: attributionLabel.frame.height)
}
// MARK: GESTURE METHODS
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
if let touch = touches.first
{
// Find which image the tap was inside
var objectSelectedIndicator: Bool = false
for (ivIndex, imageView) in previewViewArray.enumerated()
{
if imageView.frame.contains(touch.location(in: imageRingView))
{
// print("CVC - IMAGEVIEW: \(imageView) CONTAINS SELECTION")
objectSelectedIndicator = true
// Check whether the image has already been selected
var alreadySelected = false
for (index, _) in selectedIDs.enumerated()
{
if index == ivIndex
{
// print("CVC - IMAGEVIEW CHECK 1")
alreadySelected = true
// The image was selected for a second time, so de-select the image
selectedIDs.remove(at: index)
}
}
// print("CVC - IMAGEVIEW CHECK 2")
if !alreadySelected
{
if forSpot
{
if let spot = spot
{
selectedIDs.append(spot.spotContent[ivIndex].contentID)
}
}
else if forRepair
{
if let repair = repair
{
selectedIDs.append(repair.repairImages[ivIndex].imageID)
}
}
}
// print("CVC - imageSelected COUNT 1: \(selectedIDs.count)")
}
}
// If at least one image has been selected, show the delete icon
if selectedIDs.count > 0
{
// An image was selected, so change the action button to the delete button
actionButtonLabel.text = "\u{1F5D1}"
}
else
{
// No images are selected, so change the action button to the upload button
actionButtonLabel.text = "\u{2713}"
}
// print("CVC - SWITCH BUTTON TAP: \(switchCameraTapView.frame.contains(touch.location(in: viewContainer)))")
// print("CVC - SWITCH BUTTON TAP LOCATION: \(touch.location(in: viewContainer))")
// print("CVC - SWITCH BUTTON FRAME: \(switchCameraTapView.frame)")
// if mapViewTapView1.frame.contains(touch.location(in: mapViewContainer)) || mapViewTapView2.frame.contains(touch.location(in: mapViewContainer)) || mapViewTapView3.frame.contains(touch.location(in: mapViewContainer))
// {
// print("CVC - TOUCHED MAP")
// mapTap()
// }
if mapViewContainer.frame.contains(touch.location(in: viewContainer))
{
// print("CVC - TOUCHED MAP")
// Ensure that the user's current location is accessible - if not, don't take a picture
if mapView.userLocation.coordinate.latitude != 0.0 || mapView.userLocation.coordinate.longitude != 0.0
{
mapViewContainer.backgroundColor = Constants.Colors.recordButtonColorRecord
captureImage()
}
else
{
// Inform the user that their location has not been acquired
let alert = UtilityFunctions().createAlertOkView("Unknown Location", message: "I'm sorry, your location cannot be determined. Please wait until the map shows your current location.")
alert.show()
}
}
else if exitCameraTapView.frame.contains(touch.location(in: viewContainer))
{
// print("TOUCHED EXIT CAMERA BUTTON")
exitCamera()
}
else if switchCameraTapView.frame.contains(touch.location(in: viewContainer))
{
// print("TOUCHED SWITCH CAMERA BUTTON")
// switchCamera()
}
else if actionButtonTapView.frame.contains(touch.location(in: viewContainer))
{
// print("TOUCHED ACTION BUTTON")
// If images are selected, the delete button is showing, so delete the selected images
// Otherwise upload the images
if selectedIDs.count > 0
{
deleteImages()
}
else
{
if forSpot
{
if let spot = spot
{
// Upload the images
for (index, content) in spot.spotContent.enumerated()
{
if let image = content.image
{
let imagePath: String = NSTemporaryDirectory().stringByAppendingPathComponent(path: content.contentID! + ".jpg")
let imageURL = URL(fileURLWithPath: imagePath)
// Write the image to the file
if let imageData = UIImageJPEGRepresentation(image, 0.6)
{
try? imageData.write(to: imageURL)
AWSPrepRequest(requestToCall: AWSUploadMediaToBucket(bucket: Constants.Strings.S3BucketMedia, uploadKey: "\(content.contentID!).jpg", mediaURL: imageURL, imageIndex: index), delegate: self as AWSRequestDelegate).prepRequest()
// Start the activity indicator and hide the send image
self.actionButtonLabel.removeFromSuperview()
self.loadingIndicator.startAnimating()
}
}
}
}
}
else if forRepair
{
if let repair = repair
{
// Upload the images
for (index, rImage) in repair.repairImages.enumerated()
{
if let image = rImage.image
{
let imagePath: String = NSTemporaryDirectory().stringByAppendingPathComponent(path: rImage.imageID! + ".jpg")
let imageURL = URL(fileURLWithPath: imagePath)
// Write the image to the file
if let imageData = UIImageJPEGRepresentation(image, 0.6)
{
try? imageData.write(to: imageURL)
AWSPrepRequest(requestToCall: AWSUploadMediaToBucket(bucket: Constants.Strings.S3BucketMedia, uploadKey: "\(rImage.imageID!).jpg", mediaURL: imageURL, imageIndex: index), delegate: self as AWSRequestDelegate).prepRequest()
// Start the activity indicator and hide the send image
self.actionButtonLabel.removeFromSuperview()
self.loadingIndicator.startAnimating()
}
}
}
}
}
}
}
// else if cameraView.frame.contains(touch.location(in: viewContainer)) && !contentSelectedIndicator
// {
// print("TOUCHED CAMERA")
// captureImage()
// }
else if objectSelectedIndicator
{
// An image was selected, so highlight the image
self.refreshImageRing()
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
if let touch = touches.first
{
// if mapViewTapView1.frame.contains(touch.location(in: mapViewContainer)) || mapViewTapView2.frame.contains(touch.location(in: mapViewContainer)) || mapViewTapView3.frame.contains(touch.location(in: mapViewContainer))
// {
// print("MAP TOUCH ENDED")
// }
if mapViewContainer.frame.contains(touch.location(in: viewContainer))
{
// print("MAP TOUCH ENDED")
mapViewContainer.backgroundColor = UIColor.clear
}
else if switchCameraTapView.frame.contains(touch.location(in: viewContainer))
{
// print("SWITCH CAMERA BUTTON TOUCH ENDED")
}
else if actionButtonTapView.frame.contains(touch.location(in: viewContainer))
{
// print("ACTION BUTTON TOUCH ENDED")
}
// else if cameraView.frame.contains(touch.location(in: viewContainer))
// {
// print("CAMERA TOUCH ENDED")
// }
}
}
// MARK: MKMAPVIEW DELEGATE METHODS
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation)
{
// print("CVC - MV UPDATE 1: TRACKING MODE: \(mapView.userTrackingMode.rawValue)")
// print("CVC - MV UPDATE: HEADING: \(userLocation.heading)")
}
// MARK: CUSTOM FUNCTIONS
// Dismiss the latest View Controller presented from this VC
// This version is used when the top VC is popped from a Nav Bar button
func popViewController(_ sender: UIBarButtonItem)
{
popVC()
}
func popViewController()
{
popVC()
}
func popVC()
{
if let viewControllers = self.navigationController?.viewControllers
{
for controller in viewControllers
{
if controller is CameraMultiImageViewController
{
self.navigationController!.popViewController(animated: true)
UIApplication.shared.isIdleTimerDisabled = false
UIApplication.shared.isStatusBarHidden = false
if self.navigationController != nil
{
self.navigationController!.isNavigationBarHidden = false
}
}
}
}
// self.navigationController!.popViewController(animated: true)
}
// Populate the Image Ring
func refreshImageRing()
{
// Clear the imageRing and the imageViewArray
imageRingView.subviews.forEach({ $0.removeFromSuperview() })
previewViewArray = [UIView]()
if forSpot
{
if let spot = spot
{
if spot.spotContent.count > 0
{
imageRingView.isHidden = false
actionButton.isHidden = false
let cellSize: CGFloat = Constants.Dim.cameraViewImageCellSize
let imageSize: CGFloat = Constants.Dim.cameraViewImageSize
let imageCellGap: CGFloat = (cellSize - imageSize) / 2
// Add the imageviews to the ring view
for (index, content) in spot.spotContent.enumerated()
{
let imageViewBase: CGPoint = basepointForCircleOfCircles(index, mainCircleRadius: imageRingDiameter / 2, radius: cellSize / 2, distance: (imageRingDiameter / 2) - (cellSize / 2)) // - (imageCellGap / 2))
let cellContainer = UIView(frame: CGRect(x: imageViewBase.x, y: imageViewBase.y, width: cellSize, height: cellSize))
cellContainer.layer.cornerRadius = cellSize / 2
cellContainer.clipsToBounds = true
let imageContainer = UIView(frame: CGRect(x: imageCellGap, y: imageCellGap, width: imageSize, height: imageSize))
imageContainer.layer.cornerRadius = imageSize / 2
imageContainer.clipsToBounds = true
imageContainer.backgroundColor = UIColor.white
cellContainer.addSubview(imageContainer)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: imageSize, height: imageSize))
imageView.image = content.image
imageContainer.addSubview(imageView)
imageRingView.addSubview(cellContainer)
previewViewArray.append(cellContainer)
// If the index is stored in the imageSelect array, it has been selected, so highlight the image
for imageID in selectedIDs
{
if imageID == content.contentID
{
cellContainer.backgroundColor = UIColor.red.withAlphaComponent(0.3)
}
}
}
}
else
{
imageRingView.isHidden = true
actionButton.isHidden = true
}
}
}
else if forRepair
{
if let repair = repair
{
if repair.repairImages.count > 0
{
imageRingView.isHidden = false
actionButton.isHidden = false
let cellSize: CGFloat = Constants.Dim.cameraViewImageCellSize
let imageSize: CGFloat = Constants.Dim.cameraViewImageSize
let imageCellGap: CGFloat = (cellSize - imageSize) / 2
// Add the imageviews to the ring view
for (index, rImage) in repair.repairImages.enumerated()
{
let imageViewBase: CGPoint = basepointForCircleOfCircles(index, mainCircleRadius: imageRingDiameter / 2, radius: cellSize / 2, distance: (imageRingDiameter / 2) - (cellSize / 2)) // - (imageCellGap / 2))
let cellContainer = UIView(frame: CGRect(x: imageViewBase.x, y: imageViewBase.y, width: cellSize, height: cellSize))
cellContainer.layer.cornerRadius = cellSize / 2
cellContainer.clipsToBounds = true
let imageContainer = UIView(frame: CGRect(x: imageCellGap, y: imageCellGap, width: imageSize, height: imageSize))
imageContainer.layer.cornerRadius = imageSize / 2
imageContainer.clipsToBounds = true
imageContainer.backgroundColor = UIColor.white
cellContainer.addSubview(imageContainer)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: imageSize, height: imageSize))
imageView.image = rImage.image
imageContainer.addSubview(imageView)
imageRingView.addSubview(cellContainer)
previewViewArray.append(cellContainer)
// If the index is stored in the imageSelect array, it has been selected, so highlight the image
for imageID in selectedIDs
{
if imageID == rImage.imageID
{
cellContainer.backgroundColor = UIColor.red.withAlphaComponent(0.3)
}
}
}
}
else
{
imageRingView.isHidden = true
actionButton.isHidden = true
}
}
}
}
// Called when the map is tapped
func mapTap()
{
// print("CVC - VIEW MAP VC")
// // Create a back button and title for the Nav Bar
// let backButtonItem = UIBarButtonItem(title: "\u{2190}",
// style: UIBarButtonItemStyle.plain,
// target: self,
// action: #selector(CameraMultiImageViewController.popViewController(_:)))
// backButtonItem.tintColor = Constants.Colors.colorTextNavBar
// let ncTitle = UIView(frame: CGRect(x: screenSize.width / 2 - 50, y: 10, width: 100, height: 40))
// let ncTitleText = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
// ncTitleText.text = "Caption"
// ncTitleText.font = UIFont(name: Constants.Strings.fontAlt, size: 14)
// ncTitleText.textColor = Constants.Colors.colorTextNavBar
// ncTitleText.textAlignment = .center
// ncTitle.addSubview(ncTitleText)
// Instantiate the TextViewController and pass the Images to the VC
let mapVC = MapViewController()
// // Assign the created Nav Bar settings to the Tab Bar Controller
// mapVC.navigationItem.setLeftBarButton(backButtonItem, animated: true)
// mapVC.navigationItem.titleView = ncTitle
self.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal
self.present(mapVC, animated: true, completion: nil)
// if let navController = self.navigationController
// {
// navController.pushViewController(mapVC, animated: true)
// }
// // Save an action in Core Data
// CoreDataFunctions().logUserflowSave(viewController: NSStringFromClass(type(of: self)), action: #function.description)
}
// func triggerCloseCameraView()
// {
// print("TRIGGER CLOSE -> BACK TO VIEW CONTROLLER")
// self.presentingViewController!.dismiss(animated: true, completion:
// {
// print("PARENT VC: \(String(describing: self.cameraDelegate))")
// if let parentVC = self.cameraDelegate
// {
// print("TRY TO CVC HIDE LOADING SCREEN")
// parentVC.triggerLoadingScreenOn(screenOn: false)
// }
// })
// }
// Called when the action button is pressed with images selected. Deletes the selected images from the image array
func deleteImages()
{
// Sort the array and then reverse the order so that the latest indexes are removed first
selectedIDs.sort()
selectedIDs.reverse()
for imageID in selectedIDs
{
if forSpot
{
if let spot = spot
{
for (index, content) in spot.spotContent.enumerated()
{
if content.contentID == imageID
{
spot.spotContent.remove(at: index)
}
}
}
}
else if forRepair
{
if let repair = repair
{
for (index, rImage) in repair.repairImages.enumerated()
{
if rImage.imageID == imageID
{
repair.repairImages.remove(at: index)
}
}
}
}
}
if forSpot
{
if let spot = spot
{
// Now run through the images and rename them based on order
for (index, content) in spot.spotContent.enumerated()
{
content.contentID = spot.spotID + "-" + String(index + 1)
}
// Reset the imageSelected array, hide the delete button, and refresh the collection view
selectedIDs = [String]()
actionButtonLabel.text = "\u{2713}"
if spot.spotContent.count == 0
{
actionButton.isHidden = true
}
refreshImageRing()
}
}
else if forRepair
{
if let repair = repair
{
// Now run through the images and rename them based on order
for (index, rImage) in repair.repairImages.enumerated()
{
rImage.imageID = repair.repairID + "-" + String(index + 1)
}
// Reset the imageSelected array, hide the delete button, and refresh the collection view
selectedIDs = [String]()
actionButtonLabel.text = "\u{2713}"
if repair.repairImages.count == 0
{
actionButton.isHidden = true
}
refreshImageRing()
}
}
}
// MARK: CAMERA FUNCTIONS
func prepareSessionUseBackCamera(useBackCamera: Bool)
{
// print("IN PREPARE SESSION")
self.useBackCamera = useBackCamera
if let devices = AVCaptureDevice.devices()
{
for device in devices
{
if ((device as AnyObject).hasMediaType(AVMediaTypeVideo))
{
if (useBackCamera && (device as AnyObject).position == AVCaptureDevicePosition.back)
{
captureDevice = device as? AVCaptureDevice
beginSession()
}
else if (!useBackCamera && (device as AnyObject).position == AVCaptureDevicePosition.front)
{
captureDevice = device as? AVCaptureDevice
beginSession()
}
}
}
}
}
func beginSession()
{
if captureDevice != nil
{
captureSession = AVCaptureSession()
captureSession.sessionPreset = AVCaptureSessionPresetHigh
if let currentInputs = captureSession.inputs
{
for inputIndex in currentInputs
{
captureSession.removeInput(inputIndex as! AVCaptureInput)
}
}
let err : NSError? = nil
do
{
captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(captureDeviceInput)
}
catch _
{
print("CMIVC - error: \(String(describing: err?.localizedDescription))")
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill // CHANGE THIS
self.cameraView.layer.addSublayer(previewLayer)
previewLayer?.frame = self.cameraView.layer.frame
// print("CAMERA VIEW LAYER FRAME: \(self.cameraView.layer.frame)")
// print("PREVIEW LAYER FRAME: \(String(describing: previewLayer?.frame))")
stillImageOutput = AVCaptureStillImageOutput()
captureSession.addOutput(stillImageOutput)
if let orientationInt = AVCaptureVideoOrientation(rawValue: UIDevice.current.orientation.rawValue)
{
// print("ASSIGNING ORIENTATION 1: \(UIDevice.current.orientation.hashValue)")
if stillImageOutput != nil
{
stillImageOutput!.connection(withMediaType: AVMediaTypeVideo).videoOrientation = orientationInt
}
}
captureSession.startRunning()
}
}
func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!)
{
print("CMIVC - Capture Delegate: Did START Recording to Output File")
}
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!)
{
print("CMIVC - Capture Delegate: Did FINISH Recording to Output File")
}
func switchCamera()
{
if self.useBackCamera
{
self.useBackCamera = false
}
else
{
self.useBackCamera = true
}
if let devices = AVCaptureDevice.devices()
{
for device in devices
{
if ((device as AnyObject).hasMediaType(AVMediaTypeVideo))
{
if let currentInputs = captureSession.inputs
{
for inputIndex in currentInputs
{
captureSession.removeInput(inputIndex as! AVCaptureInput)
}
}
if (self.useBackCamera && (device as AnyObject).position == AVCaptureDevicePosition.back)
{
do
{
captureDevice = device as? AVCaptureDevice
captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(captureDeviceInput)
captureSession.removeOutput(stillImageOutput)
stillImageOutput = AVCaptureStillImageOutput()
captureSession.addOutput(stillImageOutput)
break
}
catch _
{
print("error")
}
}
else if (!self.useBackCamera && (device as AnyObject).position == AVCaptureDevicePosition.front)
{
do
{
captureDevice = device as? AVCaptureDevice
captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(captureDeviceInput)
captureSession.removeOutput(stillImageOutput)
stillImageOutput = AVCaptureStillImageOutput()
captureSession.addOutput(stillImageOutput)
break
}
catch _
{
print("error")
}
}
}
}
}
}
func exitCamera()
{
popViewController()
}
// MARK: NAVIGATION & CUSTOM FUNCTIONS
func captureImage()
{
print("IN CAPTURE IMAGE")
if let videoConnection = stillImageOutput!.connection(withMediaType: AVMediaTypeVideo)
{
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler:
{ (sampleBuffer, error) -> Void in
// Process the image data (sampleBuffer) here to get an image file we can put in our captureImageView
if sampleBuffer != nil
{
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
if let dataProvider = CGDataProvider(data: imageData! as CFData)
{
// UIImage orientation assumes a landscape (left) orientation
// We must correct this difference and set the image to default to portrait
// Device orientation 1 : Portrait (Set as default)
let deviceOrientationValue = UIDevice.current.orientation.rawValue
var imageOrientationValue = 3
// Device orientation 2 : Portrait Upside Down
if deviceOrientationValue == 2
{
imageOrientationValue = 2
}
// Device orientation 3 : Landscape Left
else if deviceOrientationValue == 3
{
imageOrientationValue = 0
}
// Device orientation 4 : Landscape Right
else if deviceOrientationValue == 4
{
imageOrientationValue = 1
}
print("CVC - DEVICE ORIENTATION (FOR IMAGE): \(UIDevice.current.orientation.rawValue)")
// Resize the image into a square
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
let rawImage = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)
let sizedImage = rawImage.cropToBounds(rawImage.size.width, height: rawImage.size.width)
print("CVC - OLD IMAGE ORIENTATION: \(rawImage.imageOrientation.rawValue)")
if let cgImage = sizedImage.cgImage
{
let imageRaw = UIImage(cgImage: cgImage, scale: 1.0, orientation: UIImageOrientation(rawValue: imageOrientationValue)!)
print("CVC - OLD IMAGE ORIENTATION: \(imageRaw.imageOrientation.hashValue)")
// Remove the orientation of the image
let image = imageRaw.imageByNormalizingOrientation()
print("CVC - NEW IMAGE ORIENTATION: \(image.imageOrientation.hashValue)")
if self.forSpot
{
if let spot = self.spot
{
// Check how many images have already been added
let imageCount = spot.spotContent.count
if imageCount < 12
{
// Create the Spot Content
let contentID = spot.spotID + "-" + String(imageCount + 1)
let userCoords = self.mapView.userLocation.coordinate
let spotContent = SpotContent(contentID: contentID, spotID: spot.spotID, datetime: Date(timeIntervalSinceNow: 0), type: Constants.ContentType.image, lat: userCoords.latitude, lng: userCoords.longitude)
spotContent.image = image
spot.spotContent.append(spotContent)
// Update the spot location and datetime
self.spot!.datetime = Date(timeIntervalSinceNow: 0)
self.spot!.lat = userCoords.latitude
self.spot!.lng = userCoords.longitude
self.refreshImageRing()
}
}
}
else if self.forRepair
{
if let repair = self.repair
{
// Check how many images have already been added
let imageCount = repair.repairImages.count
if imageCount < 12
{
// Create the RepairImage Object
let imageID = repair.repairID + "-" + String(imageCount + 1)
let repairImage = RepairImage(imageID: imageID, repairID: repair.repairID, datetime: Date(timeIntervalSinceNow: 0))
repairImage.image = image
repair.repairImages.append(repairImage)
// Update the repair location and datetime
self.repair!.datetime = Date(timeIntervalSinceNow: 0)
self.refreshImageRing()
}
}
}
}
}
}
})
}
}
// Correct Video Orientation Issues
func orientationFromTransform(transform: CGAffineTransform) -> (orientation: UIImageOrientation, isPortrait: Bool)
{
var assetOrientation = UIImageOrientation.up
var isPortrait = false
// print("CHECK A: \(transform.a)")
// print("CHECK B: \(transform.b)")
// print("CHECK C: \(transform.c)")
// print("CHECK D: \(transform.d)")
if transform.a == 0 && transform.b == 1.0 && transform.c == -1.0 && transform.d == 0
{
assetOrientation = .right
isPortrait = true
}
else if transform.a == 0 && transform.b == -1.0 && transform.c == 1.0 && transform.d == 0
{
assetOrientation = .left
isPortrait = true
}
else if transform.a == 1.0 && transform.b == 0 && transform.c == 0 && transform.d == 1.0
{
assetOrientation = .up
}
else if transform.a == -1.0 && transform.b == 0 && transform.c == 0 && transform.d == -1.0
{
assetOrientation = .down
}
// print("assetOrientation: \(assetOrientation.hashValue)")
return (assetOrientation, isPortrait)
}
func clearTmpDirectory()
{
do
{
let tmpDirectory = try FileManager.default.contentsOfDirectory(atPath: NSTemporaryDirectory())
try tmpDirectory.forEach
{ file in
let path = String.init(format: "%@%@", NSTemporaryDirectory(), file)
try FileManager.default.removeItem(atPath: path)
}
}
catch
{
print(error)
}
}
// The equation to find the top-left edge of a circle in the circle of circles
func basepointForCircleOfCircles(_ circle: Int, mainCircleRadius: CGFloat, radius: CGFloat, distance: CGFloat) -> CGPoint
{
let numberOfCirclesInCircle: Int = 12
let angle: CGFloat = (2.0 * CGFloat(circle) * CGFloat.pi) / CGFloat(numberOfCirclesInCircle)
let radian90: CGFloat = CGFloat(90) * (CGFloat.pi / CGFloat(180))
let radian45: CGFloat = CGFloat(45) * (CGFloat.pi / CGFloat(180))
let circleH: CGFloat = radius / cos(radian45)
// print("CVC - RADIAN90: \(radian90), CIRCLE HYPOTENUSE: \(circleH)")
let adjustRadian: CGFloat = atan((circleH / 2) / mainCircleRadius) * 2
// print("CVC - RADIAN45: \(radian45), ADJUST RADIAN: \(adjustRadian)")
let x = round(mainCircleRadius + distance * cos(angle - radian90 - adjustRadian) - radius)
let y = round(mainCircleRadius + distance * sin(angle - radian90 - adjustRadian) - radius)
// print("CVC - CIRCLE BASEPOINT FOR CIRCLE: \(circle): \(x), \(y), angle: \(angle), radius: \(radius), distance: \(distance)")
return CGPoint(x: x, y: y)
}
// MARK: AWS DELEGATE METHODS
func showLoginScreen()
{
print("CVC - SHOW LOGIN SCREEN")
// Load the LoginVC
let loginVC = LoginViewController()
self.navigationController!.pushViewController(loginVC, animated: true)
}
func processAwsReturn(_ objectType: AWSRequestObject, success: Bool)
{
// print("CVC - processAwsReturn:")
print(objectType)
print(success)
DispatchQueue.main.async(execute:
{
// Process the return data based on the method used
switch objectType
{
case let awsCreateRandomID as AWSCreateRandomID:
if success
{
if let randomID = awsCreateRandomID.randomID
{
if self.forSpot && awsCreateRandomID.randomIdType == Constants.randomIdType.random_spot_id
{
// Current user coords
let userCoords = self.mapView.userLocation.coordinate
// Create the Spot
self.spot = Spot(spotID: randomID, userID: Constants.Data.currentUser.userID, datetime: Date(timeIntervalSinceNow: 0), lat: userCoords.latitude, lng: userCoords.longitude)
}
}
}
else
{
// Show the error message
let alertController = UIAlertController(title: "Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
{ (result : UIAlertAction) -> Void in
print("OK")
self.popViewController()
}
alertController.addAction(okAction)
alertController.show()
// Stop the activity indicator and shoow the send image
self.loadingIndicator.stopAnimating()
self.actionButton.addSubview(self.actionButtonLabel)
}
case let awsUploadMediaToBucket as AWSUploadMediaToBucket:
if success
{
// print("CVC - AWSUploadMediaToBucket SUCCESS")
if awsUploadMediaToBucket.imageIndex == 0
{
// The first image was successfully uploaded, so upload the data
// This ensures that entities don't exist without some media
if self.forSpot
{
AWSPrepRequest(requestToCall: AWSSpotPut(spot: self.spot), delegate: self as AWSRequestDelegate).prepRequest()
}
else if self.forRepair
{
let repairPut = AWSRepairPut(repair: self.repair, newImages: true)
AWSPrepRequest(requestToCall: repairPut, delegate: self as AWSRequestDelegate).prepRequest()
}
}
}
else
{
// Show the error message
let alert = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.")
alert.show()
// Stop the activity indicator and shoow the send image
self.loadingIndicator.stopAnimating()
self.actionButton.addSubview(self.actionButtonLabel)
}
case _ as AWSSpotPut:
if success
{
print("CVC - AWSSpotPut SUCCESS")
// Notify the parent view that the AWS Put completed
if let parentVC = self.cameraDelegate
{
parentVC.returnFromCamera(updatedRow: nil)
}
// Stop the activity indicator and shoow the send image
self.loadingIndicator.stopAnimating()
self.actionButton.addSubview(self.actionButtonLabel)
// Return to the parentVC
self.popViewController()
}
else
{
// Show the error message
let alert = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.")
alert.show()
// Stop the activity indicator and shoow the send image
self.loadingIndicator.stopAnimating()
self.actionButton.addSubview(self.actionButtonLabel)
}
case _ as AWSRepairPut:
if success
{
print("CVC - AWSRepairPut SUCCESS")
// Notify the parent view that the AWS Put completed
if let parentVC = self.cameraDelegate
{
parentVC.returnFromCamera(updatedRow: self.repairRow)
}
// Stop the activity indicator and shoow the send image
self.loadingIndicator.stopAnimating()
self.actionButton.addSubview(self.actionButtonLabel)
// Return to the parentVC
self.popViewController()
}
else
{
// Show the error message
let alert = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.")
alert.show()
// Stop the activity indicator and shoow the send image
self.loadingIndicator.stopAnimating()
self.actionButton.addSubview(self.actionButtonLabel)
}
default:
print("CVC-DEFAULT: THERE WAS AN ISSUE WITH THE DATA RETURNED FROM AWS")
// Show the error message
let alertController = UIAlertController(title: "Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
{ (result : UIAlertAction) -> Void in
print("OK")
self.popViewController()
}
alertController.addAction(okAction)
alertController.show()
}
})
}
}
|
//
// tcClase1.swift
// Swift II
//
// Created by Daniel Fuentes on 6/4/15.
// Copyright (c) 2015 Daniel Fuentes. All rights reserved.
//
import Cocoa
class tcClase1: NSObject {
}
|
//
// PostListCell.swift
// reddit
//
// Created by Juan Cruz Ghigliani on 07/12/2019.
// Copyright © 2019 Juan Cruz Ghigliani. All rights reserved.
//
import UIKit
class PostListCell: UITableViewCell {
@IBOutlet weak var userLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var numCommentLabel: UILabel!
@IBOutlet weak var thumbImage: UIImageView!
@IBOutlet weak var dismissButton: UIButton!
@IBOutlet weak var visitedLabel: UILabel!
@IBOutlet weak var titleAlignToSuperConstraint: NSLayoutConstraint!
var viewModel: PostListCellViewModel? {
didSet {
displayModelInfo()
}
}
override func prepareForReuse() {
thumbImage.image = nil
}
@IBAction func dismissPostTap() {
viewModel?.dismiss()
}
func displayModelInfo() {
guard let viewModel = self.viewModel else { return }
userLabel.text = viewModel.author
timeLabel.text = viewModel.created
titleLabel.text = viewModel.title
numCommentLabel.text = viewModel.numComments
visitedLabel.isHidden = viewModel.visited
if let thumbnailPath = viewModel.thumbnail,
let thumbnailUrl = URL(string: thumbnailPath) {
thumbImage.isHidden = false
thumbImage.load(url: thumbnailUrl)
titleAlignToSuperConstraint.priority = .defaultLow
} else {
thumbImage.isHidden = true
titleAlignToSuperConstraint.priority = .required
}
}
}
|
//
// FilterViewController.swift
// NewsApp
//
// Created by Maxim Yakhin on 12.12.2020.
// Copyright © 2020 Max Yakhin. All rights reserved.
//
import UIKit
class FilterViewController: UIViewController {
var sourceDelegate = SourceFilterDelegate()
var countryDelegate = CountryFilterDelegate()
var categoryDelegate = CategoryFilterDelegate()
@IBOutlet weak var sourcePickerView: UIPickerView!
@IBOutlet weak var countryPickerView: UIPickerView!
@IBOutlet weak var categoryPickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
sourcePickerView.delegate = sourceDelegate
sourcePickerView.dataSource = sourceDelegate
countryPickerView.delegate = countryDelegate
countryPickerView.dataSource = countryDelegate
categoryPickerView.delegate = categoryDelegate
categoryPickerView.dataSource = categoryDelegate
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ChecklistNavigation.swift
// Umbrella
//
// Created by Lucas Correa on 12/02/2019.
// Copyright © 2019 Security First. All rights reserved.
//
import Foundation
import UIKit
class ChecklistNavigation: DeepLinkNavigationProtocol {
//
// MARK: - Properties
//
// MARK: - Initializer
/// Init
init() {
}
//
// MARK: - Functions
/// Go to screen
func goToScreen() {
let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
if appDelegate.window?.rootViewController is UITabBarController {
let tabBarController = (appDelegate.window?.rootViewController as? UITabBarController)!
tabBarController.selectedIndex = 2
}
}
}
|
//
// ThirdViewController.swift
// i2020_03_14_Coordinator
//
// Created by Bradford, Phillip on 3/14/20.
// Copyright © 2020 Bradford, Phillip. All rights reserved.
//
import UIKit
class ThirdViewController: UIViewController, Storyboarded {
var coordinator: MainCoordinator?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
|
//
// AgentSuccessViewController.swift
// hecApp-iOS
//
// Created by Asianark on 16/3/2016.
// Copyright © 2016 Asianark. All rights reserved.
//
import UIKit
class AgentSuccessViewController: UIViewController {
@IBOutlet weak var btn: UIButton!
@IBOutlet weak var R0: UILabel!
@IBOutlet weak var R1L1: UILabel!
@IBOutlet weak var R1L2: UILabel!
@IBOutlet weak var R1L3: UILabel!
@IBOutlet weak var R2L1: UILabel!
@IBOutlet weak var R2L2: UILabel!
@IBOutlet weak var R2L3: UILabel!
@IBOutlet weak var viewBackground: UIView!
var value1 = "" // row 1 value
var value2 = "" // row 2 value
var tag = 0
var topBarView:NavigationTopBarView!
var titleView = UILabel()
var backButtonView:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationTopBarView()
}
func setupNavigationTopBarView() {
viewBackground.backgroundColor = UIColor.hecNaviBarGreenColor()
topBarView = NavigationTopBarView()
titleView.textColor = UIColor.whiteColor()
if tag == 1{
titleView.text = "添加会员成功"
R0.text = "恭喜您, 添加成功!"
R1L1.text = "会员名 : "
R1L2.text = value1
R2L1.text = "密码 : "
R2L2.text = value2
R2L2.textColor = UIColor.colorWithHexString("08A09D")
}
if tag == 2{
titleView.text = "转账成功"
R0.text = "恭喜您,转账成功!"
R1L1.text = "会员名 : "
R1L2.text = value1
R2L1.text = "转账金额 : "
R2L2.text = value2 + "元"
R2L2.textColor = UIColor.colorWithHexString("08A09D")
}
titleView.font = UIFont.boldSystemFontOfSize(18.0)
titleView.textAlignment = .Center
titleView.sizeToFit()
topBarView.naviItem.titleView = titleView
backButtonView = UIButton(frame: CGRectMake(0,0,44,44))
backButtonView.setImage(UIImage(named: "btn_back"), forState: .Normal)
let naviBackButton = UIBarButtonItem(customView: backButtonView)
let leftspacer = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
leftspacer.width = -20;
self.topBarView.naviItem.leftBarButtonItems = [leftspacer,naviBackButton]
self.topBarView.pushNavigationItem(topBarView.naviItem, animated: true)
let gestreRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.goBack))
backButtonView.addGestureRecognizer(gestreRecognizer)
backButtonView.userInteractionEnabled = true
self.view.addSubview(topBarView)
}
func goBack() {
let svc = AgentTransferViewController()
svc.isClickde = false
self.navigationController!.popViewControllerAnimated(true)
}
@IBAction func next(sender: AnyObject) {
let svc = AgentTransferViewController()
svc.isClickde = false
self.navigationController!.popViewControllerAnimated(true)
}
}
|
//
// EventsProvider.swift
// Brizeo
//
// Created by Mobile on 1/5/17.
// Copyright © 2017 Kogi Mobile. All rights reserved.
//
import Foundation
import Crashlytics
import SwiftyUserDefaults
import FBSDKShareKit
import Moya
import CoreLocation
import FormatterKit
extension DefaultsKeys {
static let lastEventsUpdate = DefaultsKey<Date?>("lastEventsUpdate")
}
class EventsProvider {
// MARK: - Types
typealias EventsCompletion = (Result<[Event]>) -> Void
static var isLoading = false
// MARK: - Class methods
class func updateUserEventsIfNeeds() {
guard UserProvider.shared.currentUser != nil else {
print("no current user")
return
}
guard UserProvider.isUserLoggedInFacebook() else {
print("current user is not logged in Facebook")
return
}
//TODO: check it
/*
// update each 24 hours
if Defaults[.lastEventsUpdate] != nil && Defaults[.lastEventsUpdate]!.isInSameDayOf(date: Date()) {
print("Don't need to update")
return
}*/
guard isLoading == false else {
print("We are already loading events now.")
return
}
newFetchUserEventsFromFacebook/*fetchUserEventsFromFacebook*/ { (result) in
switch(result) {
case .success(let events):
if events.count == 0 {
Defaults[.lastEventsUpdate] = Date()
return
}
APIService.performRequest(request: .saveEvents(events: events), completionHandler: { (result) in
switch result {
case .success(_):
print("Successfully saved events")
Defaults[.lastEventsUpdate] = Date()
break
case .failure(_):
break
}
})
break
case .failure(_):
break
default:
break
}
}
}
class func getEvents(contentType type: EventsContentType, sortingFlag: SortingFlag, location: CLLocationCoordinate2D, completion: @escaping EventsCompletion) {
if type == .all {
getAllEvents(sortingFlag: sortingFlag, location: location, completion: completion)
} else {
getMatchedEvents(sortingFlag: sortingFlag, location: location, completion: completion)
}
}
class func getAllEvents(sortingFlag: SortingFlag, location: CLLocationCoordinate2D, completion: @escaping EventsCompletion) {
APIService.performRequest(request: .getEvents(sortFlag: sortingFlag.APIPresentation, longitude: location.longitude, latitude: location.latitude)) { (result) in
switch result {
case .success(let response):
guard response.statusCode == 200 else {
completion(.failure(APIError(code: response.statusCode, message: nil)))
return
}
do {
let events = try response.mapArray(Event.self)
completion(.success(events))
}
catch (let error) {
completion(.failure(APIError(error: error)))
}
break
case .failure(let error):
completion(.failure(APIError(error: error)))
break
}
}
}
class func getMatchedEvents(sortingFlag: SortingFlag, location: CLLocationCoordinate2D, completion: @escaping EventsCompletion) {
var sortingFlagString = ""
if sortingFlag == .nearest {
sortingFlagString = "distance"
} else {
sortingFlagString = sortingFlag.APIPresentation
}
APIService.performRequest(request: .getMatchedEvents(userId: UserProvider.shared.currentUser!.objectId, sortFlag: sortingFlagString, longitude: location.longitude, latitude: location.latitude)) { (result) in
switch result {
case .success(let response):
guard response.statusCode == 200 else {
completion(.failure(APIError(code: response.statusCode, message: nil)))
return
}
do {
let events = try response.mapArray(Event.self)
completion(.success(events))
}
catch (let error) {
completion(.failure(APIError(error: error)))
}
break
case .failure(let error):
completion(.failure(APIError(error: error)))
break
}
}
}
// MARK: - Private methods
fileprivate class func fetchAttendingsForEvent(with eventId: String, completion: @escaping (Result<[String]>) -> Void){
FBSDKGraphRequest(graphPath: "\(eventId)", parameters: UserProvider.FacebookConstants.newEventParameters).start { (connection, result, error) in
if error != nil {
CLSNSLogv("ERROR: Error issuing graph request: %@", getVaList([error! as CVarArg]))
print("WOW error")
completion(.failure(APIError(error: error!)))
return
}
guard let baseResult = result as? [String: Any] else {
completion(.failure(APIError(code: 0, message: "Error: Can't parse data from Facebook.")))
return
}
var persons = [String]()
if let attendingsDict = baseResult["attending"] as? [String: Any], let attendings = attendingsDict["data"] as? [[String: Any]] {
let installedAttendings = attendings.filter({ ($0["installed"] as! Bool) == true }).map({ $0["id"] as! String })
persons.append(contentsOf: installedAttendings)
}
if let interestedDict = baseResult["interested"] as? [String: Any], let interesteds = interestedDict["data"] as? [[String: Any]] {
let installedInterested = interesteds.filter({ ($0["installed"] as! Bool) == true }).map({ $0["id"] as! String })
persons.append(contentsOf: installedInterested)
}
if persons.count == 0 {
persons.append("-1")
}
completion(.success(persons))
}
}
fileprivate class func newFetchUserEventsFromFacebook(completion: @escaping (Result<[Event]>) -> Void) {
isLoading = true
guard UserProvider.isUserLoggedInFacebook() else {
completion(.failure(APIError(code: 0, message: "Error: Can't fetch data from Facebook because user is not logged in.")))
isLoading = false
return
}
var parameters = UserProvider.FacebookConstants.newEventsParameters
let newValue = (parameters["fields"]! as NSString).replacingOccurrences(of: "since()", with: "since(\(Int64(Date().timeIntervalSince1970)))")
parameters["fields"] = newValue
FBSDKGraphRequest(graphPath: "me", parameters: parameters).start { (connection, result, error) in
if error != nil {
CLSNSLogv("ERROR: Error issuing graph request: %@", getVaList([error! as CVarArg]))
isLoading = false
completion(.failure(APIError(error: error!)))
return
}
guard let baseResult = result as? [String: Any], let eventsData = baseResult["events"] as? [String: Any], let eventsArray = eventsData["data"] as? [[String: Any]] else {
completion(.failure(APIError(code: 0, message: "Error: Can't parse data from Facebook.")))
return
}
let attendedEvents = eventsArray
var events = [Event]()
for eventData in attendedEvents {
// start date
var startDate: Date? = nil
if let startDateStr = eventData["start_time"] as? String, let date = Helper.convertFacebookStringToDate(string: startDateStr) {
startDate = date
}
if startDate == nil || startDate!.isInPast {
continue
}
// is cancelled
if let isCancelledString = eventData["is_canceled"] as? Bool {
if isCancelledString == true {
continue
}
}
// location
var longitude: Double? = nil
var latitude: Double? = nil
if let place = eventData["place"] as? [String: Any], let location = place["location"] as? [String: Any] {
latitude = location["latitude"] as? Double
longitude = location["longitude"] as? Double
}
if longitude == nil || latitude == nil {
continue
}
let name = eventData["name"] as? String
let description = eventData["description"] as? String
let id = eventData["id"] as! String
// cover
var coverUrl: String?
if let coverDict = eventData["cover"] as? [String: Any], let url = coverDict["source"] as? String {
coverUrl = url
}
// attending count & persons
let attendingCount = eventData["attending_count"] as? Int ?? 0
let interestedCount = eventData["interested_count"] as? Int ?? 0
// combine data into new event object
let event = Event(facebookId: id, name: name, information: description, latitude: latitude, longitude: longitude, imageLink: coverUrl, attendingsCount: attendingCount + interestedCount, startDate: startDate)
events.append(event)
}
if events.count == 0 {
isLoading = false
completion(.success(events))
}
var eventDict = [String: Event]()
_ = events.map({ eventDict[$0.facebookId] = $0 })
for (eventId, _) in eventDict {
fetchAttendingsForEvent(with: eventId, completion: { (result) in
switch (result) {
case .success(let persons):
eventDict[eventId]?.attendingsIds = persons
break
case .failure(_):
eventDict.removeValue(forKey: eventId)
break
default:
break
}
if Array(eventDict.values).filter({ $0.attendingsIds == nil }).count == 0 {
isLoading = false
completion(.success(Array(eventDict.values)))
}
})
}
}
}
fileprivate class func fetchUserEventsFromFacebook(completion: @escaping (Result<[Event]>) -> Void) {
guard UserProvider.isUserLoggedInFacebook() else {
completion(.failure(APIError(code: 0, message: "Error: Can't fetch data from Facebook because user is not logged in.")))
return
}
var parameters = UserProvider.FacebookConstants.eventParameters
let newValue = (parameters["fields"]! as NSString).replacingOccurrences(of: "since()", with: "since(\(Int64(Date().timeIntervalSince1970)))")
parameters["fields"] = newValue
FBSDKGraphRequest(graphPath: "me", parameters: parameters).start { (connection, result, error) in
if error != nil {
CLSNSLogv("ERROR: Error issuing graph request: %@", getVaList([error! as CVarArg]))
completion(.failure(APIError(error: error!)))
return
}
guard let baseResult = result as? [String: Any], let eventsData = baseResult["events"] as? [String: Any], let eventsArray = eventsData["data"] as? [[String: Any]] else {
completion(.failure(APIError(code: 0, message: "Error: Can't parse data from Facebook.")))
return
}
// filter events to get only attended by current user
/*let attendedEvents = eventsArray.filter({
if let status = $0["rsvp_status"] as? String {
return status == "attending"
}
return false
})*/
let attendedEvents = eventsArray
var events = [Event]()
for eventData in attendedEvents {
// start date
var startDate: Date? = nil
if let startDateStr = eventData["start_time"] as? String, let date = Helper.convertFacebookStringToDate(string: startDateStr) {
startDate = date
}
if startDate == nil || startDate!.isInPast {
continue
}
// is cancelled
if let isCancelledString = eventData["is_canceled"] as? Bool {
if isCancelledString == true {
continue
}
}
// location
var longitude: Double? = nil
var latitude: Double? = nil
if let place = eventData["place"] as? [String: Any], let location = place["location"] as? [String: Any] {
latitude = location["latitude"] as? Double
longitude = location["longitude"] as? Double
}
if longitude == nil || latitude == nil {
continue
}
let name = eventData["name"] as? String
let description = eventData["description"] as? String
let id = eventData["id"] as! String
// cover
var coverUrl: String?
if let coverDict = eventData["cover"] as? [String: Any], let url = coverDict["source"] as? String {
coverUrl = url
}
// attending count & persons
let attendingCount = eventData["attending_count"] as? Int ?? 0
let interestedCount = eventData["interested_count"] as? Int ?? 0
var attendingIds: [String] = [String]()
if let attendingUsersDict = eventData["attending"] as? [String: Any], let
attendingUsers = attendingUsersDict["data"] as? [[String: String]] {
attendingIds.append(contentsOf: attendingUsers.map({ $0["id"]! }))
}
if let interestedUsersDict = eventData["interested"] as? [String: Any], let
interestedUsers = interestedUsersDict["data"] as? [[String: String]] {
attendingIds.append(contentsOf: interestedUsers.map({ $0["id"]! }))
}
// combine data into new event object
let event = Event(facebookId: id, name: name, information: description, latitude: latitude, longitude: longitude, imageLink: coverUrl, attendingsCount: attendingCount + interestedCount, startDate: startDate, attendingIds: attendingIds)
events.append(event)
}
completion(.success(events))
}
}
}
|
//
// ImageDetailViewController.swift
// ImagePickerDemo
//
// Created by SanJyou on 2019/06/10.
// Copyright © 2019 SanJyou. All rights reserved.
//
import UIKit
import Photos
class ImageDetailViewController: UIViewController {
@IBOutlet weak var mainView: UIView!
public var selectedAssets : Array<PHAsset> = []
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "写真の追加"
let boundSize : CGSize = UIScreen.main.bounds.size
let imageViewLength : Int = Int(boundSize.width / 2)
for (i, asset) in self.selectedAssets.enumerated() {
var x = 0
let y = Int(i / 2) * imageViewLength
if i % 2 != 0 {
x = imageViewLength
}
let imageView = UIImageView.init(frame: CGRect(x: x, y: y, width: imageViewLength, height: imageViewLength))
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: boundSize.width, height: boundSize.width), contentMode: .default, options: nil) { (img, _) in
imageView.image = img
}
self.mainView.addSubview(imageView)
}
}
}
|
//
// FitnessPalViewController.swift
// Cal App
//
// Created by Basil Latif on 3/20/17.
// Copyright © 2017 Basil Latif. All rights reserved.
//
import UIKit
class FitnessPalViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var web: UIWebView!
@IBOutlet weak var url: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.web.delegate = self
self.web.scrollView.isScrollEnabled = true
self.web.scalesPageToFit = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func load(_ sender: Any) {
let webpage: String = self.url.text!
let url = URL(string: webpage)
let request = URLRequest(url: url!)
web.loadRequest(request)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// GameModel.swift
// TicTacToe
//
// Created by Yuan Chang on 6/24/21.
//
import Foundation
struct Game {
// var rotate: Bool = false
private(set) var moves: [Move?]
private(set) var isPlayer1Turn: Bool = true
private(set) var win: Bool = false
private(set) var draw: Bool = false
init() {
// empty game
moves = Array(repeating: nil, count: 9)
}
// scale back to none
mutating func restartAnimation() {
for index in moves.indices {
moves[index]?.scale.toggle()
}
}
mutating func choose(index: Int) {
if moves[index] == nil {
if isPlayer1Turn {
moves[index] = Move(player1: true, boardIndex: index, scale: false)
} else {
moves[index] = Move(player1: false, boardIndex: index, scale: false)
}
win = checkWin()
draw = checkDraw()
isPlayer1Turn.toggle()
} else {
print("Clicked on an existing place")
}
}
func checkWin() -> Bool {
// all the possible win conditions
let winConditions: Set<Set<Int>> = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8],[2,4,6]]
let currentPlayerMoves = moves.compactMap {
$0 // all of the moves
}.filter {
$0.player1 == isPlayer1Turn // all of the data
}
let currentPlayerPositions = Set(currentPlayerMoves.map {
$0.boardIndex
})
for condition in winConditions {
if condition.isSubset(of: currentPlayerPositions) {
return true
}
}
return false
}
func checkDraw() -> Bool {
let winAtLastMove = checkWin()
let numMovesMade = moves.compactMap {$0}.count
if numMovesMade == 9 {
// if won at 9 moves, display win instead of draw
if winAtLastMove {
return false
} else {
print("Draw")
return true
}
}
return false
}
// mutating func rotation() {
// rotate.toggle()
// }
struct Move {
let player1: Bool
var boardIndex: Int
var moveIndicator: String {
if player1 {
return "xmark"
} else {
return "circle"
}
}
// for animation
var scale: Bool = true
}
}
|
//
// Alert.swift
// Ashish Chauhan
//
// Created by Ashish Chauhan on 15/11/17.
// Copyright © 2017 Ashish Chauhan. All rights reserved.
//
import Foundation
import UIKit
class Alert {
// MARK: Alert methods
class func Alert(_ message: String, okButtonTitle: String? = nil, target: UIViewController? = nil) {
//BZBanner.showMessage(nil, message: message)
}
class func showOkAlert(title: String?, message: String)
{
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Ok".localize(), style: .cancel, handler: nil)
alertController.addAction(cancelAction)
if let topViewController: UIViewController = Helper.topMostViewController(rootViewController: Helper.rootViewController()) {
topViewController.present(alertController, animated: true, completion: nil)
} else if let viewC = AppDelegate.delegate.window?.rootViewController {
viewC.present(alertController, animated: true, completion: nil)
}
}
class func showOkAlertWithCallBack(title: String, message: String ,completeion_: @escaping (_ compl:Bool)->())
{
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Ok".localize(), style: .cancel, handler: { (action:UIAlertAction!) -> Void in
completeion_(true) //returns true in callback to perform action on last screen
})
alertController.addAction(cancelAction)
if let topViewController: UIViewController = Helper.topMostViewController(rootViewController: Helper.rootViewController()) {
topViewController.present(alertController, animated: true, completion: nil)
} else if let viewC = AppDelegate.delegate.window?.rootViewController {
viewC.present(alertController, animated: true, completion: nil)
}
/*
let topViewController: UIViewController = Helper.topMostViewController(rootViewController: Helper.rootViewController())!
topViewController.present(alertController, animated: true, completion: nil)
*/
}
class func showOkGrayAlertWithCallBack(title: String, message: String ,completeion_: @escaping (_ compl:Bool)->())
{
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Ok".localize(), style: .cancel, handler: { (action:UIAlertAction!) -> Void in
completeion_(true) //returns true in callback to perform action on last screen
})
cancelAction.setValue(UIColor.gray, forKey: "titleTextColor")
alertController.addAction(cancelAction)
if let topViewController: UIViewController = Helper.topMostViewController(rootViewController: Helper.rootViewController()) {
topViewController.present(alertController, animated: true, completion: nil)
} else if let viewC = AppDelegate.delegate.window?.rootViewController {
viewC.present(alertController, animated: true, completion: nil)
}
/*
let topViewController: UIViewController = Helper.topMostViewController(rootViewController: Helper.rootViewController())!
topViewController.present(alertController, animated: true, completion: nil)
*/
}
class func showAlert(title: String? = nil, message: String? = nil, style: UIAlertControllerStyle = .alert, actions: UIAlertAction...) {
let topViewController: UIViewController? = Helper.topMostViewController(rootViewController: Helper.rootViewController())
var strTitle: String = ""
if let titleStr = title {
strTitle = titleStr
} else {
strTitle = ConstantTextsApi.AppName.localizedString
}
let alertController = UIAlertController(title: nil, message: message, preferredStyle: style)
if !actions.isEmpty {
for action in actions {
alertController.addAction(action)
}
} else {
let cancelAction = UIAlertAction(title: ConstantTextsApi.cancel.localizedString, style: .default, handler: nil)
alertController.addAction(cancelAction)
}
topViewController?.present(alertController, animated: true, completion: nil)
}
class func showAlertWithAction(title: String?, message: String?, style: UIAlertControllerStyle, actionTitles:[String?], action:((UIAlertAction) -> Void)?) {
showAlertWithActionWithCancel(title: nil, message: message, style: style, actionTitles: actionTitles, showCancel: false, deleteTitle: nil, action: action)
}
class func showAlertWithActionWithCancel(title: String?, message: String?, style: UIAlertControllerStyle, actionTitles:[String?], showCancel:Bool, deleteTitle: String? ,_ viewC: UIViewController? = nil, action:((UIAlertAction) -> Void)?) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: style)
if deleteTitle != nil {
let deleteAction = UIAlertAction(title: deleteTitle, style: .destructive, handler: action)
alertController.addAction(deleteAction)
}
for (_, title) in actionTitles.enumerated() {
let action = UIAlertAction(title: title, style: .default, handler: action)
alertController.addAction(action)
}
if showCancel {
let cancelAction = UIAlertAction(title: ConstantTextsApi.cancel.localizedString, style: .default, handler: nil)
alertController.addAction(cancelAction)
}
if let viewController = viewC {
viewController.present(alertController, animated: true, completion: nil)
} else {
let topViewController: UIViewController? = Helper.topMostViewController(rootViewController: Helper.rootViewController())
topViewController?.present(alertController, animated: true, completion: nil)
}
}
//Logout Alert
class func showAlertWithActionWithColor(title: String?, message: String?, actionTitle: String?, showCancel:Bool,_ viewC: UIViewController? = nil, action:((UIAlertAction) -> Void)?) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
if showCancel {
let cancelAction = UIAlertAction(title: ConstantTextsApi.cancel.localizedString, style: .default, handler: nil)
cancelAction.setValue(UIColor.actionRedColor, forKey: "titleTextColor")
alertController.addAction(cancelAction)
}
let action = UIAlertAction(title: actionTitle, style: .default, handler: action)
action.setValue(UIColor.appOrangeColor, forKey: "titleTextColor")
alertController.addAction(action)
if let viewController = viewC {
viewController.present(alertController, animated: true, completion: nil)
} else {
let topViewController: UIViewController? = Helper.topMostViewController(rootViewController: Helper.rootViewController())
topViewController?.present(alertController, animated: true, completion: nil)
}
}
//More Options ActionSheet
class func showAlertSheetWithColor(title: String?, message: String?, actionItems: [[String: Any]], showCancel:Bool,_ viewC: UIViewController? = nil, action:((UIAlertAction) -> Void)?) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
for actionItem in actionItems {
if let title = actionItem[Constant.keys.kTitle] as? String, let color = actionItem[Constant.keys.kColor] as? UIColor {
let action = UIAlertAction(title: title, style: .default, handler: action)
action.setValue(color, forKey: "titleTextColor")
alertController.addAction(action)
}
}
if showCancel {
let cancelAction = UIAlertAction(title: ConstantTextsApi.cancel.localizedString, style: .cancel, handler: nil)
cancelAction.setValue(UIColor.actionBlackColor, forKey: "titleTextColor")
alertController.addAction(cancelAction)
}
if let viewController = viewC {
viewController.present(alertController, animated: true, completion: nil)
} else {
let topViewController: UIViewController? = Helper.topMostViewController(rootViewController: Helper.rootViewController())
topViewController?.present(alertController, animated: true, completion: nil)
}
}
}
|
//
// ViewController.swift
// AlgorithmSwift
//
// Created by Liangzan Chen on 11/8/17.
// Copyright © 2017 clz. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//testPivot()
//testBST()
//testStringExtension()
//testArrayExtension()
//testArray()
/*
// Do any additional setup after loading the view, typically from a nib.
testMaxSumOfSubArray()
testKnapSack()
testLongestPalindromeSubstring()
testSoduku()
testRatInMaze()
testKnightTour()
testWordBreaking()
testQueenProblem()
testWordMatrix()
testSubsetsOfSum()
testStringPermutation()
checkStringRotation()
testPhonePads()
testStringsOfNBits()
testMinJumps()
testBracketPairs()
testHashTable()
//testHeap()
//testFizzBuzz()
//testStringSearch()
//testPrimes()
//testURLShortener()
//testGraph()
//testSum()
//testBitSet()
//testShuffle()
//testSortByLastName()
//testHanoiTower()
//testStairs()
//testPriorityQueue()
//testStringToInt()
//testPivot()
//testStockProfit()
//testArray()
//testRange()
//testClosures()
//testBits()
testBST()
testNumber2Words()
testSumDigits()
testEggDrop()
testLRUCache()
testRodProfits()
testRopeCut()
testCoinProblem()
testConferenceRoom()
testMatrix()
testMaxSumOfSubArray()
testArrayExtension()
testStringExtension()
testMissingTwoNumbers()
testPalindrome()
testDequ()
testGCD()
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Test
func testKnapSack() {
let weightValues: [(w: Int, v: Int)] = [ (30, 120), (20, 80), (10, 30), (5, 15), (40, 160)]
print("naive: \(knapSackNaive(weightValues, 50))")
print("dp: \(knapSackDP(weightValues, 50))")
}
func testLongestPalindromeSubstring() {
let str = "bananasananabs"
print(longestPalindromeSubstring(str))
}
func testSoduku() {
let matrix = [
[0,0,7,4,0,3,0,8,0],
[0,0,0,0,2,0,4,7,1],
[0,0,6,0,0,5,0,0,0],
[3,0,1,0,0,8,0,0,0],
[0,5,0,0,6,0,0,3,0],
[0,0,0,3,0,0,5,0,2],
[0,0,0,9,0,0,8,0,0],
[7,8,9,0,3,0,0,0,0],
[0,3,0,2,0,4,7,0,0]]
/*
[[5,0,0,0,0,1,3,0,0],
[0,0,0,0,6,5,1,7,0],
[0,0,0,4,0,0,0,2,5],
[0,6,0,0,7,0,0,3,0],
[0,7,5,0,0,0,6,8,0],
[0,8,0,0,4,0,0,1,0],
[8,2,0,0,0,6,0,0,0],
[0,5,6,3,8,0,0,0,0],
[0,0,1,7,0,0,0,0,3]] */
if let solution = soduku(matrix) {
for row in solution {
print(row)
}
}
}
func testRatInMaze() {
let maze = [ [1,1,1,0,0,0,0],
[1,0,1,0,1,1,1],
[1,0,1,1,1,0,1],
[1,0,0,0,0,1,1],
[1,0,0,0,1,1,0],
[1,1,1,1,0,1,1],
[1,0,1,0,0,0,1]]
print("maze:")
for row in maze {
print(row)
}
print("Solution:")
if let path = ratPath(in: maze) {
for row in path {
print(row)
}
}
else {
print("no path out")
}
}
func testKnightTour() {
if let tour = knightTourPostions() {
for row in tour {
print(row.map{String(format: "%02d", $0)})
}
}
}
func testWordBreaking() {
let words: Set<String> = ["I", "have", "a", "book", "read", "ocean", "Sam", "am", "rain", "look", "do"]
let str = "Idoreadabook"
if let found = wordBreakNaive(str, words) {
print(found)
}
else {
print("\(str) not breakable")
}
if let dpFound = wordBreakDP(str, words) {
print(dpFound)
}
}
func testQueenProblem() {
let n = 8
let positions = queenPositions(n)
for row in positions {
print(row)
}
}
func testWordMatrix() {
let matrix : [[Character]] = [ ["t", "o", "w", "c", "d" ],
["a", "h", "n", "z", "x" ],
["h", "w", "o", "i", "o" ],
["o", "r", "n", "r", "n" ],
["a", "b", "r", "i", "n" ] ]
for m in matrix {
print(m)
}
let word = "horizon"
if let found = find(word: word, in: matrix) {
for row in found {
print(row)
}
}
else {
print("\(word) not found")
}
}
func testSubsetsOfSum() {
let n = 4
printAllSubsets(of: n)
print(allSubsets(of: n))
let a = [2, 10, 6, 8, 4]
let sum = 16
let count = countSubsetsOfSum(a, 16)
print("\(count)subsets whose sum is \(sum) " )
}
func testStringPermutation() {
let str = "abcd"
let perms = permutations(str)
print(perms)
}
func checkStringRotation() {
let str1 = "aiwotmocz"
let str2 = "tmoczaiwo"
if isRotated(str1, str2) {
print("\(str1) is rotation of \(str2)")
}
else {
print("\(str1) is not rotation of \(str2)")
}
}
func testPhonePads() {
let phoneNumbers = [2,3,4]
printLettersOfPhoneNumbers(phoneNumbers)
}
func testStringsOfNBits() {
let n = 3
printStringsOfNBits(n)
}
func testMinJumps() {
let array = [1, 3, 5, 3, 3,1,1,6,1,1,1,1,1,4]
var mem = [Int: Int]()
let min = findMinJumps(array, startIndex: 0, &mem)
print("The minimum number of jumps is \(min)")
}
func testBracketPairs() {
let n = 4
printBracketPairs(of: n)
}
func testNumber2Words() {
let n: UInt = 6_110_112_054_103_708_583
print(number2Words(n))
}
func testSumDigits() {
let n = 34567
print(sumOfDigits(n))
}
func testEggDrop() {
for egg in 1..<5 {
for floor in 1..<18 {
print("dropping \(egg) eggs from \(floor) floors takes \(eggDrop(numberOfEggs: egg, numberOfFloors: floor)) tries")
}
}
}
func testLRUCache() {
let cache = LRUCache<Int, String>(capacity: 3)
cache.setValue("One", for: 1)
cache.setValue("Two", for: 2)
cache.setValue("Three", for: 3)
cache.getValue(for: 2)
cache.getValue(for: 4)
cache.setValue("Five", for: 5)
cache.setValue("Four", for: 4)
}
/*
Length 1 2 3 4 5 6 7 8 9 10
Price 1 5 8 9 10 17 17 20 24 30
*/
func testRodProfits() {
let prices:[Double] = [1.0, 5.0, 8.0, 9.0, 10.0, 17.0, 17.0, 20.0, 24.0, 30.0]
let length = 7
print("Max profit of rod with lenth of \(length) is \(maxProfitsOfCuts(prices, rodLen: length))")
}
func testRopeCut() {
for len in 2..<13 {
print("production of cuts for rope length \(len) is \(maxProductionOfCuts(len))")
}
}
func testCoinProblem() {
let coins = [1, 2, 5, 10]
let value = 9
print("\(countOfWayUsingCoins(coins, value: value)) of coin combinations")
print("\(minNumberOfCoins(coins, value: value)) coins are needed.")
}
func testConferenceRoom() {
let meetings: [(startTime: Double, endTime: Double)] = [(8.0, 9.0), (1.0, 4.0), (5.0, 6.0), (2.0, 6.0)]
let scheduledMeetings = maxMeetings(meetings)
for meeting in scheduledMeetings {
print("meetings: \(meeting)")
}
print("mininum \(minRooms(meetings)) rooms needed.")
}
func testMatrix() {
for i in 1..<5 {
let count = countOfPaths(rows: i, cols: i)
print("there are \(count) paths to reach \(i)x\(i)")
}
let matrix = [
[1, 1, 1],
[1, 1, 1],
[1, -1, 1]]
let count = countOfPaths(for: matrix)
print("there are \(count) paths to reach point(\(matrix.count),\(matrix[0].count))")
}
func testMaxSumOfSubArray() {
let numbers = [1, 2, -1, 3, 5, -3, 6]// [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("max sum is \(maxSumOfSubArray(numbers))")
}
func testArrayExtension() {
let nums = [1,8,3,5,7]
print(nums.allSubArray())
let strings = ["I", "like", "you"]
print(strings.allSubArray())
}
func testStringExtension() {
let numbers = "-2532"
if let i = numbers.toInt() {
print("numbers is \(i)")
}
let strings = "abcd"
print(strings.allSubStrings())
}
func testMissingTwoNumbers() {
let num1 = [1, 3, 4, 6, 7, 8]
let num2: [Int] = []
let num3 = [3]
let num4 = [1,2,3,4,6,7]
let m1 = findTwoMissingNumbers(num1)
print("Missing: \(m1.0), \(m1.1)")
let m2 = findTwoMissingNumbers(num2)
print("Missing: \(m2.0), \(m2.1)")
let m3 = findTwoMissingNumbers(num3)
print("Missing: \(m3.0), \(m3.1)")
let m4 = findTwoMissingNumbers(num4)
print("Missing: \(m4.0), \(m4.1)")
}
func testPalindrome() {
let strings = ["abcdcba", "sksfkgslg", "ilmnggnmli"]
for s in strings {
if s.isPalindrom() {
print("\(s) is a palindrome")
}
else {
print("\(s) is NOT a palindrome")
}
}
}
func testHanoiTower() {
print("Move 2 disks")
hanoiTower(2, source: "A", aux: "B", dest: "C")
print("Move 3 disks")
hanoiTower(3, source: "A", aux: "B", dest: "C")
print("Move 4 disks")
hanoiTower(4, source: "A", aux: "B", dest: "C")
}
func testStairs() {
var mem: [Int] = Array(repeating: 0, count: 10) // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in 1..<mem.count {
print("ways of \(i) stairs: \(possibleStairWays(i, &mem))")
}
}
func testSortByLastName() {
let names = ["Jack Chen", "Apple Apple", "Tom Hanks", "Jerry John", "Sam Adams", "Tony Battsy", "John"]
print("sorted by last Name: \(sortByLastName(names))")
}
func testBits() {
let count = BitSet.setBitsCount(7 << 3)
print(count)
}
func testDequ() {
var deq = Deque<String>()
var anotherDeq = Deque<String>()
deq.enqueueAtFront("c")
deq.enqueueAtFront("b")
deq.enqueueAtFront("a")
deq.enqueueAtBack("d")
deq.enqueueAtBack("e")
deq.enqueueAtBack("f")
//at this momement the deq has ["a","b","c","d","e","f"]
while let element = deq.dequeueAtBack() {
print(element) //should print "f","e","d","c","b","a"
anotherDeq.enqueueAtFront(element)
}
print("\n")
//at this momement the anotherDeq has ["a","b","c","d","e","f"]
while let element = anotherDeq.dequeueAtFront() {
print(element) //should print "a","b","c","d","e","f"
}
}
func testShuffle() {
var a = [1, 2, 3, 4, 5, 6, 7, 8]
a.shuffle()
print(a)
}
func testHashTable() {
var hashTable = HashTable<String, String>(capacity: 13)
hashTable["lastName"] = "Hanks"
hashTable["firstName"] = "Tom"
hashTable["Career"] = "Actor"
if let lastName = hashTable["lastName"] {
print("old lastName: \(lastName)")
_ = hashTable.updateValue("Jerry", forKey: "lastName")
print("new lastName: \(hashTable["lastName"]!)")
}
}
func testFizzBuzz() {
func fizzBuzz(_ numberOfTurns: Int) {
for i in 1...numberOfTurns {
var result = ""
if i % 3 == 0 {
result += "Fizz"
}
if i % 5 == 0 {
result += (result.isEmpty ? "" : " ") + "Buzz"
}
if result.isEmpty {
result += "\(i)"
}
print(result)
}
}
fizzBuzz(20)
}
func testBitSet() {
var bits = BitSet(size: 150)
bits[22] = true
bits[99] = true
print(bits)
}
func testStringSearch() {
let myString = "Hello world"
if let i = myString.indexOf("world") {
print(i)
}
}
func testSum() {
let myArray = [3, 2, 10, 5, 43, 57, 23, 12, 90, 86, 52, 100]
let mySorted = [2, 4, 5, 10, 12, 23, 43, 52, 57, 86, 90, 100]
if let (i, j) = twoSum(myArray, 95) {
print("( \(i), \(j) )")
}
if let (i, j) = twoSortedSum(mySorted, 95) {
print("( \(i), \(j) )")
}
let sum = threeSum(myArray, target: 105)
print(sum)
}
func testClosures() {
class SimpleClass {
var value: Int = 0
}
var x = SimpleClass()
var y = SimpleClass()
let closure = { [x] in
print(x.value, y.value)
}
closure()
x.value = 10
y.value = 13
closure()
}
func testPrimes() {
let n = 1097 //446185740
let primes = firstPrimes(n)
if isPrime(n) {
print("\(n) is a prime")
print(primes)
}
}
func testStockProfit() {
let prices: [Double] = [200.0, 500.0, 1000.0, 700.0, 30.0, 400.0, 900.0, 400.0, 50.0]
if let profit = maxProfit(prices) {
print("profit: \(profit.profit), buyDateIndex: \(profit.buyDateIndex), sellDateIndex: \(profit.sellDateIndex)")
}
}
func testArray() {
let numbers = [1, 2, 3, 4]
print("\(numbers.powerset)")
}
func testHeap() {
var heap = Heap(elements: [4, 2, 10, 5, 43, 57, 23, 12, 90, 86, 52, 100], priorityFunction: > )
/*heap.enqueue(10)
heap.enqueue(15)
heap.enqueue(5)
heap.enqueue(20)
heap.enqueue(9)
heap.enqueue(100)
heap.enqueue(35) */
while !heap.isEmpty {
if let item = heap.dequeue() {
print(item)
}
}
}
func testURLShortener() {
var shortener = URLShortener(domainName: "http://shor.ty/")
_ = shortener.shortenFast("http://www.apple.com")
_ = shortener.shortenFast("http://www.safeway.com")
_ = shortener.shortenFast("http://www.badurl.com/list1")
shortener.addBlackList("http://www.badurl.com/list1")
shortener.addBlackList("http://www.badurl.com/list2")
shortener.addBlackList("http://www.badurl.com/list3")
shortener.addBlackList("http://www.badurl.com/list4")
if let appleUrl = shortener.expandFast("http://shor.ty/0") {
print(appleUrl)
}
let url2Check = "http://shor.ty/1"
if let expanded = shortener.expandFast(url2Check) {
if !shortener.isSecure(url2Check) {
print("\(expanded) is a unsafe url")
}
else {
print("\(expanded) is a safe url")
}
}
}
func testRange() {
let range1: Range = Range<Int>(5...18)
let range2: Range = Range<Int>(3...15)
print(range1.intersect(range2))
}
func testBST() {
let array = [2, 4, 6, 8, 9, 10, 13, 15, 17, 18, 19, 21, 25]
let tree = BinarySearchTree<Int>.createBST(from: array)!
let tree1 = BinarySearchTree<Int>.createBST(from: array)!
let tree2 = BinarySearchTree<Int>.createBST(from: array)!
if tree.isBalanced() {
print("tree is balanced")
}
else {
print("tree is not balaced")
}
var path = [BinarySearchTree<Int>]()
tree.traverseAllRoot2LeafPaths(&path){ nodes in
var str = "["
for (index, node) in nodes.enumerated() {
str += index == 0 ? "\(node.value)" : "->\(node.value)"
}
str += "]"
print(str)
}
print(tree.toArray())
var sum = 0
transformToGreaterSumTree(tree1, &sum)
print("greater sum tree")
print(tree1)
let _ = transformToSumTree(tree2)
print("sum tree")
print(tree2)
print("traverse boundary anti-clockwise")
tree.traverseBounaryAntiClockWise() { print($0) }
print("breadth first traverse")
tree.traverseBreadthFirst() { print($0) }
if let node = tree.leastCommonAncestor(4, 8) {
print("lease common ancestor: \(node.value)")
}
print("traverse in level order")
tree.traverseLevelOrder{ print($0) }
print("traverse preorder")
tree.traversePreOrder() { print($0) }
print("traverse preorder interatively")
tree.traversePreOrderInteratively() { print($0) }
print("all left leaves: \(tree.allLeftLeaves())")
print("all left leaves iteratively: \(tree.allLeftLeavesIteratively())")
print("traverse in order")
tree.traverseInOrder() { print($0) }
let mirror = tree.createMirror()
print("traverse mirror in order")
mirror.traverseInOrder{ print($0) }
if !mirror.isValidBST(Int.min, Int.max) {
print("a mirror of BST is not a valid BST")
}
if tree.isMirror(of: mirror) {
print("a mirror of BST is its mirror")
}
print("traverse in order with stack")
tree.traverseInOrderWithStack() { print($0) }
print("traverse in order interatively")
tree.traverseInOrderInteratively() { print($0) }
print("traverse post order")
tree.traversePostOrder() { print($0) }
print("traverse post order interatively")
tree.traversePostOrderIteratively() { print($0) }
print("tree height: \(tree.height())")
print("minHeight: \(tree.minimumDepth())")
let heightAndDiameter = tree.heightAndDiameter()
print("height:\(heightAndDiameter.height) diameter: \(heightAndDiameter.diameter)")
print("total number of nodes \(tree.count)")
if let node = tree.searchIteratively(13) {
/*
if let pre = node.predecessor() {
print(pre.value)
pre.remove()
}*/
node.insert(100)
if !tree.isValidBST(Int.min, Int.max) {
print("tree becomes invalid")
}
}
}
func testPivot() {
let nums = [1, 5, 9, 13, 13, 15,15, 34,66,60]
if let pivot = indexFromAscendingToDescending(nums) {
print("pivot: \(pivot) :\(nums[pivot])")
}
else {
print("no pivot")
}
print("done")
}
func testGCD() {
let a = 64, b = -24
let g = gcd(a, b)
print(g)
}
func testStringToInt() {
let s = "123799abc"
let v = str2Int(s, 16)
}
func testStack() {
var myStack : Stack<Int> = [ 5, 6, 3, 6]
myStack.push(8)
myStack.pop()
myStack.pop()
print(myStack)
}
func testMergeSort() {
var myArray = [4, 2, 10, 5, 43, 57, 23, 12, 90, 86, 52, 100]
mergeSort(&myArray)
}
func testGraph() {
let adjacencyList = AdjacencyList<String>()
let singapore = adjacencyList.createVertex(data: "Singapore")
let tokyo = adjacencyList.createVertex(data: "Tokyo")
let hongKong = adjacencyList.createVertex(data: "Hong Kong")
let detroit = adjacencyList.createVertex(data: "Detroit")
let sanFrancisco = adjacencyList.createVertex(data: "San Francisco")
let washingtonDC = adjacencyList.createVertex(data: "Washington DC")
let austinTexas = adjacencyList.createVertex(data: "Austin Texas")
let seattle = adjacencyList.createVertex(data: "Seattle")
adjacencyList.addEdge(from: singapore, to: hongKong, weight: 300)
adjacencyList.addEdge(from: singapore, to: tokyo, weight: 500)
adjacencyList.addEdge(from: hongKong, to: tokyo, weight: 250)
adjacencyList.addEdge(from: tokyo, to: detroit, weight: 450)
adjacencyList.addEdge(from: tokyo, to: washingtonDC, weight: 300)
adjacencyList.addEdge(from: hongKong, to: sanFrancisco, weight: 600)
adjacencyList.addEdge(from: detroit, to: austinTexas, weight: 50)
adjacencyList.addEdge(from: austinTexas, to: washingtonDC, weight: 292)
adjacencyList.addEdge(from: sanFrancisco, to: washingtonDC, weight: 337)
adjacencyList.addEdge(from: washingtonDC, to: seattle, weight: 277)
adjacencyList.addEdge(from: sanFrancisco, to: seattle, weight: 218)
adjacencyList.addEdge(from: austinTexas, to: sanFrancisco, weight: 297)
print(adjacencyList)
print(adjacencyList.weight(from: singapore, to: seattle))
}
func testPriorityQueue() {
var heap = PriorityQueue<String>(ascending: false, startingValues: ["tao", "ming", "zack", "tom", "winnie", "jack"])
print(heap.peek()!)
print(heap.pop()!)
for x in heap {
print(x)
}
let y = heap[4]
print(y)
}
}
|
//
// DataError.swift
// MapsAOPA
//
// Created by Konstantin Zyryanov on 2/15/17.
// Copyright © 2017 Konstantin Zyryanov. All rights reserved.
//
import Foundation
extension AOPAError {
static func dataError(_ error: NSError) -> AOPAError {
if let errorCode = XMLParser.ErrorCode(rawValue: error.code) {
switch errorCode {
case XMLParser.ErrorCode.documentStartError,
XMLParser.ErrorCode.emptyDocumentError,
XMLParser.ErrorCode.prematureDocumentEndError,
XMLParser.ErrorCode.invalidHexCharacterRefError,
XMLParser.ErrorCode.invalidDecimalCharacterRefError,
XMLParser.ErrorCode.invalidCharacterRefError,
XMLParser.ErrorCode.invalidCharacterError,
XMLParser.ErrorCode.characterRefAtEOFError,
XMLParser.ErrorCode.characterRefInPrologError,
XMLParser.ErrorCode.characterRefInEpilogError,
XMLParser.ErrorCode.characterRefInDTDError,
XMLParser.ErrorCode.entityRefAtEOFError,
XMLParser.ErrorCode.entityRefInPrologError,
XMLParser.ErrorCode.entityRefInEpilogError,
XMLParser.ErrorCode.entityRefInDTDError,
XMLParser.ErrorCode.parsedEntityRefAtEOFError,
XMLParser.ErrorCode.parsedEntityRefInPrologError,
XMLParser.ErrorCode.parsedEntityRefInEpilogError,
XMLParser.ErrorCode.parsedEntityRefInInternalSubsetError,
XMLParser.ErrorCode.entityReferenceWithoutNameError,
XMLParser.ErrorCode.entityReferenceMissingSemiError,
XMLParser.ErrorCode.parsedEntityRefNoNameError,
XMLParser.ErrorCode.parsedEntityRefMissingSemiError,
XMLParser.ErrorCode.undeclaredEntityError,
XMLParser.ErrorCode.unparsedEntityError,
XMLParser.ErrorCode.entityIsExternalError,
XMLParser.ErrorCode.entityIsParameterError,
XMLParser.ErrorCode.encodingNotSupportedError,
XMLParser.ErrorCode.stringNotStartedError,
XMLParser.ErrorCode.stringNotClosedError,
XMLParser.ErrorCode.namespaceDeclarationError,
XMLParser.ErrorCode.entityNotStartedError,
XMLParser.ErrorCode.entityNotFinishedError,
XMLParser.ErrorCode.lessThanSymbolInAttributeError,
XMLParser.ErrorCode.attributeNotStartedError,
XMLParser.ErrorCode.attributeNotFinishedError,
XMLParser.ErrorCode.attributeHasNoValueError,
XMLParser.ErrorCode.attributeRedefinedError,
XMLParser.ErrorCode.literalNotStartedError,
XMLParser.ErrorCode.literalNotFinishedError,
XMLParser.ErrorCode.commentNotFinishedError,
XMLParser.ErrorCode.processingInstructionNotStartedError,
XMLParser.ErrorCode.processingInstructionNotFinishedError,
XMLParser.ErrorCode.notationNotStartedError,
XMLParser.ErrorCode.notationNotFinishedError,
XMLParser.ErrorCode.attributeListNotStartedError,
XMLParser.ErrorCode.attributeListNotFinishedError,
XMLParser.ErrorCode.mixedContentDeclNotStartedError,
XMLParser.ErrorCode.mixedContentDeclNotFinishedError,
XMLParser.ErrorCode.elementContentDeclNotStartedError,
XMLParser.ErrorCode.elementContentDeclNotFinishedError,
XMLParser.ErrorCode.xmlDeclNotStartedError,
XMLParser.ErrorCode.xmlDeclNotFinishedError,
XMLParser.ErrorCode.conditionalSectionNotStartedError,
XMLParser.ErrorCode.conditionalSectionNotFinishedError,
XMLParser.ErrorCode.externalSubsetNotFinishedError,
XMLParser.ErrorCode.doctypeDeclNotFinishedError,
XMLParser.ErrorCode.misplacedCDATAEndStringError,
XMLParser.ErrorCode.cdataNotFinishedError,
XMLParser.ErrorCode.misplacedXMLDeclarationError,
XMLParser.ErrorCode.spaceRequiredError,
XMLParser.ErrorCode.separatorRequiredError,
XMLParser.ErrorCode.nmtokenRequiredError,
XMLParser.ErrorCode.nameRequiredError,
XMLParser.ErrorCode.pcdataRequiredError,
XMLParser.ErrorCode.uriRequiredError,
XMLParser.ErrorCode.publicIdentifierRequiredError,
XMLParser.ErrorCode.ltRequiredError,
XMLParser.ErrorCode.gtRequiredError,
XMLParser.ErrorCode.ltSlashRequiredError,
XMLParser.ErrorCode.equalExpectedError,
XMLParser.ErrorCode.tagNameMismatchError,
XMLParser.ErrorCode.unfinishedTagError,
XMLParser.ErrorCode.standaloneValueError,
XMLParser.ErrorCode.invalidEncodingNameError,
XMLParser.ErrorCode.commentContainsDoubleHyphenError,
XMLParser.ErrorCode.invalidEncodingError,
XMLParser.ErrorCode.externalStandaloneEntityError,
XMLParser.ErrorCode.invalidConditionalSectionError,
XMLParser.ErrorCode.entityValueRequiredError,
XMLParser.ErrorCode.notWellBalancedError,
XMLParser.ErrorCode.extraContentError,
XMLParser.ErrorCode.invalidCharacterInEntityError,
XMLParser.ErrorCode.parsedEntityRefInInternalError,
XMLParser.ErrorCode.entityRefLoopError,
XMLParser.ErrorCode.entityBoundaryError,
XMLParser.ErrorCode.invalidURIError,
XMLParser.ErrorCode.uriFragmentError,
XMLParser.ErrorCode.noDTDError,
XMLParser.ErrorCode.unknownEncodingError: return .IncorrectDataReturned
case XMLParser.ErrorCode.internalError,
XMLParser.ErrorCode.outOfMemoryError,
XMLParser.ErrorCode.delegateAbortedParseError: return .Unknown
}
}
return .Unknown
}
}
|
import UIKit
var str = "Hello, playground"
// sort + 首尾
//func longestCommonPrefix(_ strs: [String]) -> String {
// var result = ""
// if strs.count > 0 {
// if let firstObjc = strs.first {
// if strs.count > 1 {
//
// let numbers = strs.sorted()
//// print(numbers)
// let first = numbers.first!
// let last = numbers.last!
//
// let lastArray = Array(last)
// for (index, firstChar) in first.enumerated() {
// if lastArray[index] != firstChar {
// return result
// }
//
// result += String(firstChar)
// }
// } else {
// result = firstObjc
// }
// }
// }
// return result
//}
//func longestCommonPrefix(_ strs: [String]) -> String {
// var result = ""
// if strs.count > 0 {
// if let firstObjc = strs.first {
// if strs.count > 1 {
// let remainderArray = strs[1..<strs.count]
// for char in firstObjc {
// let flag = result + String(char)
// for objc in remainderArray {
// if !objc.hasPrefix(flag) {
// return result
// }
// }
//
// result = flag
// }
// } else {
// return firstObjc
// }
//
// }
// }
// return result
// }
// 二分法
func longestCommonPrefix(_ strs: [String]) -> String {
var result = ""
guard strs.count > 1 else {
return strs.first ?? ""
}
let min_string = strs.sorted().first!
var low = 0
var height = min_string.count
while low < height {
let mid = low + (height - low + 1) / 2
if compareString(strs: strs, flag: mid) {
low = mid
} else {
height = mid - 1
}
}
result = String(min_string.prefix(low))
return result
}
func compareString(strs: [String], flag: Int) -> Bool {
guard let str_0 = strs.first else{
return false
}
let flag_prefix = str_0.prefix(flag)
for str in strs {
if str.prefix(flag) != flag_prefix {
return false
}
}
return true
}
let array = ["flowerdsadadada","flightsss","flight"]
longestCommonPrefix(array)
|
// FIXME: Only defining _POSIXError for Darwin at the moment.
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
/// Enumeration describing POSIX error codes.
@objc public enum POSIXError : Int32 {
// FIXME: These are the values for Darwin. We need to get the Linux
// values as well.
/// Operation not permitted.
case EPERM = 1
/// No such file or directory.
case ENOENT = 2
/// No such process.
case ESRCH = 3
/// Interrupted system call.
case EINTR = 4
/// Input/output error.
case EIO = 5
/// Device not configured.
case ENXIO = 6
/// Argument list too long.
case E2BIG = 7
/// Exec format error.
case ENOEXEC = 8
/// Bad file descriptor.
case EBADF = 9
/// No child processes.
case ECHILD = 10
/// Resource deadlock avoided.
case EDEADLK = 11
/// 11 was EAGAIN.
/// Cannot allocate memory.
case ENOMEM = 12
/// Permission denied.
case EACCES = 13
/// Bad address.
case EFAULT = 14
/// Block device required.
case ENOTBLK = 15
/// Device / Resource busy.
case EBUSY = 16
/// File exists.
case EEXIST = 17
/// Cross-device link.
case EXDEV = 18
/// Operation not supported by device.
case ENODEV = 19
/// Not a directory.
case ENOTDIR = 20
/// Is a directory.
case EISDIR = 21
/// Invalid argument.
case EINVAL = 22
/// Too many open files in system.
case ENFILE = 23
/// Too many open files.
case EMFILE = 24
/// Inappropriate ioctl for device.
case ENOTTY = 25
/// Text file busy.
case ETXTBSY = 26
/// File too large.
case EFBIG = 27
/// No space left on device.
case ENOSPC = 28
/// Illegal seek.
case ESPIPE = 29
/// Read-only file system.
case EROFS = 30
/// Too many links.
case EMLINK = 31
/// Broken pipe.
case EPIPE = 32
/// math software.
/// Numerical argument out of domain.
case EDOM = 33
/// Result too large.
case ERANGE = 34
/// non-blocking and interrupt i/o.
/// Resource temporarily unavailable.
case EAGAIN = 35
/// Operation would block.
public static var EWOULDBLOCK: POSIXError { return EAGAIN }
/// Operation now in progress.
case EINPROGRESS = 36
/// Operation already in progress.
case EALREADY = 37
/// ipc/network software -- argument errors.
/// Socket operation on non-socket.
case ENOTSOCK = 38
/// Destination address required.
case EDESTADDRREQ = 39
/// Message too long.
case EMSGSIZE = 40
/// Protocol wrong type for socket.
case EPROTOTYPE = 41
/// Protocol not available.
case ENOPROTOOPT = 42
/// Protocol not supported.
case EPROTONOSUPPORT = 43
/// Socket type not supported.
case ESOCKTNOSUPPORT = 44
/// Operation not supported.
case ENOTSUP = 45
/// Protocol family not supported.
case EPFNOSUPPORT = 46
/// Address family not supported by protocol family.
case EAFNOSUPPORT = 47
/// Address already in use.
case EADDRINUSE = 48
/// Can't assign requested address.
case EADDRNOTAVAIL = 49
/// ipc/network software -- operational errors
/// Network is down.
case ENETDOWN = 50
/// Network is unreachable.
case ENETUNREACH = 51
/// Network dropped connection on reset.
case ENETRESET = 52
/// Software caused connection abort.
case ECONNABORTED = 53
/// Connection reset by peer.
case ECONNRESET = 54
/// No buffer space available.
case ENOBUFS = 55
/// Socket is already connected.
case EISCONN = 56
/// Socket is not connected.
case ENOTCONN = 57
/// Can't send after socket shutdown.
case ESHUTDOWN = 58
/// Too many references: can't splice.
case ETOOMANYREFS = 59
/// Operation timed out.
case ETIMEDOUT = 60
/// Connection refused.
case ECONNREFUSED = 61
/// Too many levels of symbolic links.
case ELOOP = 62
/// File name too long.
case ENAMETOOLONG = 63
/// Host is down.
case EHOSTDOWN = 64
/// No route to host.
case EHOSTUNREACH = 65
/// Directory not empty.
case ENOTEMPTY = 66
/// quotas & mush.
/// Too many processes.
case EPROCLIM = 67
/// Too many users.
case EUSERS = 68
/// Disc quota exceeded.
case EDQUOT = 69
/// Network File System.
/// Stale NFS file handle.
case ESTALE = 70
/// Too many levels of remote in path.
case EREMOTE = 71
/// RPC struct is bad.
case EBADRPC = 72
/// RPC version wrong.
case ERPCMISMATCH = 73
/// RPC prog. not avail.
case EPROGUNAVAIL = 74
/// Program version wrong.
case EPROGMISMATCH = 75
/// Bad procedure for program.
case EPROCUNAVAIL = 76
/// No locks available.
case ENOLCK = 77
/// Function not implemented.
case ENOSYS = 78
/// Inappropriate file type or format.
case EFTYPE = 79
/// Authentication error.
case EAUTH = 80
/// Need authenticator.
case ENEEDAUTH = 81
/// Intelligent device errors.
/// Device power is off.
case EPWROFF = 82
/// Device error, e.g. paper out.
case EDEVERR = 83
/// Value too large to be stored in data type.
case EOVERFLOW = 84
/// Program loading errors.
/// Bad executable.
case EBADEXEC = 85
/// Bad CPU type in executable.
case EBADARCH = 86
/// Shared library version mismatch.
case ESHLIBVERS = 87
/// Malformed Macho file.
case EBADMACHO = 88
/// Operation canceled.
case ECANCELED = 89
/// Identifier removed.
case EIDRM = 90
/// No message of desired type.
case ENOMSG = 91
/// Illegal byte sequence.
case EILSEQ = 92
/// Attribute not found.
case ENOATTR = 93
/// Bad message.
case EBADMSG = 94
/// Reserved.
case EMULTIHOP = 95
/// No message available on STREAM.
case ENODATA = 96
/// Reserved.
case ENOLINK = 97
/// No STREAM resources.
case ENOSR = 98
/// Not a STREAM.
case ENOSTR = 99
/// Protocol error.
case EPROTO = 100
/// STREAM ioctl timeout.
case ETIME = 101
/// No such policy registered.
case ENOPOLICY = 103
/// State not recoverable.
case ENOTRECOVERABLE = 104
/// Previous owner died.
case EOWNERDEAD = 105
/// Interface output queue is full.
case EQFULL = 106
/// Must be equal largest errno.
public static var ELAST: POSIXError { return EQFULL }
// FIXME: EOPNOTSUPP has different values depending on __DARWIN_UNIX03 and
// KERNEL.
}
#endif // os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
|
//
// Word+Creation.swift
// Translator
//
// Created by Dmitry Melnikov on 27/06/2019.
// Copyright © 2019 Дмитрий Мельников. All rights reserved.
//
import CoreData
extension Word {
/// Convenient alternative of init by create or update pattern
static func create(text: String, context: NSManagedObjectContext) -> Word? {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Word")
let predicate = NSPredicate(format: "id=%@", text)
fetchRequest.predicate = predicate
guard let fetchRequestResults = try? context.fetch(fetchRequest),
let requestResults = fetchRequestResults as? [Word] else { return nil }
if requestResults.isEmpty {
let word = NSEntityDescription.insertNewObject(forEntityName: "Word", into: context) as? Word
word?.id = text
return word
} else {
return requestResults.first
}
}
// MARK: - unwrapped properties for avoid "if let overhead"
var unwrappedId: String {
return id ?? "There is no value for id field"
}
var translations: Set<Translation> {
let translationsAray = translation?.compactMap { element -> Translation? in
return element as? Translation
}
guard let translation = translationsAray else {
NSLog("There is no Translation value for Word entity")
return []
}
return Set(translation)
}
}
|
//
// FirstViewController.swift
// JLY
//
// Created by Rui Zheng on 2014-10-17.
// Copyright (c) 2014 Rui Zheng. All rights reserved.
//
import UIKit
import CoreLocation
let NavigationBarHeight=44, StatusBarHeight=20, SearchBarHeight=44
class MapViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {
var gmaps: GMSMapView?
let locationManager = CLLocationManager()
@IBOutlet weak var mapViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mapViewContainer.hidden=true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//Move camera to predefined location
var target: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 51.6, longitude: 17.2)
var camera: GMSCameraPosition = GMSCameraPosition(target: target, zoom: 6, bearing: 0, viewingAngle: 0)
var container:CGRect?=CGRectMake(0, CGFloat(NavigationBarHeight+SearchBarHeight), self.view.bounds.width, self.view.bounds.height-super.tabBarController!.tabBar.bounds.height-CGFloat(NavigationBarHeight+SearchBarHeight))
container=self.mapViewContainer.bounds
gmaps = GMSMapView.mapWithFrame(container!, camera: camera)
if let map = gmaps? {
map.myLocationEnabled = true
map.camera = camera
map.delegate = self
self.mapViewContainer.addSubview(map)
self.mapViewContainer.hidden=false
}
//get the current location and display
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println("Succeed: ")
var current_location: CLLocation?=locations[0] as? CLLocation
if let current_cordinate = (current_location!.coordinate) as CLLocationCoordinate2D?{
self.updateGoogleMapView(current_cordinate)
}
locationManager.stopUpdatingLocation()
}
func updateGoogleMapView(target: CLLocationCoordinate2D!)->Bool{
if let camera: GMSCameraPosition = GMSCameraPosition(target: target, zoom: 13, bearing: 0, viewingAngle: 0) as GMSCameraPosition?{
self.gmaps?.clear()
self.gmaps?.moveCamera(GMSCameraUpdate.setCamera(camera))
if let marker = GMSMarker() as GMSMarker?{
marker.position=target
marker.appearAnimation=kGMSMarkerAnimationPop
marker.map=self.gmaps
}
return true
}else{
return false
}
}
func mapView(mapView: GMSMapView!, didTapMarker marker: GMSMarker!) -> Bool {
self.performSegueWithIdentifier("ToMarkerDetailSegue", sender: marker)
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier=="ToMarkerDetailSegue"{
var dest=segue.destinationViewController as MarkerDetailViewController
dest.marker=sender as GMSMarker
}
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error while updating location " + error.localizedDescription)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// OAuthViewController.swift
// 小峰微博
//
// Created by apple on 17/10/19.
// Copyright © 2017年 Student. All rights reserved.
//
import UIKit
class OAuthViewController: UIViewController {
public lazy var webView=UIWebView()
@objc
public func close()
{
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
view=webView
webView.delegate=self
title="登陆新浪微博"
navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OAuthViewController.close))
self.webView.loadRequest(URLRequest(url:NetworkTools.sharedTools.OAuthURL))
navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(OAuthViewController.autoFill))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc
public func autoFill()
{
let js="document.getElementById('userId').value='1195745286@qq.com';"+"document.getElementById('passwd').value='619375'"
webView.stringByEvaluatingJavaScript(from: js)
}
}
extension OAuthViewController:UIWebViewDelegate
{
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
guard let url=request.url,url.host == "www.baidu.com" else
{
return true
}
guard let query=url.query , query.hasPrefix("code=") else
{
print("取消授权")
return false
}
let code=query.substring(from: "code=".endIndex)
print("授权码是"+code)
UserAccountViewModel.sharedUserAccount.loadAccessToken(code: code){
(isSuccessed)->() in
if !isSuccessed
{
return
}
print("成功了")
self.dismiss(animated: false){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBSwitchRootViewControllerNotification), object: "welcome")
}
}
return false
}
}
|
import Foundation
/// An object representing a schema that describes the structure and syntax of the header.
/// Get more info: https://swagger.io/specification/#headerObject
public struct SpecHeaderSchema: Codable, Equatable, Changeable {
// MARK: - Nested Types
private enum CodingKeys: String, CodingKey {
case schema
case isExploded = "explode"
case examples
case example
}
// MARK: - Instance Properties
/// The schema defining the type used for the header.
public var schema: SpecComponent<SpecSchema>
/// When this is `true`, header values of type `array` or `object` generate separate parameters
/// for each value of the array or key-value pair of the map.
/// For other types of headers this property has no effect.
/// Default value is `false`.
public var isExploded: Bool?
/// Examples of the media type.
/// Each example object should match the media type and specified schema.
/// The `examples` field is mutually exclusive of the `example` field.
/// Furthermore, if referencing a `schema` which contains an example,
/// the `examples` value shall override the example provided by the schema.
public var examples: [String: SpecComponent<SpecExample>]?
/// Example of the media type.
/// The example should match the specified schema and encoding properties if present.
/// The `example` field is mutually exclusive of the `examples` field.
/// Furthermore, if referencing a `schema` which contains an example,
/// the `example` value shall override the example provided by the schema.
/// To represent examples of media types that cannot naturally be represented in JSON or YAML,
/// a string value can contain the example with escaping where necessary.
public var example: SpecEmbeddedExample?
// MARK: - Initializers
/// Creates a new instance with the provided values.
public init(
schema: SpecComponent<SpecSchema>,
isExploded: Bool? = nil,
examples: [String: SpecComponent<SpecExample>]? = nil,
example: SpecEmbeddedExample? = nil
) {
self.schema = schema
self.isExploded = isExploded
self.examples = examples
self.example = example
}
}
|
//
// DetailPatientGuideCell.swift
// HISmartPhone
//
// Created by DINH TRIEU on 12/26/17.
// Copyright © 2017 MACOS. All rights reserved.
//
import UIKit
class DetailPatientGuideCell: BaseTableViewCell {
weak var diagnose: Diagnose? {
didSet {
self.contentLabel1.text = self.diagnose?.solution
self.contentLabel2.text = self.diagnose?.solve
self.contentLabel3.text = self.diagnose?.advice
}
}
//MARK: UIControl
private let titleLabel1: UILabel = {
let label = UILabel()
label.text = "Hướng xử lý:"
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize, weight: UIFont.Weight.medium)
return label
}()
private let contentLabel1: UILabel = {
let label = UILabel()
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
label.numberOfLines = 0
return label
}()
private let titleLabel2: UILabel = {
let label = UILabel()
label.text = "Xử lí:"
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize, weight: UIFont.Weight.medium)
return label
}()
private let contentLabel2: UILabel = {
let label = UILabel()
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
label.numberOfLines = 0
return label
}()
private let titleLabel3: UILabel = {
let label = UILabel()
label.text = "Lời dặn:"
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize, weight: UIFont.Weight.medium)
return label
}()
private let contentLabel3: UILabel = {
let label = UILabel()
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
label.numberOfLines = 0
return label
}()
//MARK: Initialize
override func setupView() {
self.setupViewTitle1()
self.setupViewContentLabel1()
self.setupViewTitleLabel2()
self.setupViewContentLabel2()
self.setupViewTitleLabel3()
self.setupViewContentLabel3()
}
//MARK: Feature
//MARK: SetupView
private func setupViewTitle1() {
self.addSubview(self.titleLabel1)
if #available(iOS 11, *) {
self.titleLabel1.snp.makeConstraints { (make) in
make.left.equalTo(self.safeAreaLayoutGuide)
.offset(Dimension.shared.normalHorizontalMargin)
make.top.equalToSuperview().offset(Dimension.shared.largeVerticalMargin)
}
} else {
self.titleLabel1.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(Dimension.shared.normalHorizontalMargin)
make.top.equalToSuperview().offset(Dimension.shared.largeVerticalMargin)
}
}
}
private func setupViewContentLabel1() {
self.addSubview(self.contentLabel1)
if #available(iOS 11, *) {
self.contentLabel1.snp.makeConstraints { (make) in
make.left.equalTo(self.safeAreaLayoutGuide).offset(132 * Dimension.shared.widthScale)
make.right.equalToSuperview().offset(-Dimension.shared.mediumHorizontalMargin)
make.top.equalTo(self.titleLabel1)
}
} else {
self.contentLabel1.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(132 * Dimension.shared.widthScale)
make.right.equalToSuperview().offset(-Dimension.shared.mediumHorizontalMargin)
make.top.equalTo(self.titleLabel1)
}
}
}
private func setupViewTitleLabel2() {
self.addSubview(self.titleLabel2)
self.titleLabel2.snp.makeConstraints { (make) in
make.left.equalTo(self.titleLabel1)
make.top.equalTo(self.contentLabel1.snp.bottom).offset(Dimension.shared.largeVerticalMargin)
}
}
private func setupViewContentLabel2() {
self.addSubview(self.contentLabel2)
self.contentLabel2.snp.makeConstraints { (make) in
make.left.equalTo(self.contentLabel1)
make.top.equalTo(self.titleLabel2)
make.right.equalToSuperview().offset(-Dimension.shared.mediumHorizontalMargin)
}
}
private func setupViewTitleLabel3() {
self.addSubview(self.titleLabel3)
self.titleLabel3.snp.makeConstraints { (make) in
make.left.equalTo(self.titleLabel1)
make.top.equalTo(self.contentLabel2.snp.bottom).offset(Dimension.shared.largeVerticalMargin)
}
}
private func setupViewContentLabel3() {
self.addSubview(self.contentLabel3)
self.contentLabel3.snp.makeConstraints { (make) in
make.left.equalTo(self.contentLabel2)
make.top.equalTo(self.titleLabel3)
make.right.equalToSuperview().offset(-Dimension.shared.mediumHorizontalMargin)
make.bottom.equalToSuperview().offset(-Dimension.shared.largeVerticalMargin)
}
}
}
|
//
// NODMaterial.swift
// NuoDunProject
//
// Created by lxzhh on 15/7/14.
// Copyright (c) 2015年 lxzhh. All rights reserved.
//
import UIKit
class NODMaterial: NODObject {
var materialName : String?
var materialID : String?
var materialCount : Int?
required init?(_ map: Map) {
super.init()
mapping(map)
}
// Mappable
override func mapping(map: Map) {
materialName <- map["CLMC"]
materialID <- map["CLBM"]
materialCount <- map["SL"]
}
override var description: String {
get{
return "materialName:\(materialName) \n materialID:\(materialID)"
}
}
override class func saveKey() -> String?{
return "NODMaterial"
}
override class func loadJsonRootKey() -> String?{
return "CL"
}
}
|
//
// Ship.swift
// Battleship
//
// Created by Gacheru, Emmanuel K on 12/7/18.
// Copyright © 2018 Gacheru, Emmanuel K. All rights reserved.
//
import Foundation
class Ship
{
var size : Int
var positions : [Position]
init(size: Int, positions : [Position])
{
self.size = size;
self.positions = positions;
}
}
|
//
// MapViewController.swift
// College Profile Builder 1
//
// Created by jcysewski on 2/11/16.
// Copyright © 2016 jcysewski. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate
{
@IBOutlet weak var myMapView: MKMapView!
@IBOutlet weak var myTextField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
myLocationManager.delegate = self
myLocationManager.requestAlwaysAuthorization()
myLocationManager.startUpdatingLocation()
myMapView.delegate = self
myMapView.showsUserLocation = true
myMapView.userLocation.title = "My Location"
addPinAnnotation()
}
@IBAction func searchButtonTapped(sender: AnyObject)
{
geoCodeLocation(myTextField.text!)
myTextField.resignFirstResponder() //closes keyboard
}
func displayMap(MyPlaceMark: CLPlacemark) //ClPlaceMark represents placemark data for a geographic location
{
let myLocation = MyPlaceMark
let mySpan = MKCoordinateSpanMake(1.0, 1.0)
let myRegion = MKCoordinateRegionMake((myLocation.location?.coordinate)!, mySpan)
myMapView.setRegion(myRegion, animated: true)
let myPin = MKPointAnnotation()
myPin.coordinate = (myLocation.location?.coordinate)!
myPin.title = MyPlaceMark.name
myMapView.addAnnotation(myPin)
myTextField.text = MyPlaceMark.name
}
func geoCodeLocation(mySearch: String)
{
//Cl GeoCoder provides services for convirting between a coordinate and the user friendly representation
let myGeoCode = CLGeocoder()
myGeoCode.geocodeAddressString(mySearch)
{ (placemarks, error) -> Void in
if error != nil
{
print("error")
}
else
{
self.displayMap((placemarks?.first)!)
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////
let myLocationManager = CLLocationManager()
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
print(myLocationManager.location)
}
func addPinAnnotation()
{
let myCoordinate = CLLocationCoordinate2DMake(42.155275, -88.136782)
let myAnnotation = MKPointAnnotation()
myAnnotation.coordinate = myCoordinate
myAnnotation.title = "Catlow"
myAnnotation.subtitle = "Theater"
myMapView.addAnnotation(myAnnotation)
setCenterOfMap(myCoordinate) //sets on the pin
//setCenterOfMap((myLocationManager.location?.coordinate)!) //sets on location
}
func setCenterOfMap(Location: CLLocationCoordinate2D)
{
let mySpan = MKCoordinateSpan(latitudeDelta: 0.007, longitudeDelta: 0.007)
let myRegion = MKCoordinateRegion(center: Location, span: mySpan)
myMapView.setRegion(myRegion, animated: true)
}
}
|
import UIKit
import AVFoundation
let appDelegateObj = UIApplication.shared.delegate as! AppDelegate
let USERDEFAULT = UserDefaults.standard
class CommonMethods: NSObject {
// MARK:- showAlert Method
static func showAlert(_ messageT:String,title:String,targetViewController: UIViewController){
let alertController = UIAlertController(title: messageT, message: title, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
targetViewController.present(alertController, animated: true, completion: nil)
}
// MARK:- showAlert Method
static func showAlertwithOneAction(_ messageT:String,title:String,targetViewController: UIViewController,okHandler: @escaping ((UIAlertAction?) -> Void)){
let alertController = UIAlertController(title: messageT, message: title, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: okHandler)
alertController.addAction(okAction)
targetViewController.present(alertController, animated: true, completion: nil)
}
// show alert view with Ok and cancel actions
static func showAlertViewWithTwoActions(title alerTitle:String ,message alertMessage:String, preferredStyle style:UIAlertController.Style, okLabel: String, cancelLabel: String, targetViewController: UIViewController,okHandler: ((UIAlertAction?) -> Void)!, cancelHandler: ((UIAlertAction?) -> Void)!){
let alertController = UIAlertController(title: alerTitle, message: alertMessage, preferredStyle: style)
let okAction = UIAlertAction(title: okLabel, style: .default, handler: okHandler)
let cancelAction = UIAlertAction(title: cancelLabel, style: .default,handler: cancelHandler)
cancelAction.setValue(UIColor.red, forKey: "titleTextColor")
// Add Actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present Alert Controller
targetViewController.present(alertController, animated: true, completion: nil)
}
// MARK:- PutShadow Method
static func putShadow(button: UIButton, cornerRadious:Int) {
// button.layer.borderWidth = 1
button.layer.cornerRadius = CGFloat(cornerRadious)
button.layer.shadowOffset = CGSize(width: 1, height: 1)
button.layer.shadowRadius = 6
// button.layer.shadowColor = UIColor.black.cgColor
button.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)
button.layer.shadowOpacity = 0.2
// view.layer.shadowColor = #colorLiteral(red: 0.5607843137, green: 0.5607843137, blue: 0.5607843137, alpha: 1)
button.layer.masksToBounds = true
button.clipsToBounds = false
}
static func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
// static func isValidPassword(testStr:String) -> Bool {
// let regularExpression = "(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,16})$"
// let passwordValidation = NSPredicate.init(format: "SELF MATCHES %@", regularExpression)
// return passwordValidation.evaluate(with: testStr)
// }
static func isValidPassword(testStr:String) -> Bool {
let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[a-z])(?=.*[$@$#!%*?&])[A-Za-z\\d$@$#!%*?&]{8,}")
return passwordTest.evaluate(with: testStr)
}
static func isvalidnumber(value: String) -> Bool {
// let PHONE_REGEX = "^((\\+)|(00))[0-9]{6,14}$"
let PHONE_REGEX = "^[0-9._%+-]{4,15}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
}
extension StringProtocol where Index == String.Index {
var isEmptyField: Bool {
return trimmingCharacters(in: .whitespaces) == ""
}
}
extension String {
func removingWhitespaces() -> String {
return components(separatedBy: .whitespaces).joined()
}
func trim() -> String{
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
var containsSpecialCharacter: Bool {
let regex = ".*[^A-Za-z0-9].*"
let testString = NSPredicate(format:"SELF MATCHES %@", regex)
return testString.evaluate(with: self)
}
}
|
//
// Color.swift
// TinderClone
//
// Created by JD on 20/08/20.
//
import SwiftUI
extension Color {
static let electricPink = Color(UIColor(red: 253/255, green: 17/255, blue: 115/255, alpha: 1.0))
static let gold = Color(UIColor(red: 254/255, green: 129/255, blue: 35/255, alpha: 1.0))
public static var random: Color {
return Color(UIColor(red: CGFloat(drand48()),
green: CGFloat(drand48()),
blue: CGFloat(drand48()), alpha: 1.0))
}
}
|
//
// AppDetailViewController.swift
// assignment
//
// Created by Jae Kyung Lee on 25/04/2018.
// Copyright © 2018 Jae Kyung Lee. All rights reserved.
//
import UIKit
// MARK: - AppDetail Delegate
protocol AppDetailViewDelegate: class {
func downloadScreenShotsFromUrls(urls :[String])
}
class AppDetailViewController: UIViewController {
// MARK: - Types
// Constants for embeded information tableView
private struct Constants {
static let CellHeight: CGFloat = 40
static let SellerName = "판매자"
static let Age = "연령"
static let SellerWebsite = "개발자 웹사이트"
}
// MARK: - Properties
//scroll view
@IBOutlet weak var scrollView: UIScrollView!
//containers
@IBOutlet weak var detailContainer: UIView!
@IBOutlet weak var screenshotsContainer: UIView!
@IBOutlet weak var descriptionContainer: UIView!
@IBOutlet weak var informationTableViewContainer: UIView!
//icon container components
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var appTitle: UILabel!
@IBOutlet weak var company: UILabel!
//scroe
@IBOutlet weak var rating: UILabel!
@IBOutlet weak var userRatingCount: UILabel!
@IBOutlet weak var score: UILabel!
@IBOutlet weak var contentAdvisoryRating: UILabel!
//new feature container
@IBOutlet weak var version: UILabel!
@IBOutlet weak var releaseNotes: UITextView!
@IBOutlet weak var realeaseNoteReadMoreBtn: UIButton!
//description
@IBOutlet weak var descriptionView: UITextView!
@IBOutlet weak var readMoreBtn: UIButton!
@IBOutlet weak var information: UITableView!
weak var delegate: AppDetailViewDelegate?
//expanded views gap
var gaps = [CGFloat(0), CGFloat(0)]
//to expand view store original heights
var descriptionViewHeight: CGFloat?
var releaseNotesHeight: CGFloat?
// embeded info tableview datasource
lazy var informationDataSource: EmbededInformationDatasource = {
return EmbededInformationDatasource(info: [])
}()
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
initialize()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
//delete icon image when navigate away
icon.image = nil
}
// MARK: - IBAction
@IBAction func releaseNoteReadMoreBtnPressed(_ sender: Any) {
expandView(view: self.releaseNotes, originalHeight: releaseNotesHeight, button: realeaseNoteReadMoreBtn)
}
// read more button for description view
@IBAction func descriptionViewReadMoreBtnPressed(_ sender: Any) {
expandView(view: descriptionView, originalHeight: descriptionViewHeight, button: readMoreBtn)
}
// MARK: - Main
func initialize() {
//set app title multiline available
setTitleMultilne()
//store original view height for expanding views
storeDescriptionViewHeight()
storeReleaseNotesViewHeight()
}
func configure(detail: AppDetail?, index: Int) {
guard let detail = detail else {
return
}
let viewModel: DetailViewModel = DetailViewModel(detail: detail, index: index)
//download icon image
Utils.downloadImage(imageUrlStr: viewModel.iconUrl, completion: { (image, error) in
if error != nil {
print(error.debugDescription)
}
DispatchQueue.main.async {
self.icon.image = image
}
})
appTitle.text = viewModel.appTitle
company.text = viewModel.company
rating.text = viewModel.rating
userRatingCount.text = "\(viewModel.userRatingCount)개의 평가"
score.text = "#\(viewModel.score)"
contentAdvisoryRating.text = viewModel.contentAdvisoryRating
version.text = "버전 \(viewModel.version)"
releaseNotes.text = viewModel.releaseNotes
descriptionView.text = viewModel.description
releaseNotes.isScrollEnabled = false
descriptionView.isScrollEnabled = false
//configure embeded information tableview
information.rowHeight = Constants.CellHeight
information.delegate = informationDataSource
information.dataSource = informationDataSource
informationDataSource.updateInformation(info: [ EmbededInfo(key: Constants.SellerName , value: viewModel.company),
EmbededInfo(key: Constants.Age , value: viewModel.contentAdvisoryRating),
EmbededInfo(key: Constants.SellerWebsite , value: viewModel.sellerUrl)])
information.reloadData()
//download screenShots
delegate?.downloadScreenShotsFromUrls(urls: viewModel.screenshots)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "embededSegue" {
let embededViewController = segue.destination as! EmbededScrollViewController
delegate = embededViewController
}
}
// MARK: - Helpers
func setTitleMultilne() {
appTitle.lineBreakMode = .byWordWrapping
appTitle.numberOfLines = 0
}
func storeDescriptionViewHeight() {
descriptionViewHeight = descriptionView.frame.height
}
func storeReleaseNotesViewHeight() {
releaseNotesHeight = releaseNotes.frame.height
}
func expandView(view: UIView, originalHeight: CGFloat?, button: UIButton) {
guard let origin = originalHeight else { return }
//change view constraints
view.translatesAutoresizingMaskIntoConstraints = false
view.sizeToFit()
//calculate added height
guard let gap = calHeightGap(origin: origin, new: view.frame.height) else {
button.isHidden = true
return
}
//move below views
switch view {
case releaseNotes:
gaps[0] = gap
//move below screenshots, description to down
let screenshots = screenshotsContainer.frame
screenshotsContainer.frame = CGRect(x: screenshots.origin.x, y: screenshots.origin.y + gap, width: screenshots.width, height: screenshots.height)
let description = descriptionContainer.frame
descriptionContainer.frame = CGRect(x: description.origin.x, y: description.origin.y + gap, width: description.width, height: description.height)
break
case descriptionView:
gaps[1] = gap
//move below information tableview to down
let infoFrame = informationTableViewContainer.frame
informationTableViewContainer.frame = CGRect(x: infoFrame.origin.x, y: infoFrame.origin.y + gap, width: infoFrame.width, height: infoFrame.height)
break
default:
return
}
//stretch detail container - all expanded gaps added
let container = detailContainer.frame
detailContainer.frame = CGRect(x: container.origin.x, y: container.origin.y, width: container.width, height: container.height + gaps[0] + gaps[1])
//reset scrollView size
var insideContentRect = CGRect.zero
for view in scrollView.subviews {
insideContentRect = insideContentRect.union(view.frame)
}
scrollView.contentSize = insideContentRect.size
//remove button
button.isHidden = true
}
func calHeightGap(origin: CGFloat, new: CGFloat) -> CGFloat? {
if new > origin {
return new - origin
}
return nil
}
}
extension AppDetailViewController: UIScrollViewDelegate {
}
|
//
// CustomAlertController.swift
// Lenna
//
// Created by Agustiar on 5/14/19.
// Copyright © 2019 sdtech. All rights reserved.
//
import UIKit
protocol confirmMessageDelegate {
func confirmdelegate(newMessage: String)
}
class ConfirmationCustomAlertController: UIViewController {
@IBOutlet weak var confirmationAlertView: UIView!
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var iconAlert: UIImageView!
@IBOutlet weak var titleAlert: UILabel!
@IBOutlet weak var messageAlert: UILabel!
var titleText = String()
var messageText = String()
var buttonAction: (() -> Void)?
var alertHeader = String()
var confirmDelegate : confirmMessageDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setupView()
headerView.layer.cornerRadius = 10
headerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
confirmationAlertView.layer.cornerRadius = 10
round()
}
func round(){
}
func setupView(){
titleAlert.text = titleText
messageAlert.text = messageText
headerView.backgroundColor = UIColor.init(named: alertHeader)
}
@IBAction func confirmationYes(_ sender: UIButton) {
confirmDelegate?.confirmdelegate(newMessage: "Ya")
buttonAction?()
dismiss(animated: true, completion: nil)
}
@IBAction func confirmationNo(_ sender: UIButton) {
confirmDelegate?.confirmdelegate(newMessage: "Tidak")
dismiss(animated: true, completion: nil)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.