text
stringlengths 8
1.32M
|
|---|
//
// BluetoothColorsExtension.swift
// Blade Runner
//
// Created by Alfred Ly on 5/18/17.
// Copyright © 2017 Apple Inc. All rights reserved.
//
import UIKit
extension UIColor{
class func bluetoothBlueColor() -> UIColor{
return UIColor(red: 26.0/255.0, green: 118.0/255.0, blue: 245.0/255.0, alpha: 1.0)
}
class func bluetoothGreenColor() -> UIColor{
return UIColor(red: 0.0/255.0, green: 212.0/255.0, blue: 142.0/255.0, alpha: 1.0)
}
class func bluetoothRedColor() -> UIColor{
return UIColor(red: 246.0/255.0, green: 65.0/255.0, blue: 56.0/255.0, alpha: 1.0)
}
class func bluetoothOrangeColor() -> UIColor{
return UIColor(red: 255.0/255.0, green: 128.0/255.0, blue: 0/255.0, alpha: 1.0)
}
}
|
//
// FoodChainCollectionViewCell.swift
// Food Aggregator
//
// Created by Chashmeet on 12/10/18.
// Copyright © 2018 Chashmeet Singh. All rights reserved.
//
import UIKit
class FoodChainCollectionViewCell: BaseCollectionViewCell, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var navigationController: UINavigationController!
var foodCourt: FoodCourt! {
didSet {
foodChainLabel.text = foodCourt.address
vendorCollectionView.reloadData()
}
}
let foodChainLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.font = UIFont.boldSystemFont(ofSize: 18)
return label
}()
lazy var vendorCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1.0)
collectionView.register(VendorCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.showsHorizontalScrollIndicator = false
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
override func setupViews() {
super.setupViews()
setupCell()
}
func setupCell() {
backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1.0)
addSubview(foodChainLabel)
addConstraintsWithFormat(format: "H:|-4-[v0]-4-|", views: foodChainLabel)
addSubview(vendorCollectionView)
addConstraintsWithFormat(format: "H:|-4-[v0]-4-|", views: vendorCollectionView)
addConstraintsWithFormat(format: "V:|-4-[v0(32)]-8-[v1]-4-|", views: foodChainLabel, vendorCollectionView)
layer.cornerRadius = 8
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return foodCourt.restaurants.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! VendorCollectionViewCell
let restaurant = foodCourt.restaurants[indexPath.item]
cell.imageView.image = UIImage(named: restaurant.name)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: self.vendorCollectionView.frame.height, height: self.vendorCollectionView.frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 8
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = FoodChainViewController()
vc.foodCourt = foodCourt
self.navigationController.pushViewController(vc, animated: true)
}
}
|
//
// GLurl.swift
// ChaosKit
//
// Created by Fu Lam Diep on 14.06.15.
// Copyright (c) 2015 Fu Lam Diep. All rights reserved.
//
import Foundation
/*
|--------------------------------------------------------------------------
| Location Selector
|--------------------------------------------------------------------------
*/
/**
This struct is used to select attribute locations from a GLProgram object
anonymously.
*/
public struct GLurl : CustomStringConvertible, Hashable, StringLiteralConvertible, ArrayLiteralConvertible {
private static var _delimiter : Character = "."
/// The attribute type
private let _domains : [String]
/// String representation of the url
public var description : String {
get {return _domains.joinWithSeparator(String(GLurl._delimiter))}
}
/// Hashvalue representation
public var hashValue: Int {get{return description.hashValue}}
/**
Initializes the url with passed domains, where index 0 is top level
- parameter domains:
*/
public init (_ domains: [String]) {
_domains = domains
}
/**
Initializes the url with given type and domain
- parameter type: The type name for the anonymous attribute location
- parameter domain: The domain to specify the context
*/
public init (arrayLiteral domains: String...) {
self.init(domains)
}
/**
Initializes the url with given domain
- parameter domain:
- parameter subdomain:
- parameter subdomains:
*/
public init (_ domain: String, _ subdomain: GLAttributeType, _ subdomains: String...) {
self.init([domain, subdomain.rawValue] + subdomains)
}
/**
Initializes the url with given domain
- parameter domain:
- parameter subdomain:
- parameter subdomains:
*/
public init (_ domain: GLUrlDomain, _ subdomain: GLAttributeType, _ subdomains: String...) {
self.init([domain.rawValue, subdomain.rawValue] + subdomains)
}
/**
Initializes the url with default top level domain
- parameter subdomain:
- parameter subdomains:
*/
public init (_ subdomain: GLAttributeType, _ subdomains: String...) {
self.init([GLUrlDomain.Default.rawValue, subdomain.rawValue] + subdomains)
}
/**
Initializes the url with given domain
- parameter domain:
- parameter subdomain:
- parameter subdomains:
*/
public init (_ domain: String, _ subdomain: GLUniformType, _ subdomains: String...) {
self.init([domain, subdomain.rawValue] + subdomains)
}
/**
Initializes the url with given domain
- parameter domain:
- parameter subdomain:
- parameter subdomains:
*/
public init (_ domain: GLUrlDomain, _ subdomain: GLUniformType, _ subdomains: String...) {
self.init([domain.rawValue, subdomain.rawValue] + subdomains)
}
/**
Initializes the url with default top level domain
- parameter subdomain:
- parameter subdomains:
*/
public init (_ subdomain: GLUniformType, _ subdomains: String...) {
self.init([GLUrlDomain.Default.rawValue, subdomain.rawValue] + subdomains)
}
/**
Initalizer to assign a selecotr variable with a string literal
- parameter stringLiteral:
*/
public init(stringLiteral value: String) {
self.init(value.characters.split(1, allowEmptySlices: false, isSeparator: {(value: Character) -> Bool in return value == GLurl._delimiter}).map { String($0) })
}
/**
Initalizer to assign a selecotr variable with a string literal
- parameter stringLiteral:
*/
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
/**
Initalizer to assign a selecotr variable with a string literal
- parameter stringLiteral:
*/
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
}
/**
Compare function for Hashable/Equatable protocol
- parameter left:
- parameter right:
:return: Returns true when the hashables has the same values
*/
public func ==(left: GLurl, right: GLurl) -> Bool {
return left.description == right.description
}
public enum GLUrlDomain : String {
case Default = "default"
case Vertex = "vertex"
case Model = "model"
case Normal = "normal"
case Camera = "camera"
case Surface = "surface"
case Light = "light"
case ColorMap = "colormap"
case DiffuseMap = "diffusemap"
case NormalMap = "normalmap"
case BumpMap = "bumpmap"
case HeightMap = "heightmap"
case DisplacementMap = "displacementmap"
case SpecularMap = "specularmap"
case GlowMap = "glowmap"
}
public enum GLAttributeType : String {
case Position = "position"
case Normal = "normal"
case Color = "color"
case TexCoord = "texcoord"
case Tangent = "tangent"
case Bitangent = "bitangent"
}
public enum GLUniformType : String {
case Transformation = "transformation"
case Projection = "projection"
case Sampler = "sampler"
case Enabled = "enabled"
case AmbientCoefficient = "ambientcoefficient"
case Intensity = "intensity"
case PhongExp = "phongexp"
case Direction = "direction"
case Reflection = "reflection"
case Enable = "enable"
}
public let GL_VPOSITION : String = "vertex.position"
public let GL_VNORMAL : String = "vertex.normal"
public let GL_VCOLOR : String = "vertex.color"
public let GL_VREFLECTION : String = "vertex.reflection"
public let GLUrlVertexPosition : GLurl = GLurl(.Vertex, .Position)
public let GLUrlVertexNormal : GLurl = GLurl(.Vertex, .Normal)
public let GLUrlSurfaceColor : GLurl = GLurl(.Vertex, .Color)
public let GLUrlSurfaceReflection : GLurl = GLurl(.Surface, .Reflection)
public let GLUrlColorMapTexCoord : GLurl = GLurl(.ColorMap, .TexCoord)
public let GLUrlDiffuseMapTexCoord : GLurl = GLurl(.DiffuseMap, .TexCoord)
public let GLUrlNormalMapTexCoord : GLurl = GLurl(.NormalMap, .TexCoord)
public let GLUrlBumpMapTexCoord : GLurl = GLurl(.BumpMap, .TexCoord)
public let GLUrlHeightMapTexCoord : GLurl = GLurl(.HeightMap, .TexCoord)
public let GLUrlDisplacementMapTexCoord : GLurl = GLurl(.DisplacementMap, .TexCoord)
public let GLUrlSpecularMapTexCoord : GLurl = GLurl(.SpecularMap, .TexCoord)
public let GLUrlGlowMapTexCoord : GLurl = GLurl(.GlowMap, .TexCoord)
public let GLUrlColorMapTangent : GLurl = GLurl(.ColorMap, .Tangent)
public let GLUrlDiffuseMapTangent : GLurl = GLurl(.DiffuseMap, .Tangent)
public let GLUrlNormalMapTangent : GLurl = GLurl(.NormalMap, .Tangent)
public let GLUrlBumpMapTangent : GLurl = GLurl(.BumpMap, .Tangent)
public let GLUrlHeightMapTangent : GLurl = GLurl(.HeightMap, .Tangent)
public let GLUrlDisplacementMapTangent : GLurl = GLurl(.DisplacementMap, .Tangent)
public let GLUrlSpecularMapTangent : GLurl = GLurl(.SpecularMap, .Tangent)
public let GLUrlGlowMapTangent : GLurl = GLurl(.GlowMap, .Tangent)
public let GLUrlColorMapBitangent : GLurl = GLurl(.ColorMap, .Bitangent)
public let GLUrlDiffuseMapBitangent : GLurl = GLurl(.DiffuseMap, .Bitangent)
public let GLUrlNormalMapBitangent : GLurl = GLurl(.NormalMap, .Bitangent)
public let GLUrlBumpMapBitangent : GLurl = GLurl(.BumpMap, .Bitangent)
public let GLUrlHeightMapBitangent : GLurl = GLurl(.HeightMap, .Bitangent)
public let GLUrlDisplacementMapBitangent : GLurl = GLurl(.DisplacementMap, .Bitangent)
public let GLUrlSpecularMapBitangent : GLurl = GLurl(.SpecularMap, .Bitangent)
public let GLUrlGlowMapBitangent : GLurl = GLurl(.GlowMap, .Bitangent)
public let GLUrlColorMapSampler : GLurl = GLurl(.ColorMap, .Sampler)
public let GLUrlDiffuseMapSampler : GLurl = GLurl(.DiffuseMap, .Sampler)
public let GLUrlNormalMapSampler : GLurl = GLurl(.NormalMap, .Sampler)
public let GLUrlBumpMapSampler : GLurl = GLurl(.BumpMap, .Sampler)
public let GLUrlHeightMapSampler : GLurl = GLurl(.HeightMap, .Sampler)
public let GLUrlDisplacementMapSampler : GLurl = GLurl(.DisplacementMap, .Sampler)
public let GLUrlSpecularMapSampler : GLurl = GLurl(.SpecularMap, .Sampler)
public let GLUrlGlowMapSampler : GLurl = GLurl(.GlowMap, .Sampler)
public let GLUrlColorMapEnabled : GLurl = GLurl(.ColorMap, .Enabled)
public let GLUrlDiffuseMapEnabled : GLurl = GLurl(.DiffuseMap, .Enabled)
public let GLUrlNormalMapEnabled : GLurl = GLurl(.NormalMap, .Enabled)
public let GLUrlBumpMapEnabled : GLurl = GLurl(.BumpMap, .Enabled)
public let GLUrlHeightMapEnabled : GLurl = GLurl(.HeightMap, .Enabled)
public let GLUrlDisplacementMapEnabled : GLurl = GLurl(.DisplacementMap, .Enabled)
public let GLUrlSpecularMapEnabled : GLurl = GLurl(.SpecularMap, .Enabled)
public let GLUrlGlowMapEnabled : GLurl = GLurl(.GlowMap, .Enabled)
public let GLUrlLightIntensity : GLurl = GLurl(.Light, .Intensity)
public let GLUrlLightPosition : GLurl = GLurl(.Light, .Position)
public let GLUrlLightAmbientCoefficient : GLurl = GLurl(.Light, .AmbientCoefficient)
public let GLUrlLightSpecularEnable : GLurl = GLurl(.Light, .Specular, .Enabled)
public let GLUrlLightPhongExp : GLurl = GLurl(.Light, .PhongExp)
public let GLUrlModelViewMatrix : GLurl = GLurl(.Model, .Transformation)
public let GLUrlNormalViewMatrix : GLurl = GLurl(.Normal, .Transformation)
public let GLUrlCameraViewMatrix : GLurl = GLurl(.Camera, .Transformation)
public let GLUrlCameraProjection : GLurl = GLurl(.Camera, .Projection)
public let GLUrlCameraPosition : GLurl = GLurl(.Camera, .Position)
public let GLUrlCameraDirection : GLurl = GLurl(.Camera, .Direction)
|
import UIKit
import Flutter
import HealthKit
import UserNotificationsUI
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
var healthStore: HKHealthStore?
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let flutterViewController = self.window.rootViewController as! FlutterViewController
let storeMindfulMinutesChannel = FlutterMethodChannel(name: "de.sventropy/mindfulness-minutes", binaryMessenger: flutterViewController.binaryMessenger)
let showNotificationChannel = FlutterMethodChannel(name: "de.sventropy/notification-service", binaryMessenger: flutterViewController.binaryMessenger)
self.ensureHealthKitAuthorization()
self.ensureNotificationAuthorization()
storeMindfulMinutesChannel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
print("Called storeMindfulMinutes channel")
guard call.method == "storeMindfulMinutes" else {
result(FlutterMethodNotImplemented)
return
}
print("Method signature matches")
let minutes = call.arguments as! Int32
print("Parameter matches")
self.storeMindfulMinutes(minutes: minutes, result: result)
}
showNotificationChannel.setMethodCallHandler {
(call: FlutterMethodCall, result: @escaping FlutterResult) in
print("Called showNotification channel")
guard call.method == "showNotification" else {
result(FlutterMethodNotImplemented)
return
}
print("Method signature matches")
let args = call.arguments as! Array<Any>
let title = args[0] as! String
let message = args[1] as! String
print("Parameters match")
self.sendNotification(title: title, message: message, result: result)
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
func ensureHealthKitAuthorization() {
// Check HK availability
if !HKHealthStore.isHealthDataAvailable() {
return
}
// Initialize HK wrapper
healthStore = HKHealthStore()
// Request proper permissions for HK data access
let allTypes = Set([HKObjectType.categoryType(forIdentifier: .mindfulSession)!])
healthStore!.requestAuthorization(toShare: allTypes, read: nil) { (success, error) in
if !success {
print("HealthKit authorization not granted. Error: \(String(describing: error))")
}
}
}
func storeMindfulMinutes(minutes: Int32, result: @escaping FlutterResult) {
let endDate = Date()
let startDate = Calendar.current.date(byAdding: .minute, value: Int(minutes * -1), to: endDate)!
let mindfulSessionTime = HKCategorySample(type: HKObjectType.categoryType(forIdentifier: .mindfulSession)! , value: HKCategoryValue.notApplicable.rawValue, start: startDate , end: endDate)
print("Storing mindful session time: '\(minutes)' minutes")
self.healthStore!.save(mindfulSessionTime, withCompletion: { (success, error) in
if !success {
result(FlutterError(code: "UNAVAILABLE",
message: "Error storing mindfulness time",
details: "\(String(describing: error?.localizedDescription))"))
} else {
result(true)
}
})
}
func ensureNotificationAuthorization() {
UNUserNotificationCenter.current().requestAuthorization(
options: [[.alert, .sound, .badge]],
completionHandler: {
(granted, error) in
if !granted {
print("NotificationCenter authorization not granted. Error: \(String(describing: error))")
} else {
UNUserNotificationCenter.current().delegate = self
}
})
}
func sendNotification(title: String, message: String, result: @escaping FlutterResult) {
let content = UNMutableNotificationContent()
content.title = title
content.body = message
content.badge = 1
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1,
repeats: false)
let requestIdentifier = "de.sventropy.spiramentum2.notification"
let request = UNNotificationRequest(identifier: requestIdentifier,
content: content, trigger: trigger)
UNUserNotificationCenter.current().add(
request,
withCompletionHandler: { (error) in
if error != nil {
result(FlutterError(code: "ERROR",
message: "UserNotificationCenter add error",
details: "\(String(describing: error?.localizedDescription))"))
} else {
result(true)
}
})
}
override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
override func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
|
//
// ArtPollReply.swift
// SwiftyArtNet
//
// Created by Jaime on 11/13/19.
// Copyright © 2019 Jaimeeee. All rights reserved.
//
import Foundation
struct ArtPollReply: ArtNetPacket {
let nodeName: String
// TODO: Make MAC address configurable since we are not getting it from the system
private let macBlocks: [UInt8] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
private var IPv4Address: String? {
var address: String?
// Get list of all interfaces on the local machine:
var ifaddr: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return nil }
guard let firstAddr = ifaddr else { return nil }
// For each interface ...
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
// Check for IPv4 or IPv6 interface:
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) {
// Check interface name:
let name = String(cString: interface.ifa_name)
if name == "en0" {
// Convert interface address to a human readable string:
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
return address
}
func reply() -> Data? {
// Make sure we have an IP Address
guard let ipAddress = IPv4Address else {
assert(false, "no wifi address :(")
return nil
}
let ipBlocks = ipAddress.split(separator: ".").compactMap { UInt8($0) }
// Initialize data
var data = Data(count: 238)
// Header [8 bytes]
data.replaceSubrange(0..<8, with: header.data(using: .utf8)!)
// OpCode [8 - 10]
data.replaceSubrange(8..<10, with: withUnsafeBytes(of: ArtNetOpCode.pollReply.rawValue.littleEndian) {
Data($0)
})
// IP Address [10 - 14]
for block in 0..<4 {
let range = (10 + block)..<(11 + block)
data.replaceSubrange(range, with: withUnsafeBytes(of: ipBlocks[block]) { Data($0) })
}
// Port Number [14 - 16]
data.replaceSubrange(14..<16, with: withUnsafeBytes(of: portNumber.littleEndian) { Data($0) })
// NetSwitch [18] = 0
// SubSwitch [19] = 0
// Status1 [23]
// bit 0 = 0 UBEA not present
// bit 0 = 1 UBEA present
// bit 1 = 0 Not capable of RDM (Uni-directional DMX)
// bit 1 = 1 Capable of RDM (Bi-directional DMX)
// bit 2 = 0 Booted from flash (normal boot)
// bit 2 = 1 Booted from ROM (possible error condition)
// bit 3 = Not used
// bit 54 = 00 Universe programming authority unknown
// bit 54 = 01 Universe programming authority set by front panel controls
// bit 54 = 10 Universe programming authority set by network
// bit 76 = 00 Indicators Normal
// bit 76 = 01 Indicators Locate
// bit 76 = 10 Indicators Mute
data.replaceSubrange(23..<24, with: withUnsafeBytes(of: UInt8(0b0)) { Data($0) })
// ESTA Code [24 - 26]
data.replaceSubrange(24..<26, with: "tm".data(using: .utf8)!)
// Short Name
let shortHigherBound = min(nodeName.count, 18)
data.replaceSubrange(26..<(26 + shortHigherBound), with: nodeName.data(using: .utf8)!)
let longHigherBound = min(nodeName.count, 64)
data.replaceSubrange(44..<(44 + longHigherBound), with: nodeName.data(using: .utf8)!)
// Number of Ports
data.replaceSubrange(173..<174, with: withUnsafeBytes(of: UInt8(1)) { Data($0) })
// Port 1
data.replaceSubrange(174..<175, with: withUnsafeBytes(of: UInt8(0b11000101)) { Data($0) })
// Port 1 good input
// data.replaceSubrange(178..<179, with: withUnsafeBytes(of: UInt8(0x10000)) { Data($0) })
// Port 1 good output
// data.replaceSubrange(183..<184, with: withUnsafeBytes(of: UInt8(0x0F)) { Data($0) })
// Port 1 address
data.replaceSubrange(190..<191, with: withUnsafeBytes(of: UInt8(1)) { Data($0) })
// MAC Address [201 - 207]
for block in 0..<6 {
let range = (201 + block)..<(202 + block)
data.replaceSubrange(range, with: withUnsafeBytes(of: macBlocks[block]) { Data($0) })
}
// Status2 [212]
// bit 0 = 0 Node does not support web browser
// bit 0 = 1 Node supports web browser configuration
// bit 1 = 0 Node's IP address is manually configured
// bit 1 = 1 Node's IP address is DHCP configured
// bit 2 = 0 Node is not DHCP capable
// bit 2 = 1 Node is DHCP capable
// bit 2-7 not implemented, transmit as zero
data.replaceSubrange(212..<213, with: withUnsafeBytes(of: UInt8(0b110)) { Data($0) })
return data
}
}
|
import UIKit
import ThemeKit
import SnapKit
class ReleaseNotesViewController: MarkdownViewController {
private let urlManager: UrlManager
private let presented: Bool
private let closeHandler: (() -> ())?
let bottomHolder = UIView()
init(viewModel: MarkdownViewModel, handleRelativeUrl: Bool, urlManager: UrlManager, presented: Bool, closeHandler: (() -> ())? = nil) {
self.urlManager = urlManager
self.presented = presented
self.closeHandler = closeHandler
super.init(viewModel: viewModel, handleRelativeUrl: handleRelativeUrl)
navigationItem.largeTitleDisplayMode = .automatic
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
title = "release_notes.title".localized
if presented {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "button.close".localized, style: .plain, target: self, action: #selector(onClose))
}
super.viewDidLoad()
bottomHolder.backgroundColor = .themeTyler
let separator = UIView()
bottomHolder.addSubview(separator)
separator.snp.makeConstraints { maker in
maker.leading.top.trailing.equalToSuperview()
maker.height.equalTo(1)
}
separator.backgroundColor = .themeSteel10
let twitterButton = UIButton()
bottomHolder.addSubview(twitterButton)
twitterButton.snp.makeConstraints { maker in
maker.leading.equalToSuperview().inset(CGFloat.margin8)
maker.top.bottom.equalToSuperview()
maker.width.equalTo(52)
}
twitterButton.addTarget(self, action: #selector(onTwitterTap), for: .touchUpInside)
twitterButton.setImage(UIImage(named: "filled_twitter_24"), for: .normal)
let telegramButton = UIButton()
bottomHolder.addSubview(telegramButton)
telegramButton.snp.makeConstraints { maker in
maker.leading.equalTo(twitterButton.snp.trailing).offset(CGFloat.margin8)
maker.top.bottom.equalToSuperview()
maker.width.equalTo(52)
}
telegramButton.addTarget(self, action: #selector(onTelegramTap), for: .touchUpInside)
telegramButton.setImage(UIImage(named: "filled_telegram_24"), for: .normal)
let redditButton = UIButton()
bottomHolder.addSubview(redditButton)
redditButton.snp.makeConstraints { maker in
maker.leading.equalTo(telegramButton.snp.trailing).offset(CGFloat.margin8)
maker.top.bottom.equalToSuperview()
maker.width.equalTo(52)
}
redditButton.addTarget(self, action: #selector(onRedditTap), for: .touchUpInside)
redditButton.setImage(UIImage(named: "filled_reddit_24"), for: .normal)
let followUsLabel = UILabel()
bottomHolder.addSubview(followUsLabel)
followUsLabel.snp.makeConstraints { maker in
maker.centerY.equalToSuperview()
maker.trailing.equalToSuperview().inset(CGFloat.margin24)
}
followUsLabel.font = .caption
followUsLabel.textColor = .themeGray
followUsLabel.text = "release_notes.follow_us".localized
}
override func makeTableViewConstraints(tableView: UIView) {
tableView.snp.makeConstraints { maker in
maker.leading.top.trailing.equalToSuperview()
}
view.addSubview(bottomHolder)
bottomHolder.snp.makeConstraints { maker in
maker.top.equalTo(tableView.snp.bottom)
maker.leading.trailing.equalToSuperview()
maker.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
maker.height.equalTo(83)
}
}
@objc private func onClose() {
dismiss(animated: true, completion: { [weak self] in
self?.closeHandler?()
})
}
@objc private func onTwitterTap() {
urlManager.open(url: "https://twitter.com/\(AppConfig.appTwitterAccount)", from: nil)
}
@objc private func onTelegramTap() {
urlManager.open(url: "https://t.me/\(AppConfig.appTelegramAccount)", from: nil)
}
@objc private func onRedditTap() {
urlManager.open(url: "https://www.reddit.com/r/\(AppConfig.appRedditAccount)", from: nil)
}
}
extension ReleaseNotesViewController: UIAdaptivePresentationControllerDelegate {
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
closeHandler?()
}
}
|
//
// DistParserDelegate.swift
// FetchInstallerPkg
//
// Created by Armin Briegel on 2021-06-15.
//
import Foundation
@objc class DistParserDelegate : NSObject, XMLParserDelegate {
enum Elements: String {
case pkgref = "pkg-ref"
case auxinfo
case key
case string
case title
}
var title = String()
var buildVersion = String()
var productVersion = String()
var installerVersion = String()
private var elementName = String()
private var parsingAuxinfo = false
private var currentKey = String()
private var currentString = String()
private var keysParsed = 0
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
if elementName == Elements.pkgref.rawValue {
if attributeDict["id"] == "InstallAssistant" {
if let version = attributeDict["version"] {
self.installerVersion = version
}
}
}
if elementName == Elements.auxinfo.rawValue {
parsingAuxinfo = true
}
if elementName == Elements.key.rawValue {
currentKey = String()
}
if elementName == Elements.string.rawValue {
currentString = String()
}
self.elementName = elementName
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == Elements.auxinfo.rawValue {
parsingAuxinfo = false
}
if elementName == Elements.key.rawValue {
keysParsed += 1
}
if elementName == Elements.string.rawValue {
if currentKey == "BUILD" {
buildVersion = currentString
} else if currentKey == "VERSION" {
productVersion = currentString
}
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if (!data.isEmpty) {
if self.elementName == Elements.title.rawValue {
title += data
} else if self.elementName == "key" && parsingAuxinfo {
currentKey += data
} else if self.elementName == "string" && parsingAuxinfo {
currentString += data
}
}
}
}
|
//
// UIStoryboardExtension.swift
// Buckey
//
// Created by tunay alver on 15.04.2020.
// Copyright © 2020 tunay alver. All rights reserved.
//
import UIKit
extension UIStoryboard {
func instantiateViewController<T: UIViewController>() -> T {
return self.instantiateViewController(withIdentifier: T.identifier) as! T
}
}
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//variables
let maximumNumberOfLoginAttempts = 10
var currentLogininAttempt = 0
var x = 0.0, y = 0.0, z = 0.0
//type anotation
var welcomeMessage: String
welcomeMessage = "Hello"
var red, green, blue: Double
//naming, containing Unicode
let 你好 = "你好世界"
//changing the variable value
var friendlyWelcome = "Hello"
friendlyWelcome = "Bonjour"
//print(_:seperator:terminator:)
print(friendlyWelcome)
print("The current value of friendlyWelcome is \(friendlyWelcome)")
//comment
/*This is comment*/
//Int, default is Int32 or Int64
let unsignMinValue = UInt8.min
let minValue = Int8.min;
let unsignMaxValue = UInt8.max
let maxValue = Int8.min;
//Float 32 Double 64
let pi = 3.14159 //pi will be considered as Double!
//Int number value
let decimalInteger = 17
let binaryInteger = 0b10001
let octalInteger = 0o21
let hexadecimalInteger = 0x11
//Float(Double) number value
let decimalDouble = 12.1875
let exponentDouble = 1.2185e1
let hexadecimalDouble = 0xC.3p0
//Number more easy for reading
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
//Int transition
let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)
//Int <-> Float(Double)
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pie = Double(three) + pointOneFourOneFiveNine
let integerPi = Int(pie)
//type alias
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min
//Bool
let orangeAreOrange = true
let turnipsAreDelicious = false
if turnipsAreDelicious {
print("Mmm, tasty turnips")
} else {
print("Eww, turnips are horrible")
}
//tuples, different types in a tuple is legal
let http404Error = (404, "Not Found")
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
print("The status message is \(statusMessage)")
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
print("The status code is \(http404Error.0)")
//give tuples element a name
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode) and description is \(http200Status.description)")
//optionals
var serverResponseCode: Int? = 404
serverResponseCode = nil
serverResponseCode = 200
var surveyAnswer: String? //If an optional variable is not assgined value, it's nil at first.
//get the value of a optional using !, call forced unwrapping
if serverResponseCode != nil {
print("ServerResponseCode has an integer value of \(serverResponseCode!)")
}
//optional binding
let possibleNumber = "1232" // If = "123xx", toInt() cannot get the int, return nil
/*in below case, possibleNumber.toInt() is optional*/
if let actualNubmer = possibleNumber.toInt() { //Int(possibleNumber) in Swift2.0
print("\'\(possibleNumber)\' has an integer value of \(actualNubmer)")
} else {
print("\'\(possibleNumber)\' could not be converted to an integer")
}
//implicitly unwrapped optionals
let possibleString: String? = "An optional string"
let forceString: String! = possibleString!
let assumedString: String! = "An implicitly unwrapped optional string"
let implicitsString: String = assumedString
if let definteString = assumedString {
print(definteString)
}
if assumedString != nil { //considered it as a normal optional
print(assumedString)
}
//error handling
/*
func someFuction() throws {//The function may throw some error}
do {
try someFuction()
//some code
} catch {
//throw some error
}
*/
//assert
let age = -3
assert(age >= 0, "A person's age cannot be less than zero")
|
//
// ViewController.swift
// Routify
//
// Created by iosdev on 12.4.2021.
//
import UIKit
import Firebase
import MapKit
class DetailViewController: UIViewController, MKMapViewDelegate {
var distance: Int = 0
var uploader = "~John"
var postTitle = "Title"
var postDescription = "Description"
var coordinates : [GeoPoint] = [GeoPoint(latitude: 60.197468,longitude: 24.928335),GeoPoint(latitude: 60.205623,longitude: 24.935941)]
@IBOutlet weak private var map: MKMapView!
@IBOutlet weak private var labelDistance: UILabel!
@IBOutlet weak private var labelDuration: UILabel!
@IBOutlet weak private var labelUploader: UILabel!
@IBOutlet weak private var labelTitle: UINavigationItem!
@IBOutlet weak private var labelDescription: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
refresh()
print(NSStringFromClass(type(of: self)))
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.red
renderer.lineWidth = 4.0
return renderer
}
func refresh() {
labelUploader.text = uploader
labelTitle.title = postTitle
labelDescription.text = postDescription
refreshmap()
refreshinfocards()
}
func refreshinfocards()
{
let duration = TimeInterval(Double(distance) / 1.4)
if distance > 1000{
labelDistance.text = String(Double(distance) / 1000) + "km"
}
else {
labelDistance.text = String(distance) + "m"
}
labelDuration.text = duration.format(using: [.calendar, .hour, .minute, .second])
}
func refreshmap() {
map.delegate = self
map.addOverlay((cordsToPoly(cords: coordinates)), level: MKOverlayLevel.aboveRoads)
if let first = map.overlays.first {
let rect = map.overlays.reduce(first.boundingMapRect, {$0.union($1.boundingMapRect)})
map.setVisibleMapRect(rect, edgePadding: UIEdgeInsets(top: 50.0, left: 50.0, bottom: 50.0, right: 50.0), animated: true)
}
}
}
|
//
// СustomizableTabItem.swift
// KPCTabsControl
//
// Created by Danil Kristalev on 19/09/2019.
// Copyright © 2019 Cédric Foellmi. All rights reserved.
//
import Cocoa
public protocol СustomizableTabItem {
var tabStyle: Style? { get }
}
|
//
// SuccessViewController.swift
// Demo
//
// Created by TrivialWorks on 30/12/19.
// Copyright © 2019 TrivialWorks. All rights reserved.
//
import UIKit
class SuccessViewController: UIViewController {
//MARK:- Outlets & variables
@IBOutlet weak var resultTypeLbl: UILabel!
@IBOutlet weak var emailLbl: UILabel!
@IBOutlet weak var usernameLbl: UILabel!
var userEmail = ""
var userName = ""
var socialType = ""
//MARK:- LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
emailLbl.text = userEmail
usernameLbl.text = userName
resultTypeLbl.text = "---Result (\(socialType))---"
}
//MARK:- Button Action
@IBAction func backAction(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
}
|
//
// AppClassID.swift
// Surface
//
// Created by Nandini on 15/01/18.
// Copyright © 2018 Appinventiv. All rights reserved.
//
import Foundation
import UIKit
enum AppClassID: String {
case ID = "ID"
// Signup Screen
case phoneNumCell = "PhoneNumCell"
case textFieldCell = "TextFieldCell"
case termsAndConditionsCell = "TermsAndConditionsCell"
case signupButtonCell = "SignupButtonCell"
case loginButtonCell = "LoginButtonCell"
case appLogoCell = "AppLogoCell"
case CountryCodeCell = "CountryCodeCell"
case feedCell = "FeedCell"
case featuredCell = "FeaturedCell"
case GalleryCell = "GalleryCell"
case FilterCell = "FilterCell"
case VideoFiltersCollectionCell = "VideoFiltersCollectionCell"
case AccountManagementCell = "AccountManagementCell"
var cellID : String {
switch self {
case .ID:
return self.rawValue
default:
return self.rawValue.appending(AppClassID.ID.rawValue)
}
}
}
|
//
// ViewController.swift
// Exam
//
// Created by mac2 on 20/10/21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var NicjnameTF: UITextField!
@IBOutlet weak var ContraseñaTF: UITextField!
@IBOutlet weak var RedesSocialesBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func IngresarBtn(_ sender: UIButton) {
performSegue(withIdentifier: "Ingresar", sender: self)
}
@IBAction func RegistroBtn(_ sender: UIButton) {
//performSegue(withIdentifier: "Registro", sender: self)
}
@IBAction func RecuperarBtn(_ sender: UIButton) {
// performSegue(withIdentifier: "Recuperar", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Ingresar"{
let destino = segue.destination as! ViewController_Bienvenida
destino.recibirNickName = NicjnameTF.text ?? "John Smith"
}
}
@IBAction func AceptarRedesSoBtn(_ sender: UIButton) {
print(sender.titleLabel)
}
}
|
//
// FloatingSlides.swift
// RealmVideo
//
// Created by Patrick Balestra on 5/12/16.
// Copyright © 2016 Patrick Balestra. All rights reserved.
//
import UIKit
class FloatingSlides: UIView {
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
func setUp() {
layer.shadowOffset = CGSize(width: 1, height: 1)
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOpacity = 0.5
let singleTap = UITapGestureRecognizer(target: self, action: #selector(hideSlides))
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
addGestureRecognizer(singleTap)
let pan = UIPanGestureRecognizer(target: self, action: #selector(moveSlides))
pan.maximumNumberOfTouches = 1
pan.minimumNumberOfTouches = 1
addGestureRecognizer(pan)
singleTap.requireGestureRecognizerToFail(pan)
}
/// Snap the slides to the nearest corner.
///
/// - parameter point: Point where the view was released.
/// - parameter view: Floating view displaying the slides.
func snapPositionToNearestPoint(point: CGPoint, view: UIView) {
let sector = SlidePosition.findPosition(point, slidesSize: view.frame)
let snappedCenter = sector.snapTo(view.frame)
view.center = snappedCenter
}
// MARK: UIPanGestureRecognizer
/// Move the slides to the next corner
func moveSlides(pan: UIPanGestureRecognizer) {
switch pan.state {
case .Changed:
if let view = pan.view {
let translation = pan.translationInView(view)
view.center = CGPoint(x: view.center.x + translation.x, y: view.center.y + translation.y)
pan.setTranslation(CGPointZero, inView: view)
}
case .Ended:
if let panView = pan.view {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: [], animations: {
self.snapPositionToNearestPoint(panView.center, view: panView)
}, completion: nil)
}
default: break
}
}
// MARK: UITapGestureRecognizer
/// Hide the slides with a single tap
func hideSlides() {
var alpha: CGFloat = 1.0
if alpha == 1.0 {
alpha = 0.1
}
UIView.animateWithDuration(1.0) {
self.alpha = alpha
}
}
}
|
// SORTED //
// Sort ints
let numbers: [Int] = [1, 3, 5, 2, 4, 11, 6, 7, 9]
let sortedNumbers = numbers.sorted()
print(sortedNumbers)
// Sort strings
let names: [String] = ["Michael", "Shawn", "Hector", "Johnny", "Sam", "Percy"]
// Challenge: Sort the following array into two separate arrays, one for ints and one for strings. Strings should be sorted alphabetically, and ints should be sorted from greatest to least.
let randomArray: [Any] = ["Seven", 7, 6, "seven", 5, "Six", "0", 0]
|
import Bow
// MARK: Optics extensions
public extension Validated {
/// Provides an Iso to go from/to this type to its `Kind` version.
static var fixIso: Iso<Validated<E, A>, ValidatedOf<E, A>> {
return Iso(get: id, reverseGet: Validated.fix)
}
/// Provides a Fold based on the Foldable instance of this type.
static var fold: Fold<Validated<E, A>, A> {
return fixIso + foldK
}
/// Provides a Traversal based on the Traverse instance of this type.
static var traversal: Traversal<Validated<E, A>, A> {
return fixIso + traversalK
}
}
// MARK: Instance of `Each` for `Validated`
extension Validated: Each {
public typealias EachFoci = A
public static var each: Traversal<Validated<E, A>, A> {
return traversal
}
}
|
//
// AchievementsRowView.swift
// Falling Ball
//
// Created by Ethan Humphrey on 3/11/20.
// Copyright © 2020 Ethan Humphrey. All rights reserved.
//
import SwiftUI
struct AchievementsRowView: View {
@State var achievement: Achievement
@State var achievementRect: CGRect = .zero
@State var achievementImage: UIImage? = nil
@State var achievementString: String = ""
@State var sharePresented: Bool = false
var body: some View {
VStack {
HStack {
Image(achievement.imageName)
Text(achievement.name)
Spacer()
if achievement.progress >= 1 {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(Color(.systemGreen))
}
Button(action: {
self.achievementImage = UIApplication.shared.windows[0].rootViewController?.presentedViewController?.view.asImage(rect: self.achievementRect)
if self.achievement.progress == 0 {
self.achievementString = "I'm working my way towards earning the \(self.achievement.name) achievement in Stacker!"
}
else if self.achievement.progress >= 1 {
self.achievementString = "I've earned the \(self.achievement.name) achievement in Stacker!"
}
else {
self.achievementString = "I am \(self.achievement.progress*100)% of the way towards earning the \(self.achievement.name) achievement in Stacker!"
}
self.sharePresented = true
}) {
Image(systemName: "square.and.arrow.up")
.padding(.trailing)
.accentColor(Color(.systemPurple))
}
}
.font(.headline)
Divider()
HStack {
Text(achievement.description)
.multilineTextAlignment(.leading)
Spacer()
}
ProgressBar(value: achievement.progress, accentColor: achievement.progress >= 1 ? Color(.systemGreen) : Color(.systemPurple))
}
.padding()
.background(Color(.secondarySystemBackground))
.cornerRadius(30)
.background(RectGetter(rect: self.$achievementRect))
.sheet(isPresented: self.$sharePresented) {
ShareSheet(activityItems: [self.achievementImage, self.achievementString])
.accentColor(Color(.systemPurple))
}
}
}
struct RectGetter: View {
@Binding var rect: CGRect
var body: some View {
GeometryReader { proxy in
self.createView(proxy: proxy)
}
}
func createView(proxy: GeometryProxy) -> some View {
DispatchQueue.main.async {
let frame = proxy.frame(in: .global)
self.rect = CGRect(x: frame.minX, y: frame.minY - frame.height/2 + 7, width: frame.width, height: frame.height)
}
return Rectangle().fill(Color.clear)
}
}
struct AchievementsRowView_Previews: PreviewProvider {
static var previews: some View {
AchievementsRowView(achievement: .kingAchievement)
}
}
|
//
// File.swift
// CafeNomad
//
// Created by Albert on 2018/10/31.
// Copyright © 2018 Albert.C. All rights reserved.
//
import Foundation
struct CallAPI2 {
static func callApi(call: @escaping ([CafeAPI]) -> Void) {
var callCafeApi = [CafeAPI]()
let urlObj = URL(string: "https://cafenomad.tw/api/v1.2/cafes/")
let task = URLSession.shared.dataTask(with: urlObj!) { (data, response, error) in
guard let getData = data else { return }
do {
let dataInfo = try JSONDecoder().decode([CafeAPI].self, from: getData)
call(dataInfo)
} catch {
print("error")
}
}.resume()
}
}
|
//
// ViewController.swift
// iWeather
//
// Created by Maher Aldemerdash on 2016-06-21.
// Copyright © 2016 Maher Aldemerdash. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var weather : Weather!
@IBOutlet weak var cityNameLbl: UILabel!
@IBOutlet weak var descLbl: UILabel!
@IBOutlet weak var tempLbl: UILabel!
@IBOutlet weak var mainIcon: UIImageView!
@IBOutlet weak var timeLbl: UILabel!
@IBOutlet weak var dateLbl: UILabel!
var timeFormatter : NSDateFormatter!
var dateFormatter : NSDateFormatter!
override func viewDidLoad() {
super.viewDidLoad()
weather = Weather()
timeFormatter = NSDateFormatter()
timeFormatter.timeStyle = .ShortStyle
timeLbl.text = timeFormatter.stringFromDate(NSDate())
dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateLbl.text = dateFormatter.stringFromDate(NSDate())
weather.downloadWeatherDetail { () -> () in
self.updateLabels()
}
}
func updateLabels() {
cityNameLbl.text = weather.cityName
descLbl.text = weather.des
let roundTemp = round(Double(weather.temp)!)
tempLbl.text = "\(roundTemp)" + "°"
mainIcon.image = UIImage(named: "\(weather.icon)")
}
}
|
//
// SwitchInterfaceController.swift
// MyWatch_Swift
//
// Created by huangshuimei on 16/1/31.
// Copyright © 2016年 huangshuimei. All rights reserved.
//
import WatchKit
import Foundation
class SwitchInterfaceController: WKInterfaceController {
@IBAction func switchClick(value: Bool) {
print("\(value)")
}
@IBOutlet var switchView: WKInterfaceSwitch!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
|
//
// LoginViewController.swift
// map
//
// Created by user on 21.03.2021.
//
import UIKit
import Firebase
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
emailTextField.layer.cornerRadius = emailTextField.frame.height/2
emailTextField.layer.borderWidth = 2
emailTextField.layer.borderColor = UIColor.gray.cgColor
passwordTextField.layer.cornerRadius = emailTextField.frame.height/2
passwordTextField.layer.borderWidth = 2
passwordTextField.layer.borderColor = UIColor.gray.cgColor
loginButton.layer.cornerRadius = 25
loginButton.layer.borderWidth = 2
loginButton.layer.borderColor = UIColor.systemIndigo.cgColor
}
@IBAction func loginButtonPressed(_ sender: Any) {
if let email = emailTextField.text, let password = passwordTextField.text {
Auth.auth().signIn(withEmail: email, password: password) { [weak self] authResult, error in
if let e = error {
let alert = UIAlertController(title: "Error", message: e.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
self?.present(alert, animated: true)
}
else {
self?.performSegue(withIdentifier: "LogIn", sender: self)
}
}
}
}
}
|
//
// Extentions.swift
// LoginTemplate
//
// Created by Mahesh Rathod on 16/07/20.
// Copyright © 2020 MR SQUARE. All rights reserved.
//
import Foundation
import UIKit
class UIManager{
static func setupShadow(view:UIView){
view.layer.cornerRadius = 25
view.layer.shadowColor = UIColor(hue: 0.643, saturation: 0.061, brightness: 0.906, alpha: 1).cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 0);
view.layer.shadowOpacity = 1
view.layer.shadowRadius = 4
}
static func setupShadowForOtp(view:UIView){
view.layer.cornerRadius = 10
view.layer.shadowColor = UIColor(hue: 0.643, saturation: 0.061, brightness: 0.906, alpha: 1).cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 0);
view.layer.shadowOpacity = 1
view.layer.shadowRadius = 4
}
static func setupButtonShadow(button:UIButton){
button.layer.cornerRadius = 25
button.layer.shadowColor = Colors.colorPrimary.cgColor
button.layer.shadowOffset = CGSize(width: 0, height: 0);
button.layer.shadowOpacity = 0.7
button.layer.shadowRadius = 4
}
static func lblColorChange(mainString:String,subString:String) -> NSAttributedString{
let stringValue = mainString
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: Colors.colorPrimary, forText: subString)
return attributedString
}
}
extension NSMutableAttributedString {
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
}
|
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "OutlawSimd",
products: [
.library(name: "OutlawSimd", targets: ["OutlawSimd"])
],
dependencies: [
.package(url: "https://github.com/Molbie/Outlaw.git", from: "4.0.0")
],
targets: [
.target(name: "OutlawSimd", dependencies: ["Outlaw"]),
.testTarget(name: "OutlawSimdTests", dependencies: ["OutlawSimd"])
]
)
|
//
// ARVideoView.swift
// VideoLive-iOS
//
// Created by 余生丶 on 2021/6/21.
//
import UIKit
class ARVideoView: UIView {
@IBOutlet weak var renderView: UIView!
@IBOutlet weak var placeholderView: UIView!
@IBOutlet weak var headImageView: UIImageView!
@IBOutlet weak var audioImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
fileprivate var borderLayer: CAShapeLayer?
var uid: String?
var userName: String? {
didSet {
nameLabel.text = userName
}
}
var headUrl: String? {
didSet {
headImageView.sd_setImage(with: NSURL(string: headUrl!) as URL?, placeholderImage: UIImage(named: "icon_head"))
}
}
class func videoView(uid: String?) -> ARVideoView {
let video = Bundle.main.loadNibNamed("ARVideoView", owner: nil, options: nil)![0] as! ARVideoView
video.uid = uid
return video
}
override var frame: CGRect {
didSet {
if (headImageView != nil) {
headImageView.layer.cornerRadius = frame.width * 0.3/2
}
if frame.width == ARScreenWidth {
borderLayer?.removeFromSuperlayer()
borderLayer = nil
} else {
swiftDrawBoardDottedLine(width: 3, lenth: 1, space: 0, cornerRadius: 0, color: UIColor.white)
}
}
}
func swiftDrawBoardDottedLine(width: CGFloat, lenth: CGFloat, space: CGFloat, cornerRadius: CGFloat, color:UIColor) {
borderLayer?.removeFromSuperlayer()
borderLayer = nil
self.layer.cornerRadius = cornerRadius
borderLayer = CAShapeLayer()
borderLayer?.bounds = self.bounds
borderLayer?.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY);
borderLayer?.path = UIBezierPath(roundedRect: borderLayer!.bounds, cornerRadius: cornerRadius).cgPath
borderLayer?.lineWidth = width / UIScreen.main.scale
borderLayer?.lineDashPattern = [lenth,space] as [NSNumber]
borderLayer?.lineDashPhase = 0.1;
borderLayer?.fillColor = UIColor.clear.cgColor
borderLayer?.strokeColor = color.cgColor
self.layer.addSublayer(borderLayer!)
}
}
|
//
// SettingsKeys.swift
// f26Core
//
// Created by David on 07/04/2018.
// Copyright © 2018 com.smartfoundation. All rights reserved.
//
/// Specifies settings keys
public enum SettingsKeys {
case isSignedInYN
}
|
//
// ViewController.swift
// SwiftGameOne
//
// Created by Monstar on 16/7/25.
// Copyright © 2016年 Monstar. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer:AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
playBgMusic()
}
override func viewWillDisappear(animated: Bool) {
audioPlayer.stop()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func playBgMusic() {
let musicPath = NSBundle.mainBundle().pathForResource("startMusic", ofType: "wav")
//指定音乐路径
let url = NSURL(fileURLWithPath: musicPath!)
audioPlayer = try?AVAudioPlayer(contentsOfURL: url,fileTypeHint: nil)
audioPlayer.numberOfLoops = -1
audioPlayer.volume = 0.5
audioPlayer.prepareToPlay()
audioPlayer.play()
}
@IBAction func StartGame(sender: AnyObject) {
let sb = UIStoryboard(name:"Main",bundle: nil)
let vc = sb.instantiateViewControllerWithIdentifier("StartViewController")as!StartViewController
self.presentViewController(vc, animated: true, completion: nil)
}
}
|
//
// SearchMoviesViewControllerDelegate.swift
// PopUpCorn
//
// Created by Elias Paulino on 25/04/19.
// Copyright © 2019 Elias Paulino. All rights reserved.
//
import Foundation
protocol SearchMoviesViewControllerDelegate: AnyObject {
func searchMovieWasSelected(movie: DetailableMovie, atPosition position: Int)
}
|
//
// MainMenuScene.swift
// IOSWars
//
// Created by Younggi Kim on 2020-02-13.
// Copyright © 2020 CoderDroids. All rights reserved.
//
import SpriteKit
class OptionScene: SKScene {
var helpButton : SKSpriteNode!
var backButton : SKSpriteNode!
var effectSlider : UISlider!
var musicSlider : UISlider!
override func didMove(to view: SKView )
{
helpButton = self.childNode( withName : "HelpButton" ) as! SKSpriteNode
backButton = self.childNode( withName : "BackButton" ) as! SKSpriteNode
let h = UIScreen.main.bounds.height
effectSlider = UISlider(frame: CGRect(x: 200, y: h * 0.48, width: 100, height: 15))
effectSlider.isContinuous = true
effectSlider.maximumValue = 1.0
effectSlider.minimumValue = 0.0
effectSlider.value = Audio.instance.getEffectVolume()
effectSlider.addTarget(self, action:#selector(effectSliderControl(sender:)), for: .valueChanged)
musicSlider = UISlider(frame: CGRect(x: 200, y: h * 0.37, width: 100, height: 15))
musicSlider.isContinuous = true
musicSlider.maximumValue = 1.0
musicSlider.minimumValue = 0.0
musicSlider.value = Audio.instance.getMusicVolume()
musicSlider.addTarget(self, action:#selector(musicSliderControl(sender:)), for: .valueChanged)
view.addSubview(effectSlider)
view.addSubview(musicSlider)
}
override func willMove(from view: SKView) {
effectSlider.removeFromSuperview()
musicSlider.removeFromSuperview()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent? )
{
let touch = touches.first
if let location = touch?.location( in: self )
{
if helpButton.contains(location) {
Audio.instance.playEffect(name: "click")
} else if backButton.contains(location) {
Audio.instance.playEffect(name: "click")
let transition = SKTransition.flipHorizontal( withDuration: 0.5 )
let gameScene = SKScene(fileNamed: "MainMenuScene" )!
self.view?.presentScene( gameScene, transition: transition )
}
}
}
@IBAction func effectSliderControl(sender: UISlider)
{
Audio.instance.setEffectVolume(volume: effectSlider.value)
}
@IBAction func musicSliderControl(sender: UISlider)
{
Audio.instance.setMusicVolume(volume: musicSlider.value)
}
}
|
//
// DDPersonInfoVC.swift
// YiLuMedia
//
// Created by WY on 2019/9/10.
// Copyright © 2019 WY. All rights reserved.
//
import UIKit
class DDPersonInfoVC: DDNormalVC {
let backView = UIView()
let line1 = UIView()
let line2 = UIView()
let nameTitle = UILabel()
let nameValue = UITextField()
let gender = UILabel()
let male = UIButton()
let female = UIButton()
let idNumTitle = UILabel()
let idNumValue = UITextField()
let bottomButton = UIButton()
var personalInfo : DDAuthenticateInfo?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "authenticate_info_navi_title"|?|
// Do any additional setup after loading the view.
// self.navigationController?.navigationBar.topItem?.backBarButtonItem = UIBarButtonItem.init(title: "nil" , style: UIBarButtonItem.Style.plain, target: nil , action: nil )//去掉title
// self.navigationItem.setHidesBackButton(true , animated: true )//隐藏返回键
self.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: nil , style: UIBarButtonItem.Style.plain, target: nil , action: nil )//去掉title
_addSubviews()
_layoutSubviews()
}
}
///delegate
extension DDPersonInfoVC : UITextFieldDelegate{
}
///actions
extension DDPersonInfoVC{
@objc func action(sender:UIButton){
if sender == male{
male.isSelected = true
female.isSelected = false
}else if sender == female{
female.isSelected = true
male.isSelected = false
}else if sender == bottomButton{
mylog("next")
guard let name = nameValue.text , name.count > 0 else{
GDAlertView.alert("authenticate_info_name_placeholder"|?|, image: nil, time: 2, complateBlock: nil)
return
}
guard let idNumber = idNumValue.text , idNumber.count > 0 else{
GDAlertView.alert("authenticate_info_id_placeholder"|?|, image: nil, time: 2, complateBlock: nil)
return
}
let vc = DDIdImageVC()
// let genderStr = male.isSelected ? "1" : "2"
// vc.baseInfo = (self.nameValue.text ?? "" , genderStr , idNumValue.text ?? "")
self.personalInfo?.name = self.nameValue.text ?? ""
self.personalInfo?.id_number = idNumValue.text
self.personalInfo?.sex = male.isSelected ? "1" : "2"
vc.personalInfo = self.personalInfo
self.navigationController?.pushViewController(vc, animated: true )
}
}
}
/// UI
extension DDPersonInfoVC{
func _addSubviews() {
self.view.addSubview(backView)
self.view.addSubview(nameTitle)
self.view.addSubview(nameValue)
self.view.addSubview(gender)
self.view.addSubview(male)
self.view.addSubview(female)
self.view.addSubview(idNumTitle)
self.view.addSubview(idNumValue)
self.view.addSubview(line1)
self.view.addSubview(line2)
self.view.addSubview(bottomButton)
nameValue.delegate = self
idNumValue.delegate = self
nameTitle.text = "authenticate_info_name"|?|
nameValue.placeholder = "authenticate_info_name_placeholder"|?|
gender.text = "authenticate_info_gender"|?|
idNumTitle.text = "authenticate_info_gender"|?|
idNumValue.placeholder = "authenticate_info_id_placeholder"|?|
male.setImage(UIImage(named: "login_checkmark_select"), for: UIControl.State.selected)
male.setImage(UIImage(named: "login_checkmark"), for: UIControl.State.normal)
male.setTitle(" " + "authenticate_info_male"|?|, for: UIControl.State.normal)
male.setTitleColor(UIColor.darkGray, for: UIControl.State.normal)
female.setImage(UIImage(named: "login_checkmark_select"), for: UIControl.State.selected)
female.setTitle(" " + "authenticate_info_female"|?|, for: UIControl.State.normal)
female.setImage(UIImage(named: "login_checkmark"), for: UIControl.State.normal)
female.setTitleColor(UIColor.darkGray, for: UIControl.State.normal)
backView.backgroundColor = UIColor.white
bottomButton.setTitleColor(UIColor.darkGray, for: UIControl.State.normal)
bottomButton.setTitle("authenticate_info_next"|?|, for: UIControl.State.normal)
let immg = UIImage.getImage(startColor: UIColor.colorWithHexStringSwift("fbce35"), endColor: UIColor.colorWithHexStringSwift("f9ac35"), startPoint: CGPoint(x: 0, y: 0.5), endPoint: CGPoint(x: 1, y: 0.5), size: CGSize(width: SCREENWIDTH, height: 50))
bottomButton.setBackgroundImage(immg, for: UIControl.State.normal)
nameTitle.textColor = UIColor.darkGray
nameTitle.font = DDFont.systemFont(ofSize: 15)
gender.textColor = UIColor.darkGray
gender.font = DDFont.systemFont(ofSize: 15)
idNumTitle.textColor = UIColor.darkGray
idNumTitle.font = DDFont.systemFont(ofSize: 15)
nameValue.font = DDFont.systemFont(ofSize: 14)
idNumValue.font = DDFont.systemFont(ofSize: 14)
line1.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3)
line2.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3)
male.isSelected = true
self.male.addTarget(self , action: #selector(action(sender:)), for: UIControl.Event.touchUpInside)
self.female.addTarget(self , action: #selector(action(sender:)), for: UIControl.Event.touchUpInside)
bottomButton.addTarget(self , action: #selector(action(sender:)), for: UIControl.Event.touchUpInside)
}
func _layoutSubviews() {
self.nameValue.text = personalInfo?.name
self.idNumValue.text = personalInfo?.id_number
if (personalInfo?.sex ?? "") == "2" {//nv
self.action(sender: female)
}else {
self.action(sender: male)
}
// self.gender.text = (apiModel.data?.sex ?? "") == "1" ? "男" : "女"
let rowH : CGFloat = 40
let backViewH = rowH * 3
let backViewY = DDNavigationBarHeight + 22
backView.frame = CGRect(x: 0, y: backViewY, width: view.bounds.width, height: backViewH)
bottomButton.frame = CGRect(x: 15, y: backView.frame.maxY + 30, width: view.bounds.width - 30, height: 50)
nameTitle.sizeToFit()
gender.sizeToFit()
male.sizeToFit()
female.sizeToFit()
idNumTitle.sizeToFit()
let titleX : CGFloat = 10
nameTitle.frame = CGRect(x: titleX, y: backView.frame.minY, width: nameTitle.bounds.width + 5, height: rowH)
gender.frame = CGRect(x: titleX, y: nameTitle.frame.maxY, width: gender.bounds.width + 5, height: rowH)
idNumTitle.frame = CGRect(x: titleX, y: gender.frame.maxY, width: idNumTitle.bounds.width + 5, height: rowH)
let subtitleX : CGFloat = idNumTitle.frame.maxX + 10
nameValue.frame = CGRect(x: subtitleX, y: nameTitle.frame.minY, width: view.bounds.width - subtitleX, height: rowH)
male.frame = CGRect(x: subtitleX, y: gender.frame.minY, width: male.bounds.width, height: rowH)
female.frame = CGRect(x: male.frame.maxX + 20, y: gender.frame.minY, width: female.bounds.width, height: rowH)
idNumValue.frame = CGRect(x: subtitleX, y: idNumTitle.frame.minY, width: view.bounds.width - subtitleX, height: rowH)
let lineH : CGFloat = 1
line1.frame = CGRect(x: 0, y: backView.frame.minY + rowH - lineH/2, width: view.bounds.width, height: lineH)
line2.frame = CGRect(x: 0, y: backView.frame.minY + rowH * 2 - lineH/2, width: view.bounds.width, height: lineH)
bottomButton.layer.cornerRadius = bottomButton.bounds.height/2
bottomButton.clipsToBounds = true
}
}
|
//
// PageDotsViewController.swift
// Mars Watch
//
// Created by Rob Whitaker on 07/04/2017.
// Copyright © 2017 RWAPP. All rights reserved.
//
import Foundation
import UIKit
final class PageDotsViewController: UIViewController {
// Controls the display of the dots at the bottom of the screen when we swipe between views
@IBOutlet private weak var pageControl: UIPageControl!
@IBOutlet private weak var containerView: UIView!
private var pageViewController: PageViewController?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let pageViewController = segue.destination as? PageViewController {
self.pageViewController = pageViewController
self.pageViewController?.pageDotsDelegate = self
}
}
@IBAction func pageDotsTapped(_ sender: Any) {
let page = pageControl.currentPage
pageViewController?.pageSelected(page: page)
}
}
extension PageDotsViewController: PageDotsViewControllerDelegate {
func pageViewController(pageViewController: PageViewController,
didUpdatePageCount count: Int) {
pageControl.numberOfPages = count
}
func pageViewController(pageViewController: PageViewController,
didUpdatePageIndex index: Int) {
pageControl.currentPage = index
}
}
|
//
// OpponentViewController.swift
// SportBook
//
// Created by Bui Minh Duc on 6/26/17.
// Copyright © 2017 dinosys. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class OpponentViewController: BaseViewController {
fileprivate let disposeBag = DisposeBag()
@IBOutlet weak var tableView: UITableView!
var currentTournament : TournamentModel?
let viewModel = OpponentViewModel()
let opponentCell = "OpponentCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "opponent_list".localized
self.configureViewModel()
self.loadOpponents()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func loadOpponents(){
self.viewModel.loadOpponentList().subscribe(onCompleted: { _ in
self.tableView.reloadData()
}).addDisposableTo(self.disposeBag)
}
func configureViewModel(){
self.viewModel.tournament.value = self.currentTournament
}
}
extension OpponentViewController : UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
let cell = tableView.dequeueReusableCell(withIdentifier: self.opponentCell) as! OpponentCell
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let opponentCell = cell as! OpponentCell
opponentCell.configureUI()
}
}
|
//
// HistoryTableViewCell.swift
// TipWorks
//
// Created by Tuan-Lung Wang on 8/13/17.
// Copyright © 2017 Tuan-Lung Wang. All rights reserved.
//
import UIKit
class HistoryTableViewCell: UITableViewCell {
@IBOutlet weak var paymentLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
}
|
//
// ObjLoader.swift
// ObjLoader
//
// Created by Neal Sidhwaney on 9/5/20.
// Copyright © 2020 Neal Sidhwaney. All rights reserved.
//
import Foundation
import CoreImage
import AppKit
struct Vertex {
let x, y, z : Double
init (_ doubles : [Double]) {
x = doubles[0]
y = doubles[1]
z = doubles[2]
}
}
struct VertexTexture {
let u, v : Double
init (_ doubles : [Double]) {
u = doubles[0]
v = doubles[1]
}
}
struct VertexNormal {
let x, y, z : Double
init (_ doubles : [Double]) {
x = doubles[0]
y = doubles[1]
z = doubles[2]
}
}
struct Face {
var vertexIndices : (Int, Int, Int)!
var materialName : String = ""
}
struct ObjFile {
var vertices : [Vertex] = []
var vertexTextures : [VertexTexture] = []
var vertexNormals : [VertexNormal] = []
var faces : [Face] = []
}
struct Material {
let specularExponent : Double
let dissolution : Double
let illumination : Int
let diffuse : RGB
let ambient : RGB
let specular : RGB
}
func parseNumbers<T : LosslessStringConvertible> (_ line : Substring) -> [T] {
return line.split(separator: " ").dropFirst().map() { T(String($0))! }
}
extension Substring {
// A replacement for String.trimmingCharacters that returns a Substring instead of a String to avoid making a copy.
func trimToSubstring(in toTrim : CharacterSet) -> Substring {
if (self.startIndex == self.endIndex) {
return self
}
var startIndex = self.startIndex
// Make endIndex inclusive of last element.
var endIndex = self.index(self.endIndex, offsetBy: -1)
// if we're passed a 1 element string that does not contain a character to be trimmed, we'll end up testing it twice
// alternative is to handle it as a special case.
while startIndex <= endIndex && toTrim.contains(self[startIndex].unicodeScalars.first!) {
startIndex = self.index(startIndex, offsetBy: 1)
}
while endIndex > startIndex && toTrim.contains(self[endIndex].unicodeScalars.first!) {
endIndex = self.index(endIndex, offsetBy: -1)
}
if startIndex > endIndex { // all characters in the string were trimmed characters
return ""
}
return self[startIndex...endIndex]
}
}
func readMtlFile(_ mtlFile : String) -> [String : Material] {
var ret : [String : Material] = [:]
let objFileData = try! String(contentsOfFile: mtlFile)
let lines = objFileData.split(separator: "\n")
for var i in 0..<lines.count {
let x = lines[i].trimToSubstring(in: .whitespacesAndNewlines)
if x.starts(with: "#") || x.isEmpty {
continue
}
if (x.starts(with: "newmtl")) {
let materialName = String(x.split(separator: " ")[1])
var specularExponent : Double!
var dissolution : Double!
var illumination : Int!
var kd : RGB!
var ka : RGB!
var ks : RGB!
for j in i + 1..<lines.count {
let mtlLine = lines[j]
if mtlLine.starts(with:"Ns ") {
specularExponent = parseNumbers(mtlLine)[0]
continue
}
if mtlLine.starts(with:"d ") {
dissolution = parseNumbers(mtlLine)[0]
continue
}
if mtlLine.starts(with:"illum ") {
illumination = parseNumbers(mtlLine)[0]
continue
}
if mtlLine.starts(with:"Kd ") {
kd = RGB(parseNumbers(mtlLine))!
continue
}
if mtlLine.starts(with:"Ka ") {
ka = RGB(parseNumbers(mtlLine))!
continue
}
if mtlLine.starts(with:"Ks ") {
ks = RGB(parseNumbers(mtlLine))!
continue
}
if mtlLine.trimToSubstring(in: .whitespacesAndNewlines).isEmpty ||
mtlLine.starts(with: "newmtl") {
i = j
break
}
}
ret[materialName] = Material(specularExponent: specularExponent,
dissolution: dissolution,
illumination: illumination,
diffuse: kd,
ambient: ka,
specular: ks)
}
}
return ret
}
func readObjFile(_ objFile : String) -> ObjFile {
let objFileData = try! String(contentsOfFile: objFile)
let lines = objFileData.split(separator: "\n")
var o = ObjFile()
var materialName : Substring = ""
for x in lines {
if x.starts(with: "#") {
continue
}
if x.starts(with: "usemtl ") {
materialName = x.split(separator: " ").last!
continue
}
if x.starts(with: "v ") {
o.vertices.append(Vertex(parseNumbers(x)))
continue
}
if x.starts(with: "vt ") {
o.vertexTextures.append(VertexTexture(parseNumbers(x)))
continue
}
if x.starts(with: "vn ") {
o.vertexNormals.append(VertexNormal(parseNumbers(x)))
continue
}
if (x.starts(with: "f ")) {
let vertexIndices : [Int] = parseNumbers(x)
o.faces.append(Face(vertexIndices: (vertexIndices[0], vertexIndices[1], vertexIndices[2]),
materialName: String(materialName)))
continue
}
}
return o
}
|
import OverampedCore
import Persist
import SwiftUI
struct SettingsView: View {
@AppStorage("enabledAdvancedStatistics")
private var enabledAdvancedStatistics = false
@SceneStorage("SettingsView.isShowingIgnoredHostnames")
private var isShowingIgnoredHostnames = false
// MARK: Basic statistics
@PersistStorage(persister: .basicStatisticsResetDate)
private var basicStatisticsResetDate: Date?
@PersistStorage(persister: .replacedLinksCount)
private var replacedLinksCount: Int
@PersistStorage(persister: .redirectedLinksCount)
private var redirectedLinksCount: Int
@State
private var hasCollectedAnyBasicStatistics = false
// MARK: Advanced statistics
@PersistStorage(persister: .advancedStatisticsResetDate)
private var advancedStatisticsResetDate: Date?
@PersistStorage(persister: .replacedLinks)
private var replacedLinks: [ReplacedLinksEvent]
@PersistStorage(persister: .redirectedLinks)
private var redirectedLinks: [RedirectLinkEvent]
@State
private var hasCollectedAnyAdvancesStatistics = false
// MARK: Ignored hostnames
@PersistStorage(persister: .ignoredHostnames)
private(set) var ignoredHostnames: [String]
var body: some View {
List {
Section(footer: Text("Basic statistics last reset: \(basicStatisticsResetDate?.formatted() ?? "Never").")) {
ClearBasicStatisticsView()
.onReceive(_replacedLinksCount.persister.publisher.combineLatest(_redirectedLinksCount.persister.publisher)) { (replacedLinksCount, redirectedLinksCount) in
hasCollectedAnyBasicStatistics = replacedLinksCount > 0 || redirectedLinksCount > 0
}
.disabled(!hasCollectedAnyBasicStatistics)
}
Section(footer: Text("Advanced statistics includes the domains and timestamps of replaced and redirect links.\nAdvanced statistics last reset: \(advancedStatisticsResetDate?.formatted() ?? "Never").")) {
Toggle(
isOn: $enabledAdvancedStatistics,
label: { Text("Collect Advanced Statistics") }
)
.onReceive(_replacedLinks.persister.publisher.combineLatest(_redirectedLinks.persister.publisher)) { (replacedLinks, redirectedLinks) in
hasCollectedAnyAdvancesStatistics = replacedLinks.contains(where: { !$0.domains.isEmpty }) || !redirectedLinks.isEmpty
}
ClearAdvancedStatisticsView()
.disabled(!hasCollectedAnyAdvancesStatistics)
}
Section(footer: Text("Overamped will not redirect to the canonical version of websites it has been disabled on.")) {
NavigationLink(
isActive: $isShowingIgnoredHostnames
) {
IgnoredHostnamesView()
} label: {
HStack {
Text("Disabled Websites")
Spacer()
Text(ignoredHostnames.count.formatted())
.foregroundColor(Color(.secondaryLabel))
}
}
}
}
.background(Color(.systemGroupedBackground))
.navigationBarTitle("Settings")
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
|
//
// CRMContactPreferences.swift
// SweepBright
//
// Created by Kaio Henrique on 6/9/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
class CRMLocationPreference: Object, SWBJSONMapper {
dynamic var id: String = NSUUID().UUIDString
dynamic var name: String = ""
let contacts = LinkingObjects(fromType: CRMContactPreferences.self, property: "locations")
override class func primaryKey() -> String? { return "id" }
func initWithJSON(json: JSON) {
self.id = json["id"].string ?? self.id
self.name = json["name"].stringValue
}
}
class CRMContactPreferences: Object {
dynamic var id: String = NSUUID().UUIDString
dynamic var contact: CRMContact?
let min_rooms = RealmOptional<Int>()
let max_price = RealmOptional<Float>()
dynamic var is_investor: Bool = false
dynamic var negotiation: String?
let locations = List<CRMLocationPreference>()
override class func primaryKey() -> String? { return "id" }
}
extension CRMContactPreferences: SWBJSONMapper {
func initWithJSON(json: JSON) {
self.id = self.contact?.id ?? self.id
self.min_rooms.value = json["min_rooms"].int
self.max_price.value = json["max_price"].float
self.is_investor = json["is_investor"].boolValue
self.negotiation = json["negotiation"].string
}
}
|
//
// Score.swift
// SimonSays
//
// Created by Radomyr Bezghin on 3/30/21.
//
import Foundation
///
/// Score object stores all the data related to the scoles and levels.
///
struct Score {
private(set) var currentScore: Int {
didSet{
if maxScore < currentScore{
maxScore = currentScore
}
}
}
private(set) var currentLevel: Int
private(set) var maxScore: Int
mutating func resetScore() {
currentScore = 0
currentLevel = 1
}
mutating func nextLevel(){
currentLevel += 1
}
mutating func addScore(){
currentScore += currentLevel * 2
}
}
|
//
// HomeViewController.swift
// wemap
//
// Created by Nguyen Hoan on 26/05/2021.
//
import UIKit
import CoreLocation
import WeMapSDK
import SideMenu
enum RightBarButtonStatus {
case exten
case back
}
enum Mode {
case Normal
case TenPositon
}
class HomeViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var vLocator: UIView!
@IBOutlet weak var vSearch: UIView!
@IBOutlet weak var btnRight: UIButton!
@IBOutlet weak var tfSearch: UITextField!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var vSearchRoad: UIView!
@IBOutlet weak var actionBackMode: UIButton!
@IBAction func ActionBack(_ sender: Any) {
self.mode = .Normal
self.wemapView.removeAllAnnotation()
self.resetDestPosition()
}
public var mode: Mode = .Normal {
didSet {
if mode == .Normal {
vSearch.isHidden = false
// vLocator.isHidden = false
vSearchRoad.isHidden = false
} else {
vSearch.isHidden = true
// vLocator.isHidden = true
vSearchRoad.isHidden = true
// tableView.isHidden = true
}
}
}
var menu = SideMenuNavigationController(rootViewController: LeftMenuViewController())
let imageNameCirclek = "cart.circle.fill"
let imageNameFixMotobike = "gearshape.fill"
let imageNameFuel = "cylinder.fill"
let leftMenu = LeftMenuViewController()
var typePosition: typePositions = .CircleK
let locationManager = CLLocationManager()
// var centerMyhome: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 21.0266469, longitude: 105.7615744)
var centerMyhome: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 20.993893749513248, longitude: 105.82176090675364)
var wemapView: WeMapView = WeMapView()
var resutlsSearch: [WeMapPlace] = []
var resultPoints: [CLLocationCoordinate2D] = []
var statusRightBar: RightBarButtonStatus = .exten {
didSet {
if self.statusRightBar == .exten {
if #available(iOS 13.0, *) {
btnRight.setImage(UIImage(systemName: "line.horizontal.3"), for: .normal)
} else {
// Fallback on earlier versions
}
wemapView.isHidden = false
vLocator.isHidden = false
vSearchRoad.isHidden = false
} else {
if #available(iOS 13.0, *) {
btnRight.setImage(UIImage(systemName: "arrow.backward"), for: .normal)
} else {
// Fallback on earlier versions
}
wemapView.isHidden = true
vLocator.isHidden = true
vSearchRoad.isHidden = true
}
}
}
func locationManager(
_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]
) {
if let location = locations.first {
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
self.centerMyhome = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
wemapView = WeMapView(frame: view.bounds)
wemapView.setCenter(centerMyhome, zoomLevel: 12, animated: true)
wemapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(wemapView)
view.bringSubviewToFront(actionBackMode)
view.bringSubviewToFront(vLocator)
view.bringSubviewToFront(vSearch)
view.bringSubviewToFront(vSearchRoad)
vSearch.setShadowRadiusView()
vSearch.layer.cornerRadius = 12
vLocator.setShadowRadiusView()
vLocator.layer.cornerRadius = 25
vSearchRoad.setShadowRadiusView()
vSearchRoad.layer.cornerRadius = 25
wemapView.delegate = self
tfSearch.delegate = self
leftMenu.delegate = self
tableView.register(UINib(nibName: "ResultCell", bundle: nil), forCellReuseIdentifier: "ResultCell")
tableView.delegate = self
tableView.dataSource = self
menu = SideMenuNavigationController(rootViewController: leftMenu)
menu.leftSide = true
menu.presentationStyle = .menuSlideIn
menu.statusBarEndAlpha = 0
menu.menuWidth = 300
self.menu.presentationStyle.presentingEndAlpha = 0.5
SideMenuManager.default.leftMenuNavigationController = menu
SideMenuManager.default.addScreenEdgePanGesturesToPresent(toView: view, forMenu: .left)
}
@IBAction func extendAction(_ sender: Any) {
wemapView.isHidden = false
if self.statusRightBar == .back {
changeStateRight()
} else {
if self.statusRightBar == .exten {
self.present(self.menu, animated: true, completion: nil)
}
}
}
@IBAction func localAction(_ sender: Any) {
wemapView.setCenter(centerMyhome, zoomLevel: 15, animated: true)
}
@IBAction func searchRoad(_ sender: Any) {
let nextVC = SearchViewController()
navigationController?.pushViewController(nextVC, animated: true)
}
func changeStateRight() {
if self.statusRightBar == .exten {
self.statusRightBar = .back
} else {
self.statusRightBar = .exten
}
}
}
extension HomeViewController: WeMapViewDelegate {
func WeMapViewDidFinishLoadingMap(_ wemapView: WeMapView) {
let coordinates = [
centerMyhome
]
// Fill an array with point annotations and add it to the map.
var pointAnnotations = [WeMapPointAnnotation]()
for coordinate in coordinates {
let point = WeMapPointAnnotation(coordinate)
point.title = "\(coordinate.latitude), \(coordinate.longitude)"
pointAnnotations.append(point)
}
// Create a data source to hold the point data
let shapeSource = WeMapShapeSource(identifier: "home-source", points: pointAnnotations)
// Create a style layer for the symbol
let shapeLayer = WeMapSymbolStyleLayer(identifier: "home-symbols", source: shapeSource)
// Add the image to the style's sprite
if #available(iOS 13.0, *) {
if let image = UIImage(systemName: "circlebadge.fill") {
wemapView.setImage(image, forName: "icon-house")
}
} else {
// Fallback on earlier versions
}
// Tell the layer to use the image in the sprite
shapeLayer.iconImageName = NSExpression(forConstantValue: "icon-house")
// Add the source and style layer to the map
wemapView.addSource(shapeSource)
wemapView.addLayer(shapeLayer)
// Add a single tap gesture recognizer. This gesture requires the built-in WeMapView tap gestures (such as those for zoom and annotation selection) to fail.
let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleMapTap(sender:)))
for recognizer in wemapView.getGestureRecognizers() where recognizer is UITapGestureRecognizer {
singleTap.require(toFail: recognizer)
}
wemapView.addGestureRecognizer(singleTap)
}
// func wemapView(_ wemapView: WeMapView, annotationCanShowCallout annotation: WeMapAnnotation) -> Bool {
// return true
// }
// MARK: - Feature interaction
@objc func handleMapTap(sender: UITapGestureRecognizer) {
self.tfSearch.endFloatingCursor()
self.tfSearch.endEditing(true)
let point = sender.location(in: sender.view!)
let touchCoordinate = wemapView.convert(point, toCoordinateFrom: sender.view!)
if sender.state == .ended {
if mode == .Normal {
wemapView.removeAllAnnotation()
// Try matching the exact point first.
wemapView.selectAnnotation(WeMapPointAnnotation(touchCoordinate), animated: false, completionHandler: {})
tfSearch.text = String(touchCoordinate.latitude) + ", " + String(touchCoordinate.longitude)
} else {
let layerIdentifiers: Set = ["dest-position"]
// Try matching the exact point first.
let point = sender.location(in: sender.view!)
// for pointAnnotation in wemapView.visibleFeatures(at: point, styleLayerIdentifiers: layerIdentifiers) {
// wemapView.selectAnnotation(pointAnnotation, animated: false, completionHandler: {})
// return
// }
let touchCoordinate = wemapView.convert(point, toCoordinateFrom: sender.view!)
let touchLocation = CLLocation(latitude: touchCoordinate.latitude , longitude: touchCoordinate.longitude )
// Otherwise, get all features within a rect the size of a touch (44x44).
let touchRect = CGRect(origin: point, size: .zero).insetBy(dx: -22.0, dy: -22.0)
let possibleFeatures = wemapView.visibleFeatures(inCGRect: touchRect, styleLayerIdentifiers: Set(layerIdentifiers))
// Select the closest feature to the touch center.
let closestFeatures = possibleFeatures?.sorted(by: {
return CLLocation(latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude).distance(from: touchLocation) < CLLocation(latitude: $1.coordinate.latitude, longitude: $1.coordinate.longitude).distance(from: touchLocation)
})
if let feature = closestFeatures?.first {
// wemapView.selectAnnotation(feature, animated: false, completionHandler: {})
let nextVC = RouteViewController()
nextVC.endLocation = feature.coordinate
self.navigationController?.pushViewController(nextVC, animated: true)
return
}
}
}
}
}
extension HomeViewController: UITextFieldDelegate {
func textFieldDidChangeSelection(_ textField: UITextField) {
let completeHandler: ([WeMapPlace]) -> Void = { [weak self] wemapPlaces in
guard let `self` = self else {return}
if wemapPlaces.isEmpty {
DispatchQueue.main.async {
self.resutlsSearch = []
self.tableView.reloadData()
}
return
}
let start = CLLocation(latitude: self.centerMyhome.latitude, longitude: self.centerMyhome.longitude)
func sortPositon(pl1: WeMapPlace,pl2: WeMapPlace) -> Bool {
let end1 = CLLocation(latitude: pl1.location.latitude, longitude: pl1.location.longitude)
let end2 = CLLocation(latitude: pl2.location.latitude, longitude: pl2.location.longitude)
return start.distance(from: end1) < start.distance(from: end2)
}
self.resutlsSearch = wemapPlaces.sorted(by: sortPositon)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
if self.statusRightBar == .exten {
changeStateRight()
}
let wemapSearch = WeMapSearch()
//gioi han so luong du lieu tra ve
let wemapOptions = WeMapSearchOptions(24, focusPoint: CLLocationCoordinate2D(latitude: 21.031772, longitude: 105.799508), latLngBounds: WeMapLatLonBounds(minLon: 104.799508, minLat: 20.031772, maxLon: 105.799508, maxLat: 21.031772))
if textField.text ?? "" != "" {
wemapSearch.search(textField.text ?? "", wemapSearchOptions: wemapOptions, completeHandler: completeHandler)
}
}
func resetDestPosition() {
wemapView.removeLayer("dest-position")
wemapView.removeSource("dest-source")
}
func setDestPosition() {
resetDestPosition()
let coordinates = self.resultPoints
// Fill an array with point annotations and add it to the map.
var pointAnnotations = [WeMapPointAnnotation]()
for coordinate in coordinates {
let point = WeMapPointAnnotation(coordinate)
point.title = "\(coordinate.latitude), \(coordinate.longitude)"
pointAnnotations.append(point)
}
// Create a data source to hold the point data
let shapeSource = WeMapShapeSource(identifier: "dest-source", points: pointAnnotations)
// Create a style layer for the symbol
let shapeLayer = WeMapSymbolStyleLayer(identifier: "dest-position", source: shapeSource)
// Add the image to the style's sprite
var imageName = self.imageNameCirclek
if self.typePosition == .FixMotobike {
imageName = self.imageNameFixMotobike
}
if self.typePosition == .Fuel {
imageName = self.imageNameFuel
}
if #available(iOS 13.0, *) {
if let image = UIImage(systemName: imageName) {
wemapView.setImage(image, forName: "dest-image")
}
} else {
// Fallback on earlier versions
}
// Tell the layer to use the image in the sprite
shapeLayer.iconImageName = NSExpression(forConstantValue: "dest-image")
// Add the source and style layer to the map
wemapView.addSource(shapeSource)
wemapView.addLayer(shapeLayer)
}
}
extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resutlsSearch.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell") as? ResultCell else {
return UITableViewCell()
}
cell.selectionStyle = .none
cell.lblName.text = resutlsSearch[indexPath.row].placeName
cell.lblDistrict.text = setAddress(place: resutlsSearch[indexPath.row])
let start = CLLocation(latitude: centerMyhome.latitude, longitude: centerMyhome.longitude)
let end = CLLocation(latitude: resutlsSearch[indexPath.row].location.latitude, longitude: resutlsSearch[indexPath.row].location.longitude)
cell.lblDistant.text = String(Double(round(start.distance(from: end)/1000 * 100) / 100)) + " km"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
changeStateRight()
wemapView.setCenter(resutlsSearch[indexPath.row].location, zoomLevel: 16, animated: true)
wemapView.removeAllAnnotation()
wemapView.selectAnnotation(WeMapPointAnnotation(resutlsSearch[indexPath.row].location), animated: false, completionHandler: {})
self.tfSearch.text = resutlsSearch[indexPath.row].placeName
}
func setAddress(place: WeMapPlace) -> String{
var rs: [String] = []
if !place.housenumber.isEmpty {
rs.append(place.housenumber)
}
if !place.street.isEmpty {
rs.append(place.street)
}
if !place.district.isEmpty {
rs.append(place.district)
}
if !place.city.isEmpty {
rs.append(place.city)
}
if rs.isEmpty {
return ""
}
return rs.joined(separator: ", ")
}
}
extension HomeViewController: LeftMenuViewControllerDelegate {
func setPosition(type: typePositions) {
self.mode = .TenPositon
self.wemapView.removeAllAnnotation()
let wemapSearch = WeMapSearch()
//gioi han so luong du lieu tra ve
let wemapOptions = WeMapSearchOptions(24, focusPoint: centerMyhome, latLngBounds: WeMapLatLonBounds(minLon: 104.799508, minLat: 20.031772, maxLon: 105.799508, maxLat: 21.031772))
var searchText = "circle k"
if type == .CircleK {
searchText = "circle k"
}
if type == .FixMotobike {
searchText = "sữa xe máy"
}
if type == .Fuel {
searchText = "cây xăng"
}
self.typePosition = type
wemapSearch.search(searchText, wemapSearchOptions: wemapOptions ) {[weak self] wemapPlace in
guard let `self` = self else {return}
let start = CLLocation(latitude: self.centerMyhome.latitude, longitude: self.centerMyhome.longitude)
func sortPositon(pl1: WeMapPlace,pl2: WeMapPlace) -> Bool {
let end1 = CLLocation(latitude: pl1.location.latitude, longitude: pl1.location.longitude)
let end2 = CLLocation(latitude: pl2.location.latitude, longitude: pl2.location.longitude)
return start.distance(from: end1) < start.distance(from: end2)
}
let places = wemapPlace.sorted(by: sortPositon).prefix(10)
self.wemapView.selectAnnotation(WeMapPointAnnotation(self.centerMyhome), animated: false, completionHandler: {})
self.resultPoints = []
for place in places {
self.resultPoints.append(place.location)
// self.wemapView.selectAnnotation(WeMapPointAnnotation(place.location), animated: false, completionHandler: {})
}
self.setDestPosition()
}
}
func wemapView(_ weMapView: WeMapView, annotationCanShowCallout annotation: WeMapAnnotation) -> Bool {
return true
}
func wemapView(_ weMapView: WeMapView, annotation: WeMapAnnotation, calloutAccessoryControlTapped control: UIControl) {
print("tap tap")
}
}
|
//
// DocumentsCoordinator.swift
// Benjamin
//
// Created by Vlados iOS on 7/10/19.
// Copyright © 2019 Vladislav Shilov. All rights reserved.
//
import UIKit
final class DocumentsCoordinator: FinishFlowSupportable {
// MARK: - Properties
private let applicationContext: IApplicationContext
private let router: Routable
// MARK: - Flow handlers
var finishFlow: (() -> Void)?
//MARK: Initialization
required init(router: Routable,
context: IApplicationContext) {
self.applicationContext = context
self.router = router
}
}
// MARK: - TabBarItemSupportable
extension DocumentsCoordinator: TabBarItemSupportable {
var title: String {
return "Документы"
}
var iconKey: ImageKeys? {
return nil
}
}
// MARK: - Coordinatable
extension DocumentsCoordinator: Coordinatable {
func start() {
showDocumentsModule()
}
func showDocumentsModule() {
let controller = DocumentsViewController.instanceFromStoryboard(.main)
router.setRootModule(controller)
}
}
|
//
// DataResponse.swift
// myTube
//
// Created by Quyen Dang on 9/25/17.
// Copyright © 2017 Quyen Dang. All rights reserved.
//
import UIKit
import ObjectMapper
class YResponse: Mappable {
var kind: String?
var etag: String?
var nextPageToken: String?
var prevPageToken: String?
var pageInfo: PageInfo?
required init?(map: Map) {
}
func mapping(map: Map) {
kind <- map["kind"]
etag <- map["etag"]
nextPageToken <- map["nextPageToken"]
prevPageToken <- map["prevPageToken"]
pageInfo <- map["pageInfo"]
}
func fetchNextData() {
if nextPageToken == nil {
return
}
}
}
|
//
// Places.swift
// RoadTripPlanner
//
// Created by Deepthy on 10/24/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
import Contacts
final class Places: NSObject, MKAnnotation {
var title: String?
var cllocation: CLLocation
var regionRadius: Double
var location: String?
var type: String?
var distance : Double?
var coordinate : CLLocationCoordinate2D
init(title: String, location: String, type: String, cllocation: CLLocation, distance: Double!, coordinate: CLLocationCoordinate2D) {
self.title = title//"title"
self.cllocation = cllocation
self.coordinate = coordinate
self.regionRadius = 0.0
self.location = location//"location"
self.type = type//"type"
self.distance = distance
}
init(cllocation: CLLocation, distance: Double!, coordinate: CLLocationCoordinate2D) {
self.title = "title"
self.cllocation = cllocation
self.coordinate = coordinate
self.regionRadius = 0.0
self.location = "location"
self.type = "type"
self.distance = distance
}
var subtitle: String? {
return location//locationName
}
var imageName: String? {
if type == "start" { return "startflag" }
else if type == "finish" { return "finishflag" }
else if type == "restaurants" || type == "food, restaurant" { return "food30" }
else if type == "auto" { return "gasstation30" }
else { return "custommarker" }
}
// Function to calculate the distance from given location.
func calculateDistance(fromLocation: CLLocation?) {
distance = cllocation.distance(from: fromLocation!)
}
// Annotation right callout accessory opens this mapItem in Maps app
func mapItem() -> MKMapItem {
let addressDict = [CNPostalAddressStreetKey: subtitle!]
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = title
return mapItem
}
var markerTintColor: UIColor {
switch type {//discipline {
case "auto"?:
return .orange
case "entertaintment"?:
return .purple
case "hotels"?:
return .blue
case "restaurants"?, "food, restaurant"?:
return UIColor(red: 22/255, green: 134/255, blue: 36/255, alpha: 1)//.green
case "arts"?:
return .cyan
case "publicservicesgovt"?:
return .yellow
default:
return .purple
}
}
}
|
//
// DataTableCell.swift
// SampleDisplayData
//
// Created by Julius on 02/08/2020.
// Copyright © 2020 Julius. All rights reserved.
//
import UIKit
class DataTableCell: UITableViewCell {
let cellView: UIView = {
let view = UIView()
//view.backgroundColor = .red
view.layer.cornerRadius = 10
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
//label
let userNameLabel: UILabel = {
let label = UILabel()
//label.text = "Day 1"
label.textColor = .blue
label.font = UIFont.boldSystemFont(ofSize: 14)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let saveAccountLabel: UILabel = {
let label = UILabel()
//label.text = "Day 1"
label.textColor = .orange
label.font = UIFont.boldSystemFont(ofSize: 14)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let saveDatetLabel: UILabel = {
let label = UILabel()
//label.text = "2020-07-26 17:15"
label.textColor = .black
label.font = UIFont.boldSystemFont(ofSize: 14)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let saveAmountLabel: UILabel = {
let label = UILabel()
label.text = "USD 2"
label.textColor = .orange
label.font = UIFont.boldSystemFont(ofSize: 14)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let receiveLabel: UILabel = {
let label = UILabel()
label.text = "KES 510"
label.textColor = .orange
label.font = UIFont.boldSystemFont(ofSize: 14)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let accountTypeLabel: UILabel = {
let label = UILabel()
label.text = "KES 510"
label.textColor = .orange
label.font = UIFont.boldSystemFont(ofSize: 14)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
//image
private let loginImage: UIImageView = {
let saveImageView = UIImageView()
saveImageView.image = UIImage(named: "mobile_trans")
saveImageView.translatesAutoresizingMaskIntoConstraints = false
return saveImageView
}()
var singleData: SampleData! {
didSet {
let nome = "Mobile"
userNameLabel.text = singleData.username
//saveAccountLabel.text = singleData.saveAccount
//saveAccountLabel.text = singleData?.accountType ?
saveAmountLabel.text = singleData.saveAmount
saveDatetLabel.text = singleData.saveDate
accountTypeLabel.text = nome
//accountTypeLabel.text = singleData.accountType
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
//new
addSubview(cellView)//1st container
cellView.addSubview(userNameLabel)//2nd instead container
cellView.addSubview(saveDatetLabel)//contact
cellView.addSubview(saveAmountLabel)//send
cellView.addSubview(accountTypeLabel)//receive
//cellView.addSubview(editButton)
cellView.addSubview(loginImage)//profile image
NSLayoutConstraint.activate([
cellView.topAnchor.constraint(equalTo: self.topAnchor, constant: 10),
cellView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10),
cellView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10),
cellView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
//name constraint
userNameLabel.heightAnchor.constraint(equalToConstant: 200).isActive = true
userNameLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
userNameLabel.centerYAnchor.constraint(equalTo: cellView.centerYAnchor, constant: -20).isActive = true
userNameLabel.leftAnchor.constraint(equalTo: cellView.leftAnchor, constant: 70).isActive = true
//contact constraint
saveDatetLabel.heightAnchor.constraint(equalToConstant: 200).isActive = true
saveDatetLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
saveDatetLabel.centerYAnchor.constraint(equalTo: cellView.centerYAnchor, constant: 10).isActive = true
saveDatetLabel.leftAnchor.constraint(equalTo: cellView.leftAnchor, constant: 70).isActive = true
//send constraint
saveAmountLabel.heightAnchor.constraint(equalToConstant: 200).isActive = true
saveAmountLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
saveAmountLabel.centerYAnchor.constraint(equalTo: cellView.centerYAnchor, constant: -20).isActive = true
saveAmountLabel.leftAnchor.constraint(equalTo: cellView.leftAnchor, constant: 280).isActive = true
//receive constraint
accountTypeLabel.heightAnchor.constraint(equalToConstant: 200).isActive = true
accountTypeLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
accountTypeLabel.centerYAnchor.constraint(equalTo: cellView.centerYAnchor, constant: 10).isActive = true
accountTypeLabel.leftAnchor.constraint(equalTo: cellView.leftAnchor, constant: 280).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// PhotoContentView.swift
// Ubiquity
//
// Created by SAGESSE on 4/22/17.
// Copyright © 2017 SAGESSE. All rights reserved.
//
import UIKit
///
/// display photo resources
///
internal class PhotoContentView: AnimatedImageView, Displayable {
// displayer delegate
weak var displayerDelegate: DisplayableDelegate?
// display asset
func willDisplay(with asset: Asset, in library: Library, orientation: UIImageOrientation) {
logger.trace?.write()
// have any change?
guard _asset !== asset else {
return
}
// save context
_asset = asset
_library = library
_donwloading = false
// update image
backgroundColor = .ub_init(hex: 0xf0f0f0)
let thumbSize = BrowserAlbumLayout.thumbnailItemSize
let thumbOptions = DataSourceOptions()
let largeSize = CGSize(width: asset.ub_pixelWidth, height: asset.ub_pixelHeight)
let largeOptions = DataSourceOptions(progressHandler: { [weak self, weak asset] progress, response in
DispatchQueue.main.async {
// if the asset is nil, the asset has been released
guard let asset = asset else {
return
}
// update progress
self?._updateContentsProgress(progress, response: response, asset: asset)
}
})
_requests = [
// request thumb iamge
library.ub_requestImage(for: asset, targetSize: thumbSize, contentMode: .aspectFill, options: thumbOptions) { [weak self, weak asset] contents, response in
// if the asset is nil, the asset has been released
guard let asset = asset else {
return
}
// if the request status is completed or cancelled, clear the request
// `contents` is nil, the task need download
// `ub_error` not is nil, the task an error
// `ub_cancelled` is true, the task is canceled
// `ub_degraded` is false, the task is completed
if self?._asset === asset && response.ub_error != nil || response.ub_cancelled || (contents != nil && !response.ub_degraded) {
self?._requests?[0] = nil
}
// the image is vaild?
guard (self?.image?.size.width ?? 0) < (contents?.size.width ?? 0) else {
return
}
// update contents
self?._updateContents(contents, response: response, asset: asset)
},
// request large image
library.ub_requestImage(for: asset, targetSize: largeSize, contentMode: .aspectFill, options: largeOptions) { [weak self, weak asset] contents, response in
// if the asset is nil, the asset has been released
guard let asset = asset else {
return
}
// if the request status is completed or cancelled, clear the request
// `contents` is nil, the task need download
// `ub_error` not is nil, the task an error
// `ub_cancelled` is true, the task is canceled
// `ub_degraded` is false, the task is completed
if self?._asset === asset && response.ub_error != nil || response.ub_cancelled || (contents != nil && !response.ub_degraded) {
self?._requests?[1] = nil
}
// the image is vaild?
guard (self?.image?.size.width ?? 0) < (contents?.size.width ?? 0) else {
return
}
// update contents
self?._updateContents(contents, response: response, asset: asset)
}
]
}
// end display asset
func endDisplay(with asset: Asset, in library: Library) {
logger.trace?.write()
// when are requesting an image, please cancel it
_requests?.forEach { request in
request.map { request in
// reveal cancel
library.ub_cancelRequest(request)
}
}
// clear context
_asset = nil
_requests = nil
_library = nil
// clear contents
self.image = nil
// stop animation if needed
stopAnimating()
}
private func _updateContents(_ contents: UIImage?, response: Response, asset: Asset) {
// the current asset has been changed?
guard _asset === asset else {
// change, all reqeust is expire
logger.debug?.write("\(asset.ub_localIdentifier) image is expire")
return
}
logger.trace?.write("\(asset.ub_localIdentifier) => \(contents?.size ?? .zero)")
// update contents
ub_setImage(contents ?? self.image, animated: true)
}
private func _updateContentsProgress(_ progress: Double, response: Response, asset: Asset) {
// the current asset has been changed?
guard _asset === asset else {
// change, all reqeust is expire
logger.debug?.write("\(asset.ub_localIdentifier) progress is expire")
return
}
// if the library required to download
// if download completed start animation is an error
if !_donwloading && progress < 1 {
_donwloading = true
// start downloading
displayerDelegate?.displayer(self, didStartRequest: asset)
}
// only in the downloading to update progress
if (_donwloading) {
// update donwload progress
displayerDelegate?.displayer(self, didReceive: progress)
}
// if the donwload completed or an error occurred, end of the download
if (_donwloading && progress >= 1) || (response.ub_error != nil) {
_donwloading = false
// complate download
displayerDelegate?.displayer(self, didComplete: response.ub_error)
}
}
private var _asset: Asset?
private var _library: Library?
private var _requests: [Request?]?
private var _donwloading: Bool = false
}
|
//
// Copyright © 2020 Tasuku Tozawa. All rights reserved.
//
public protocol MemoryCaching: AnyObject {
func insert(_ data: Data?, forKey key: String)
func remove(forKey key: String)
func removeAll()
subscript(_ key: String) -> Data? { get set }
}
public final class MemoryCache {
public struct Configuration {
public static let `default` = Configuration(
costLimit: Int(Self.defaultCostLimit()),
countLimit: Int.max
)
public let costLimit: Int
public let countLimit: Int
public init(costLimit: Int, countLimit: Int) {
self.costLimit = costLimit
self.countLimit = countLimit
}
public static func defaultCostLimit() -> UInt64 {
let totalMemory = ProcessInfo.processInfo.physicalMemory
return totalMemory / 4
}
}
private lazy var cache: NSCache<NSString, AnyObject> = {
let cache = NSCache<NSString, AnyObject>()
cache.totalCostLimit = config.costLimit
cache.countLimit = config.countLimit
return cache
}()
private let lock = NSLock()
private let config: Configuration
// MARK: - Lifecycle
public init(config: Configuration = .default) {
self.config = config
}
}
extension MemoryCache: MemoryCaching {
// MARK: - MemoryCaching
public func insert(_ data: Data?, forKey key: String) {
guard let data = data else { return remove(forKey: key) }
lock.lock(); defer { lock.unlock() }
cache.setObject(data as AnyObject, forKey: key as NSString)
}
public func remove(forKey key: String) {
lock.lock(); defer { lock.unlock() }
cache.removeObject(forKey: key as NSString)
}
public func removeAll() {
lock.lock(); defer { lock.unlock() }
cache.removeAllObjects()
}
public subscript(key: String) -> Data? {
get {
return cache.object(forKey: key as NSString) as? Data
}
set {
return insert(newValue, forKey: key)
}
}
}
|
//
// ViewController.swift
// beltReview
//
// Created by J on 7/18/2018.
// Copyright © 2018 J. All rights reserved.
//
// ========= MAIN VC ==========
import UIKit
import CoreData
class ViewController: UIViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@IBOutlet weak var tableView: UITableView!
var tableData: [Note] = []
//✈️ from ADD EDIT VC SEGUE
@IBAction func unwindsegueFromAddEditVC(segue: UIStoryboardSegue) {
let src = segue.source as! AddEditVC
let title = src.titleAddEditTextField.text!
let note = src.noteAddEditTextView.text!
let date = src.dateAddEditPicker.date
print("inside --- unwind segue ------")
if src.editmode == true {
if let indexPathAddEditVC = src.indexPathAddEditVC as? IndexPath {
let item = tableData[indexPathAddEditVC.row]
item.title = title
item.note = note
item.date = date
print("edit======== ", title, note, date)
appDelegate.saveContext()
tableView.reloadData()
}
}
else{
// let title = src.titleAddEditTextField.text!
// let note = src.noteAddEditTextView.text!
// let date = src.dateAddEditPicker.date
print("got back with ", title, note, date)
let newNote = Note(context: context)
newNote.title = title
newNote.note = note
newNote.date = date
newNote.completed = false
appDelegate.saveContext()
tableData.append(newNote)
tableView.reloadData()
}
}
@IBAction func addPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "addEditSegue", sender: sender)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = 70
fetchAll()
}
//get ALL 📆
func fetchAll() {
let request:NSFetchRequest<Note> = Note.fetchRequest()
//order by date:
let sortByDate = NSSortDescriptor(key: #keyPath(Note.date), ascending: false)
let sortByCompleted = NSSortDescriptor(key: #keyPath(Note.completed), ascending: false)
request.sortDescriptors = [sortByCompleted,sortByDate]
do {
tableData = try context.fetch(request)
} catch {
print("couldn't fetchAll from DB", error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// print("prepareForSegue to ShowVC!")
// if let indexPath = sender as? IndexPath{
// if segue.identifier == "ShowSegue"{
// let dest = segue.destination as! ShowVC
// print("going to ShowVC through ShowSegue from prepare segue func in ViewController")
// let note = tableData[indexPath.row]
// dest.note = note
// dest.indexPath = indexPath
// }
// else if segue.identifier == "AddEditSegue"{
// print("going to AddEditVC as add item")
// let nav = segue.destination as! UINavigationController
// let dest_2 = nav.topViewController as! AddEditVC
// let note = tableData[indexPath.row]
// print(note)
// dest_2.note = note
// dest_2.indexPath = indexPath
// }
// }
//
// }
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// go to del
if let indexPath = sender as? IndexPath {
if segue.identifier == "showSegue" {
//grab data from tabledata
let title = tableData[indexPath.row].title
let note = tableData[indexPath.row].note
let date = tableData[indexPath.row].date
print("-----------")
print(title, note, date)
let dest = segue.destination as! ShowVC
//date
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
dest.titleShow = title as! String
dest.noteShow = note as! String
dest.dateShow = formatter.string(from: date!)
}
//EDIT
else if segue.identifier == "addEditSegue" && tableData[indexPath.row].completed == false {
let nav = segue.destination as! UINavigationController
let dest = nav.topViewController as! AddEditVC
let title = tableData[indexPath.row].title
let note = tableData[indexPath.row].note
let date = tableData[indexPath.row].date
dest.editmode = true
dest.titleEdit = title as! String
dest.noteEdit = note as! String
dest.dateEdit = date!
dest.indexPathAddEditVC = indexPath // to send the indxpath and have a value
}
}
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ThisCell", for: indexPath) as! ThisCell
let cellData = tableData[indexPath.row]
//set the cell labels in main view
cell.titleLabel.text = tableData[indexPath.row].title
//date
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
cell.dateCellLabel.text = formatter.string(from: tableData[indexPath.row].date!)
//set the cell delegate
cell.delegate = self
cell.indexPathThisCell = indexPath
// change bg img for checked button
//set the img and that was checked in the delegate
if cellData.completed == true {
cell.buttonCellOutlet.setBackgroundImage(UIImage(named: "check"), for: .normal)
} else {
cell.buttonCellOutlet.setBackgroundImage(UIImage(named:"unchecked"), for: .normal)
}
// // img set short way
// let imgName = cellData.completed ? "check" : "nocheck"
// cell.buttonCellOutlet.setBackgroundImage(UIImage(named: imgName), for: .normal)
return cell
}
//DELETE & EDIT SWIPE ACTIONS
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
//delete
let deleteAction = UIContextualAction(style: .destructive, title: "DELETE") {action, view, completetionHandler in
self.context.delete(self.tableData[indexPath.row])
self.tableData.remove(at: indexPath.row)
self.appDelegate.saveContext()
tableView.deleteRows(at: [indexPath], with: .automatic)
completetionHandler(true)
}
//edit
let note = tableData[indexPath.row]
if note.completed == false {
let editAction = UIContextualAction(style: .normal, title: "Edit") {action, view, completionHandler in
self.performSegue(withIdentifier: "addEditSegue", sender: indexPath)
completionHandler(false)
}
editAction.backgroundColor = .blue
let swipeConfig = UISwipeActionsConfiguration(actions: [deleteAction, editAction])
return swipeConfig
} else {
let swipeConfig = UISwipeActionsConfiguration(actions: [deleteAction])
return swipeConfig
}
// return swipeConfig
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showSegue", sender: indexPath)
}
}
extension ViewController: ThisCellDelegate {
func buttonChecked(from sender: ThisCell, indexPath: IndexPath) {
// let indexPath = tableView.indexPath(for: sender)!
if tableData[indexPath.row].completed == true {
tableData[indexPath.row].completed = false
} else {
tableData[indexPath.row].completed = true
}
appDelegate.saveContext()
fetchAll()
// // short way
// tableData[indexPath.row].completed = !tableData[indexPath.row].completed
// or
// tableView.reloadRows(at: [indexPath], with: .automatic)
tableView.reloadData()
}
}
|
//
// String+Extension.swift
// Swift_Project
//
// Created by HongpengYu on 2018/8/23.
// Copyright © 2018 HongpengYu. All rights reserved.
//
import UIKit
private let patternTitle = "(?<=title>).*(?=</title)"
extension String {
/// 传入ulr 解析html对应的标题
static func parseHTMLTitle(_ urlString: String, completion:@escaping ((String?) -> ())){
// 转义中文字符
guard let urlStr = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: urlStr) else {
completion(nil)
return
}
DispatchQueue.global().async {
do {
let html = try String(contentsOf: url, encoding: .utf8)
let range = html.range(of: patternTitle, options: String.CompareOptions.regularExpression, range: html.startIndex..<html.endIndex, locale: nil)
guard let tempRange = range else {
DispatchQueue.main.async(execute: {
completion(nil)
})
return
}
let titleStr = html[tempRange]
DispatchQueue.main.async(execute: {
completion(String(titleStr))
})
} catch {
DispatchQueue.main.async(execute: {
completion(nil)
})
}
}
}
}
|
//
// searchResultsController.swift
// Deposits
//
// Created by Biswajit Palei on 27/07/21.
//
import UIKit
import Combine
class SearchResultsController: UITableViewController, UISearchResultsUpdating {
var deposits : [DepositViewModel]?
private var searchResult : [DepositViewModel] = []
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResult.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DepositTableViewCell", for: indexPath) as! DepositTableViewCell
cell.depositViewModel = searchResult[indexPath.row]
return cell
}
func updateSearchResults(for searchController: UISearchController) {
let keyword = searchController.searchBar.text ?? ""
self.searchResult = self.deposits?.filter({$0.search(keyword: keyword)}) ?? []
self.tableView.reloadData()
}
}
//UITableViewDataSource , UITableViewDelegate
extension SearchResultsController {
private func configureTableView() {
tableView.delegate = self
tableView.dataSource = self
let depositNib = UINib(nibName: "DepositTableViewCell", bundle: Bundle(for: DepositTableViewCell.self))
tableView.register(depositNib, forCellReuseIdentifier: "DepositTableViewCell")
}
}
|
//
// ApplicationService.swift
// AppOfApps
//
// Created by ナム Nam Nguyen on 7/9/18.
// Copyright © 2018 Nguyen Pte, Ltd. All rights reserved.
//
import UIKit
protocol ApplicationService: UIApplicationDelegate { }
|
//
// DWBorderButton.swift
// Movie
//
// Created by Daniel on 16/3/15.
// Copyright © 2016年 Daniel. All rights reserved.
//
import UIKit
class DWBorderButton: UIButton {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override func awakeFromNib() {
self.layer.cornerRadius = 4.0
self.backgroundColor = UIColor.buyButtonColor()
}
}
|
//
// Event.swift
// ppvis-2
//
// Created by Алина Ненашева on 30.11.20.
//
import Foundation
class Event {
var date: Date
var menu: [String]
var numberOfGuests: Int
init(date: Date, menu: [String], numberOfGuests: Int) {
self.date = date
self.menu = menu
self.numberOfGuests = numberOfGuests
}
}
|
//
// DefaultSettings.swift
// Weather App v2.0
//
// Created by Ilya Senchukov on 17.03.2021.
//
import Foundation
class DefaultSettings {
static let shared = DefaultSettings()
private let defaultIDs = [
"703448",
"702658"
]
private let key = "cities"
func setDefaultIDs() {
if getIDs() == nil {
setIDs(defaultIDs)
}
}
func addId(id: String) {
guard var ids = getIDs() else {
return
}
ids.append(id)
setIDs(ids)
}
func getIDs() -> [String]? {
return UserDefaults.standard.stringArray(forKey: key)
}
private func setIDs(_ ids: [String]) {
UserDefaults.standard.setValue(ids, forKey: key)
}
}
|
//
// HIPEventedPropertyTests.swift
// HIPEventedPropertyTests
//
// Created by Steve Johnson on 7/14/16.
// Copyright © 2016 Hipmunk, Inc. All rights reserved.
//
import XCTest
@testable import HIPEventedProperty
class Counter {
var n = 0
func increment() {
n += 1
}
}
class ValueBag<T> {
var val: T
init(_ val: T) {
self.val = val
}
func set(_ val: T) {
self.val = val
}
}
class HIPEventSourceTests: XCTestCase {
func testSubscribeAndUnsubscribe() {
let memoryTag1 = NSObject()
let events = HIPEventSource()
let counter = Counter()
let unsubscribe = events.subscribe(withObject: memoryTag1, callback: counter.increment)
events.fireEvent()
XCTAssertEqual(counter.n, 1)
unsubscribe()
events.fireEvent()
XCTAssertEqual(counter.n, 1)
}
func testSubscribeAndDeallocate() {
var memoryTag1: NSObject? = NSObject()
let events = HIPEventSource()
let counter = Counter()
_ = events.subscribe(withObject: memoryTag1!, callback: counter.increment)
events.fireEvent()
XCTAssertEqual(counter.n, 1)
memoryTag1 = nil
events.fireEvent()
XCTAssertEqual(counter.n, 1)
}
func testRemoveAllSubscribers() {
let memoryTag1 = NSObject()
let events = HIPEventSource()
let counter = Counter()
_ = events.subscribe(withObject: memoryTag1, callback: counter.increment)
events.fireEvent()
XCTAssertEqual(counter.n, 1)
events.removeAllSubscribers()
events.fireEvent()
XCTAssertEqual(counter.n, 1)
}
func testSubscribeOnce() {
let memoryTag1 = NSObject()
let events = HIPEventSource()
let counter = Counter()
_ = events.subscribeOnce(withObject: memoryTag1, callback: counter.increment)
events.fireEvent()
XCTAssertEqual(counter.n, 1)
events.fireEvent()
XCTAssertEqual(counter.n, 1)
}
}
class NonEquatableType {
}
class HIPObservableTests: XCTestCase {
func testSubscribeToValue() {
let memoryTag1 = NSObject()
let obs = HIPObservable<Bool>(false)
let valueBag = ValueBag<Bool>(obs.value)
_ = obs.subscribeToValue(withObject: memoryTag1, onChange: valueBag.set)
obs.value = true
XCTAssertTrue(valueBag.val)
obs.value = false
XCTAssertFalse(valueBag.val)
}
func testSubscribeOnceToValue() {
let memoryTag1 = NSObject()
let obs = HIPObservable<Bool>(false)
let valueBag = ValueBag<Bool>(obs.value)
_ = obs.subscribeOnceToValue(withObject: memoryTag1, onChange: valueBag.set)
obs.value = true
XCTAssertTrue(valueBag.val)
obs.value = false
XCTAssertTrue(valueBag.val)
}
func testSubscribeToSlidingWindow() {
let memoryTag1 = NSObject()
let obs = HIPObservable<Bool>(false)
let initialVal: (Bool, Bool) = (false, false)
let valueBag = ValueBag<(Bool, Bool)>(initialVal)
_ = obs.subscribeToSlidingWindow(withObject: memoryTag1, onChange: { valueBag.set(($0, $1)) })
obs.value = true
XCTAssertEqual(valueBag.val.0, false)
XCTAssertEqual(valueBag.val.1, true)
obs.value = false
XCTAssertEqual(valueBag.val.0, true)
XCTAssertEqual(valueBag.val.1, false)
}
func testDebugSubscribe() {
let obs = HIPObservable<Bool>(false)
let valueBag = ValueBag<Bool>(obs.value)
obs.debugSubscribe(onChange: valueBag.set)
obs.value = true
XCTAssertTrue(valueBag.val)
obs.value = false
XCTAssertFalse(valueBag.val)
}
func testMap() {
let obs = HIPObservable<Bool>(false)
let mappedObs = obs.map({ !$0 })
let valueBag = ValueBag<Bool>(mappedObs.value)
mappedObs.debugSubscribe(onChange: valueBag.set)
obs.value = true
XCTAssertFalse(valueBag.val)
obs.value = false
XCTAssertTrue(valueBag.val)
}
func testFilter() {
let obs = HIPObservable<Bool>(true)
let filteredObs = try! obs.filter({ $0 })
let valueBag = ValueBag<Bool>(filteredObs.value)
filteredObs.debugSubscribe(onChange: valueBag.set)
obs.value = true
XCTAssertTrue(valueBag.val)
obs.value = false
XCTAssertTrue(valueBag.val)
}
func testFilterFail() {
let obs = HIPObservable<Bool>(false)
XCTAssertThrowsError(try obs.filter({ $0 }), "Observable creation should fail") {
switch $0 {
case HIPObservableError.InvalidInitialValue: break
default: XCTFail("Wrong error")
}
}
}
func testSkipping() {
let obs = HIPObservable<Int>(0, { _, newValue in return newValue % 2 == 0 }) // skip all even numbers
let valueBag = ValueBag<Int>(obs.value)
obs.debugSubscribe(onChange: valueBag.set)
obs.value += 1
XCTAssertEqual(valueBag.val, 1)
obs.value += 1
XCTAssertEqual(valueBag.val, 1)
obs.value += 1
XCTAssertEqual(valueBag.val, 3)
obs.value += 1
XCTAssertEqual(valueBag.val, 3)
obs.value += 1
XCTAssertEqual(valueBag.val, 5)
}
}
class HIPReadOnlyObservableTests: XCTestCase {
func testReadOnlyObservable() {
// setting obs.value is not possible (enforced by type system!); you have to use provided setter function
let (obs, setter) = HIPReadOnlyObservable<Int>.create(1)
setter(2)
XCTAssertEqual(obs.value, 2)
setter(3)
XCTAssertEqual(obs.value, 3)
}
}
class HIPLegacyShimTests: XCTestCase {
func testEquatable() {
let equatableObs = HIPObservableEquatable<Int>(0)
let counter = Counter()
_ = equatableObs.subscribe(withObject: equatableObs, callback: counter.increment)
equatableObs.value = 0
XCTAssertEqual(counter.n, 0)
equatableObs.value = 1
XCTAssertEqual(counter.n, 1)
equatableObs.value = 1
XCTAssertEqual(counter.n, 1)
equatableObs.value = 2
XCTAssertEqual(counter.n, 2)
}
func testOptional() {
let optionalObs = HIPEventedPropertyOptional<Int>(nil)
let counter = Counter()
_ = optionalObs.subscribe(withObject: optionalObs, callback: counter.increment)
optionalObs.value = nil
XCTAssertEqual(counter.n, 0)
optionalObs.value = 1
XCTAssertEqual(counter.n, 1)
optionalObs.value = 1
XCTAssertEqual(counter.n, 1)
optionalObs.value = 2
XCTAssertEqual(counter.n, 2)
optionalObs.value = nil
XCTAssertEqual(counter.n, 3)
}
}
|
import UIKit
private enum RecipeFormBaseSectionRow: Int, CaseIterable {
case photo
case name
case note
}
private enum RecipeFormSection: Int, CaseIterable {
case base
case ingredients
case steps
}
// swiftlint:disable anyobject_protocol
protocol RecipeFormTableProviderDelegate: class {
var tableView: UITableView! { get }
func provider(_ provider: RecipeFormTableProvider, didDequeueNameTextField textField: UITextField)
func provider(_ provider: RecipeFormTableProvider, didDequeueNoteTextField textField: UITextField)
func providerDidSelectAddPhoto(_ provider: RecipeFormTableProvider)
func providerDidSelectAddIngredient(_ provider: RecipeFormTableProvider)
func providerDidSelectAddStep(_ provider: RecipeFormTableProvider)
}
// swiftlint:enable anyobject_protocol
class RecipeFormTableProvider: NSObject, UITableViewDataSource, UITableViewDelegate {
weak var delegate: RecipeFormTableProviderDelegate?
private var image: UIImage?
private var ingredients = [Ingredient]()
private var steps = [String]()
func insert(_ image: UIImage) {
self.image = image
let indexPath = IndexPath(row: RecipeFormBaseSectionRow.photo.rawValue,
section: RecipeFormSection.base.rawValue)
delegate?.tableView.reloadRows(at: [indexPath], with: .automatic)
}
func insert(_ ingredient: Ingredient) {
let indexPath = IndexPath(row: ingredients.count, section: RecipeFormSection.ingredients.rawValue)
ingredients.append(ingredient)
delegate?.tableView.insertRows(at: [indexPath], with: .automatic)
}
func insert(_ step: String) {
let indexPath = IndexPath(row: steps.count, section: RecipeFormSection.steps.rawValue)
steps.append(step)
delegate?.tableView.insertRows(at: [indexPath], with: .automatic)
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return RecipeFormSection.allCases.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case RecipeFormSection.base.rawValue:
return RecipeFormBaseSectionRow.allCases.count
case RecipeFormSection.ingredients.rawValue:
return ingredients.count + 1
case RecipeFormSection.steps.rawValue:
return steps.count + 1
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case RecipeFormSection.base.rawValue:
return baseCell(with: tableView, indexPath: indexPath)
case RecipeFormSection.ingredients.rawValue:
return ingredientCell(with: tableView, indexPath: indexPath)
case RecipeFormSection.steps.rawValue:
return stepCell(with: tableView, indexPath: indexPath)
default:
return UITableViewCell()
}
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let delegate = delegate else {
return
}
switch indexPath.section {
case RecipeFormSection.base.rawValue:
if indexPath.row == RecipeFormBaseSectionRow.photo.rawValue {
delegate.providerDidSelectAddPhoto(self)
}
case RecipeFormSection.ingredients.rawValue:
if ingredients.count == indexPath.row {
delegate.providerDidSelectAddIngredient(self)
}
case RecipeFormSection.steps.rawValue:
if steps.count == indexPath.row {
delegate.providerDidSelectAddStep(self)
}
default:
return
}
}
// MARK: - Private
private func baseCell(with tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case RecipeFormBaseSectionRow.photo.rawValue:
return photoCell(with: tableView, indexPath: indexPath)
case RecipeFormBaseSectionRow.name.rawValue:
return nameCell(with: tableView, indexPath: indexPath)
case RecipeFormBaseSectionRow.note.rawValue:
return noteCell(with: tableView, indexPath: indexPath)
default:
return UITableViewCell()
}
}
private func photoCell(with tableView: UITableView, indexPath: IndexPath) -> RecipePhotoTableViewCell {
let cell: RecipePhotoTableViewCell = tableView.dequeueReusableCellForIndexPath(indexPath)
if let image = image {
cell.populate(with: image)
}
return cell
}
private func nameCell(with tableView: UITableView, indexPath: IndexPath) -> RecipeNameTableViewCell {
let cell: RecipeNameTableViewCell = tableView.dequeueReusableCellForIndexPath(indexPath)
delegate?.provider(self, didDequeueNameTextField: cell.nameTextField)
return cell
}
private func noteCell(with tableView: UITableView, indexPath: IndexPath) -> RecipeNoteTableViewCell {
let cell: RecipeNoteTableViewCell = tableView.dequeueReusableCellForIndexPath(indexPath)
delegate?.provider(self, didDequeueNoteTextField: cell.noteTextField)
return cell
}
private func ingredientCell(with tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
if ingredients.count > indexPath.row {
return ingredientItemCell(with: tableView, indexPath: indexPath)
} else {
return ingredientActionCell(with: tableView, indexPath: indexPath)
}
}
private func ingredientItemCell(with tableView: UITableView, indexPath: IndexPath) -> RecipeItemTableViewCell {
let ingredient = ingredients[indexPath.row]
let cell: RecipeItemTableViewCell = tableView.dequeueReusableCellForIndexPath(indexPath)
cell.populate(with: ingredient.details)
return cell
}
private func ingredientActionCell(with tableView: UITableView, indexPath: IndexPath) -> RecipeActionTableViewCell {
let cell: RecipeActionTableViewCell = tableView.dequeueReusableCellForIndexPath(indexPath)
cell.populate(with: "recipeFormTableProvider.addIngredient".localized())
return cell
}
private func stepCell(with tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
if steps.count > indexPath.row {
return stepItemCell(with: tableView, indexPath: indexPath)
} else {
return stepActionCell(with: tableView, indexPath: indexPath)
}
}
private func stepItemCell(with tableView: UITableView, indexPath: IndexPath) -> RecipeItemTableViewCell {
let step = steps[indexPath.row]
let cell: RecipeItemTableViewCell = tableView.dequeueReusableCellForIndexPath(indexPath)
cell.populate(with: step)
return cell
}
private func stepActionCell(with tableView: UITableView, indexPath: IndexPath) -> RecipeActionTableViewCell {
let cell: RecipeActionTableViewCell = tableView.dequeueReusableCellForIndexPath(indexPath)
cell.populate(with: "recipeFormTableProvider.addStep".localized())
return cell
}
}
|
//
// QuizViewController.swift
// Quiz
//
// Created by 横溝心美 on 2020/12/11.
// Copyright © 2020 横溝心美. All rights reserved.
//
import UIKit
class QuizViewController: UIViewController {
//問題文を格納する配列
var quizArray = [Any]()
//正解数を数える為の変数
var correctAnswer: Int = 0
//答えのラベルを表示
@IBOutlet weak var answerImage: UIImageView!
//クイズを表示する為のTextView
@IBOutlet var quizTextView: UITextView!
//選択肢のボタン
@IBOutlet weak var choice1: UIButton!
@IBOutlet weak var choice2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
choice1.titleLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping
choice1.titleLabel!.numberOfLines = 0
choice1.titleLabel!.textAlignment = NSTextAlignment.center
choice2.titleLabel!.lineBreakMode = NSLineBreakMode.byWordWrapping
choice2.titleLabel!.numberOfLines = 0
choice2.titleLabel!.textAlignment = NSTextAlignment.center //quizArrayに問題文、2つの選択肢、答えの番号が入った配列を追加
quizArray.append(["農園で半ば強制的にコーヒー豆の収穫作業をさせられている子供は児童労働に該当するか?", "Yes","NO",1])
quizArray.append(["国際労働機関ILOによると、5~17歳の子どものおよそ1億5,200万人が児童労働をしています。(2016年調査) これは世界の子どもの25人に一人の割合ですか?", "Yes","No",2])
quizArray.append(["子どもの就労人口は多い場所からアフリカ、アジア太平洋、南北アメリカ、欧州・中央アジア ですが、特に児童労働が多い国は?", "ブルキナファソ","チャド",2])
quizArray.append(["2019年現在、フィリピンの大統領はドゥテルテです。彼は、麻薬の撲滅と児童の保護に注力し、犯罪者に対してはその場での射殺も辞さない超法規的な政策を掲げ、国際社会に波紋を投げかけました。正しいのはどちらですか?", " 保護者以外の人物が一緒に街を歩いていても逮捕されない"," 危ない場所は閉鎖または立ち入り禁止",2])
quizArray.append(["子どもたちの状況に改善があった指標は以下のとおりです。・5歳未満で死亡する子ども・発育阻害の子ども・学校に通う子ども ・児童労働に従事する子ども ・児童婚または強制的に結婚させられる少女 ・10代で出産する少女 ・殺害される子ども その指標の中で、唯一、悪化している数値は、紛争により避難を強いられた子どもだと思いますか?", "Yes","NO",1])
quizArray.append(["児童労働に従事している子どもを男女別に見ると、中東・北アフリカと、ラテンアメリカとカリブ海諸国では、男の子の割合が女の子よりもわずかに多くなっています。その他の地域においては、児童労働に従事している子どもの男女比はほぼ同じです。では家庭内での無給の労働を強いられる割合がより高いのはどちらですか?", "女の子","男の子",1])
//問題文をシャッフル
quizArray.shuffle()
choiceQuiz()
// Do any additional setup after loading the view.
}
func choiceQuiz() {
//一時的にクイズを取り出しておく配列
let tmpArry = quizArray[0] as! [Any]
//問題文を表示
quizTextView.text = tmpArry[0] as? String
//選択肢ボタンにそれぞれの選択肢をセット
choice1.setTitle(tmpArry[1] as? String, for: .normal)
choice2.setTitle(tmpArry[2] as? String, for: .normal)
}
func performSegueToResult(){
performSegue(withIdentifier: "toResultView", sender: nil)
}
@IBAction func choiceAnswer(sender: UIButton){
//問題文をtmpArraに出す
let tmpArray = quizArray[0] as! [Any]
//もし答えが完全一致のとき ボタンのタグ
if tmpArray[3] as! Int == sender.tag{
//正解数を増やす
correctAnswer = correctAnswer + 1
//正解したら丸の画像をanswerviewに出す
answerImage.image = UIImage(named: "maru.png")
} else {
//間違っていたらバツの画像をanswerviewに出す
answerImage.image = UIImage(named: "batsu.png")
}
//解いた問題をquizArrayから取り除く
quizArray.remove(at: 0)
//解いた問題数の合計があらかじめ設定していた問題数に達したら結果画面へ
if quizArray.count == 0{
performSegueToResult()
}else{
choiceQuiz()
}
}
@IBAction func next(_ sender: Any) {
}
//セグエを準備(perpre)するときに呼ばれるメゾット
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toResultView" {
let resultViewController = segue.destination as! ResultViewController
resultViewController.correctAnswer = self.correctAnswer
}
}
/*
// 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.
}
*/
}
|
//
// CadastrarVendedorViewController.swift
// Zap
//
// Created by Matheus Herminio de Carvalho on 30/09/17.
// Copyright © 2017 Zap. All rights reserved.
//
import UIKit
import FirebaseDatabase
class CadastrarVendedorViewController: UIViewController, UITextFieldDelegate {
var dbref: DatabaseReference!
let defaults = UserDefaults.standard
var loja_id: DatabaseReference!
var vendedor_id: DatabaseReference!
@IBOutlet weak var nomeLojaTextField: UITextField!
@IBOutlet weak var nomeVendedorTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.nomeLojaTextField.delegate = self
self.nomeLojaTextField.tag = 0
self.nomeVendedorTextField.delegate = self
self.nomeVendedorTextField.tag = 1
dbref = Database.database().reference()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cadastrarButton(_ sender: Any?) {
//DECLARACAO DE ALERTS
let alertNomeLoja = UIAlertController(title: "Loja Inválida", message: "Por favor, digite o nome da loja.", preferredStyle: UIAlertControllerStyle.alert)
alertNomeLoja.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
let alertNomeVendedor = UIAlertController(title: "Vendedor Inválido", message: "Por favor, digite o nome do vendedor.", preferredStyle: UIAlertControllerStyle.alert)
alertNomeVendedor.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
//VALIDACOES
var dadosValidos = true
if dadosValidos {
if let nomeLoja = self.nomeLojaTextField.text {
if nomeLoja == "" {
self.present(alertNomeLoja, animated: true, completion: nil)
dadosValidos = false
}
} else {
dadosValidos = false
}
}
if dadosValidos {
if let nomeVendedor = self.nomeVendedorTextField.text {
if nomeVendedor == "" {
self.present(alertNomeVendedor, animated: true, completion: nil)
dadosValidos = false
}
} else {
dadosValidos = false
}
}
//PROCESSAMENTO DOS DADOS
if dadosValidos {
self.dbref.child("lojas").queryOrdered(byChild: "nome").queryEqual(toValue: self.nomeLojaTextField.text!).observeSingleEvent(of: .value, with: { (snapshot) in
var existeLoja = false
for snap in snapshot.children {
let value = (snap as! DataSnapshot).value as? NSDictionary
let nomeLoja = value?["nome"] as? String ?? ""
print("Nome da loja: \(nomeLoja)")
if nomeLoja == self.nomeLojaTextField.text! {
print("A LOJA EXISTE")
existeLoja = true
self.loja_id = (snap as! DataSnapshot).ref
print("Loja_ID: \(self.loja_id.key)")
}
}
if !existeLoja {
print("A LOJA NÃO EXISTE")
self.loja_id = self.dbref.child("lojas").childByAutoId()
self.loja_id.setValue(["nome": self.nomeLojaTextField.text!])
print("NOVA LOJA ADICIONADA")
}
if self.vendedor_id == nil {
self.vendedor_id = self.dbref.child("vendedores").childByAutoId()
self.vendedor_id.setValue(["nome": self.nomeVendedorTextField.text!, "loja_id": self.loja_id.key, "disponivel": true])
print("NOVO VENDEDOR ADICIONADO")
self.defaults.set(self.vendedor_id.key, forKey: "Vendedor")
self.defaults.set(self.loja_id.key, forKey: "LojaKey")
print("NOVO VENDEDOR GRAVADO")
} else {
print("VENDEDOR EXISTE")
}
self.defaults.set("segueSelExiste", forKey: "TipoAcesso")
self.performSegue(withIdentifier: "moveToChatVendedor", sender: self)
}) { (error) in
print(error.localizedDescription)
dadosValidos = false
}
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Try to find next responder
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textField.resignFirstResponder()
self.cadastrarButton(nil)
}
// Do not add a line break
return false
}
}
|
// SignedNumericExtensionsTests.swift - Copyright 2020 SwifterSwift
@testable import SwifterSwift
import XCTest
final class SignedNumericExtensionsTests: XCTestCase {
func testString() {
let number1: Double = -1.2
XCTAssertEqual(number1.string, "-1.2")
let number2: Float = 2.3
XCTAssertEqual(number2.string, "2.3")
}
func testAsLocaleCurrency() {
let number1: Double = 3.2
XCTAssertEqual(number1.asLocaleCurrency, "$3.20")
let number2 = Double(10.23)
if let symbol = Locale.current.currencySymbol {
XCTAssertNotNil(number2.asLocaleCurrency!)
XCTAssert(number2.asLocaleCurrency!.contains(symbol))
}
XCTAssertNotNil(number2.asLocaleCurrency!)
XCTAssert(number2.asLocaleCurrency!.contains("\(number2)"))
let number3 = 10
if let symbol = Locale.current.currencySymbol {
XCTAssertNotNil(number3.asLocaleCurrency)
XCTAssert(number3.asLocaleCurrency!.contains(symbol))
}
XCTAssertNotNil(number3.asLocaleCurrency)
XCTAssert(number3.asLocaleCurrency!.contains("\(number3)"))
}
}
|
// RUN: %target-parse-verify-swift
struct UTF8Test {}
|
//
// UserCollectionViewCell.swift
// SocialApp
//
// Created by Дима Давыдов on 06.10.2020.
//
import UIKit
class UserCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var avatarView: UIImageView!
@IBOutlet weak var likeButton: LikeUIButton!
}
|
//
// Queue.swift
// AlgorithmSwift
//
// Created by Liangzan Chen on 11/13/17.
// Copyright © 2017 clz. All rights reserved.
//
import Foundation
public struct Queue<T> {
fileprivate var array = [T]()
public var isEmpty: Bool {
return array.isEmpty
}
public var count: Int {
return array.count
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
if array.isEmpty {
return nil
}
else {
return array.removeFirst()
}
}
public var peek: T? {
return array.first
}
public mutating func removeAll() {
array.removeAll()
}
}
public struct Queue1<T> {
private var stack1 = Stack<T>()
private var stack2 = Stack<T>()
public mutating func enqueue(_ element: T) {
stack1.push(element)
}
public mutating func dequeue() -> T? {
if !stack2.isEmpty {
return stack2.pop()
}
else {
while !stack1.isEmpty {
stack2.push(stack1.pop()!)
}
return stack2.pop()
}
}
}
public struct Deque1<T> {
private var stack1 = Stack<T>()
private var stack2 = Stack<T>()
public mutating func enqueueAtFront(_ element: T) {
if !stack2.isEmpty {
stack2.push(element)
}
else {
while !stack1.isEmpty {
stack2.push(stack1.pop()!)
}
stack2.push(element)
}
}
public mutating func enqueueAtBack(_ element: T) {
stack1.push(element)
}
public mutating func dequeueAtFront() -> T? {
if !stack2.isEmpty {
return stack2.pop()
}
else {
while !stack1.isEmpty {
stack2.push(stack1.pop()!)
}
return stack2.pop()
}
}
public mutating func dequeueAtBack() -> T? {
if !stack1.isEmpty {
return stack1.pop()
}
else {
while !stack2.isEmpty {
stack1.push(stack2.pop()!)
}
return stack1.pop()
}
}
}
|
//
// HippoManager.swift
// Hippo
//
// Created by Vishal on 11/11/18.
// Copyright © 2018 clicklabs. All rights reserved.
//
import Hippo
#if canImport(IQKeyboardManager)
import IQKeyboardManager
#endif
#if canImport(HippoCallClient)
import HippoCallClient
#endif
/**
This class is Created to have a singleton instance of delegate handler.
This is example class anyone can use it or can create there own.
To get it working set "HippoConfig.shared.setHippoDelegate(delegate: HippoManager.shared)" :
1. application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool in appDelegate
2. pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) where you have declared PKPushRegistryDelegate
**/
class HippoManager: HippoDelegate {
static let shared = HippoManager()
func hippoUnreadCount(_ totalCount: Int) {
/**
Write your code to set total unread count of logged in user
**/
}
func hippoUserUnreadCount(_ usersCount: [String : Int]) {
/**
Write your code to set unread count of indiviual user list you have given in "getUnreadCount"
**/
}
func hippoDeinit() {
#if canImport(IQKeyboardManager)
IQKeyboardManager.shared().isEnableAutoToolbar = true
IQKeyboardManager.shared().isEnabled = true
#endif
}
func hippoDidLoad() {
/**
Here hippo Screen appears, Perform action you want to do on screen aperring
Example: Disable Any keyboard manger you are using.
**/
#if canImport(IQKeyboardManager)
IQKeyboardManager.shared().isEnabled = false
IQKeyboardManager.shared().isEnableAutoToolbar = false
#endif
}
func hippoMessageRecievedWith(response: [String : Any], viewController: UIViewController) {
/**
This delegate is for the Button action on message,
example : Payment, webview, or any other screen
**/
}
//This delegate will only work if you add 'Hippo/Call' in pod file
#if canImport(HippoCallClient)
func loadCallPresenterView(request: CallPresenterRequest) -> CallPresenter? {
/**
This function is called when some one call Or app user wants to call,
Change this function as per your requirements.
Note: nil means no screen will be presented and videoCall/Audio call will not work
**/
switch request.callType {
case .video:
let videoView = VideoCallView.loadVideoCallView()
return videoView
case .audio:
if #available(iOS 10.0, *) {
let audioCallPresenter = AudioCallPresenter.shared
audioCallPresenter.setWith(callUUID: request.uuid, isDialedByUser: request.isDialedByUser)
return audioCallPresenter
}
}
return nil
}
#endif
}
|
//
// Tree.swift
// tree
//
// Created by Котов Иван on 12.03.2020.
// Copyright © 2020 Котов Иван. All rights reserved.
//
import Foundation
class Tree< Value> {
private class Node {
public var key: String
public var value: Value
public var left:Node? = nil
public var right:Node? = nil
public var height:Int = 0
init(_key: String, _value: Value) {
self.key = _key
self.value = _value
}
}
private var root:Node? = nil
init() {
}
init(key: String, value: Value)
{
self.root = Node(_key: key,_value: value)
}
private func _height(node:Node?) -> Int
{
return node?.height ?? 0
}
private func recalcHeight(node: Node)
{
node.height = max(_height(node: node.left), _height(node: node.right)) + 1
}
private func deltaHeight(node: Node) -> Int
{
return _height(node: node.right) - _height(node:node.left)
}
private func rotateLeft(node:Node) -> Node
{
let newRoot = node.right
node.right = newRoot!.left
newRoot!.left = node
recalcHeight(node: node)
recalcHeight(node: newRoot!)
return newRoot!
}
private func rotateRight(node: Node) -> Node
{
let newRoot = node.left
node.left = newRoot?.right
newRoot?.right = node
recalcHeight(node: node)
recalcHeight(node: newRoot!)
return newRoot!
}
private func balance(node: Node) -> Node
{
recalcHeight(node: node)
if (deltaHeight(node: node) < -1)
{
if (node.left != nil && deltaHeight(node: node.left!) > 0)
{
node.left = rotateLeft(node: node.left!)
}
return rotateRight(node: node)
} else if (deltaHeight(node: node) > 1)
{
if (node.right != nil && deltaHeight(node: node.right!) < 0)
{
node.right = rotateRight(node: node.right!)
}
return rotateLeft(node: node)
}
return node
}
private func _add(key: String, value: Value, node: Node?) -> Node
{
guard let tmp = node else {
return Node(_key: key, _value: value)
}
if (key < tmp.key) {
tmp.left = _add(key: key, value: value, node: tmp.left)
} else if (key == tmp.key)
{
tmp.value = value
return tmp
} else
{
tmp.right = _add(key: key, value: value, node: tmp.right)
}
return balance(node: tmp)
}
func add(key: String, value: Value)
{
if (key != "") {
root = _add(key: key, value: value, node: root)
}
}
private func findmin(node: Node) -> Node
{
guard let tmp = node.left else
{
return node
}
return findmin(node: tmp)
}
private func removemin(node: Node) -> Node?
{
guard let tmp = node.left else {
return node.right;
}
node.left = removemin(node: tmp);
return balance(node: node);
}
private func _remove(node: Node?, key: String) -> Node?
{
guard let tmp = node else {
return nil
}
if( key < tmp.key )
{
tmp.left = _remove(node: tmp.left,key: key);
}
else if( key > tmp.key )
{
tmp.right = _remove(node: tmp.right,key: key);
}
else
{
let q = tmp.left;
let r = tmp.right;
guard let right = r else {
return q;
}
let min = findmin(node:right);
min.right = removemin(node:right);
min.left = q;
return balance(node:min);
}
return balance(node:tmp);
}
func remove(key:String)
{
if (key != "") {
root = _remove(node: root, key: key)
}
}
func get(key:String) -> Value?
{
if (key == "") {
return nil
}
var cur = root
while cur != nil {
if ( cur?.key == key)
{
return cur?.value
} else if (key < cur!.key)
{
cur = cur?.left
} else {
cur = cur?.right
}
}
return nil
}
}
|
//
// Planet.swift
// Little Orion
//
// Created by Thomas Ricouard on 25/11/2016.
// Copyright © 2016 Thomas Ricouard. All rights reserved.
//
import GameplayKit
import SceneKit
struct PlanetId: Equatable, Hashable {
let systemId: UniverseId
let index: Int
var hashValue: Int {
get {
return systemId.hashValue * index.hashValue
}
}
init(systemId: UniverseId, index: Int) {
self.systemId = systemId
self.index = index
}
}
//MARK: - Planet
class PlanetEntity: SystemBody, Discoverable {
static let planetRessourceModifier = ResourcesLoader.loadPlanetResource(name: "planetResourcesModifier")!
static let planetNames = ResourcesLoader.loadArrayTextResource(name: "planetsText")!
enum Kind: UInt32 {
case desert, oceanic, toxic, continental, frozen, volcanic
private static let _count: Kind.RawValue = {
var maxValue: UInt32 = 0
while let _ = Kind(rawValue: maxValue) {
maxValue += 1
}
return maxValue
}()
static func randomKind() -> Kind {
let rand = arc4random_uniform(_count)
return Kind(rawValue: rand)!
}
func name() -> String {
return planetNames[Int(rawValue)]
}
func image() -> UIImage {
return UIImage(named: ResourcesLoader.loadArrayTextResource(name: "planetsText")![Int(rawValue)])!
}
func ressources() -> [String: Int] {
return planetRessourceModifier[name()]!
}
}
var discovered: Bool {
return store.state.playerState.player.discoveredPlanets.contains(id)
}
var dayToDiscover: Int {
return 200
}
let id: PlanetId
let kind: Kind
let scale: CGFloat
var planet3D: Planet3D! = nil
//resource
let food: Food
let energy: Energy
let mineral: Mineral
let reseach: Research
var resourceScore: Int {
get {
return food.abundance.rawValue +
energy.abundance.rawValue +
mineral.abundance.rawValue +
reseach.abundance.rawValue
}
}
//The radius, in KM of the planet.
var radius: CGFloat {
get {
return UniverseRules.basePlanetsRadius * scale
}
}
//How many space are buildable on this planet.
var space: Int {
get {
let divider = (UniverseRules.basePlanetsRadius * UniverseRules.superPlanetScale) / CGFloat(UniverseRules.planetMaxSpace)
return Int(radius / divider)
}
}
//A planet may or may not have inhabitants.
private var inhabitants: [Pop]?
//The parent system of the planet.
let system: SystemEntity
public init(in system: SystemEntity, order: Int) {
id = PlanetId(systemId: system.id, index: order)
self.system = system
kind = Kind.randomKind()
var tmpScale = CGFloat((arc4random_uniform(600) + 400)) / 1000
if tmpScale > 0.9 && arc4random_uniform(UniverseRules.superPlanetSpwawnProbability) == 1 {
//1 out of X chance to generate a super planet if scale is already big.
tmpScale = UniverseRules.superPlanetScale
}
scale = tmpScale
food = Food(abundance: PlanetResource.Abundance(rawValue: kind.ressources()["Food"]!)!)
mineral = Mineral(abundance: PlanetResource.Abundance(rawValue: kind.ressources()["Mineral"]!)!)
energy = Energy(abundance: PlanetResource.Abundance(rawValue: kind.ressources()["Energy"]!)!)
reseach = Research(abundance: PlanetResource.Abundance(rawValue: kind.ressources()["Research"]!)!)
super.init(name: "Planet \(order)")
planet3D = Planet3D(planet: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func inhabitantsCount() -> Int {
if let inhabitants = inhabitants {
return inhabitants.count
}
return 0
}
func addInhabitants(pop: Pop) {
if inhabitants == nil {
inhabitants = [Pop]()
}
inhabitants?.append(pop)
}
}
//MARK: - 3D
class Planet3D {
var skybox: [UIImage] {
get {
return [#imageLiteral(resourceName: "Skybox_PositiveX"),
#imageLiteral(resourceName: "Skybox_NegativeX"),
#imageLiteral(resourceName: "Skybox_PositiveY"),
#imageLiteral(resourceName: "Skybox_NegativeY"),
#imageLiteral(resourceName: "Skybox_PositiveZ"),
#imageLiteral(resourceName: "Skybox_NegativeZ")]
}
}
var sphere: SCNSphere {
get {
let sphere = SCNSphere(radius: 5.0)
let textureName = planet.kind.name() + "Texture"
let material = SCNMaterial()
material.diffuse.contents = UIImage(named: textureName)
material.specular.contents = planet.system.star.kind.textureFillColor()
material.shininess = 0.8
sphere.materials = [material]
return sphere
}
}
var light: SCNNode {
get {
let omniLightNode = SCNNode()
omniLightNode.light = SCNLight()
omniLightNode.light?.color = planet.system.star.kind.textureFillColor()
omniLightNode.light?.type = .omni
omniLightNode.position = SCNVector3Make(0, 40, 40)
return omniLightNode
}
}
var planet: PlanetEntity! = nil
init(planet: PlanetEntity) {
self.planet = planet
}
}
//MARK: - Resources
class PlanetResource {
var name: String {
get {
return ""
}
}
var description: String {
get {
return ""
}
}
let abundance: Abundance
enum Abundance: Int {
case none, low, average, plenty, enormous
func abundancyDescription() -> String {
return "Coming soon"
}
}
init(abundance: Abundance) {
let randomness = arc4random_uniform(3)
if randomness == 1 && abundance.rawValue > 0 {
self.abundance = Abundance(rawValue: abundance.rawValue - 1)!
}
else if randomness == 2 && abundance.rawValue < 4 {
self.abundance = Abundance(rawValue: abundance.rawValue + 1)!
}
else {
self.abundance = abundance
}
}
}
class Food: PlanetResource {
override var name: String {
get {
return "Food"
}
}
override var description: String {
get {
return "The foods available on the planet"
}
}
}
class Mineral: PlanetResource {
override var name: String {
get {
return "Mineral"
}
}
override var description: String {
get {
return "The minerals available on the planet"
}
}
}
class Energy: PlanetResource {
override var name: String {
get {
return "Energy"
}
}
override var description: String {
get {
return "The energy available on the planet"
}
}
}
class Research: PlanetResource {
override var name: String {
get {
return "Science"
}
}
override var description: String {
get {
return "The research (for science) available on the planet"
}
}
}
|
//
// SegueProtocol.swift
// POP
//
// Created by Gang Chen on 16/12/22.
// Copyright © 2016年 陈刚. All rights reserved.
//
import UIKit
//Segue的改造,参考 Natasha 的文章:https://www.natashatherobot.com/protocol-oriented-segue-identifiers-swift/
protocol SegueHandlerType {
associatedtype SegueIdentifier: RawRepresentable
}
extension SegueHandlerType where Self: UIViewController,
SegueIdentifier.RawValue == String
{
//利用自建的类型执行perform
func performSegue(with identifier: SegueIdentifier,
sender: Any?) {
performSegue(withIdentifier: identifier.rawValue, sender: sender)
}
//对于prepare方法,只需返回对应的Identifier
func segueIdentifier(for segue: UIStoryboardSegue) -> SegueIdentifier {
guard let identifier = segue.identifier,
let segueIdentifier = SegueIdentifier(rawValue: identifier) else {
fatalError("Invalid segue identifier \(segue.identifier).") }
return segueIdentifier
}
}
|
//
// Film+CoreDataProperties.swift
// StarWars
//
// Created by Michael Meyer on 10/29/18.
// Copyright © 2018 Michael Meyer. All rights reserved.
//
//
import Foundation
import CoreData
extension Film {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Film> {
return NSFetchRequest<Film>(entityName: "Film")
}
@NSManaged public var director: String?
@NSManaged public var episode_id: Int16
@NSManaged public var opening_crawl: String?
@NSManaged public var producer: String?
@NSManaged public var release_date: String?
@NSManaged public var title: String?
@NSManaged public var url: String?
}
|
//
// Data+Extension.swift
// Crypto
//
// Created by lonnie on 2020/8/14.
// Copyright © 2020 lonnie. All rights reserved.
//
import Foundation
public extension Data {
init(hex: String) throws {
self.init()
var buffer: UInt8?
var skip = hex.hasPrefix("0x") ? 2 : 0
for char in hex.unicodeScalars.lazy {
guard skip == 0 else {
skip -= 1
continue
}
guard char.value >= 48 && char.value <= 102 else {
throw CryptoError.codingError
}
let v: UInt8
let c: UInt8 = UInt8(char.value)
switch c {
case let c where c <= 57:
v = c - 48
case let c where c >= 65 && c <= 70:
v = c - 55
case let c where c >= 97:
v = c - 87
default:
throw CryptoError.codingError
}
if let b = buffer {
append(b << 4 | v)
buffer = nil
} else {
buffer = v
}
}
if let b = buffer {
append(b)
}
}
var hex: String {
return `lazy`.reduce("") {
var s = String($1, radix: 16)
if s.count == 1 {
s = "0" + s
}
return $0 + s
}
}
init(random count: Int) {
var items = [UInt8](repeating: 0, count: count)
arc4random_buf(&items, items.count)
self.init(items)
}
func string(_ encoding: Encoding) throws -> String {
var value: String?
switch encoding {
case .ascii:
value = String(data: self, encoding: .ascii)
case .utf8:
value = String(data: self, encoding: .utf8)
case .hex:
value = hex
case .base64:
value = self.base64EncodedString()
}
guard let item = value else {
throw CryptoError.codingError
}
return item
}
func process(_ options: ProcessOptions) throws -> Data {
switch options.method {
case .encrypt(let algorithm):
return try symmetryCrypt(algorithm, .encrypt, options)
case .decrypt(let algorithm):
return try symmetryCrypt(algorithm, .decrypt, options)
case .digest(let digest):
return digest.process(self)
case .hmac(let algorithm):
guard let key: DataConvertable = options[.key] else { throw CryptoError.invalidKey }
return try HMAC(algorithm, key: key.toData()).process(self)
case .changeEncoding:
return self
}
}
func symmetryCrypt(_ algorithm: SymmetricCipher.Algorithm, _ operation: SymmetricCipher.Operation, _ options: ProcessOptions) throws -> Data {
let mode: SymmetricCipher.Mode = options[.mode] ?? .cbc
let padding: SymmetricCipher.Padding = options[.padding] ?? .pkcs7
guard let key: DataConvertable = options[.key] else { throw CryptoError.invalidKey }
var iv: DataConvertable!
if let theIV: DataConvertable = options[.iv] {
iv = theIV
} else {
iv = Data()
}
let cipher = try SymmetricCipher(
algorithm,
key: key.toData(),
iv: iv.toData(),
padding: padding,
mode: mode
)
return try cipher.process(operation, self)
}
}
|
//
// PowerOf.swift
// MyGestureRecognizer
//
// Created by Marcin on 10.07.2017.
// Copyright © 2017 Marcin Włoczko. All rights reserved.
//
import Foundation
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
|
//
// Operation.swift
// Pods
//
// Created by Armando Contreras on 9/15/15.
//
//
import Foundation
import UIKit
class Operation: NSOperation {
// use the KVO mechanism to indicate that changes to "state" affect other properties as well
class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> {
return ["state"]
}
// MARK: State Management
private enum State: Int, Comparable {
/// The initial state of an `Operation`.
case Initialized
/// The `Operation` is ready to begin evaluating conditions.
case Pending
/// The `Operation` is evaluating conditions.
case EvaluatingConditions
/**
The `Operation`'s conditions have all been satisfied, and it is ready
to execute.
*/
case Ready
/// The `Operation` is executing.
case Executing
/**
Execution of the `Operation` has finished, but it has not yet notified
the queue of this.
*/
case Finishing
/// The `Operation` has finished executing.
case Finished
/// The `Operation` has been cancelled.
case Cancelled
}
func execute() {
print("\(self.dynamicType) must override `execute()`.")
finish()
}
/**
Indicates that the Operation can now begin to evaluate readiness conditions,
if appropriate.
*/
func willEnqueue() {
state = .Pending
}
/// Private storage for the `state` property that will be KVO observed.
private var _state = State.Initialized
private var state: State {
get {
return _state
}
set(newState) {
// Manually fire the KVO notifications for state change, since this is "private".
willChangeValueForKey("state")
switch (_state, newState) {
case (.Cancelled, _):
break // cannot leave the cancelled state
case (.Finished, _):
break // cannot leave the finished state
default:
assert(_state != newState, "Performing invalid cyclic state transition.")
_state = newState
}
didChangeValueForKey("state")
}
}
private var _internalErrors = [NSError]()
override func cancel() {
cancelWithError()
}
func cancelWithError(error: NSError? = nil) {
if let error = error {
_internalErrors.append(error)
}
state = .Cancelled
}
private(set) var observers = [OperationObserver]()
func addObserver(observer: OperationObserver) {
assert(state < .Executing, "Cannot modify observers after execution has begun.")
observers.append(observer)
}
private var hasFinishedAlready = false
final func finish(errors: [NSError] = []) {
if !hasFinishedAlready {
hasFinishedAlready = true
state = .Finishing
state = .Finished
}
}
}
// Simple operator functions to simplify the assertions used above.
private func <(lhs: Operation.State, rhs: Operation.State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
private func ==(lhs: Operation.State, rhs: Operation.State) -> Bool {
return lhs.rawValue == rhs.rawValue
}
|
import Foundation
protocol CharactersDelegate: AnyObject {
func selectedCharacter(position: Int)
}
|
//
// ImageStore.swift
// Homepwner
//
// Created by Tres Bailey on 12/9/14.
// Copyright (c) 2014 TRESBACK. All rights reserved.
//
import UIKit
class ImageStore: NSObject {
var imageDict = [String:UIImage]()
/*
Init method for registering to get Low Memory Notfiications
*/
override init() {
super.init()
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: "clearCache:", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
}
/*
Removes all images from the cache
*/
func clearCache(note: NSNotification) {
println("Flushing \(imageDict.count) images out of the cache")
imageDict.removeAll(keepCapacity: false)
}
/*
Creates a new path in the documents directory for storing images
*/
func imagePathForKey(key: String) -> String {
let documentsDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentDirectory = documentsDirectories.first as String
return documentDirectory.stringByAppendingPathComponent(key)
}
func setImage(image: UIImage, forKey key: String) {
imageDict[key] = image
// Create full path for image
let imagePath = imagePathForKey(key)
// Turn image into JPEG data
// Could use UIImagePNGRepresentation for Bronze Challenge
let data = UIImageJPEGRepresentation(image, 0.5)
// Write it to full path
data.writeToFile(imagePath, atomically: true)
}
func imageForKey(key: String) -> UIImage? {
if let existingImage = imageDict[key] {
return existingImage
} else {
let imagePath = imagePathForKey(key)
if let imageFromDisk = UIImage(contentsOfFile: imagePath) {
setImage(imageFromDisk, forKey: key)
return imageFromDisk
} else {
return nil
}
}
}
func deleteImageForKey(key: String) {
imageDict.removeValueForKey(key)
let imagePath = imagePathForKey(key)
NSFileManager.defaultManager().removeItemAtPath(imagePath, error: nil)
}
}
|
//
// RequestTopRateMovie.swift
// PruebaGlobalHitss
//
// Created by Bart on 15/09/21.
//
import Foundation
enum ApiError: Error{
case noDataAvailable
case canNotProcessData
}
class APIService : NSObject {
private let sourcesURL = URL(string: "https://api.themoviedb.org/3/movie/top_rated?api_key=4de2b7fb774fce18b8da4eab0d9441cd&language=en-US&page=1")!
func apiToGetTopRateMovie(completion : @escaping (Result<ResponseTopRate,ApiError>) -> ()){
URLSession.shared.dataTask(with: sourcesURL) { (data, urlResponse, error) in
if let data = data {
do{
let jsonDecoder = JSONDecoder()
let empData = try jsonDecoder.decode(ResponseTopRate.self, from: data)
completion(.success(empData))
return
}catch{
completion(.failure(.canNotProcessData))
}
}
}.resume()
}
}
|
//
// DividendTableVIewCell.swift
// Dividendos
//
// Created by Alliston Aleixo on 24/07/16.
// Copyright © 2016 Alliston Aleixo. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
class DividendTableViewCell : UITableViewCell {
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var companyLabel: UILabel!;
@IBOutlet weak var companyCodeLabel: UILabel!;
@IBOutlet weak var approvationDate: UILabel!;
@IBOutlet weak var exDate: UILabel!;
@IBOutlet weak var dividendImage: UIImageView!;
override func layoutSubviews() {
super.layoutSubviews();
self.cardView.alpha = 1.0;
self.cardView.layer.masksToBounds = false;
self.cardView.layer.shadowOffset = CGSize(width: 1.2, height: 1.2);
self.cardView.layer.shadowRadius = 1;
self.cardView.layer.shadowOpacity = 0.2;
self.cardView.layer.borderWidth = 0.3;
self.cardView.layer.borderColor = UIColor(red: 212/255, green: 212/255, blue: 212/255, alpha: 1).cgColor;
}
}
|
//
// MinimedPumpManagerState.swift
// Loop
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import LoopKit
import RileyLinkKit
import RileyLinkBLEKit
public struct MinimedPumpManagerState: RawRepresentable, Equatable {
public typealias RawValue = PumpManager.RawStateValue
public static let version = 2
public var batteryChemistry: BatteryChemistryType
public var preferredInsulinDataSource: InsulinDataSource
public var pumpColor: PumpColor
public var pumpModel: PumpModel
public var pumpID: String
public var pumpRegion: PumpRegion
public var lastValidFrequency: Measurement<UnitFrequency>?
public var lastTuned: Date?
public var pumpSettings: PumpSettings {
get {
return PumpSettings(pumpID: pumpID, pumpRegion: pumpRegion)
}
set {
pumpID = newValue.pumpID
pumpRegion = newValue.pumpRegion
}
}
public var pumpState: PumpState {
get {
var state = PumpState()
state.pumpModel = pumpModel
state.timeZone = timeZone
state.lastValidFrequency = lastValidFrequency
state.lastTuned = lastTuned
return state
}
set {
if let model = newValue.pumpModel {
pumpModel = model
}
lastValidFrequency = newValue.lastValidFrequency
lastTuned = newValue.lastTuned
timeZone = newValue.timeZone
}
}
public var rileyLinkConnectionManagerState: RileyLinkConnectionManagerState?
public var timeZone: TimeZone
public init(batteryChemistry: BatteryChemistryType = .alkaline, preferredInsulinDataSource: InsulinDataSource = .pumpHistory, pumpColor: PumpColor, pumpID: String, pumpModel: PumpModel, pumpRegion: PumpRegion, rileyLinkConnectionManagerState: RileyLinkConnectionManagerState?, timeZone: TimeZone, lastValidFrequency: Measurement<UnitFrequency>? = nil) {
self.batteryChemistry = batteryChemistry
self.preferredInsulinDataSource = preferredInsulinDataSource
self.pumpColor = pumpColor
self.pumpID = pumpID
self.pumpModel = pumpModel
self.pumpRegion = pumpRegion
self.rileyLinkConnectionManagerState = rileyLinkConnectionManagerState
self.timeZone = timeZone
self.lastValidFrequency = lastValidFrequency
}
public init?(rawValue: RawValue) {
guard
let version = rawValue["version"] as? Int,
let batteryChemistryRaw = rawValue["batteryChemistry"] as? BatteryChemistryType.RawValue,
let insulinDataSourceRaw = rawValue["insulinDataSource"] as? InsulinDataSource.RawValue,
let pumpColorRaw = rawValue["pumpColor"] as? PumpColor.RawValue,
let pumpID = rawValue["pumpID"] as? String,
let pumpModelNumber = rawValue["pumpModel"] as? PumpModel.RawValue,
let pumpRegionRaw = rawValue["pumpRegion"] as? PumpRegion.RawValue,
let timeZoneSeconds = rawValue["timeZone"] as? Int,
let batteryChemistry = BatteryChemistryType(rawValue: batteryChemistryRaw),
let insulinDataSource = InsulinDataSource(rawValue: insulinDataSourceRaw),
let pumpColor = PumpColor(rawValue: pumpColorRaw),
let pumpModel = PumpModel(rawValue: pumpModelNumber),
let pumpRegion = PumpRegion(rawValue: pumpRegionRaw),
let timeZone = TimeZone(secondsFromGMT: timeZoneSeconds)
else {
return nil
}
var rileyLinkConnectionManagerState: RileyLinkConnectionManagerState? = nil
// Migrate
if version == 1
{
if let oldRileyLinkPumpManagerStateRaw = rawValue["rileyLinkPumpManagerState"] as? [String : Any],
let connectedPeripheralIDs = oldRileyLinkPumpManagerStateRaw["connectedPeripheralIDs"] as? [String]
{
rileyLinkConnectionManagerState = RileyLinkConnectionManagerState(autoConnectIDs: Set(connectedPeripheralIDs))
}
} else {
if let rawState = rawValue["rileyLinkConnectionManagerState"] as? RileyLinkConnectionManagerState.RawValue {
rileyLinkConnectionManagerState = RileyLinkConnectionManagerState(rawValue: rawState)
}
}
let lastValidFrequency: Measurement<UnitFrequency>?
if let frequencyRaw = rawValue["lastValidFrequency"] as? Double {
lastValidFrequency = Measurement<UnitFrequency>(value: frequencyRaw, unit: .megahertz)
} else {
lastValidFrequency = nil
}
self.init(
batteryChemistry: batteryChemistry,
preferredInsulinDataSource: insulinDataSource,
pumpColor: pumpColor,
pumpID: pumpID,
pumpModel: pumpModel,
pumpRegion: pumpRegion,
rileyLinkConnectionManagerState: rileyLinkConnectionManagerState,
timeZone: timeZone,
lastValidFrequency: lastValidFrequency
)
}
public var rawValue: RawValue {
var value: [String : Any] = [
"batteryChemistry": batteryChemistry.rawValue,
"insulinDataSource": preferredInsulinDataSource.rawValue,
"pumpColor": pumpColor.rawValue,
"pumpID": pumpID,
"pumpModel": pumpModel.rawValue,
"pumpRegion": pumpRegion.rawValue,
"timeZone": timeZone.secondsFromGMT(),
"version": MinimedPumpManagerState.version,
]
if let rileyLinkConnectionManagerState = rileyLinkConnectionManagerState {
value["rileyLinkConnectionManagerState"] = rileyLinkConnectionManagerState.rawValue
}
if let frequency = lastValidFrequency?.converted(to: .megahertz) {
value["lastValidFrequency"] = frequency.value
}
return value
}
}
extension MinimedPumpManagerState {
static let idleListeningEnabledDefaults: RileyLinkDevice.IdleListeningState = .enabled(timeout: .minutes(4), channel: 0)
}
extension MinimedPumpManagerState: CustomDebugStringConvertible {
public var debugDescription: String {
return [
"## MinimedPumpManagerState",
"batteryChemistry: \(batteryChemistry)",
"preferredInsulinDataSource: \(preferredInsulinDataSource)",
"pumpColor: \(pumpColor)",
"pumpID: ✔︎",
"pumpModel: \(pumpModel.rawValue)",
"pumpRegion: \(pumpRegion)",
"lastValidFrequency: \(String(describing: lastValidFrequency))",
"timeZone: \(timeZone)",
String(reflecting: rileyLinkConnectionManagerState),
].joined(separator: "\n")
}
}
|
import Foundation
final class IndexPathManager {
weak private var component: Component?
init(component: Component) {
self.component = component
}
func computeIndexPath(_ indexPath: IndexPath) -> IndexPath {
guard let component = component,
let dataSource = component.componentDataSource,
component.model.layout.infiniteScrolling,
component.model.items.count >= dataSource.buffer else {
return indexPath
}
let index = indexPath.item
let wrapped = (index - dataSource.buffer < 0)
? (component.model.items.count + (index - dataSource.buffer))
: (index - dataSource.buffer)
let adjustedIndex = wrapped % component.model.items.count
return IndexPath(item: adjustedIndex, section: 0)
}
}
|
import Foundation
public struct ScienceOutputs: Codable {
public init(instances: [Instance] = []) {
self.instances = instances
details = "mega-flop-do-the-math: 08/26/2020, 15:46:50"
version = "0.02-beta"
}
public let instances: [Instance]
public let details, version: String
}
public struct Instance: Codable {
public init(id: String, features: Features) {
self.id = id
self.features = features
}
public let features: Features
public let id: String
}
public struct Features: Codable {
public init(mskHealth: Decimal, approved: Bool) {
self.mskHealth = mskHealth
mskHealthApproved = approved
relativeInjRate = 0
prediction = 0
}
public let prediction, mskHealth, relativeInjRate: Decimal
public let mskHealthApproved: Bool
}
|
//
// Created by Daniel Heredia on 2/27/18.
// Copyright © 2018 Daniel Heredia. All rights reserved.
//
// Online Book Reader
import Foundation
class Display {
var activeBook: Book?
var activeUser: User?
var pageNumber: Int
init() {
self.pageNumber = 0
}
func display(user: User) {
// Display a user
self.activeUser = user
self.refreshUsername()
}
func display(book: Book) {
// Display a book
self.activeBook = book
self.pageNumber = 0
self.refreshTitle()
self.refreshDetails()
self.refreshDetails()
}
func clearUser() {
// Clears the current user
self.activeUser = nil
self.refreshUsername()
}
func clearBook() {
// Clears the current book
self.activeBook = nil
self.pageNumber = 0
self.refreshTitle()
self.refreshDetails()
self.refreshDetails()
}
func turnPageForward() {
self.pageNumber += 1
self.refreshPage()
}
func turnPageBackward() {
self.pageNumber -= 1
self.refreshPage()
}
func refreshUsername() {
// Refresh the username display
}
func refreshTitle() {
// Updates the title
}
func refreshPage() {
// Refresh the page
}
func refreshDetails() {
// Refresh the details of the book
}
}
class Book {
let id: Int
let title: String
init(id: Int, title: String) {
self.id = id
self.title = title
}
}
class User {
let id: Int
let name: String
private(set) var registerDate: Date
private(set) var renewalDate: Date
init(id: Int, name: String, registerDate: Date) {
self.id = id
self.name = name
self.registerDate = registerDate
self.renewalDate = registerDate.addingTimeInterval(30000)
}
func renewMembership() {
// Renews the membership of the user
}
}
class UserManager {
private(set) var users: [Int: User]
init() {
self.users = [Int: User]()
}
func addUser(id: Int, name: String) -> User {
let user = User(id: id, name: name, registerDate: Date())
self.users[id] = user
return user
}
func removeUser(_ user: User) -> Bool {
if self.users[user.id] === user {
self.users[user.id] = nil
return true
} else {
return false
}
}
func removeUser(withId id: Int) -> User? {
if let user = self.users[id] {
self.users[id] = nil
return user
} else {
return nil
}
}
func findUser(withId id: Int) -> User? {
return self.users[id]
}
}
class Library {
private(set) var books: [Int: Book]
init() {
self.books = [Int: Book]()
}
func addBook(id: Int, title: String) -> Book {
let book = Book(id: id, title: title)
self.books[id] = book
return book
}
func removeBook(_ book: Book) -> Bool {
if self.books[book.id] === book {
self.books[book.id] = nil
return true
} else {
return false
}
}
func removeBook(withId id: Int) -> Book? {
if let book = self.books[id] {
self.books[id] = nil
return book
} else {
return nil
}
}
func findBook(withId id: Int) -> Book? {
return self.books[id]
}
}
class OnlineReaderSystem {
let library: Library
let userManager: UserManager
let display: Display
init() {
self.library = Library()
self.userManager = UserManager()
self.display = Display()
}
var activeBook: Book? {
didSet {
if let activeBook = activeBook {
self.display.display(book: activeBook)
} else {
self.display.clearBook()
}
}
}
var activeUser: User? {
didSet {
if let activeUser = activeUser {
self.display.display(user: activeUser)
} else {
self.display.clearUser()
}
}
}
}
|
//
// ViewController.swift
// SlideOutMenu
//
// Created by Yoh on 6/14/15.
// Copyright (c) 2015 Harmony Bunny. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var open: UIBarButtonItem!
@IBOutlet weak var catLabel: UILabel!
var varView: ItemType = .AllTypes
func categoryChangeNotificationReceived(notification: NSNotification) {
varView = SharedAppState.selectedCategory
setTitle()
}
func setTitle() {
switch varView {
case .AllTypes:
catLabel.text = "All"
case .BWViewType:
catLabel.text = "BW"
case .LandscapesViewType:
catLabel.text = "Landscapes"
case .ArchitectureViewType:
catLabel.text = "Architecture"
case .CityViewType:
catLabel.text = "City"
case .DesignViewType:
catLabel.text = "Design"
case .LoveViewType:
catLabel.text = "Love"
case .NatureViewType:
catLabel.text = "Nature"
case .MiscViewType:
catLabel.text = "Misc"
case .PeopleViewType:
catLabel.text = "People"
case .ArtViewType:
catLabel.text = "Art"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("categoryChangeNotificationReceived:"),
name: "SelectedCategoryChange",
object: nil)
open.target = self.revealViewController()
open.action = Selector("revealToggle:")
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
setTitle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// ViewControllerConstants.swift
// BoardlyLogin
//
// Created by Mateusz Dziubek on 08/12/2018.
// Copyright © 2018 Mateusz Dziubek. All rights reserved.
//
let HOME_VIEW_CONTROLLER_ID = "homeViewController"
|
//
// ViewController.swift
// DecomposedAR
//
// Created by Adam Bell on 5/23/20.
// Copyright © 2020 Adam Bell. All rights reserved.
//
import ARKit
import Decomposed
import UIKit
class ViewController: UIViewController, ARSCNViewDelegate {
var sceneView: ARSCNView!
var circleLayer: CALayer!
var displayLink: CADisplayLink!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .black
setupARView()
self.circleLayer = CALayer()
circleLayer.isDoubleSided = true
circleLayer.backgroundColor = UIColor.white.cgColor
view.layer.addSublayer(circleLayer)
}
// MARK: - AR Setup
func setupARView() {
self.sceneView = ARSCNView(frame: .zero)
view.addSubview(sceneView)
sceneView.delegate = self
sceneView.showsStatistics = true
sceneView.autoenablesDefaultLighting = true
sceneView.automaticallyUpdatesLighting = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = [.horizontal, .vertical]
let options: ARSession.RunOptions = [.resetTracking, .removeExistingAnchors]
sceneView.session.run(configuration, options: options)
self.displayLink = CADisplayLink(target: self, selector: #selector(displayLinkTick))
displayLink.add(to: .main, forMode: .common)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
sceneView.frame = view.bounds
circleLayer.bounds = CGRect(origin: .zero, size: CGSize(width: 10.0, height: 10.0))
circleLayer.anchorPoint = CGPoint(x: 0.0, y: 0.0)
circleLayer.position = CGPoint(x: 5.0, y: 5.0)
circleLayer.zPosition = 1.0
}
// MARK: - ARSCNViewDelegate
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
// Create a custom object to visualize the plane geometry and extent.
let plane = Plane(anchor: planeAnchor, sceneView: sceneView)
// Add the visualization to the ARKit-managed node so that it tracks
// changes in the plane anchor as plane estimation continues.
node.addChildNode(plane)
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
// Update only anchors and nodes set up by `renderer(_:didAdd:for:)`.
guard let planeAnchor = anchor as? ARPlaneAnchor,
let plane = node.childNodes.first as? Plane
else { return }
// Update ARSCNPlaneGeometry to the anchor's new estimated shape.
if let planeGeometry = plane.meshNode.geometry as? ARSCNPlaneGeometry {
planeGeometry.update(from: planeAnchor.geometry)
}
// Update extent visualization to the anchor's new bounding rectangle.
if let extentGeometry = plane.extentNode.geometry as? SCNPlane {
extentGeometry.width = CGFloat(planeAnchor.extent.x)
extentGeometry.height = CGFloat(planeAnchor.extent.z)
plane.extentNode.simdPosition = planeAnchor.center
}
}
// MARK: - DisplayLink
@objc func displayLinkTick() {
sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in
node.geometry?.firstMaterial?.diffuse.contents = UIColor.white
}
guard let intersectingAnchor = sceneView.hitTest(CGPoint(x: view.bounds.midX, y: view.bounds.midY), types: [.existingPlaneUsingGeometry]).first else { return }
guard let anchor = intersectingAnchor.anchor, let anchorNode = sceneView.node(for: anchor) else { return }
guard let planeNode = anchorNode.childNodes.first as? Plane else { return }
planeNode.extentNode.geometry?.firstMaterial?.diffuse.contents = UIColor.blue
guard let translation = sceneView.unprojectPoint(CGPoint(x: sceneView.bounds.midX, y: sceneView.bounds.midY), ontoPlane: anchor.transform) else { return }
print(translation)
guard let frame = sceneView.session.currentFrame else { return }
let camera = frame.camera
let mx = float4x4(
[1/Float(100), 0, 0, 0],
[0, -1/Float(100), 0, 0], //flip Y axis; it's directed up in 3d world while for CA on iOS it's directed down
[0, 0, 1, 0],
[0, 0, 0, 1]
)
let model = anchor.transform * simd_float4x4(simd_quatf(angle: .pi / -2.0, axis: normalize(simd_float3(1.0, 0.0, 0.0)))) * mx
let view = camera.viewMatrix(for: .portrait)
let proj = camera.projectionMatrix(for: .portrait, viewportSize: sceneView.bounds.size, zNear: 0.01, zFar: 1000)
let modelViewProjection = simd_mul(proj, simd_mul(view, model))
var atr = CATransform3D(modelViewProjection)
let norm = CATransform3DMakeScale(0.5, -0.5, 1) //on iOS Y axis is directed down, but we flipped it formerly, so return back!
let shift = CATransform3DMakeTranslation(1, -1, 0) //we should shift it to another end of projection matrix output before flipping
let screen_scale = CATransform3DMakeScale(sceneView.bounds.size.width, sceneView.bounds.size.height, 1)
atr = CATransform3DConcat(CATransform3DConcat(atr, shift), norm)
// atr = CATransform3DConcat(atr, CATransform3DMakeAffineTransform(frame.displayTransform(for: .portrait, viewportSize: sceneView.bounds.size)))
atr = CATransform3DConcat(atr, screen_scale) //scale back to pixels
CATransaction.begin()
CATransaction.setDisableActions(true)
circleLayer.transform = atr
CATransaction.commit()
print(circleLayer.frame)
}
}
|
//
// Utility.swift
// BMI Calculator
//
// Created by Peter Wu on 11/15/18.
// Copyright © 2018 Peter Wu. All rights reserved.
//
import Foundation
import os.log
// Keeps track of input mode and input context
class InputCoordinator: NSObject, NSCoding {
private (set)var mode: Mode
private (set)var weightContext: MeasurementContext
private (set)var heightContext: MeasurementContext
private var activeInputContext: MeasurementContext?
override init() {
self.mode = Mode.Viewing
self.weightContext = MeasurementContext(type: .weight, system: .imperial)
self.heightContext = MeasurementContext(type: .height, system: .imperial)
}
required init?(coder: NSCoder) {
if let mode = Mode(rawValue: coder.decodeInteger(forKey: InputCoordinatorCodingKeys.mode)),
let weightContext = coder.decodeObject(forKey: InputCoordinatorCodingKeys.weightContext) as? MeasurementContext,
let heightContext = coder.decodeObject(forKey: InputCoordinatorCodingKeys.heightCOntext) as? MeasurementContext {
self.mode = mode
self.weightContext = weightContext
self.heightContext = heightContext
self.activeInputContext = coder.decodeObject(forKey: InputCoordinatorCodingKeys.activeInputContext) as? MeasurementContext
} else {
return nil
}
}
func encode(with coder: NSCoder) {
coder.encode(mode.rawValue, forKey: InputCoordinatorCodingKeys.mode)
coder.encode(weightContext, forKey: InputCoordinatorCodingKeys.weightContext)
coder.encode(heightContext, forKey: InputCoordinatorCodingKeys.heightCOntext)
guard let activeContext = activeInputContext else { return }
coder.encode(activeContext, forKey: InputCoordinatorCodingKeys.activeInputContext)
}
func currentInputContext() -> MeasurementContext? {
return activeInputContext
}
func deactivateInput() {
activeInputContext = nil
mode = .Viewing
saveInputContext()
}
func activateWeightInput() {
activeInputContext = weightContext
mode = .Inputting
saveInputContext()
}
func activateHeightInput() {
activeInputContext = heightContext
mode = .Inputting
saveInputContext()
}
/// changes measurementSystem of active context based on index
func updateInputMeasurement(forIndex index: Int) {
// update input measurement
switch index {
case 0:
activeInputContext!.system = .imperial
case 1:
activeInputContext!.system = .metric
default:
break
}
saveInputContext()
}
func saveInputContext() {
//encode data
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false)
UserDefaults.standard.set(data, forKey: "inputCoordinator")
os_log("InputContext saved")
} catch {
os_log("Unable to archive InputCoordinator")
}
}
static func loadInputContext() -> InputCoordinator? {
guard let data = UserDefaults.standard.data(forKey: "inputCoordinator") else {
os_log("Unable to retrieve inputCoordinator data from userDefauls")
return nil
}
do {
let data = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
if let inputCoordinator = data as? InputCoordinator {
return inputCoordinator
} else {
return nil
}
} catch {
os_log("Unable to unarchive InputCoordinator data")
return nil
}
}
enum Mode: Int {
case Inputting = 1
case Viewing = 2
}
}
/// Context keeps track of the context of the measurement. For example, a measurement of height in imperial system, or measurement of weight in metric system
class MeasurementContext: NSObject, NSCoding {
var type: MeasurementType
var system: MeasurementSystem
init(type: MeasurementType, system: MeasurementSystem) {
self.type = type
self.system = system
}
required init?(coder: NSCoder) {
if let type = MeasurementType(rawValue: coder.decodeInteger(forKey: MeasurementContextCodingKeys.type)),
let system = MeasurementSystem(rawValue: coder.decodeInteger(forKey: MeasurementContextCodingKeys.system)) {
self.type = type
self.system = system
} else {
return nil
}
}
func encode(with coder: NSCoder) {
coder.encode(type.rawValue, forKey: MeasurementContextCodingKeys.type)
coder.encode(system.rawValue, forKey: MeasurementContextCodingKeys.system)
}
// MARK: Input State Management
/// There are three mutually exclusive state. Either the user is inputting weight, or inputting height, or simply viewing (none). InputState enum
/// encapsulates these mutually exclusive state.
///
enum MeasurementType: Int {
case weight = 1
case height = 2
}
/// Enum for categorizing two types of input. An input is either metric or imperial system.
///
/// - metric: represents metric system input
/// - imperial: represents imperial system input
enum MeasurementSystem: Int {
case metric = 1
case imperial = 2
}
}
struct MeasurementContextCodingKeys {
static let type = "type"
static let system = "system"
}
struct InputCoordinatorCodingKeys {
static let mode = "mode"
static let weightContext = "weightContext"
static let heightCOntext = "heightContext"
static let activeInputContext = "activeInputContext"
}
|
//
// LabelLatLng.swift
// BubbleTeaLocation
//
// Created by Jack on 21/2/2562 BE.
// Copyright © 2562 Jack. All rights reserved.
//
import Foundation
struct LabelLatLng: Decodable {
let label: String
let lat: Double
let lng: Double
}
|
//
// ViewController.swift
// Campus Walk
//
// Created by Samuel Fox on 10/13/18.
// Copyright © 2018 sof5207. All rights reserved.
//
import UIKit
import MapKit
class CampusBuilding : NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
let title : String?
let favorite : Bool?
init(title:String?, coordinate:CLLocationCoordinate2D, favorite:Bool) {
self.title = title
self.coordinate = coordinate
self.favorite = favorite
}
}
class FavoriteBuilding : NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
let title : String?
let favorite : Bool?
init(title:String?, coordinate:CLLocationCoordinate2D, favorite:Bool) {
self.title = title
self.coordinate = coordinate
self.favorite = favorite
}
}
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, PlotBuildingDelegate, OptionsDelegate, SaveImageDelegate {
@IBOutlet var mapView: MKMapView!
@IBOutlet var navBar: UINavigationItem!
@IBOutlet var directionsButton: UIBarButtonItem!
@IBOutlet var showStepsButton: UIBarButtonItem!
let mapModel = CampusModel.sharedInstance
let locationManager = CLLocationManager()
let userMapLocation = MKUserLocation()
let kSpanLatitudeDelta = 0.027
let kSpanLongitudeDelta = 0.027
let kSpanLatitudeDeltaZoom = 0.002
let kSpanLongitudeDeltaZoom = 0.002
let kInitialLatitude = 40.8012
let kInitialLongitude = -77.859909
var directionsAlert = UIAlertController()
var allAnnotations = [MKAnnotation]()
var allFavorites = [MKAnnotation]()
var allBuildings = false
var userLocation = false
var mapTypeIndex = 0
var favorites = false
var namesOfFavorites = [String]()
var allAnnotationsNames = [String]()
var fromLocation = String()
var toLocation = String()
var currentPaths = [MKOverlay]()
var steps = [MKRoute.Step]()
var savedImages = [String:UIImage]()
var savedDetails = [String:String]()
@IBOutlet var etaLabel: UILabel!
@IBAction func showSteps(_ sender: Any) {
let stepsTableView = self.storyboard?.instantiateViewController(withIdentifier: "StepsTableView") as! StepsTableViewController
stepsTableView.configure(steps)
let nav = UINavigationController(rootViewController: stepsTableView)
self.present(nav, animated: true, completion: nil)
}
func directionsToLocation(){
guard toLocation.count > 0 && fromLocation.count > 0 else { return }
etaLabel.removeFromSuperview()
mapView.removeOverlays(currentPaths)
mapView.removeAnnotations(allAnnotations)
let routeRequest = MKDirections.Request()
if fromLocation == "Current Location"{
routeRequest.source = MKMapItem.forCurrentLocation()
}
else {
let location = mapModel.buildingLocation(fromLocation)
var mapItem : MKMapItem {
let placeMark = MKPlacemark(coordinate: (location?.coordinate)!)
let item = MKMapItem(placemark: placeMark)
return item
}
routeRequest.source = mapItem
plot(building: fromLocation, changeRegion: true)
}
if toLocation == "Current Location"{
routeRequest.source = MKMapItem.forCurrentLocation()
}
else {
let location = mapModel.buildingLocation(toLocation)
var mapItem : MKMapItem {
let placeMark = MKPlacemark(coordinate: (location?.coordinate)!)
let item = MKMapItem(placemark: placeMark)
return item
}
routeRequest.destination = mapItem
plot(building: toLocation, changeRegion: false)
}
routeRequest.transportType = .walking
routeRequest.requestsAlternateRoutes = false
let directions = MKDirections(request: routeRequest)
directions.calculate { (response, error) in
guard error == nil else {print(error?.localizedDescription as Any); return}
let route = response?.routes.first!
self.mapView.addOverlay((route?.polyline)!)
self.currentPaths.append((route?.polyline)!)
self.etaLabel.text = "ETA: " +
DateFormatter.localizedString(from: Date(timeIntervalSinceNow: (response?.routes.first!.expectedTravelTime)!), dateStyle: DateFormatter.Style.none, timeStyle: DateFormatter.Style.short)
self.etaLabel.textColor = self.view.tintColor
self.navBar.titleView = self.etaLabel
self.steps = (route?.steps)!
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
switch overlay {
case is MKPolyline:
let line = MKPolylineRenderer(polyline: overlay as! MKPolyline)
line.strokeColor = UIColor.blue
line.lineWidth = 4.0
return line
default:
assert(false, "UNHANDLED OVERLAY")
}
}
@IBAction func removePaths(_ sender: Any) {
mapView.removeOverlays(currentPaths)
mapView.removeAnnotations(allAnnotations)
etaLabel.removeFromSuperview()
}
@IBAction func directionsAction(_ sender: Any) {
let alertView = UIAlertController(title: "Directions", message: nil, preferredStyle: .actionSheet)
alertView.popoverPresentationController?.barButtonItem = directionsButton
let actionFromDirection = UIAlertAction(title: "From", style: .default) { (action) in
let newAlertView = UIAlertController(title: "Use Current Location", message: nil, preferredStyle: .actionSheet)
let yes = UIAlertAction(title: "Yes", style: .default) {(action) in
self.fromLocation = "Current Location"
let alertView = UIAlertController(title: "Directions", message: nil, preferredStyle: .actionSheet)
self.alertConfigure(self.fromLocation, self.toLocation, alertView)
alertView.popoverPresentationController?.barButtonItem = self.directionsButton
self.present(alertView, animated: true, completion: nil)
}
newAlertView.addAction(yes)
let no = UIAlertAction(title: "No, a Building", style: .default) {(action) in
self.performSegue(withIdentifier: "BuildingList", sender: "FROM")
}
newAlertView.addAction(no)
let actionCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
newAlertView.addAction(actionCancel)
self.present(newAlertView, animated: true, completion: nil)
}
alertView.addAction(actionFromDirection)
let actionToDirection = UIAlertAction(title: "To", style: .default) { (action) in
let newAlertView = UIAlertController(title: "Use Current Location", message: nil, preferredStyle: .actionSheet)
let yes = UIAlertAction(title: "Yes", style: .default) {(action) in
self.toLocation = "Current Location"
let alertView = UIAlertController(title: "Directions", message: nil, preferredStyle: .actionSheet)
self.alertConfigure(self.fromLocation, self.toLocation, alertView)
alertView.popoverPresentationController?.barButtonItem = self.directionsButton
self.present(alertView, animated: true, completion: nil)
}
newAlertView.addAction(yes)
let no = UIAlertAction(title: "No, a Building", style: .default) {(action) in
self.performSegue(withIdentifier: "BuildingList", sender: "TO")
}
newAlertView.addAction(no)
let actionCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
newAlertView.addAction(actionCancel)
self.present(newAlertView, animated: true, completion: nil)
}
alertView.addAction(actionToDirection)
let actionGoDirection = UIAlertAction(title: "Go", style: .default) {(action) in
self.directionsToLocation()
}
alertView.addAction(actionGoDirection)
let actionCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertView.addAction(actionCancel)
directionsAlert = alertView
self.present(alertView, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
let coordinate = CLLocationCoordinate2D(latitude: kInitialLatitude, longitude: kInitialLongitude)
let span = MKCoordinateSpan(latitudeDelta: kSpanLatitudeDelta, longitudeDelta: kSpanLongitudeDelta)
let region = MKCoordinateRegion(center: coordinate, span: span)
mapView.setRegion(region, animated: true)
mapView.delegate = self
locationManager.delegate = self
let trackButton = MKUserTrackingBarButtonItem(mapView: self.mapView)
navBar.leftBarButtonItem = trackButton
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if CLLocationManager.locationServicesEnabled() {
let status = CLLocationManager.authorizationStatus()
switch status {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
default:
break
}
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .denied, .restricted:
mapView.showsUserLocation = false
userLocation = false
case .authorizedAlways, .authorizedWhenInUse:
mapView.showsUserLocation = true
mapView.userTrackingMode = .followWithHeading
userLocation = true
default:
break
}
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
if userLocation {
mapView.userTrackingMode = .followWithHeading
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
switch annotation {
case is CampusBuilding:
return annotationView(forCampusBuilding: annotation as! CampusBuilding)
case is FavoriteBuilding:
return annotationView(forFavoriteBuilding: annotation as! FavoriteBuilding)
default:
return nil
}
}
func annotationView(forCampusBuilding campusBuilding:CampusBuilding) -> MKAnnotationView {
let identifier = "BuildingPin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView {
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: campusBuilding, reuseIdentifier: identifier)
view.pinTintColor = MKPinAnnotationView.redPinColor()
view.animatesDrop = true
view.canShowCallout = true
let button = UIButton(type: .detailDisclosure)
button.setTitle("X", for: .normal)
button.setImage(UIImage(named: "delete"), for: .normal)
view.rightCalloutAccessoryView = button
view.leftCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
return view
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
let name = view.annotation?.title
if namesOfFavorites.contains(name!!){
let index = namesOfFavorites.firstIndex(of: name!!)
namesOfFavorites.remove(at: index!)
allFavorites.remove(at: index!)
}
if allAnnotationsNames.contains(name!!) {
let index = allAnnotationsNames.firstIndex(of: name!!)
allAnnotationsNames.remove(at: index!)
allAnnotations.remove(at: index!)
}
mapView.removeAnnotation(view.annotation!)
}
if control == view.leftCalloutAccessoryView {
let detailView = self.storyboard?.instantiateViewController(withIdentifier: "DetailView") as! DetailViewController
detailView.delegate = self
let buildingName = view.annotation?.title
let imageName = mapModel.buildingPhotoName(buildingName!!)
var image = UIImage()
if imageName!.count > 0 {
image = UIImage(named: imageName!)!
}
else {
image = UIImage(named: "addPhoto")!
}
detailView.configure(image, buildingName!!, savedImages, savedDetails)
let nav = UINavigationController(rootViewController: detailView)
self.present(nav, animated: true, completion: nil)
}
}
func plot(building: String, changeRegion : Bool = true) {
if allAnnotationsNames.contains(building) {
return
}
let coordinate = mapModel.buildingLocation(building)?.coordinate
let title = building
let span = MKCoordinateSpan(latitudeDelta: kSpanLatitudeDeltaZoom, longitudeDelta: kSpanLongitudeDeltaZoom)
if changeRegion {
let region = MKCoordinateRegion(center: coordinate!, span: span)
self.mapView.setRegion(region, animated: true)
}
let campusBuilding = CampusBuilding(title: title, coordinate: coordinate!, favorite: false)
allAnnotations.append(campusBuilding)
allAnnotationsNames.append(building)
self.mapView.addAnnotation(campusBuilding)
}
func annotationView(forFavoriteBuilding favoriteBuilding:FavoriteBuilding) -> MKAnnotationView {
let identifier = "BuildingFavoritePin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView {
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: favoriteBuilding, reuseIdentifier: identifier)
view.pinTintColor = MKPinAnnotationView.greenPinColor()
view.animatesDrop = true
view.canShowCallout = true
let button = UIButton(type: .detailDisclosure)
button.setTitle("X", for: .normal)
button.setImage(UIImage(named: "delete"), for: .normal)
view.rightCalloutAccessoryView = button
}
return view
}
func plotFavorite(building: String) {
let coordinate = mapModel.buildingLocation(building)?.coordinate
let title = building
let campusBuilding = FavoriteBuilding(title: title, coordinate: coordinate!, favorite: true)
allFavorites.append(campusBuilding)
self.mapView.addAnnotation(campusBuilding)
}
func userLocation(_ toggle : Bool){
userLocation = toggle
if CLLocationManager.locationServicesEnabled() && toggle {
let status = CLLocationManager.authorizationStatus()
switch status {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .authorizedAlways, .authorizedWhenInUse:
mapView.showsUserLocation = true
mapView.userTrackingMode = .followWithHeading
locationManager.startUpdatingHeading()
default:
break
}
}
else {
mapView.showsUserLocation = false
}
}
func showAllBuildings(_ toggle : Bool){
allBuildings = toggle
if toggle == true {
for i in 0..<mapModel.numberOfBuildings(){
plot(building: mapModel.nameOfBuilding(i), changeRegion: false)
}
}
else {
mapView.removeAnnotations(allAnnotations)
}
}
func mapType(_ type : Int){
mapTypeIndex = type
switch type{
case 0:
mapView.mapType = .standard
case 1:
mapView.mapType = .satellite
case 2:
mapView.mapType = .hybrid
default:
return
}
}
func showFavorites(_ toggle: Bool) {
favorites = toggle
if toggle == true {
for i in namesOfFavorites{
plotFavorite(building: i)
}
}
else {
mapView.removeAnnotations(allFavorites)
}
}
func favoriteBuilding(name: String) {
if namesOfFavorites.contains(name) {
let index = namesOfFavorites.firstIndex(of: name)
namesOfFavorites.remove(at: index!)
mapView.removeAnnotation(allFavorites[index!])
allFavorites.remove(at: index!)
return
}
let coordinate = mapModel.buildingLocation(name)?.coordinate
let title = name
namesOfFavorites.append(name)
let favoriteBuilding = FavoriteBuilding(title: title, coordinate: coordinate!, favorite : true)
allFavorites.append(favoriteBuilding)
}
func alertConfigure(_ from : String, _ to : String, _ alertView : UIAlertController) {
if from.count>1 {
let fromLocationAction = UIAlertAction(title: "From \(from)", style: .default) { (action) in
self.performSegue(withIdentifier: "BuildingList", sender: "FROM")
}
alertView.addAction(fromLocationAction)
}
else {
let fromLocationAction = UIAlertAction(title: "From", style: .default) { (action) in
self.performSegue(withIdentifier: "BuildingList", sender: "FROM")
}
alertView.addAction(fromLocationAction)
}
if to.count>1 {
let toLocationAction = UIAlertAction(title: "To \(to)", style: .default) { (action) in
self.performSegue(withIdentifier: "BuildingList", sender: "TO")
}
alertView.addAction(toLocationAction)
}
else {
let toLocationAction = UIAlertAction(title: "To", style: .default) { (action) in
self.performSegue(withIdentifier: "BuildingList", sender: "TO")
}
alertView.addAction(toLocationAction)
}
let go = UIAlertAction(title: "Go", style: .default) {(action) in
self.directionsToLocation()
}
alertView.addAction(go)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertView.addAction(cancelAction)
}
func directionsFrom(name: String) {
fromLocation = name
let alertView = UIAlertController(title: "Directions", message: nil, preferredStyle: .actionSheet)
alertConfigure(fromLocation, toLocation, alertView)
alertView.popoverPresentationController?.barButtonItem = directionsButton
self.present(alertView, animated: true, completion: nil)
return
}
func directionsTo(name: String) {
toLocation = name
let alertView = UIAlertController(title: "Directions", message: nil, preferredStyle: .actionSheet)
alertConfigure(fromLocation, toLocation, alertView)
alertView.popoverPresentationController?.barButtonItem = directionsButton
self.present(alertView, animated: true, completion: nil)
return
}
func save(_ building: String, _ image: UIImage) {
savedImages[building] = image
}
func saveDetails(_ building: String, _ details: String) {
savedDetails[building] = details
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "BuildingList":
let navController = segue.destination as! UINavigationController
let buildingListViewController = navController.topViewController as! TableViewController
buildingListViewController.delegate = self
buildingListViewController.configure(namesOfFavorites, sender)
case "OptionsSegue":
let navController = segue.destination as! UINavigationController
let optionsController = navController.topViewController as! OptionsViewController
optionsController.delegate = self
optionsController.configure(userLocation: userLocation, allBuildings: allBuildings, mapType: mapTypeIndex, favorites: favorites)
default:
assert(false, "Unhandled Segue")
}
}
}
|
//
// Date+Sync.swift
// Trans
//
// Created by Scott Jones on 3/6/16.
// Copyright © 2016 *. All rights reserved.
//
import Foundation
extension SequenceType where Generator.Element : NSDate {
public func earliest()->NSDate {
return NSDate(timeIntervalSince1970: map { $0.timeIntervalSince1970 }
.flatMap { $0 }
.reduce(NSTimeInterval(FLT_MAX)) { $0 < $1 ? $0 : $1 })
}
public func latest()->NSDate {
return NSDate(timeIntervalSince1970:map { $0.timeIntervalSince1970 }
.flatMap { $0 }
.reduce(0) { $0 > $1 ? $0 : $1 })
}
}
|
//
// CardInlineView.swift
// Monri
//
// Created by Jasmin Suljic on 31/10/2019.
//
import UIKit
import Caishen
public class CardInlineView: CardTextField {
public func getCard() -> Card {
let card: CaishenCard = self.card
return Card(number: card.bankCardNumber.rawValue, cvc: card.cardVerificationCode.rawValue, expMonth: Int(card.expiryDate.month), expYear: Int(card.expiryDate.year))
}
}
|
// ViewControllerSeleccionarImagen.swift
// ProyectoRecuerdos
import UIKit
class ViewControllerSeleccionarImagen: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
// Declaracion de elementos de interfaz
@IBOutlet weak var imagenUsuario: UIImageView!
@IBOutlet weak var btListo: UIButton!
// Declaracion de variables y constantes
var seleccionoImagen = false
var preSeleccionoImagen : UIImage!
// Declaracion de elementos para seleccionar imagen
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// Si el usuario ya habia seleccionado una imagen previamente y retorna a esta vista
// muestra la imagen que fue preseleccionada
if seleccionoImagen {
imagenUsuario.image = preSeleccionoImagen
}
btListo.bordesRedondos(radio: Double(btListo.frame.size.height))
// Configuracion de Navigation Bar
title = "Elige una fotografía"
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Funciones control de fotografias
// Cargar la imagen del usuario desde galeria
@IBAction func cargarImagen(_ sender: UIButton) {
let imagen = UIImagePickerController()
imagen.delegate = self
imagen.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagen.allowsEditing = false
self.present(imagen, animated: true);
}
// Cargar la imagen del usuario desde la camara
@IBAction func capturarImagen(_ sender: UIButton) {
let imagen = UIImagePickerController()
imagen.delegate = self
imagen.sourceType = UIImagePickerControllerSourceType.camera
imagen.allowsEditing = false
self.present(imagen, animated: true);
}
// Mostrar la imagen seleccionada
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let imagen = info[UIImagePickerControllerOriginalImage] as? UIImage {
imagenUsuario.image = imagen
seleccionoImagen = true
}
self.dismiss(animated: true, completion: nil)
}
// MARK: - Funciones PREPARE
// Metodo para enviar informacion
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Manda la imagen a la vista anterior
if sender as! UIButton == btListo {
let vistaAgregarUsuario = segue.destination as! ViewControllerAgregarUsuario
if seleccionoImagen {
vistaAgregarUsuario.fotoUsuario = imagenUsuario.image
vistaAgregarUsuario.seleccionoImagen = true
}
else {
vistaAgregarUsuario.seleccionoImagen = false
}
}
}
// MARK: - Funciones de bloqueo de Orientación
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.landscape
}
override var shouldAutorotate: Bool {
return false
}
}
|
import UIKit
var name : String? = nil
if let unwrapped = name {
print(unwrapped.count, "letters")
} else {
print("Missing Name")
}
//-----------------------------------------------------------------------
func great(_ name:String?) {
guard let unwrapped = name else {
print("You did not provide a name!!!")
return
}
print("Hello\(unwrapped)")
}
great(nil)
great("Matheus")
//-----------------------------------------------------------------------
func uppercase(string: String?) -> String? {
guard let string = string else {
return nil
}
return string.uppercased()
}
if let result = uppercase(string: "Hello") {
print(result)
}
//-----------------------------------------------------------------------
func validate(_ passWord:Int?) -> Bool {
guard let password = passWord else {
print("\nYou didn't pass password, please pass some valid.")
return false
}
if password == 123 {
print("Authenticated Successfully!")
return true
} else {
print("Password Incorrect!, Please try again")
}
return false
}
validate(nil) //false
validate(124) //false
validate(123) //true
//-----------------------------------------------------------------------
let racers = ["Hamilton", "Verstappen", "Vettel"]
let winnerWasVE = racers.first?.hasPrefix("Ve")
//-----------------------------------------------------------------------
var listaTelefonic = ["Matheus Santos":"9981015281", "Marcela Santos":"996566444", "Josi Dourado":"996645544", "Jaum":"999999999" ]
struct listPassword {
let name: String
let login: String
let password: String
}
let searchListPhone : [String] = {
var list = [String]()
for i in listaTelefonic {
if i.key.hasPrefix("M") {
list.append(i.key + " : " + i.value)
}
}
return list
}()
print(searchListPhone)
//-----------------------------------------------------------------------
enum PasswordError: Error {
case obvious
}
func checkPassword(_ password: String) throws -> Bool {
if password == "password" {
throw PasswordError.obvious
}
return true
}
//First form to use a throw function ----> Mais usual
do {
try checkPassword("password")
print("That password is good!")
} catch {
print("You can't use that password.")
}
//Second form to use a throw function ----> Alternativa
//Aqui estou transformando o valor de retorno da funcao (result) em um optional
if let result = try? checkPassword("password") {
print("Result was \(result)")
} else {
print("D'oh!!!")
}
//Third form to use a throw function ----> Evitar
let resultBool = try! checkPassword("drowssap")
print(resultBool)
//-----------------------------------------------------------------------
struct Person {
let id : String
init?(_ id: String) {
if id.count == 9 {
self.id = id
} else {
return nil
}
}
}
if let matheus = Person.init("123456789") {
print("My ID: \(matheus.id)")
} else {
print("Code invalid")
}
//-----------------------------------------------------------------------
struct Website {
var url: String
init?(url: String) {
if url.hasPrefix("http") {
self.url = url
} else {
print("Invalid website URL.")
return nil
}
}
}
if let site = Website(url: "https://www.hackingwithswift.com") {
print("\n\n\(site.url)")
}
//-----------------------------------------------------------------------
class Animal {}
class Dog : Animal {
func makeNoise() {
print("AuAuAu!!!")
}
}
class Fish : Animal {}
let pets = [Fish(), Dog(), Dog(), Fish(), Dog(), Fish(), Fish()]
for pet in pets {
if let dog = pet as? Dog {
print(pet)
dog.makeNoise()
}
}
//-----------------------------------------------------------------------
class Transport { }
class Train: Transport {
var type = "public"
}
class Car: Transport {
var type = "private"
}
let travelPlans = [Train(), Car(), Train()]
for plan in travelPlans {
if let train = plan as? Train {
print("We're taking \(train.type) transport.")
}
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
|
//
// AppDelegate.swift
// Leiter
//
// Created by Hao Wang on 2018/6/30.
// Copyright © 2018 Tuluobo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 基础配置
ConfigManager.default.setup()
commonUI()
TrackerManager.shared.trace(event: "app_start", properties: launchOptions)
return true
}
}
extension AppDelegate {
private func commonUI() {
UIApplication.shared.statusBarStyle = .lightContent
UINavigationBar.appearance().barTintColor = UIColor.baseBlueColor
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]
}
}
|
//
// ProdDetailsViewController.swift
// PetsNPals
//
// Created by Isaiah Sylvester on 2021-04-05.
//
import UIKit
import BadgeHub
class ProdDetailsViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var supplierLabel: UILabel!
@IBOutlet weak var prodImageView: UIImageView!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
static var prods = [ProductModel]()
private var hub: BadgeHub?
var name = ""
var prodDescription = ""
var supplier = ""
var rating = ""
var price = ""
var img = UIImage()
private lazy var imageView: UIImageView = {
let iv = UIImageView()
iv.frame = CGRect(x: view.frame.size.width / 2 - 48,
y: 80, width: 36, height: 30)
iv.image = UIImage(named: "cart3x")
return iv
}()
override func viewDidLoad() {
super.viewDidLoad()
let cartBarItem = UIBarButtonItem(customView: imageView)
let currWidth = cartBarItem.customView?.widthAnchor.constraint(equalToConstant: 40)
currWidth?.isActive = true
let currHeight = cartBarItem.customView?.heightAnchor.constraint(equalToConstant: 40)
currHeight?.isActive = true
cartBarItem.customView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showCart)))
self.navigationItem.rightBarButtonItem = cartBarItem
setupImageView()
nameLabel.text = name
descriptionLabel.text = prodDescription
supplierLabel.text = supplier
prodImageView.image = img
ratingLabel.text = "rating: \(rating)"
priceLabel.text = "$\(price)"
}
// MARK: - Add item selected to user cart, increment the cart badge item count
@IBAction func addToCartButton(_ sender: UIButton) {
hub?.increment()
hub?.pop()
let prod = ProductModel(id: 0, url: "nil", name: name, breed: "nil", price: Double(price)!, supplier: supplier, rating: Int(rating)!, description: prodDescription, image: nil)
CartViewController.prods.append(prod)
}
// MARK: - Present Cart View populated with stored user items
@objc func showCart(){
let cartView = self.storyboard?.instantiateViewController(withIdentifier: "CartViewController") as! CartViewController
cartView.itemCount = ProdDetailsViewController.prods.count
navigationController?.pushViewController(cartView, animated: true)
}
private func setupImageView() {
hub = BadgeHub(view: imageView)
hub?.moveCircleBy(x: 8, y: 7)
hub?.scaleCircleSize(by: CGFloat(0.90))
view.addSubview(imageView)
}
}
|
//
// TeadsSASAdapterHelper.swift
// TeadsSASAdapter
//
// Created by Jérémy Grosjean on 06/11/2020.
//
import TeadsSDK
import UIKit
@objc public final class TeadsSASAdapterHelper: NSObject {
@objc public static func teadsAdSettingsToString(adSettings: TeadsAdapterSettings) -> String? {
guard let adSettingsEscapedString = adSettings.escapedString else {
return nil
}
return "teadsAdSettingsKey=\(adSettingsEscapedString)"
}
@objc public static func concatAdSettingsToKeywords(keywordsStrings: String, adSettings: TeadsAdapterSettings) -> String {
if let adSettingsStrings = teadsAdSettingsToString(adSettings: adSettings) {
return "\(keywordsStrings);\(adSettingsStrings)"
}
return keywordsStrings
}
static func stringToAdSettings(adSettingsString: String?) -> TeadsAdapterSettings? {
if let adSettingsString = adSettingsString?.removingPercentEncoding?.data(using: .utf8) {
return try? JSONDecoder().decode(TeadsAdapterSettings.self, from: adSettingsString)
}
return nil
}
}
extension TeadsAdapterSettings {
var escapedString: String? {
if let data = try? JSONEncoder().encode(self), let adSettingsString = String(data: data, encoding: .utf8) {
return adSettingsString.addingPercentEncoding(withAllowedCharacters: .urlUserAllowed)
}
return nil
}
}
struct ServerParameter: Codable {
var placementId: Int?
var teadsAdSettingsKey: String?
static func instance(from serverParameterString: String) -> Self? {
guard let data = serverParameterString.data(using: .utf8) else {
return nil
}
return try? JSONDecoder().decode(Self.self, from: data)
}
var adSettings: TeadsAdapterSettings {
TeadsSASAdapterHelper.stringToAdSettings(adSettingsString: teadsAdSettingsKey) ?? TeadsAdapterSettings()
}
}
|
//
// TokugawaViewController.swift
// onin-nihonsi
//
// Created by 内藤綜志 on 2018/12/01.
// Copyright © 2018 内藤綜志. All rights reserved.
//
import UIKit
class TokugawaViewController: UIViewController {
let screenHeight: CGFloat = UIScreen.main.bounds.height
@IBOutlet weak var ieyasuipad: UIButton!
@IBOutlet weak var hidetadaipad: UIButton!
@IBOutlet weak var iemituipad: UIButton!
@IBOutlet weak var ietunaipad: UIButton!
@IBOutlet weak var tunayosiipad: UIButton!
@IBOutlet weak var ienobuipad: UIButton!
@IBOutlet weak var ietuguipad: UIButton!
@IBOutlet weak var yosimuneipad: UIButton!
@IBOutlet weak var iesigeipad: UIButton!
@IBOutlet weak var ieharuipad: UIButton!
@IBOutlet weak var ienariipad: UIButton!
@IBOutlet weak var ieyosiipad: UIButton!
@IBOutlet weak var iesadaipad: UIButton!
@IBOutlet weak var iemotiipad: UIButton!
@IBOutlet weak var yosinobuipad: UIButton!
struct Tokugawas {
var name:String;
var age:String;
}
@IBOutlet weak var top: NSLayoutConstraint!
@IBOutlet weak var left: NSLayoutConstraint!
@IBOutlet weak var ieyasuleft: NSLayoutConstraint!
@IBOutlet weak var hidetadaleft: NSLayoutConstraint!
@IBOutlet weak var iemituleft: NSLayoutConstraint!
@IBOutlet weak var ietunaleft: NSLayoutConstraint!
@IBOutlet weak var tunayosileft: NSLayoutConstraint!
@IBOutlet weak var ienobuleft: NSLayoutConstraint!
@IBOutlet weak var ietuguleft: NSLayoutConstraint!
@IBOutlet weak var yosimuneleft: NSLayoutConstraint!
@IBOutlet weak var iesigeleft: NSLayoutConstraint!
@IBOutlet weak var ieharuleft: NSLayoutConstraint!
@IBOutlet weak var ienarileft: NSLayoutConstraint!
@IBOutlet weak var ieyosileft: NSLayoutConstraint!
@IBOutlet weak var iesadaleft: NSLayoutConstraint!
@IBOutlet weak var iemotileft: NSLayoutConstraint!
@IBOutlet weak var yosinobuleft: NSLayoutConstraint!
@IBOutlet weak var ieyasubutton: UIButton!
@IBOutlet weak var hidetadabutton: UIButton!
@IBOutlet weak var iemitubutton: UIButton!
@IBOutlet weak var ietunabutton: UIButton!
@IBOutlet weak var tunayosibutton: UIButton!
@IBOutlet weak var ienobubutton: UIButton!
@IBOutlet weak var ietugubutton: UIButton!
@IBOutlet weak var yosimunebutton: UIButton!
@IBOutlet weak var iesigebutton: UIButton!
@IBOutlet weak var ieharubutton: UIButton!
@IBOutlet weak var ienaributton: UIButton!
@IBOutlet weak var ieyosibutton: UIButton!
@IBOutlet weak var iesadabutton: UIButton!
@IBOutlet weak var iemotibutton: UIButton!
@IBOutlet weak var yosinobubutton: UIButton!
let ieyasu:UIImage = UIImage(named:"家康ipad")!
let hidetada:UIImage = UIImage(named:"秀忠ipad")!
let iemitu:UIImage = UIImage(named:"家光ipad")!
let ietuna:UIImage = UIImage(named:"家綱ipad")!
let tunayosi:UIImage = UIImage(named:"綱吉ipad")!
let ienobu:UIImage = UIImage(named:"家宣ipad")!
let ietugu:UIImage = UIImage(named:"家継ipad")!
let yosimune:UIImage = UIImage(named:"吉宗ipad")!
let iesige:UIImage = UIImage(named:"家重ipad")!
let ieharu:UIImage = UIImage(named:"家治ipad")!
let ienari:UIImage = UIImage(named:"家斉ipad")!
let ieyosi:UIImage = UIImage(named:"家慶ipad")!
let iesada:UIImage = UIImage(named:"家定ipad")!
let iemoti:UIImage = UIImage(named:"家茂ipad")!
let yosinobu:UIImage = UIImage(named:"慶喜ipad")!
static var ieyasu = Tokugawas(name:"初代 徳川家康", age: "在任:1603年 〜 1605年")
static var hidetada = Tokugawas(name:"2代 徳川秀忠", age: "在任:1605年 〜 1623年")
static var iemitu = Tokugawas(name:"3代 徳川家光", age: "在任:1623年 〜 1651年")
static var ietuna = Tokugawas(name:"4代 徳川家綱", age: "在任:1651年 〜 1680年")
static var tunayosi = Tokugawas(name:"5代 徳川綱吉", age: "在任:1680年 〜 1709年")
static var ienobu = Tokugawas(name:"6代 徳川家宣", age: "在任:1709年 〜 1712年")
static var ietugu = Tokugawas(name:"7代 徳川家継", age: "在任:1713年 〜 1716年")
static var yosimune = Tokugawas(name:"8代 徳川吉宗", age: "在任:1716年 〜 1745年")
static var iesige = Tokugawas(name:"9代 徳川家重", age: "在任:1745年 〜 1760年")
static var ieharu = Tokugawas(name:"10代 徳川家治", age: "在任:1760年 〜 1786年")
static var ienari = Tokugawas(name:"11代 徳川家斉", age: "在任:1787年 〜 1837年")
static var ieyosi = Tokugawas(name:"12代 徳川家慶", age: "在任:1837年 〜 1853年")
static var iesada = Tokugawas(name:"13代 徳川家定", age: "在任:1853年 〜 1858年")
static var iemoti = Tokugawas(name:"14代 徳川家茂", age: "在任:1858年 〜 1866年")
static var yosinobu = Tokugawas(name:"15代 徳川慶喜", age: "在任:1867年 〜 1868年")
override func viewDidLoad() {
super.viewDidLoad()
//画面サイズを取得し制約を変更
if screenHeight == 667 {
// iPhone 4S の場合 (Unit is Point.)
}
else if screenHeight == 736 {
// iPhone 6plus の場合
left.constant = 135
ieyasuleft.constant = 40
hidetadaleft.constant = 40
iemituleft.constant = 40
ietunaleft.constant = 40
tunayosileft.constant = 40
ienobuleft.constant = 40
ietuguleft.constant = 40
yosimuneleft.constant = 40
iesigeleft.constant = 40
ieharuleft.constant = 40
ienarileft.constant = 40
ieyosileft.constant = 40
iesadaleft.constant = 40
iemotileft.constant = 40
yosinobuleft.constant = 40
}
else if screenHeight == 812 {
// iPhone X の場合
}
else if screenHeight == 1024 {
//ipadの場合
left.constant = 300
ieyasuleft.constant = 40
hidetadaleft.constant = 40
iemituleft.constant = 40
ietunaleft.constant = 40
tunayosileft.constant = 40
ienobuleft.constant = 40
ietuguleft.constant = 40
yosimuneleft.constant = 40
iesigeleft.constant = 40
ieharuleft.constant = 40
ienarileft.constant = 40
ieyosileft.constant = 40
iesadaleft.constant = 40
iemotileft.constant = 40
yosinobuleft.constant = 40
ieyasubutton.setImage(ieyasu, for: .normal)
hidetadabutton.setImage(hidetada, for: .normal)
iemitubutton.setImage(iemitu, for: .normal)
ietunabutton.setImage(ietuna, for: .normal)
tunayosibutton.setImage(tunayosi, for: .normal)
ienobubutton.setImage(ienobu, for: .normal)
ietugubutton.setImage(ietugu, for: .normal)
yosimunebutton.setImage(yosimune, for: .normal)
iesigebutton.setImage(iesige, for: .normal)
ieharubutton.setImage(ieharu, for: .normal)
ienaributton.setImage(ienari, for: .normal)
ieyosibutton.setImage(ieyosi, for: .normal)
iesadabutton.setImage(iesada, for: .normal)
iemotibutton.setImage(iemoti, for: .normal)
yosinobubutton.setImage(yosinobu, for: .normal)
}
// Do any additional setup after loading the view.
}
func popup(){
let popupView:popupView = UINib(nibName: "popupView", bundle: nil).instantiate(withOwner: self,options: nil)[0] as! popupView
popupView.TokugawaLoad()
// ポップアップビュー背景色(グレーの部分)
let viewColor = UIColor.black
// 半透明にして親ビューが見えるように。透過度はお好みで。
popupView.backgroundColor = viewColor.withAlphaComponent(0.5)
// ポップアップビューを画面サイズに合わせる
popupView.frame = self.view.frame
// ダイアログ背景色(白の部分)
let baseViewColor = UIColor.white
// ちょっとだけ透明にする
popupView.baseView.backgroundColor = baseViewColor.withAlphaComponent(1)
// 角丸にする
popupView.baseView.layer.cornerRadius = 8.0
// 貼り付ける
self.view.addSubview(popupView)
}
@IBAction func First(_ sender: Any?) {
popupView.Count = 1
popup()
}
@IBAction func Second(_ sender: Any) {
popupView.Count = 2
popup()
}
@IBAction func Third(_ sender: Any) {
popupView.Count = 3
popup()
}
@IBAction func Fourth(_ sender: Any) {
popupView.Count = 4
popup()
}
@IBAction func Fifth(_ sender: Any) {
popupView.Count = 5
popup()
}
@IBAction func Sixth(_ sender: Any) {
popupView.Count = 6
popup()
}
@IBAction func Seventh(_ sender: Any) {
popupView.Count = 7
popup()
}
@IBAction func Eighth(_ sender: Any) {
popupView.Count = 8
popup()
}
@IBAction func Ninth(_ sender: Any) {
popupView.Count = 9
popup()
}
@IBAction func Tenth(_ sender: Any) {
popupView.Count = 10
popup()
}
@IBAction func Eleventh(_ sender: Any) {
popupView.Count = 11
popup()
}
@IBAction func Twelfth(_ sender: Any) {
popupView.Count = 12
popup()
}
@IBAction func Thirteenth(_ sender: Any) {
popupView.Count = 13
popup()
}
@IBAction func Fourteenth(_ sender: Any) {
popupView.Count = 14
popup()
}
@IBAction func Fifteenth(_ sender: Any) {
popupView.Count = 15
popup()
}
}
|
//
// SettingsTableViewController.swift
// 2xSpeedAudio
//
// Created by otavio on 15/11/20.
//
import UIKit
class SettingsTableViewController: UITableViewController {
var model = SettingsTableViewModel()
//MARK: - Application Lifecyle
override func viewDidLoad() {
super.viewDidLoad()
model.registerCells(on: self.tableView)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return model.sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.sections[section].rows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return model.sections[indexPath.section].rows[indexPath.row].buildCell(for: tableView, sender: self)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
model.sections[indexPath.section].rows[indexPath.row].didSelected()
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return model.sections[section].headerTitle
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return model.sections[section].footerTitle
}
}
|
//
// TableViewCell.swift
//
//
// Created by Максим Егоров on 15/03/2019.
//
import Kingfisher
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet private var cityNameLabel: UILabel!
@IBOutlet private var icon: UIImageView!
@IBOutlet private var currentTempCLabel: UILabel!
private let weatherService = WeatherServiceNetwork()
func setCell(cityName: String, tempC: String, imagePath: String) {
self.cityNameLabel.text = cityName
self.currentTempCLabel.text = tempC
weatherService.getImage(url: imagePath, sender: self.icon)
}
}
|
//
// ViewController.swift
// NestedTableViewPractice
//
// Created by appinventiv on 07/09/17.
// Copyright © 2017 appinventiv. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// Outlet of tableView------
@IBOutlet weak var tableViewOutlet: UITableView!
//Variables --------
var expandedSections : NSMutableSet = []
var countryArray: [String] = ["India"]
var stateArray: [String] = ["UP", "Punjab"]
override func viewDidLoad() {
super.viewDidLoad()
let nibHeader = UINib(nibName: "HeaderOfCell", bundle: nil)
tableViewOutlet.register(nibHeader, forHeaderFooterViewReuseIdentifier: "HeaderOfCellId")
let nibCell = UINib(nibName: "ExpandingCell", bundle: nil)
tableViewOutlet.register(nibCell, forCellReuseIdentifier: "ExpandingCellId")
tableViewOutlet.delegate = self
tableViewOutlet.dataSource = self
}
@objc func headerBtnTap (sender: UIButton) {
// print("Btn tap")
// print("Section tapped")
let sec = sender.tag
// print(sec)
let shouldExpand = !expandedSections.contains(sec)
print(expandedSections)
if (shouldExpand) {
// expandedSections.remove(sec)
//print(expandedSections)
print("if me remove hone s pehle \(expandedSections)")
expandedSections.add(sec)
print("if me add hone k baad pehle \(expandedSections)")
} else {
print("else me remove hone s pehle \(expandedSections)")
expandedSections.remove(sec)
print("else me remove hone k baad \(expandedSections)")
}
self.tableViewOutlet.reloadSections([sec], with: .bottom)
}
}
// Extension of viewcontrolller-----
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(expandedSections.contains(section)) {
return 1
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ExpandingCellId", for: indexPath) as? ExpandingCell else {
fatalError() }
cell.dataInSection = stateArray
// cell.dataInCell = cityArray
cell.contentView.backgroundColor = UIColor.brown
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return countryArray.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderOfCellId") as! HeaderOfCell
header.headerbtn.setTitle(countryArray[section], for: .normal)
header.contentView.backgroundColor = UIColor.orange
header.headerbtn.addTarget(self, action: #selector(ViewController.headerBtnTap(sender:)), for: UIControlEvents.touchUpInside)
header.headerbtn.tag = section
header.headerbtn.isUserInteractionEnabled = true
if (expandedSections.contains(section)) {
header.imageOutlet.image = UIImage(named: "down-arrow")
}
else {
header.imageOutlet.image = UIImage(named: "right-arrow")
}
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 500
}
}
|
//
// CommentEditView.swift
// Jock
//
// Created by HD on 15/3/23.
// Copyright (c) 2015年 Haidy. All rights reserved.
//
import UIKit
class CommentEditView: UIView {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var commentBtn: UIButton!
}
|
//
// ViewController.swift
// shinobiCharts
//
// Created by Luis Castillo on 4/4/16.
// Copyright © 2016 LC. All rights reserved.
//
import UIKit
class LineGraphModViewController: UIViewController,SChartDelegate
{
//properties
@IBOutlet weak var chartView: UIView!
private var chart:ShinobiChart?
private let chartDataSource = LineGraphModDataSource()
//MARK: - View Loading
override func viewDidLoad()
{
super.viewDidLoad()
chart = ShinobiChart(frame: chartView.bounds)
chartView.addSubview(chart!)
self.setupChart()
}//eom
func setupChart()
{
chart?.delegate = self
chart?.licenseKey = Constants.shared.getLicenseKey()
chart?.title = "Line Facing up"
chart?.autoresizingMask = [.flexibleHeight , .flexibleWidth]
chart?.datasource = chartDataSource
/* X axis - Dates */
let dateRange:SChartDateRange = chartDataSource.getInititalDateRange()
chart?.xAxis = SChartDateTimeAxis()
chart?.xAxis.range = dateRange
chart?.xAxis.axisPosition = SChartAxisPositionNormal
chart?.xAxis.title = "Dates"
chart?.xAxis.labelFormatString = "MM dd"
chart?.xAxis.majorTickFrequency = SChartDateFrequency.dateFrequency(withDay: 2)
// chart?.xAxis.minorTickFrequency = SChartDateFrequency.dateFrequency(withDay: 1)
//style
chart?.xAxis.style.majorGridLineStyle.showMajorGridLines = true
chart?.xAxis.style.majorTickStyle.showTicks = true
chart?.xAxis.style.majorTickStyle.showLabels = true
chart?.xAxis.style.minorTickStyle.showTicks = false
chart?.xAxis.style.minorTickStyle.showLabels = false
//axis movement
// chart?.xAxis.enableGesturePanning = true
// chart?.xAxis.enableGestureZooming = true
// chart?.xAxis.enableMomentumPanning = true
// chart?.xAxis.enableMomentumZooming = true
/* Y axis - Values */
chart?.yAxis = SChartNumberAxis()
chart?.yAxis.defaultRange = SChartRange(minimum: 0, andMaximum: 10)
chart?.yAxis.title = "Y axis"
chart?.yAxis.axisPosition = SChartAxisPositionReverse
chart?.yAxis.majorTickFrequency = 1
chart?.yAxis.minorTickFrequency = 1
chart?.yAxis.rangePaddingLow = 1
chart?.yAxis.rangePaddingHigh = 1
//style
chart?.yAxis.style.majorGridLineStyle.showMajorGridLines = true
chart?.yAxis.style.majorTickStyle.showTicks = true
chart?.yAxis.style.majorTickStyle.showLabels = true
chart?.yAxis.style.minorTickStyle.showTicks = false
chart?.yAxis.style.minorTickStyle.showLabels = false
//axis movement
// chart?.yAxis.enableGesturePanning = true
// chart?.yAxis.enableGestureZooming = true
// chart?.yAxis.enableMomentumPanning = true
// chart?.yAxis.enableMomentumZooming = true
}//eom
func setupLegend()
{
chart?.legend.isHidden = false
chart?.legend.position = SChartLegendPosition.bottomMiddle
chart?.legend.style.orientation = SChartLegendOrientation.horizontal
chart?.legend.style.horizontalPadding = 10
chart?.legend.style.symbolAlignment = SChartSeriesLegendSymbolAlignment.alignSymbolsLeft
chart?.legend.style.textAlignment = NSTextAlignment.left
}//eom
}//eoc
|
//
// CoordinatorFactory.swift
// TinkoffProject
//
// Created by Anvar Karimov on 23.02.2020.
// Copyright © 2020 tinkoff-group-5. All rights reserved.
//
import UIKit
final class CoordinatorFactory {
fileprivate let modulesFactory = ModulesFactory()
fileprivate let authFactory = AuthFactory()
}
// MARK: - CoordinatorFactoryProtocol
extension CoordinatorFactory: CoordinatorFactoryProtocol {
func makeMainCoordinator(router: Routable) -> Coordinatable & MainCoordinatorOutput {
return MainCoordinator(with: modulesFactory, router: router)
}
func makeAuthCoordinator(router: Routable) -> Coordinatable & AuthCoordinatorOutput {
return AuthCoordinator(with: authFactory, router: router)
}
}
|
import Foundation
import Kitura
import LoggerAPI
import Configuration
import CloudEnvironment
import KituraContracts
import Health
import Meow
import MongoKitten
import SwiftyJSON
public let health = Health()
class ApplicationServices {
// Service references
public let mongoDBService: MongoKitten.Database
public init() throws {
// Run service initializers
mongoDBService = try initializeServiceMongodb()
}
}
public class App {
let router = Router()
let services: ApplicationServices
public init() throws {
// Services
services = try ApplicationServices()
try Meow.init(getMongoDBAddress())
}
func postInit() throws {
// Capabilities
initializeMetrics(app: self)
// Endpoints
initializeHealthRoutes(app: self)
// register
try registerRouter()
// login
try loginRouter()
// add a thing to the user
try addThingRouter()
}
func registerRouter() throws {
let accountCollection = Meow.database["Account"]
router.all("/register", middleware: BodyParser())
router.post("/register") { request, response, next in
guard let parsedBody = request.body else {
next()
return
}
switch parsedBody {
case .json(let jsonBody):
if let email = jsonBody[AccountObjectKey.email] as? String {
if let pwd = jsonBody[AccountObjectKey.pwd] as? String {
let document: Document = [AccountObjectKey.email: email, AccountObjectKey.pwd: pwd, AccountObjectKey.things: []]
do {
let _ = try accountCollection.insert(document)
let decoder = BSONDecoder()
let accountObj: Account = try decoder.decode(Account.self, from: document)
try response.send(accountObj).end()
} catch let error {
print("!!! \(error)")
try response.send(status: .badRequest).end()
}
}
}
default:
break
}
next()
}
}
func addThingRouter() throws {
let accountCollection = Meow.database["Account"]
router.all("/add", middleware: BodyParser())
router.post("/add") { request, response, next in
guard let parsedBody = request.body else {
next()
return
}
switch parsedBody {
case .json(let jsonBody):
do {
let data = try JSONSerialization.data(withJSONObject: jsonBody, options: JSONSerialization.WritingOptions.prettyPrinted)
let decoder = JSONDecoder()
var updatedAccount = try decoder.decode(Account.self, from: data)
let docQuery = Query.init([AccountObjectKey.email: updatedAccount.email, AccountObjectKey.pwd: updatedAccount.password])
if let currentAccountDoc = try accountCollection.findOne(docQuery) {
let bsonDecoder = BSONDecoder()
let currentAccount: Account = try bsonDecoder.decode(Account.self, from: currentAccountDoc)
var currentAccountthings = currentAccount.things
for thing in updatedAccount.things {
currentAccountthings.append(thing)
}
updatedAccount.things = currentAccountthings
try accountCollection.update(to: BSONEncoder().encode(updatedAccount))
try response.send(updatedAccount).end()
}
}
catch let error {
print("!!! \(error)")
try response.send(status: .badRequest).end()
}
default:
break
}
next()
}
}
func loginRouter() throws {
let accountCollection = Meow.database["Account"]
router.all("/login", middleware: BodyParser())
router.post("/login") { request, response, next in
guard let parsedBody = request.body else {
next()
return
}
switch parsedBody {
case .json(let jsonBody):
if let email = jsonBody[AccountObjectKey.email] as? String {
if let pwd = jsonBody[AccountObjectKey.pwd] as? String {
let document: Document = [AccountObjectKey.email: email, AccountObjectKey.pwd: pwd]
do {
let docQuery = Query.init(document)
if let currentAccountDoc = try accountCollection.findOne(docQuery) {
let bsonDecoder = BSONDecoder()
let currentAccount: Account = try bsonDecoder.decode(Account.self, from: currentAccountDoc)
try response.send(currentAccount).end()
} else {
try response.send(status: .notFound).end()
}
} catch let error {
print("!!! \(error)")
try response.send(status: .badRequest).end()
}
}
}
default:
break
}
next()
}
}
public func run() throws {
try postInit()
Kitura.addHTTPServer(onPort: 8080, with: router)
Kitura.run()
}
}
struct AccountObjectKey {
static let email: String = "email"
static let pwd: String = "password"
static let things: String = "things"
}
struct Account: Codable {
var email: String
var password: String
var things: [Thing]
}
struct Thing: Codable {
let uuid: String = NSUUID.init().uuidString
}
|
//
// InfoHotlines.swift
// Riskeys
//
// Created by Carol Zhang on 8/12/16.
// Copyright © 2016 Carol Zhang. All rights reserved.
//
import Foundation
var hotlineArray = ["Depression Hotline: 8232952930" , "Suicide Hotline: 8572823" , "poop" , "salted caramel"]
|
//
// EnterLanguageViewController.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 6/28/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
protocol LanguageViewControllerDelegate: AnyObject {
func languageViewChangedLanguage()
}
final class LanguageViewController: UIViewController {
@IBOutlet private weak var gradientView: GradientView!
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var buttonConfirm: UIButton!
@IBOutlet weak var buttonConfirmLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var buttonConfirmTrailingConstraint: NSLayoutConstraint!
@IBOutlet weak var buttonConfirmBottomConstraint: NSLayoutConstraint!
private let languages = Language.list
private lazy var selectedIndex: Int = {
let current = Language.currentLanguage
return self.languages.firstIndex(where: { $0.code == current.code }) ?? 0
}()
weak var delegate: LanguageViewControllerDelegate?
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.barTintColor = .white
navigationItem.title = Localizable.Waves.Profile.Language.Navigation.title
createBackButton()
setupBigNavigationBar()
setupLanguage()
setupConstraints()
gradientView.startColor = UIColor.white.withAlphaComponent(0.0)
gradientView.endColor = UIColor.white
gradientView.direction = .vertical
}
// MARK: - Setups
private func setupLanguage() {
buttonConfirm.setTitle(Localizable.Waves.Enter.Button.Confirm.title, for: .normal)
}
private func setupConstraints() {
if Platform.isIphone5 {
buttonConfirmLeadingConstraint.constant = 16
buttonConfirmTrailingConstraint.constant = 16
buttonConfirmBottomConstraint.constant = 16
} else {
buttonConfirmLeadingConstraint.constant = 24
buttonConfirmTrailingConstraint.constant = 24
buttonConfirmBottomConstraint.constant = 24
}
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: buttonConfirmBottomConstraint.constant, right: 0)
}
// MARK: - Actions
@IBAction func confirmTapped(_ sender: Any) {
let language = languages[selectedIndex]
Language.change(language)
setupLanguage()
delegate?.languageViewChangedLanguage()
}
}
// MARK: UITableViewDataSource
extension LanguageViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return languages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: LanguageTableCell = tableView.dequeueAndRegisterCell()
let item = languages[indexPath.row]
cell.update(with: .init(icon: UIImage(named: item.icon), title: item.title, isOn: indexPath.row == selectedIndex))
return cell
}
}
// MARK: UITableViewDelegate
extension LanguageViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return LanguageTableCell.cellHeight()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndex = indexPath.row
tableView.reloadData()
let language = languages[indexPath.row]
let title = language.localizedString(key: Localizable.Waves.Enter.Button.Confirm.titleKey)
buttonConfirm.setTitle(title, for: .normal)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
setupTopBarLine()
}
}
|
import Foundation
import UIKit
@objc(RCTPortalOrigin)
class PortalOriginManager: RCTViewManager {
override func view() -> UIView! {
return PortalOrigin(registry: PortalRegistry.create())
}
override static func moduleName() -> String! {
return "RCTPortalOrigin"
}
}
|
//
// followPageVC.swift
// Crypier
//
// Created by Batuhan Saygılı on 15.01.2018.
// Copyright © 2018 batuhansaygili. All rights reserved.
//
import UIKit
import DefaultsKit
import LLSpinner
import SwiftyTimer
class followPageVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var followPageView: UITableView!
var homeCoinData:[Coin] = []
var followShortName:[String] = []
//For Shared Prefences
let defaults = Defaults()
let key = Key<[String]>("followList")
override func viewDidLoad() {
super.viewDidLoad()
LLSpinner.spin()
followShortName = defaults.get(for: key) ?? [""]
self.coinData()
self.navigationItem.title = NSLocalizedString("followlist", comment: "")
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Router.doviz = 0
Timer.every(60.seconds) { (timer: Timer) in
self.coinData()
}
homeVC.analyticsScreen(nameVC: "follow-VC")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return homeCoinData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = followPageView.dequeueReusableCell(withIdentifier: "homeCoinCell") as! homeCoinCell
cell.long.text = homeCoinData[indexPath.row].long
cell.short.text = homeCoinData[indexPath.row].short
cell.price.text =
String(format: "$%.02f", homeCoinData[indexPath.row].price)
cell.perc.text = String(homeCoinData[indexPath.row].perc) + "%"
// for Image
let long = self.homeCoinData[indexPath.row].long
let newLong = long.replacingOccurrences(of: " ", with: "-")
let url = URL(string: "http://www.coincap.io/images/coins/\(newLong).png")
cell.coinImage.kf.setImage(with: url)
let string = String(homeCoinData[indexPath.row].perc)
let needle: Character = "-"
if let idx = string.characters.index(of: needle) {
cell.perc.textColor = UIColor.red
}else if string == "0" {
cell.perc.textColor = UIColor.orange
}else {
cell.perc.textColor = UIColor.green
}
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .normal, title: NSLocalizedString("del", comment: "")) { action, index in
//self.followPageView.reloadData()
tableView.beginUpdates()
self.homeCoinData.remove(at: index.row)
self.followPageView.reloadData()
tableView.deleteRows(at: [index], with: .fade)
self.followShortName.remove(at: index.row)
self.defaults.set(self.followShortName, for: self.key)
coinSearchVC.showAlert(text:NSLocalizedString("errornotifi", comment: ""),theme: .error)
tableView.endUpdates()
}
delete.backgroundColor = UIColor.red
return [delete]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "followToCoinPage", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "followToCoinPage"{
let index = followPageView.indexPathForSelectedRow
let coinProfilVC = segue.destination as! coinProfilVC
coinProfilVC.coin = homeCoinData[(index?.row)!].short
let aString = homeCoinData[(index?.row)!].long
let newString = aString.replacingOccurrences(of: " ", with: "-")
coinProfilVC.coinLong = newString
}
}
func coinData(){
RouterUtility.shared.coin(callback: { response in
if !response.hasError {
self.homeCoinData = response.data
self.homeCoinData = self.homeCoinData.filter{ self.followShortName.contains($0.short) }
self.followPageView.reloadData()
}
})
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.