text stringlengths 8 1.32M |
|---|
//
// ViewController.swift
// KITEGURU
//
// Created by Elias Houttuijn Bloemendaal on 07-01-16.
// Copyright © 2016 Elias Houttuijn Bloemendaal. All rights reserved.
//
//
//import UIKit
//
//
//class MainViewController: UIViewController {
//
//
// override func viewDidAppear(animated: Bool) {
// super.viewDidAppear(true)
//
// // use PFUser to see if there is a current user signed in
// if PFUser.currentUser() != nil {
// } else {
// // take user to SignInViewController through a custom segue
// self.performSegueWithIdentifier("signIn", sender: self)
// }
// }
//
// @IBAction func logOutButton(sender: AnyObject) {
// PFUser.logOut()
// self.performSegueWithIdentifier("signIn", sender: self)
// }
//}
//
|
//
// UserDetailsWorker.swift
// CleanGitUsersList
//
// Created by Михаил Звягинцев on 23.10.2021.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
class UserDetailsWorker {
func fetchUserData(from url: URL, complition: @escaping(Result<UserInfoModel?, Error>) -> Void) {
NetworkManager.shared.fetchData(from: url, resultType: UserInfoModel.self) { result in
do {
let userInfo = try result.get()
complition(.success(userInfo))
} catch {
complition(.failure(error))
}
}
}
}
|
//
// ProfileCell.swift
// Twitter
//
// Created by Deeksha Prabhakar on 11/5/16.
// Copyright © 2016 Deeksha Prabhakar. All rights reserved.
//
import UIKit
@objc protocol ProfileCellDelegate {
@objc optional func segmentChanged(tweetType: String, controlCell: ProfileCell)
}
class ProfileCell: UITableViewCell {
@IBOutlet weak var bgView: UIView!
@IBOutlet weak var bgImageView: UIImageView!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var profileName: UILabel!
@IBOutlet weak var screenName: UILabel!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var tagLineLabel: UILabel!
@IBOutlet weak var followingLabel: UILabel!
@IBOutlet weak var followersLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
weak var profileDelegate:ProfileCellDelegate?
var profile:User!{
didSet {
fillCell()
}
}
func fillCell() {
if profile.profileUrl != nil {
profileImageView.alpha = 0
UIView.animate(withDuration: 0.4, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.profileImageView.setImageWith(self.profile.profileUrl!)
self.profileImageView.alpha = 1
}, completion: nil)
}
if let bgUrl = profile?.bannerImageUrl{
bgImageView.setImageWith(bgUrl)
bgImageView.clipsToBounds = true
//bgImageView.contentMode = .scaleAspectFill
}
profileName.text = profile.name
screenName.text = "@" + (profile.screenname!)
tagLineLabel.text = profile.tagline
locationLabel.text = profile.location
followingLabel.text = "\(profile.followingCount)"
followersLabel.text = "\(profile.followersCount)"
}
override func awakeFromNib() {
super.awakeFromNib()
profileImageView.layer.cornerRadius = 6
profileImageView.layer.borderColor = UIColor.white.cgColor
profileImageView.layer.borderWidth = 3
profileImageView.layer.masksToBounds = true
}
@IBAction func onTweetTypeChange(_ sender: UISegmentedControl) {
let type = sender.titleForSegment(at: sender.selectedSegmentIndex)
profileDelegate?.segmentChanged!(tweetType: type!, controlCell: self)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// ForecastTableViewCell.swift
// Module14v2
//
// Created by Сергей Гринько on 21.03.2021.
//
import UIKit
class ForecastTableViewCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var descrLabel: UILabel!
@IBOutlet weak var minTempLabel: UILabel!
@IBOutlet weak var maxTempLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// PDFTextConfigurator.swift
// Machine Details
//
// Created by David Sarkisyan on 17.03.2020.
// Copyright © 2020 DavidS. All rights reserved.
//
class PDFTextConfigurator {
let leftTabSize = "\t"
let rightTabSize = ": "
func setupPage(result: ResultModel) -> String{
var body: String = ""
body += setupScheme(result: result)
body += setupGearboxCharactaristics(result: result)
body += setupSchemeCharactaristics(result: result)
body += setupGenerator(generator: result.sourceGenerator, header: "Источник")
body += setupGenerator(generator: result.consumerGenerator, header: "Потребитель")
return body
}
private func setupScheme(result: ResultModel) -> String{
var scheme: String = "Итоговая рекомендуемая схема:" + rightTabSize + "\n" + "источник (электродвигатель) -> "
scheme += String.resultScheme(result: result)
scheme += " -> потребитель \n"
return scheme + "\n"
}
private func setupGearboxCharactaristics(result: ResultModel) -> String{
var charactaristics: String = "Характеристики редуктора: \n"
charactaristics += leftTabSize + String.resultHeader(type: .gearType) + rightTabSize + String.resultGearType(result: result) + "\n"
charactaristics += leftTabSize + "Количество ступеней" + rightTabSize + String.resultGearStage(result: result) + "\n"
charactaristics += leftTabSize + "Передаточное отношение" + rightTabSize + "\(result.gearbox.gearRatio ?? 1)" + "\n"
return charactaristics + "\n"
}
private func setupSchemeCharactaristics(result: ResultModel) -> String{
var charactaristics: String = "Характеристики всей схемы: \n"
if let gearboxGearRatio = result.gearbox.gearRatio{
let resultSchemeGearRatio = result.gearRatio(gearboxRatio: gearboxGearRatio)
charactaristics += leftTabSize + String.resultHeader(type: .schemeGearRatio) + rightTabSize + "\(Int(resultSchemeGearRatio))" + "\n"
}
if let chainTransmission = result.chainTransmission{
charactaristics += leftTabSize + "Рекомендуется применение цепной передачи с передаточным отношением" + rightTabSize + "\(chainTransmission.gearRatio)" + "\n"
}else if let beltTransmission = result.beltTransmission{
charactaristics += leftTabSize + "Рекомендуется применение ремённой передачи с передаточным отношением" + rightTabSize + "\(beltTransmission.gearRatio)" + "\n"
}
return charactaristics
}
private func setupGenerator(generator: Generator, header: String) -> String{
var resultString: String = "\n"
resultString += header + rightTabSize + "\n"
guard let frequency = generator.frequency else{return resultString}
resultString += leftTabSize + "Частота: " + String(frequency) + "\n"
guard let name = generator.name else{return resultString}
resultString += leftTabSize + "Наименование: " + name + "\n"
return resultString
}
}
|
//
// MainNavigationController.swift
// Eventhall
//
// Created by Jonas Maier on 09.05.15.
// Copyright (c) 2015 com.jonasmaier. All rights reserved.
//
import UIKit
class LogInViewController: UIViewController {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var innerView: UIControl!
@IBOutlet var phoneNumberTextField: UITextField!
@IBOutlet var logInButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
logInButton.backgroundColor = UIColor.lightGrayColor()
}
@IBAction func editingDidBegin(){
scrollView.setContentOffset(CGPointMake(0, 50), animated: true)
}
@IBAction func editingDidEnd(){
scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
}
@IBAction func hideKeyboard(){
view.endEditing(true)
}
@IBAction func logIn() {
}
}
|
//
// CreateSkillOtherInteractor.swift
// miniTopgun
//
// Created by itthipon wiwatthanasathit on 7/30/2560 BE.
// Copyright (c) 2560 Izpal. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol CreateSkillOtherBusinessLogic
{
var skillOtherEditDict:SkillOtherData? { get set }
func createSkillOther(request: CreateSkillOther.Create.Request)
func updateSkillOther(request: CreateSkillOther.Update.Request)
func fetchLevelSkill(requst: CreateSkillOther.MDLevelSkill.Request)
func showSkillOtherToEdit(request: CreateSkillOther.Edit.Request)
}
protocol CreateSkillOtherDataStore
{
//var name: String { get set }
var skillOtherEditDict:SkillOtherData? { get set }
}
class CreateSkillOtherInteractor: CreateSkillOtherBusinessLogic, CreateSkillOtherDataStore
{
var presenter: CreateSkillOtherPresentationLogic?
var worker: CreateSkillOtherWorker?
var skillOtherEditDict:SkillOtherData?
// MARK: Do something
func createSkillOther(request: CreateSkillOther.Create.Request)
{
worker = CreateSkillOtherWorker()
worker?.createSkillOther(request: request, completion: { (list) in
let response = CreateSkillOther.Create.Response(SkillOtherList: list)
self.presenter?.presentCreateSkillOther(response: response)
})
}
func updateSkillOther(request: CreateSkillOther.Update.Request)
{
worker = CreateSkillOtherWorker()
worker?.updateSkillOther(request: request, completion: { (list) in
let response = CreateSkillOther.Update.Response(SkillOtherList: list)
self.presenter?.presentUpdateSkillOther(response: response)
})
}
func showSkillOtherToEdit(request: CreateSkillOther.Edit.Request){
if let dict = skillOtherEditDict {
let response = CreateSkillOther.Edit.Response(SkillOtherList: dict)
self.presenter?.presentSkillOtherToEdit(response: response)
}
}
func fetchLevelSkill(requst: CreateSkillOther.MDLevelSkill.Request){
worker = CreateSkillOtherWorker()
worker?.fetchLevelSkill(completion: { (list) in
let response = CreateSkillOther.MDLevelSkill.Response(LevelSkillList: list)
self.presenter?.presentLevelSkill(response: response)
})
}
}
|
//
// SwiftUIViewController.swift
// GridsLab
//
// Created by Nestor Hernandez on 13/06/22.
//
import Foundation
import SwiftUI
open class SwiftUIViewController<Content: View>: UIHostingController<Content>{
override public init(rootView: Content) {
super.init(rootView: rootView)
}
// @MainActor @objc required dynamic public init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
@available(*, unavailable,
message: "Loading this view controller from a nib is unsupported in favor of initializer dependency injection."
)
@available(*, unavailable,
message: "Loading this view controller from a nib is unsupported in favor of initializer dependency injection."
)
public required init?(coder aDecoder: NSCoder) {
fatalError("Loading this view controller from a nib is unsupported in favor of initializer dependency injection.")
}
}
|
//
// NodeStub.swift
// SailingThroughHistory
//
// Created by henry on 13/4/19.
// Copyright © 2019 Sailing Through History Team. All rights reserved.
//
import Foundation
class NodeStub: Node {
required init(name: String, identifier: Int) {
Node.nextID = identifier
Node.reuseID.removeAll()
let frame = Rect(originX: 0, originY: 0, height: 0, width: 0)
super.init(name: name, frame: frame)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
override func getCompleteShortestPath(to node: Node, with ship: Pirate_WeatherEntity, map: Map) -> [Node] {
return [node]
}
}
|
import Foundation
public enum DeepLink: Hashable {
case debug
case statistics
case support
case feedback(searchURL: URL?, websiteURL: URL?, permittedOrigins: [String]?)
case settings
case about
case installationInstructions
case unlock
public init?(url: URL) {
if url.scheme == "overamped" {
self.init(appSchemeURL: url)
} else if url.host == "overamped.app" {
self.init(websiteURL: url)
} else {
return nil
}
}
private init?(appSchemeURL url: URL) {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return nil }
let path: String
if let host = url.host {
path = host
} else {
path = components.path
}
switch path {
case "statistics":
self = .statistics
case "support":
self = .support
case "feedback":
self.init(feedbackComponents: components)
case "settings":
self = .settings
case "about":
self = .about
case "debug":
self = .debug
case "installation-instructions":
self = .installationInstructions
case "unlock":
self = .unlock
default:
return nil
}
}
private init?(websiteURL url: URL) {
switch url.path {
case "/feedback":
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return nil }
self.init(feedbackComponents: components)
case "/how-to-disable-amp-in-safari" where url.fragment == "setup-overamped":
self = .installationInstructions
default:
return nil
}
}
private init(feedbackComponents components: URLComponents) {
let openURL: URL? = (components.queryItems?.first(where: { $0.name == "url" })?.value).flatMap { URL(string: $0) }
let permittedOrigins = components
.queryItems?
.first(where: { $0.name == "permittedOrigins" })?
.value
.flatMap {
$0.split(separator: ",").map(String.init(_:))
}
if openURL?.host?.contains("google.") == true, openURL?.path.hasPrefix("/search") == true || openURL?.host?.hasPrefix("news.google.") == true {
self = .feedback(searchURL: openURL, websiteURL: nil, permittedOrigins: permittedOrigins)
} else {
self = .feedback(searchURL: nil, websiteURL: openURL, permittedOrigins: permittedOrigins)
}
}
}
|
//
// Scene.swift
// Storyboard
//
// Created by Rogy on 6/22/17.
// Copyright © 2017 RogyMD. All rights reserved.
//
import UIKit
/// Represents a scene in `UIStoryboard` with required identifier.
public protocol StoryboardSceneType {
/// The storyboard type that contains scene.
///
/// - SeeAlso: `StoryboardType`
associatedtype Storyboard: StoryboardType
/// The storyboard from which the scene originated.
///
/// When this protocol is adopted by a `UIViewController` subclass, it returns unwrapped `storyboard` value.
var storyboard: UIStoryboard { get }
/// An identifier string that uniquely identifies the scene in the storyboard file. You set the identifier for a given scene in Interface Builder when configuring the storyboard file.
///
/// - Important:
/// By default when `StoryboardSceneType` is adopted by a `UIViewController` _subclass_ it returns string representation of it's _type_ for all `storyboard`-s. You could override this function.
///
/// - Parameter storyboard: `Storyboard` represents storyboard file for scene.
/// - Returns: An identifier string that uniquely identifies the scene in the storyboard file or `nil` when `storyboard` doesn't contains scene of this type.
static func sceneIdentifier(in storyboard: Storyboard) -> String?
/// Main storyboard that contains scene.
static var mainStoryboard: Storyboard { get }
}
public extension StoryboardSceneType where Self: UIViewController {
var storyboard: UIStoryboard {
return storyboard!
}
/// Scene from `mainStoryboard`.
/// - SeeAlso: `mainStoryboard`, `scene(in:)`
static var scene: Self {
return scene(in: mainStoryboard)
}
static func sceneIdentifier(in storyboard: Storyboard) -> String? {
return "\(self)"
}
/// Initialize a new scene from `storyboard` and return it.
///
/// - Parameter storyboard: Storyboard that contains scene.
/// - Returns: Initialized scene from `storyboard`.
static func scene(in storyboard: Storyboard) -> Self {
return storyboard.scene()
}
}
|
//
// ViewController.swift
// Teleport
//
// Created by KaMi on 9/5/18.
// Copyright © 2018 Nenad VULIC. All rights reserved.
//
import Cocoa
import MultipeerConnectivity
class ViewController: NSViewController {
@IBOutlet weak var teleportView: TeleportView!
@IBOutlet weak var connectionLabel: NSTextFieldCell!
var teleport: Teleport?
override func viewDidLoad() {
super.viewDidLoad()
self.teleport = Teleport.init(self)
self.connectionLabel.title = "not connected"
self.teleportView.teleportViewDelegate = self
if let deviceName = Host.current().localizedName {
NSLog(deviceName)
} else {
NSLog("teleport-host")
}
}
}
extension ViewController : TeleportViewDelegate {
func teleportCredentials(_ data: Data) {
self.teleport?.sendCredentialFile(data)
}
}
extension ViewController : TeleportDelegate {
func teleportPeerStateChange(_ connectedPeerId: MCPeerID, _ state: MCSessionState) {
DispatchQueue.main.async {
switch state {
case .notConnected:
self.connectionLabel.title = "not connected"
break
case .connecting:
self.connectionLabel.title = "connecting"
break
case .connected:
self.connectionLabel.title = "connected to \(connectedPeerId.displayName)"
break
}
}
}
}
|
/* Copyright Airship and Contributors */
import Foundation
#if canImport(AirshipCore)
import AirshipCore
#endif
/**
* Common display info.
*/
@objc(UAPreferenceCommonDisplay)
public class CommonDisplay : NSObject, Decodable {
/**
* The optional name/title.
*/
@objc
public let title: String?
/**
* The optional description/subtitle.
*/
@objc
public let subtitle: String?
/**
* The optional icon URL.
*/
@objc
public let iconURL: String?
enum CodingKeys: String, CodingKey {
case title = "name"
case subtitle = "description"
case iconURL = "icon"
}
}
|
//
// Horario.swift
// Control de Ingreso2
//
// Created by Esteban Choque Villalobos on 9/21/20.
// Copyright © 2020 Esteban Choque Villalobos. All rights reserved.
//
import Foundation
import UIKit
struct Usuario {
let username:String
let password:String
let email:String
let pic:String
let fullname:String
let occupation:String
let phone:String
let address:String
let state:String
let recinto:String
let rol:String
}
|
//
// PlayerViewController.swift
// radio
//
// Created by MacBook 13 on 10/9/18.
// Copyright © 2018 MacBook 13. All rights reserved.
//
import Foundation
import UIKit
import GoogleMobileAds
import AVKit
class PlayerViewController: UIViewController{
/*
Flag to check if is playing or not, initially this is playing
*/
private var playing:DarwinBoolean = true
/*
Timer for the thread to beggin playin the music
*/
private var gameTimer: Timer! = nil
/*
Player of the music
*/
private var player: AVPlayer!
@IBOutlet weak var volumeMaxControl: UIImageView!
@IBOutlet weak var volumeMinControl: UIImageView!
@IBOutlet weak var circularPlay: UIImageView!
@IBOutlet weak var volumeContro: UISlider!
@IBOutlet weak var loadingImage: UIImageView!
@IBOutlet weak var tittleLabel: UILabel!
@IBOutlet weak var subtittleLabel: UILabel!
@IBOutlet weak var centralImage: UIImageView!
@IBOutlet weak var hearthImage: UIImageView!
@IBOutlet weak var previousImage: UIImageView!
@IBOutlet weak var playImage: UIImageView!
@IBOutlet weak var nextImage: UIImageView!
@IBOutlet weak var downImage: UIImageView!
@IBOutlet weak var graphicMusic: UIImageView!
/*
Current radio model
*/
private var radioModel:RadioModel! = nil
/*
Contains the mini player instance
*/
private var miniPlayer:MiniPlayerView! = nil
override func viewDidLoad() {
/*
Load the gif image
*/
graphicMusic.loadGif(name: "loading")
/*
Event for the down button image
*/
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
downImage.isUserInteractionEnabled = true
downImage.addGestureRecognizer(tapGestureRecognizer)
/*
Banner
*/
let screenSize = UIScreen.main.bounds
let screenHeight = screenSize.height
let smart = kGADAdSizeSmartBannerPortrait
let banner = GADBannerView(adSize: smart)
banner.frame.origin = CGPoint(x: 0, y: screenHeight - 50) // set your own offset
banner.adUnitID = "ca-app-pub-3940256099942544/2934735716" // insert your own unit ID
banner.rootViewController = self
self.view.addSubview(banner)
let request = GADRequest()
banner.load(request)
/*
Init the labels
*/
self.updateLabels(radioModel: radioModel)
/*
Touch events for volumen icons
*/
let volumeMin = UITapGestureRecognizer(target: self, action: #selector(volumeMinTapped(tapGestureRecognizer:)))
volumeMinControl.isUserInteractionEnabled = true
volumeMinControl.addGestureRecognizer(volumeMin)
let volumeMax = UITapGestureRecognizer(target: self, action: #selector(volumeMaxTapped(tapGestureRecognizer:)))
volumeMaxControl.isUserInteractionEnabled = true
volumeMaxControl.addGestureRecognizer(volumeMax)
/*
Create the touch events for the player controls
*/
let previousGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(previousTapped(tapGestureRecognizer:)))
previousImage.isUserInteractionEnabled = true
previousImage.addGestureRecognizer(previousGestureRecognizer)
let playGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(playTapped(tapGestureRecognizer:)))
playImage.isUserInteractionEnabled = true
playImage.addGestureRecognizer(playGestureRecognizer)
let forwardGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(forwardTapped(tapGestureRecognizer:)))
nextImage.isUserInteractionEnabled = true
nextImage.addGestureRecognizer(forwardGestureRecognizer)
/*
Change the icon initially to playing
*/
playImage.image = UIImage(named: "pause_white_36dp")
/*
The loading icon initially is hidden
*/
self.loadingImage.isHidden = true
/*
Hearth icon event touch
*/
let tapGestureRecognizerHearth = UITapGestureRecognizer(target: self, action: #selector(heartTapped(tapGestureRecognizer:)))
hearthImage?.isUserInteractionEnabled = true
hearthImage?.addGestureRecognizer(tapGestureRecognizerHearth)
/*
Slider volume changes
*/
volumeContro.addTarget(self, action: #selector(sliderValueDidChange(_:)), for: .valueChanged)
/*
Set the slider volume to the initial state
*/
self.volumeContro.value = player.volume * 100
print("player.volume: \(player.volume)")
/*
Circular in the background play icon
*/
circularPlay.layer.borderWidth = 1
circularPlay.layer.masksToBounds = false
circularPlay.layer.borderColor = UIColor.black.cgColor
circularPlay.layer.cornerRadius = circularPlay.frame.height/2
circularPlay.clipsToBounds = true
/*
Remove border in circular image
*/
self.circularPlay.layer.borderWidth = 0
/*
Remove border in central image
*/
self.centralImage.layer.borderWidth = 0
/*
Set the central image
*/
updateCentralImages()
/*
Circular image in the central image
*/
centralImage.layer.borderWidth = 1
centralImage.layer.masksToBounds = false
centralImage.layer.borderColor = UIColor.black.cgColor
centralImage.layer.cornerRadius = centralImage.frame.height/2
centralImage.clipsToBounds = true
}
func updateCentralImages(){
/*
Set the central image
*/
let imageUrlString = URLS.RADIOS_HOST + (self.miniPlayer.getCurrentRadioModel().img)!
let imageUrl:URL = URL(string: imageUrlString)!
// Start background thread so that image loading does not make app unresponsive
DispatchQueue.global(qos: .userInitiated).async {
do {
if imageUrl != nil {
let imageData:NSData = try NSData(contentsOf: imageUrl)
if imageData != nil {
// When from background thread, UI needs to be updated on main_queue
DispatchQueue.main.async {
let image:UIImage = UIImage(data: imageData as Data)!
self.centralImage.image = image
/*
Circula animation for the center image
*/
DispatchQueue.main.async {
self.centralImage.rotate360Degrees(duration: 1)
}
/*
Add the background image
*/
let imageBack:UIImage = UIImage(data: imageData as Data)!
self.view.backgroundColor = UIColor(patternImage: imageBack)
/*
Add the blur effect
*/
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(blurEffectView)
self.view.sendSubview(toBack: blurEffectView)
}
}
}
} catch _ {
}
}
}
@objc func sliderValueDidChange(_ sender: UISlider) {
// Coalesce the calls until the slider valude has not changed for 0.2 seconds
/*debounce(seconds: 0.2) {
print("slider value: \(sender.value)")
}*/
player.volume = sender.value / 100
print("sender.value: \(player.volume)")
}
/*
When the user clics on the heart icon
*/
@objc func heartTapped(tapGestureRecognizer: UITapGestureRecognizer){
/*
Paint and validate the color of the heart
*/
var imageHeart = ""
if(!radioModel.hearthIt){
radioModel.hearthIt = true
imageHeart = "hearth-red"
/*
Set the false value with the server for this favorite
*/
FavoritesSettings.shared.updateFavorite(id: radioModel.id as! Int,val: true)
}
else{
radioModel.hearthIt = false
imageHeart = "hearth-empty"
/*
Set the false value with the server for this favorite
*/
FavoritesSettings.shared.updateFavorite(id: radioModel.id as! Int,val: false)
}
/*
Change the image type
*/
let image = UIImage(named: imageHeart)
hearthImage.image = image
}
func pause(){
/*
If it is playing or not change the icon
*/
playImage.image = UIImage(named: "play_arrow_white_36dp")
/*
Reset flag
*/
playing = false
self.miniPlayer.pause()
/*
Hidde the graphic music
*/
self.graphicMusic.isHidden = true
}
func play(){
/*
Change the icon
*/
playImage.image = UIImage(named: "pause_white_36dp")
/*
Change the labels
*/
self.tittleLabel.text = self.radioModel.name
self.subtittleLabel.text = self.radioModel.sourceRadio
/*
Reset flag
*/
playing = true
self.miniPlayer.play()
/*
Show the graphic music
*/
self.graphicMusic.isHidden = false
/*
Hide the controls until the rate is playing and show loading
*/
self.showLoading()
self.hideControlsPlay()
/*
Start the timer to check when already is playing and show the controls
*/
gameTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)
}
/*
Detect if already it is playing
*/
func isPlaying()->Bool {
if (self.player.rate != 0 && self.player.error == nil) {
return true
} else {
return false
}
}
/*
Timer to check when already is playing and show the controls
*/
@objc private func runTimedCode(){
/*
If tha player is already playing invalidate it
*/
if(self.isPlaying()){
gameTimer.invalidate() //Stop the timer
/*
Hide the loading control and show the normal controls
*/
self.hideLoading()
self.showControlsPlay()
}
}
func showControlsPlay(){
previousImage.isHidden = false
playImage.isHidden = false
nextImage.isHidden = false
}
func hideLoading(){
loadingImage.isHidden = true
}
func showLoading(){
loadingImage.isHidden = false
}
func hideControlsPlay(){
previousImage.isHidden = true
playImage.isHidden = true
nextImage.isHidden = true
}
func volumeMinTapped(tapGestureRecognizer: UITapGestureRecognizer){
let tappedImage = tapGestureRecognizer.view as! UIImageView
/*
Set all the volume to min
*/
player.volume = 0
self.volumeContro.value = 0
}
func volumeMaxTapped(tapGestureRecognizer: UITapGestureRecognizer){
let tappedImage = tapGestureRecognizer.view as! UIImageView
/*
Set all the volume to max
*/
player.volume = 1
self.volumeContro.value = 100
}
func previousTapped(tapGestureRecognizer: UITapGestureRecognizer){
let tappedImage = tapGestureRecognizer.view as! UIImageView
// Your action
/*
Deliver the event
*/
/*if(self.onForward != nil){
self.onForward.onForward(data: tappedImage)
}*/
/*
Play the previous song
*/
miniPlayer.previous()
/*
Update labels
*/
self.updateLabels(radioModel: self.miniPlayer.getCurrentRadioModel())
/*
Update the central image
*/
updateCentralImages()
}
func playTapped(tapGestureRecognizer: UITapGestureRecognizer){
let tappedImage = tapGestureRecognizer.view as! UIImageView
if(playing).boolValue{
pause()
}
else{
play()
}
}
func forwardTapped(tapGestureRecognizer: UITapGestureRecognizer){
let tappedImage = tapGestureRecognizer.view as! UIImageView
/*
Deliver the event
*/
/*if(self.onBackward != nil){
self.onBackward.onBackward(data: tappedImage)
}*/
/*
Play the forward song
*/
miniPlayer.forward()
/*
Update labels
*/
self.updateLabels(radioModel: self.miniPlayer.getCurrentRadioModel())
/*
Update the central image
*/
updateCentralImages()
}
@objc private func imageTapped(tapGestureRecognizer: UITapGestureRecognizer){
let tappedImage = tapGestureRecognizer.view as! UIImageView
// Your action
/*
Just close the player
*/
self.dismiss(animated: true, completion: nil)
}
func updateLabels(radioModel:RadioModel){
self.tittleLabel.text = radioModel.name
self.subtittleLabel.text = radioModel.sourceRadio
}
func setRadioModel(radioModel:RadioModel){
self.radioModel = radioModel
}
func setPlayerMusic(player: AVPlayer){
self.player = player
}
func setMiniplayer(miniPlayer:MiniPlayerView){
self.miniPlayer = miniPlayer
}
}
|
//
// GFeature.swift
// GMapService
//
// Created by Jose Zarzuela on 24/12/2014.
// Copyright (c) 2014 Jose Zarzuela. All rights reserved.
//
import Foundation
import JZBUtils
// Posibles tipos de valores que pueden establecerse en una property
public protocol GPropertyType: Printable, DebugPrintable {
}
typealias DateTime = Int64 // Since 1970
// Tambien GGeometry -> GPropertyType
extension String : GPropertyType {
public var description : String { return self }
public var debugDescription : String { return self }
}
extension Double : GPropertyType {
public var description : String { return "\(self)" }
public var debugDescription : String { return "\(self)" }
}
extension DateTime : GPropertyType { //TODO: NOOOOOOOO -> Hay que distinguir Date de un numero
public var description : String { return "\(self)" }
public var debugDescription : String { return "\(self)" }
}
extension Bool : GPropertyType {
public var description : String { return self ? "true" : "false" }
public var debugDescription : String { return self ? "true" : "false" }
}
//========================================================================================================================
public class GFeature : GAsset {
public enum GeoType : Int {
case POINT = 1, LINE = 2, POLYGON = 3
}
unowned public let table:GTable
public let geoType : GeoType
private var rawPropValues = Dictionary<String, GPropertyType?>()
private(set) public var allProperties : RONamedSubscript<String, GPropertyType?>!
private(set) public var userProperties : NamedSubscript<String, GPropertyType?>!
//------------------------------------------------------------------------------------------------------------------------
internal init(gid: String, table:GTable, geoType:GeoType) {
self.table = table
self.geoType = geoType
super.init(gid:gid)
_setNamedProperties()
}
//------------------------------------------------------------------------------------------------------------------------
required public init(coder decoder: NSCoder) {
table = decoder.decodeObjectForKey("ownerTable") as GTable
geoType = GeoType(rawValue:decoder.decodeIntegerForKey("geoType"))!
super.init(coder: decoder)
_setNamedProperties()
// Properties
let count = decoder.decodeIntegerForKey("propCount")
for var index=0; index<count; index++ {
let name = decoder.decodeObjectForKey("propName_\(index)") as String
let value = _decodePropValue(decoder, forIndex:index)
_setPropValue(name, value: value, justUserProps:false)
}
}
//------------------------------------------------------------------------------------------------------------------------
override public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(table, forKey: "ownerTable")
aCoder.encodeInteger(geoType.rawValue, forKey: "geoType")
super.encodeWithCoder(aCoder)
// Properties
aCoder.encodeInteger(rawPropValues.count, forKey: "propCount")
var index = 0
for (name, value) in rawPropValues {
aCoder.encodeObject(name, forKey: "propName_\(index)")
_encodePropValue(aCoder, forIndex:index, value:value)
index++
}
}
//------------------------------------------------------------------------------------------------------------------------
private func _decodePropValue(decoder: NSCoder, forIndex:Int) -> GPropertyType? {
let keyType = "propType_\(forIndex)"
let keyValue = "propValue_\(forIndex)"
let type = decoder.decodeIntegerForKey(keyType)
switch type {
case 0:
return nil
case 1:
return decoder.decodeObjectForKey(keyValue) as String
case 2:
return decoder.decodeDoubleForKey(keyValue)
case 3:
return decoder.decodeInt64ForKey(keyValue)
case 4:
return decoder.decodeBoolForKey(keyValue)
case 5:
let array = decoder.decodeObjectForKey(keyValue) as [Double]
return GGeometryPoint(array: array)
case 6:
let array = decoder.decodeObjectForKey(keyValue) as [[Double]]
return GGeometryLine(array: array)
case 7:
let array = decoder.decodeObjectForKey(keyValue) as [[Double]]
return GGeometryPolygon(array: array)
default:
// Aqui no deberia llegar
assertionFailure("Cannot decode unknown feature property type")
}
}
//------------------------------------------------------------------------------------------------------------------------
private func _encodePropValue(coder: NSCoder, forIndex:Int, value:GPropertyType?) {
let keyType = "propType_\(forIndex)"
let keyValue = "propValue_\(forIndex)"
switch value {
case nil:
coder.encodeInteger(0, forKey: keyType)
case let s as String:
coder.encodeInteger(1, forKey: keyType)
coder.encodeObject(s, forKey: keyValue)
case let d as Double:
coder.encodeInteger(2, forKey: keyType)
coder.encodeDouble(d, forKey: keyValue)
case let t as DateTime:
coder.encodeInteger(3, forKey: keyType)
coder.encodeInt64(t, forKey: keyValue)
case let b as Bool:
coder.encodeInteger(4, forKey: keyType)
coder.encodeBool(b, forKey: keyValue)
case let gi as GGeometryPoint:
coder.encodeInteger(5, forKey: keyType)
coder.encodeObject(gi.toArray() , forKey: keyValue)
case let gl as GGeometryLine:
coder.encodeInteger(6, forKey: keyType)
coder.encodeObject(gl.toArray() , forKey: keyValue)
case let gp as GGeometryPolygon:
coder.encodeInteger(7, forKey: keyType)
coder.encodeObject(gp.toArray() , forKey: keyValue)
default:
// Aqui no deberia llegar
assertionFailure("Cannot encode unknown feature property type")
}
}
//------------------------------------------------------------------------------------------------------------------------
public var geometry : GGeometry {
get {
let geo = _getPropValue(PROPNAME_GME_GEOMETRY, justUserProps:false)
switch geo {
case let point as GGeometryPoint:
return point
case let line as GGeometryLine:
return line
case let polygon as GGeometryPolygon:
return polygon
default:
// TODO: Aqui no deberia llegar porque todos las features deben tener geometria
return GGeometryPoint(lng: 0.0, lat: 0.0)
}
}
set {
_setPropValue(PROPNAME_GME_GEOMETRY, value: newValue, justUserProps:false)
}
}
//------------------------------------------------------------------------------------------------------------------------
public var title : String {
let titlePropName = table.layer.style.titlePropName
if let title = _getPropValue(titlePropName, justUserProps:false) as? String {
return title
} else {
// TODO: Quitar esto y retornar vacio
return "** SIN TITULO **"
}
}
//------------------------------------------------------------------------------------------------------------------------
public var style : GStyleInfo {
get {
// TODO: Como obtenemos el estilo en otros tipos
let style = table.layer.style as GStyleIndividual
return style[self]
}
set {
// TODO: Como obtenemos el estilo en otros tipos
let style = table.layer.style as GStyleIndividual
style[self] = newValue
}
}
//------------------------------------------------------------------------------------------------------------------------
internal func addProperties(props:Dictionary<String, GPropertyType?>) {
for (key, value) in props {
_setPropValue(key, value:value, justUserProps:false)
}
}
//------------------------------------------------------------------------------------------------------------------------
private func _setNamedProperties() {
// SOLO ACCEDE A PROPIEDADES NO RESERVADAS (DE LAS CONOCIDAS) DE GOOGLE
self.userProperties = NamedSubscript<String, GPropertyType?>(
getter: {
return self._getPropValue($0, justUserProps: true)
},
setter: {
let b = self._setPropValue($0, value: $1, justUserProps: true)
},
generator: {
var schema_iterator = self.table.schema.generate()
return GeneratorOf() {
while true {
if let item = schema_iterator.next() {
if !item.value.sysProp {
let name : String = item.key
return (name, self.rawPropValues[name]?)
}
} else {
return nil
}
}
}
}
)
// ACCEDE A TODAS PROPIEDADES
self.allProperties = RONamedSubscript<String, GPropertyType?>(
getter: {
return self._getPropValue($0, justUserProps: false)
},
generator: {
var schema_iterator = self.table.schema.generate()
return GeneratorOf() {
if let item = schema_iterator.next() {
let name : String = item.key
return (name, self.rawPropValues[name]?)
} else {
return nil
}
}
}
)
}
//------------------------------------------------------------------------------------------------------------------------
private func _getPropValue(name:String, justUserProps:Bool) -> GPropertyType? {
// No se retorna nada que no este en el Schema y que sea del tipo adecuado
if let (type, sysProp) = table.schema[name] {
// Comprueba si debe restringir el acceso a SOLO las propiedades de usuario
if justUserProps && sysProp {
return nil
}
return rawPropValues[name]?
} else {
return nil
}
}
//------------------------------------------------------------------------------------------------------------------------
private func _setPropValue(name:String, value: GPropertyType?, justUserProps:Bool) -> Bool {
// No se deja asignar nada que no este en el Schema y que sea del tipo adecuado
if let (type, sysProp) = table.schema[name] {
// Comprueba si debe restringir el acceso a SOLO las propiedades de usuario
if justUserProps && sysProp {
return false
}
// Y si los tipos concuerdan o es NIL
if value == nil || _valueHasProperType(value, type: type) {
rawPropValues.updateValue(value, forKey: name)
return true
}
}
return false
}
//------------------------------------------------------------------------------------------------------------------------
private func _valueHasProperType(value: GPropertyType?, type:GESchemaType) -> Bool {
switch value {
case let v as GGeometryPoint:
return (type == GESchemaType.ST_GEOMETRY) || (geoType == GeoType.POINT)
case let v as GGeometryLine:
return (type == GESchemaType.ST_GEOMETRY) || (geoType == GeoType.LINE)
case let v as GGeometryPolygon:
return (type == GESchemaType.ST_GEOMETRY) || (geoType == GeoType.POLYGON)
case let v as String:
return type == GESchemaType.ST_STRING
case let v as Double:
return type == GESchemaType.ST_NUMERIC
case let v as DateTime:
return type == GESchemaType.ST_DATE
case let v as Bool:
return type == GESchemaType.ST_BOOL
default:
return false
}
}
//------------------------------------------------------------------------------------------------------------------------
override internal var _assetClassName : String {
return "GFeature";
}
//------------------------------------------------------------------------------------------------------------------------
override internal func _debugDescriptionInner(inout strVal:String, padding:String, tabIndex:UInt) {
super._debugDescriptionInner(&strVal, padding: padding, tabIndex:tabIndex)
strVal += "\(padding)title: '\(title)'\n"
strVal += "\(padding)style: \(style)\n"
strVal += "\(padding)properties: {\n"
for (propName,(propType,sysProp)) in table.schema {
if let propValue = rawPropValues[propName] {
strVal += "\(padding) '\(propName)' : \(propType) -> \(propValue)\n"
}
}
strVal += "\(padding)}\n"
}
} |
//
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import RxFlow
class ___VARIABLE_sceneName___ViewModel: ViewModelType, Stepper {
// MARK: - Stepper
var steps = PublishRelay<Step>()
// MARK: - ViewModelType Protocol
typealias ViewModel = ___VARIABLE_sceneName___ViewModel
struct Input {
}
struct Output {
}
func transform(req: ViewModel.Input) -> ViewModel.Output {
return Output()
}
}
|
//
// InviteUpdate.swift
// Ursus Chat
//
// Created by Daniel Clelland on 6/07/20.
// Copyright © 2020 Protonome. All rights reserved.
//
import Foundation
import UrsusAirlock
enum InviteUpdate: Decodable {
case initial(InviteUpdateInitial)
case create(InviteUpdateCreate)
case delete(InviteUpdateDelete)
case invite(InviteUpdateInvite)
case accepted(InviteUpdateAccepted)
case decline(InviteUpdateDecline)
enum CodingKeys: String, CodingKey {
case initial
case create
case delete
case invite
case accepted
case decline
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch Set(container.allKeys) {
case [.initial]:
self = .initial(try container.decode(InviteUpdateInitial.self, forKey: .initial))
case [.create]:
self = .create(try container.decode(InviteUpdateCreate.self, forKey: .create))
case [.delete]:
self = .delete(try container.decode(InviteUpdateDelete.self, forKey: .delete))
case [.invite]:
self = .invite(try container.decode(InviteUpdateInvite.self, forKey: .invite))
case [.accepted]:
self = .accepted(try container.decode(InviteUpdateAccepted.self, forKey: .accepted))
case [.decline]:
self = .decline(try container.decode(InviteUpdateDecline.self, forKey: .decline))
default:
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Failed to decode \(type(of: self)); available keys: \(container.allKeys)"))
}
}
}
typealias InviteUpdateInitial = Invites
struct InviteUpdateCreate: Decodable {
var path: Path
}
struct InviteUpdateDelete: Decodable {
var path: Path
}
struct InviteUpdateInvite: Decodable {
var path: Path
var uid: String
var invite: Invite
}
struct InviteUpdateAccepted: Decodable {
var path: Path
var uid: String
}
struct InviteUpdateDecline: Decodable {
var path: Path
var uid: String
}
typealias Invites = [Path: AppInvites]
typealias AppInvites = [Path: Invite]
struct Invite: Decodable {
var ship: Ship
var app: App
var path: Path
var recipient: Ship
var text: String
}
|
//
// BaseViewController.swift
// iosApp
//
// Created by Daniel Ávila Domingo on 01/01/2021.
// Copyright © 2021 orgName. All rights reserved.
//
import UIKit
import shared
class BaseViewController<P : IBasePresenter>: UIViewController, IBaseView {
var presenter: P?
func managementResourceState(resource: Resource<AnyObject>) {
}
override func viewWillAppear(_ animated: Bool) {
presenter?.attach(view: self)
}
override func viewDidDisappear(_ animated: Bool) {
presenter?.detach()
}
func showToast(message : String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.view.backgroundColor = UIColor.black
alert.view.alpha = 0.6
alert.view.layer.cornerRadius = 15
self.present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
alert.dismiss(animated: true)
}
}
}
|
/* Calculate Average
#
# Enter scores: (-1 to finish):
# 87
# 94
# 100
# 56
# 74
# 67
# 75
# 88
# -1
#
# Average score : 80
*/
import Foundation
var array: [Int] = []
var count = 0
print("Enter scores: ")
while true {
let input = Int(readLine()!)
if input == -1 {
break
}
array.insert(input!, at: 0)
count += 1
}
var theSum = array.reduce(0, +)
var average = theSum / count
print("Average score: \(average)")
|
//
// MyChallengeRequestsVC.swift
// Etbaroon
//
// Created by dev tl on 1/30/18.
// Copyright © 2018 dev tl. All rights reserved.
//
import UIKit
import Alamofire
class MyChallengeRequestsVC: UIViewController , UITableViewDelegate ,UITableViewDataSource {
@IBOutlet weak var banner: UIImageView!
@IBOutlet weak var myChallengeRequestsTV: UITableView!
var myChRequests = [GetChallenge]()
lazy var refresher: UIRefreshControl = {
let refresher = UIRefreshControl()
refresher.addTarget(self, action: #selector(handleRefersh), for: .valueChanged)
return refresher
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "طلبات التحدي"
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
self.navigationItem.backBarButtonItem?.tintColor = UIColor.white
self.navigationItem.backBarButtonItem?.title = "back"
self.myChallengeRequestsTV.rowHeight = 200
myChallengeRequestsTV.addSubview(refresher)
myChallengeRequestsTV.tableFooterView = UIView()
myChallengeRequestsTV.separatorInset = .zero
myChallengeRequestsTV.contentInset = .zero
handleRefersh()
//rundom banner
let diceRoll = Int(arc4random_uniform(10))
let url = URLs.URL_Banner + "banner_" + String(diceRoll)+".jpg"
Alamofire.request(url).response { response in
if let data = response.data, let image = UIImage(data: data) {
self.banner.image = image
}else{
self.banner.image = UIImage(named: "banner_2")
}
}
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
handleRefersh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var isLoading: Bool = false
@objc private func handleRefersh(){
self.refresher.endRefreshing()
guard !isLoading else { return }
isLoading = true
API_AllChallenges.getAllChallengesSent(fldAppPlayerID: helper.getMyPlayerId()! ){ (error: Error?, chRequests:[GetChallenge]? )in
self.isLoading = false;
if let chRequestsReturn = chRequests {
self.myChRequests = chRequestsReturn
self.myChallengeRequestsTV.reloadData()
}}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myChRequests.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : MyChallengeRequestTVCell = myChallengeRequestsTV.dequeueReusableCell(withIdentifier: "MyChallengeRequestTVCell", for: indexPath) as! MyChallengeRequestTVCell
cell.teamName1Lbl.text = myChRequests[indexPath.row].fldAppTeamName1
cell.teamName2Lbl.text = myChRequests[indexPath.row].fldAppTeamName2
cell.matchDateTime.text = myChRequests[indexPath.row].fldAppPlaygroundName
cell.playgroundNameLbl.text = myChRequests[indexPath.row].fldAppPlaygroundName
cell.deleteObj = {
API_AllChallenges.deleteChallenge(fldAppGameID: self.myChRequests[indexPath.row].fldAppGameID ){ (error: Error?, success: Bool) in
if success {
self.setAlert(message: "تم الغاء التحدي")
self.handleRefersh()
self.myChallengeRequestsTV.reloadData()
}
}
}
return (cell)
}
func setAlert(message : String)
{
let attributedString = NSAttributedString(string: " ", attributes: [
NSAttributedStringKey.font : UIFont.systemFont(ofSize: 15), //your font here
NSAttributedStringKey.foregroundColor : UIColor.green
])
let alert = UIAlertController(title: "", message: "\(message)", preferredStyle: UIAlertControllerStyle.alert)
let imageView = UIImageView(frame: CGRect(x: 10, y: 35, width: 30, height: 30))
imageView.image = UIImage(named: "ball_icon")
alert.view.addSubview(imageView)
alert.setValue(attributedString, forKey: "attributedTitle")
alert.addAction(UIAlertAction(title: "موافق", style: UIAlertActionStyle.default, handler: nil))
present(alert, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// Reddit_ClientTests.swift
// Reddit ClientTests
//
// Created by Женя on 24.05.2021.
//
import XCTest
@testable import Reddit_Client
class Reddit_ClientTests: XCTestCase {
var networkManager: NetworkManager!
override func setUpWithError() throws {
networkManager = NetworkManager()
}
override func tearDownWithError() throws {
networkManager = nil
}
func testNetworkManagerFetchData() throws {
//Given
var successFetch = false
let fetchDataExpectation = expectation(description: "Expectation in " + #function)
//When
networkManager.fetchData { result in
if case .success = result {
successFetch = true
} else {
successFetch = false
}
fetchDataExpectation.fulfill()
}
//Then
waitForExpectations(timeout: 5.0) { _ in
XCTAssertTrue(successFetch)
}
}
}
|
//
// UIScrollViewExtension.swift
// Jock
//
// Created by HD on 15/3/20.
// Copyright (c) 2015年 Haidy. All rights reserved.
//
import UIKit
extension UIScrollView {
} |
//
// SearchBar.swift
// Solidarity
//
// Created by VIKKI on 15/03/2021.
//
import SwiftUI
struct SearchBar: View {
// @Binding = link between a property that stores data, and a view that displays and changes the data
// variable for the binding of the search text
@Binding var text: String
// variable for storing the state of the search field (editing or not)
@State var isEditing = false
var body: some View {
HStack {
TextField("Saisir un mot clé", text: $text)
.padding(7)
.padding(.horizontal, 25)
.background(Color(.systemGray6))
.cornerRadius(10)
.overlay(
HStack {
Image(systemName: "magnifyingglass")
.foregroundColor(.orange)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.leading, 8)
// if user is on input field
if isEditing {
Button(action: {
self.text = ""
}) {
Image(systemName: "multiply.circle.fill")
.foregroundColor(.gray)
.padding(.trailing, 8)
}
}
}
)
.padding(.horizontal, 10)
// when the user taps the search field
.onTapGesture {
self.isEditing = true
}
if isEditing {
Button(action: {
self.isEditing = false
self.text = ""
}) {
Text("Annuler")
}
.padding(.trailing, 10)
.transition(.move(edge: .trailing))
.animation(.default)
}
}
}
}
struct SearchBar_Previews: PreviewProvider {
static var previews: some View {
SearchBar(text: .constant(""))
}
}
|
import Foundation
struct StringConstants {
static let validField: String = "true"
static let notValidField: String = "false"
static let warningField: String = "alert"
static let warningTitle: String = "Warning!"
static let defaultEmailPlaceholder: String = "jane@example.com"
static let defaultPasswordPlaceholder: String = "••••••••••••"
static let defaultSearchPlaceholder: String = "Search"
static let defaultCryptedCharacter: String = "•"
static let defaultStoryboardName: String = "Main"
static let customeStoryBoardName: String = "CustomAlert"
static let customeAlertIdentifier: String = "customAlert"
static let emailRegexPattern: String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
static let selfMatchRegexPattern: String = "SELF MATCHES %@"
static let showPassword: String = "show"
static let hidePassword: String = "hide"
static let defaultAlertTitle: String = "Error !"
static let successTitle: String = "Success!"
static let successEmailFormat: String = "Success Email Format"
static let wrongEmailFormat: String = "Wrong Email Format"
static let emptyEmailField: String = "Empty Email Field"
static let successPasswordFormat: String = "Success Password format"
static let emptyPasswordField: String = "Empty Password Field !"
static let beCarefullPassword: String = "Be Careful Your Password Is Weak"
static let defaultAlertAgree: String = "OK"
static let defaultAlertMessage: String = "Please try again"
static let incorrectUserPassword: String = "Incorrect User Password !"
static let accountNotExist: String = "Account Doesn't Exist !"
static let fromRegisterToLogin: String = "registertoLogin"
static let fromLoginToHome: String = "loginToMain"
static let fromHomeToDetails: String = "homeToDetails"
static let fromSearchToDetails: String = "searchToDetails"
static let emptyFieldAlertMessage: String = "Please Fill the Blanks :("
static let invalidEmailAlertMessage: String = "Incorrect Email Format :("
static let emptyField: String = ""
}
|
import UIKit
import Apollo
private let token = "YOUR_TOKEN"
final class TokenAddingInterceptor: ApolloInterceptor {
func interceptAsync<Operation: GraphQLOperation>(
chain: RequestChain,
request: HTTPRequest<Operation>,
response: HTTPResponse<Operation>?,
completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
request.addHeader(name: "Authorization", value: "Bearer \(token)")
chain.proceedAsync(request: request, response: response, completion: completion)
}
}
final class NetworkInterceptorProvider: InterceptorProvider {
private let client: URLSessionClient
private let store: ApolloStore
init(client: URLSessionClient, store: ApolloStore) {
self.client = client
self.store = store
}
func interceptors<Operation>(for operation: Operation) -> [ApolloInterceptor] where Operation : GraphQLOperation {
[
TokenAddingInterceptor(),
NetworkFetchInterceptor(client: self.client),
JSONResponseParsingInterceptor(cacheKeyForObject: self.store.cacheKeyForObject),
]
}
}
final class RepositoriesViewController: UITableViewController {
private var repositories: [SearchRepositoriesQuery.Data.Search.Edge.Node.AsRepository]? {
didSet {
tableView.reloadData()
}
}
private lazy var apollo: ApolloClient = {
let client = URLSessionClient()
let cache = InMemoryNormalizedCache()
let store = ApolloStore(cache: cache)
let provider = NetworkInterceptorProvider(client: client, store: store)
let url = URL(string: "https://api.github.com/graphql")!
let transport = RequestChainNetworkTransport(
interceptorProvider: provider,
endpointURL: url
)
return .init(networkTransport: transport, store: store)
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let queryString = "GraphQL"
navigationItem.title = "Query: \(queryString)"
apollo.fetch(query: SearchRepositoriesQuery(query: queryString, count: 10), cachePolicy: .fetchIgnoringCacheData) { [weak self] result in
switch result {
case .success(let result):
result.data?.search.edges?.forEach { edge in
guard let repository = edge?.node?.asRepository?.fragments.repositoryDetails else { return }
print("Name: \(repository.name)")
print("Path: \(repository.url)")
print("Owner: \(repository.owner.resourcePath)")
print("Stars: \(repository.stargazers.totalCount)")
print("\n")
}
self?.repositories = result.data?.search.edges?.compactMap { $0?.node?.asRepository }
case .failure(let error):
print("Error: \(error)")
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repositories?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "RepositoryCell", for: indexPath) as? RepositoryCell else {
fatalError()
}
guard let repository = repositories?[indexPath.row] else {
fatalError()
}
cell.configure(with: repository.fragments.repositoryDetails)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 54.0
}
}
|
//
// USSubjectResultTableView.swift
// Usth System
//
// Created by Serx on 2017/5/20.
// Copyright © 2017年 Serx. All rights reserved.
//
import UIKit
import MJRefresh
enum ResultType {
case passing
case semester
case fail
}
enum CellType {
case simple
case detail
}
private let subjectResultTableCellIdentifier: String = "subjectResultTableCellIdentifier"
private let subjectResultDetailTableCellIdentifier: String = "subjectResultDetailTableCellIdentifier"
@objc protocol USSubjectResultTableViewDelegate: NSObjectProtocol {
func subjectResultTableViewDidSelecteCell(subject: USSubject)
func subjectResultTableViewHeaderRefreshing()
}
class USSubjectResultTableView: UIView, UITableViewDataSource, UITableViewDelegate, CYLTableViewPlaceHolderDelegate, USPlaceHolderViewDelegate {
private var data: USErrorAndData?
weak var delegate: USSubjectResultTableViewDelegate?
var tableViewType: ResultType?
private var cellType: CellType = .simple
private var _tableView: UITableView?
private var _placeHolderView: USPlaceHolderView?
//MARK: - ------Life Circle------
init() {
super.init(frame: CGRect.zero)
}
convenience init(tableViewType: ResultType , data: USErrorAndData?) {
self.init()
self.tableViewType = tableViewType
self.data = data
self.addSubview(self.tableView!)
self.layoutPageSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - ------Methods------
func layoutPageSubviews() {
self.tableView?.snp.makeConstraints({ (make) in
make.edges.equalTo(self)
})
}
func startRefresh() {
if !self.tableView!.mj_header.isRefreshing() {
self.tableView!.mj_header.beginRefreshing()
}
}
func endRefreshing() {
if (self.tableView!.mj_header.isRefreshing()) {
self.tableView!.mj_header.endRefreshing()
}
if (self.tableView!.mj_footer != nil && self.tableView!.mj_footer.isRefreshing()) {
self.tableView!.mj_footer.endRefreshing()
}
}
func reloadTableWithData(_ data: USErrorAndData?) {
self.data = data
self.tableView?.cyl_reloadData()
}
func changeTableViewCellType(_ cellType: CellType) {
if cellType == self.cellType {
return
} else {
self.cellType = cellType
if (cellType == .simple) {
self.tableView?.rowHeight = 40.0
} else {
self.tableView?.rowHeight = 100.0
}
self.tableView?.cyl_reloadData()
}
}
//MARK: - ------Delegate View------
func reloadBtnAction() {
self.startRefresh()
}
//MARK: - ------Delegate Model------
//MARK: - ------Delegate Table------
func numberOfSections(in tableView: UITableView) -> Int {
if (self.data != nil) {
if (data?.semesterArr != nil) {
let semesterArr = self.data!.semesterArr
var semesterCount = semesterArr!.count
for i in 0..<semesterArr!.count {
let semester: USSemester? = semesterArr![i] as? USSemester
if (semester != nil && semester!.subjectArr.count == 0) {
semesterCount -= 1
}
}
return semesterCount
}
}
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.data != nil) {
let semesterArr = self.data!.semesterArr
let semester: USSemester? = semesterArr![section] as? USSemester
if (semester != nil) {
return semester!.subjectArr.count
}
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var tempCell: UITableViewCell = UITableViewCell()
let semesterArr = self.data!.semesterArr
let semester: USSemester? = semesterArr![indexPath.section] as? USSemester
if (semester != nil) {
let subject: USSubject? = semester!.subjectArr[indexPath.row] as? USSubject
if (subject != nil) {
if (self.cellType == .simple) {
let cell = tableView.dequeueReusableCell(withIdentifier: subjectResultTableCellIdentifier) as! USSubjectResultTableViewCell
cell.classNameLab?.text = subject!.name
cell.scoreLab?.text = String(format: "%d", subject!.score.intValue)
tempCell = cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: subjectResultDetailTableCellIdentifier) as! USSubjectResultDetailTableViewCell
cell.classNameLab?.text = subject!.name
let scoreStr = String(format: "%d", subject!.score.intValue)
cell.scoreLab?.text = scoreStr
cell.classIdLab?.text = "课程编号:" + subject!.subjectId
cell.creditLab?.text = "学分:" + String(format: "%d", subject!.credit.intValue)
cell.typeLab?.text = "课程类型:" + subject!.type
tempCell = cell
}
}
}
return tempCell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (self.data != nil) {
let semesterArr = self.data!.semesterArr
let semester: USSemester? = semesterArr![section] as? USSemester
if (semester != nil) {
return semester!.semesterName
}
}
return nil
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let semesterArr = self.data!.semesterArr
let semester: USSemester? = semesterArr![indexPath.section] as? USSemester
if (semester != nil) {
let subject: USSubject? = semester!.subjectArr[indexPath.row] as? USSubject
if (subject != nil) {
self.delegate?.subjectResultTableViewDidSelecteCell(subject: subject!)
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK: - ------Delegate Other------
func makePlaceHolderView() -> UIView! {
let wifi: Reachability = Reachability.forLocalWiFi()
let conn: Reachability = Reachability.forInternetConnection()
if (wifi.currentReachabilityStatus() != NotReachable || conn.currentReachabilityStatus() != NotReachable) {
self.placeHolderView!.loadPlaceHolderView(with: "没有成绩", and: PlaceHolderViewType.NotData)
}
else {
self.placeHolderView!.loadPlaceHolderView(with: "数据加载失败\n请确保你的手机已经联网", and: PlaceHolderViewType.NotNetwork)
}
return self.placeHolderView!
}
//MARK: - ------Event Response------
func headerRefreshing() -> Void {
self.delegate?.subjectResultTableViewHeaderRefreshing()
}
//MARK: - ------Getters and Setters------
var tableView: UITableView? {
get {
if (_tableView != nil) {
return _tableView
}
let tableV = UITableView()
tableV.register(USSubjectResultTableViewCell.self, forCellReuseIdentifier: subjectResultTableCellIdentifier)
tableV.register(USSubjectResultDetailTableViewCell.self, forCellReuseIdentifier: subjectResultDetailTableCellIdentifier)
tableV.delegate = self
tableV.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(self.headerRefreshing))
tableV.dataSource = self
tableV.rowHeight = 40.0
tableV.separatorStyle = .none
tableV.tableFooterView = UIView()
_tableView = tableV
return _tableView
}
set {
_tableView = newValue
}
}
var placeHolderView: USPlaceHolderView? {
get {
if _placeHolderView != nil {
return _placeHolderView
}
let view = USPlaceHolderView()
view.delegate = self
_placeHolderView = view
return _placeHolderView
}
}
//MARK: - ------Serialize and Deserialize------
}
|
//
// CGPoint+Extensions.swift
// ExampleApp
//
// Created by Shadrach Mensah on 05/01/2020.
// Copyright © 2020 Shadrach Mensah. All rights reserved.
//
import Foundation
import UIKit
extension CGPoint:ExpressibleByArrayLiteral{
public typealias ArrayLiteralElement = CGFloat
public init(arrayLiteral elements: CGFloat...) {
if elements.count > 1{
self = CGPoint(x: elements.first!, y: elements.last!)
}else{
if elements.isEmpty{
self = CGPoint.zero
}else{
self = CGPoint(x: elements.first!, y: elements.first!)
}
}
}
}
extension CGPoint{
static func -(_ lhs:CGPoint, rhs:CGPoint)->CGPoint{
return lhs -= rhs
}
static func +(_ lhs:CGPoint, rhs:CGPoint)->CGPoint{
return lhs += rhs
}
static func +=(_ lhs:CGPoint, rhs:CGPoint)->CGPoint{
return [lhs.x + rhs.x, lhs.y + rhs.y]
}
static func -=(_ lhs:CGPoint, rhs:CGPoint)->CGPoint{
return [lhs.x - rhs.x, lhs.y - rhs.y]
}
}
|
//
// ReminderIPhoneVScreen.swift
// Test
//
// Created by John Greenwood on 20.04.2021.
//
import RelizKit
import RZViewBuilder
class ReminderIPhoneVScreen: RZUIPacView {
var router: ReminderR!
var vSpace : RZProtoValue {10 % self*.w}
var hSpace : RZProtoValue {10 % self*.w}
var dayButtonSize : RZProtoValue {10 % self*.w}
var planButtonHeight : RZProtoValue {15 % self*.w}
var maxWidth : RZProtoValue {self*.w - hSpace * 2*}
var skipButton = UIButton()
var titleLabel = UILabel()
var buttonsStack = UIStackView()
var datePicker = UIDatePicker()
var quoteLabel = UILabel()
var quoteAutorLabel = UILabel()
var planButton = UIButton(type: .system)
var buttons: [UIButton] = []
func create() {
createSelf()
createSkipButton()
createTitleLabel()
createButtonsStack()
createDayButtons()
createDatePicker()
createPlanButton()
createQuoteAutorLabel()
createQuoteLabel()
}
// MARK: Views creation
private func createSelf() {
self+>.color(.a3_8_9D)
}
private func createSkipButton() {
addSubview(skipButton)
skipButton+>
.x(self|*.mX - hSpace, .right).y(safeAreaInsets.top*)
.text(router.skipButtonText)
.color(.c13, .content)
.sizeToFit()
.addAction(router.skipButtonAction)
let atr: [NSAttributedString.Key: Any] = [.underlineStyle: NSUnderlineStyle.single.rawValue, .font: UIFont.boby as Any]
let str = NSMutableAttributedString(string: router.skipButtonText,
attributes: atr)
skipButton.setAttributedTitle(str, for: .normal)
}
private func createTitleLabel() {
addSubview(titleLabel)
titleLabel+>
.x(self|*.cX, .center).y(skipButton|*.mY + vSpace)
.width(maxWidth)
.lines(0)
.aligment(.center)
.font(.largeTitle)
.text(router.titleText)
.color(.c9ED | .c8, .content)
.sizeToFit()
}
private func createButtonsStack() {
addSubview(buttonsStack)
buttonsStack+>
.x(hSpace).y(titleLabel|*.mY + vSpace)
.width(self|*.w - hSpace * 2*).height(dayButtonSize)
buttonsStack.spacing = 0
buttonsStack.distribution = .equalSpacing
buttonsStack.alignment = .center
}
private func createDayButtons() {
for model in router.buttonModels {
let button = createButton(model)
buttons.append(button)
buttonsStack.addArrangedSubview(button)
}
buttonsStack.sizeToFit()
}
private func createButton(_ model: DayButtonModel) -> UIButton {
let button = UIButton()
button+>
.width(dayButtonSize).height(dayButtonSize)
.cornerRadius(dayButtonSize / 2*)
.text(model.$text)
.font(.title3)
.template(model.$isSelected.switcher([
true: .custom { [weak self] button in
guard let self = self else { return }
button+>
.color(self.router.primaryColor, .background)
.color(.c8, .content)
},
false: .custom({ [weak self] button in
guard let self = self else { return }
button+>
.color(self.router.secondaryColor, .background)
.color(self.router.primaryColor, .content)
})
]))
.addAction(model.action)
NSLayoutConstraint.activate([
button.widthAnchor.constraint(equalToConstant: dayButtonSize.getValue()),
button.heightAnchor.constraint(equalToConstant: dayButtonSize.getValue())])
return button
}
private func createDatePicker() {
addSubview(datePicker)
datePicker+>
.width(maxWidth).height(40 % self|*.h)
.x(self|*.cX, .center).y(buttonsStack|*.mY + vSpace)
.color(router.primaryColor, .content)
if #available(iOS 13.4, *) { datePicker.preferredDatePickerStyle = .wheels }
datePicker.datePickerMode = .time
datePicker.setValue(router.primaryColor, forKey: "textColor")
datePicker.addTarget(self, action: #selector(timeDidSelected), for: .valueChanged)
}
private func createPlanButton() {
addSubview(planButton)
planButton+>
.width(maxWidth).height(planButtonHeight)
.x(self|*.cX, .center).y(self|*.mY - vSpace, .down)
.color(router.primaryColor, .background)
.color(.white, .content)
.text(router.planbuttonText)
.cornerRadius(planButtonHeight / 2*)
.font(.title3)
.addAction(router.planButtonAction)
}
private func createQuoteAutorLabel() {
addSubview(quoteAutorLabel)
quoteAutorLabel+>
.x(self|*.cX, .center).y(planButton|*.y - vSpace * 2*, .down)
.text(router.quoteAutorText)
.font(.caption)
.color(.c9ED | .c8, .content)
.sizeToFit()
}
private func createQuoteLabel() {
addSubview(quoteLabel)
quoteLabel+>
.x(self|*.cX, .center).y(quoteAutorLabel|*.y - (1 % self|*.w), .down)
.text(router.quoteText)
.font(.title5)
.color(.c9ED | .c8, .content)
.sizeToFit()
}
@objc func timeDidSelected() {
router.selectedTime = datePicker.date
}
}
|
import UIKit
/// :nodoc:
public class QuizCreateQuestionTableCell: UITableViewCell {
private let questionLabel: UILabel = {
return UILabel.uiLabel(0, .byWordWrapping, "", .left, .black, .systemFont(ofSize: 15), true, false)
}()
private let answerLabel: UILabel = {
return UILabel.uiLabel(0, .byWordWrapping, "", .left, .black, .systemFont(ofSize: 15), true, false)
}()
private let pointLabel: UILabel = {
return UILabel.uiLabel(1, .byWordWrapping, "", .left, .black, .systemFont(ofSize: 15), true, false)
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .gray
self.accessoryType = .disclosureIndicator
contentView.addSubview(questionLabel)
questionLabel.setAnchors(top: contentView.topAnchor, bottom: nil, leading: contentView.leadingAnchor, trailing: contentView.trailingAnchor, spacing: .init(top: 10, left: 10, bottom: 0, right: -10))
contentView.addSubview(answerLabel)
answerLabel.setAnchors(top: questionLabel.bottomAnchor, bottom: nil, leading: contentView.leadingAnchor, trailing: contentView.trailingAnchor, spacing: .init(top: 10, left: 10, bottom: 0, right: -10))
contentView.addSubview(pointLabel)
pointLabel.setAnchors(top: answerLabel.bottomAnchor, bottom: contentView.bottomAnchor, leading: contentView.leadingAnchor, trailing: contentView.trailingAnchor, spacing: .init(top: 10, left: 10, bottom: -10, right: -10))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(_ question: Question) {
questionLabel.text = "Q: \(question.question)"
answerLabel.text = "A: \(question.answer)"
if let point = question.point {
pointLabel.text = "Total Point: \(point)"
} else {
pointLabel.text = ""
}
}
}
|
//
// Url.swift
// GoodNews
//
// Created by Steve JobsOne on 12/21/20.
//
import Foundation
extension URL {
static let url = URL(string: "https://newsapi.org/v2/top-headlines?country=us&apiKey=6e3d8d6df62346ef8408b57eb3f52e87")
}
|
//
// StarRatingView.swift
// OpenLink
//
// Created by William Welbes on 5/1/17.
// Copyright © 2017 Milwaukee Tool. All rights reserved.
//
import UIKit
protocol StarRatingViewDelegate: class {
func starRatingView(_ startRatingView: StarRatingView, didSetRatingNumber: Int)
}
class StarRatingView: UIView {
weak var delegate: StarRatingViewDelegate?
var stackView: UIStackView!
var starImageViews: [UIImageView] = []
let numberOfStars: Int = 5
var starFullImage: UIImage!
var starEmptyImage: UIImage!
var currentStarRating: Int = 0
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initViews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initViews()
}
func initViews() {
isUserInteractionEnabled = true
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.clear
starFullImage = UIImage(named: "star-fill")?.withRenderingMode(.alwaysTemplate)
starEmptyImage = UIImage(named: "star-hollow")?.withRenderingMode(.alwaysTemplate)
for _ in 0..<numberOfStars {
let starImageView = UIImageView(image: starEmptyImage, highlightedImage: starFullImage)
starImageView.translatesAutoresizingMaskIntoConstraints = false
starImageView.isUserInteractionEnabled = true
starImageView.contentMode = .scaleAspectFit
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapStar(sender:)))
starImageView.addGestureRecognizer(tapGestureRecognizer)
starImageView.addConstraint(NSLayoutConstraint(item: starImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 48.0))
starImageView.addConstraint(NSLayoutConstraint(item: starImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 46.0))
starImageViews.append(starImageView)
}
stackView = UIStackView(arrangedSubviews: starImageViews)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.spacing = 5.0
stackView.alignment = .center
stackView.distribution = .fillEqually
addSubview(stackView)
let views: [String: Any] = ["stackView": stackView]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[stackView]-0-|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[stackView]-0-|", options: [], metrics: nil, views: views))
}
@objc func didTapStar(sender: UITapGestureRecognizer) {
guard let starImageView = sender.view as? UIImageView,
let index = starImageViews.index(of: starImageView) else {
return
}
currentStarRating = index + 1
delegate?.starRatingView(self, didSetRatingNumber: currentStarRating)
updateForCurrentStarRating()
}
func updateForCurrentStarRating() {
for (index, starImageView) in starImageViews.enumerated() {
let image = index + 1 <= currentStarRating ? starFullImage : starEmptyImage
starImageView.image = image
}
}
}
extension StarRatingView: DebugViewInstantiable {
static func initView(with useCase: DebugUseCasable?) -> UIView {
let view = StarRatingView(frame: CGRect(x: 0, y: 0, width: 300, height: 32))
view.currentStarRating = 2
return view
}
}
|
//
// BodyStripper.swift
// Part of Sitrep, a tool for analyzing Swift projects.
//
// Copyright (c) 2020 Hacking with Swift
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE for license information
//
import Foundation
import SwiftSyntax
/// Scans source code to remove comments and most whitespace.
class BodyStripper: SyntaxRewriter {
/// This class only scans tokens, and this method strips content from both leading and trailing trivia.
override func visit(_ token: TokenSyntax) -> TokenSyntax {
let leading = clean(trivia: token.leadingTrivia)
let trailing = clean(trivia: token.trailingTrivia)
return TokenSyntax(token.withLeadingTrivia(leading).withTrailingTrivia(trailing)) ?? token
}
/// This removes all comments plus tab and spaces, and also collapses line breaks
func clean(trivia: Trivia) -> Trivia {
var cleanedTrivia = [TriviaPiece]()
for piece in trivia {
switch piece {
case .lineComment, .blockComment, .docLineComment, .docBlockComment:
continue
case .spaces:
continue
case .tabs:
continue
case .newlines:
cleanedTrivia.append(TriviaPiece.newlines(1))
default:
cleanedTrivia.append(piece)
}
}
return Trivia(pieces: cleanedTrivia)
}
}
|
//
// ContactDetailViewController.swift
// AC-iOS-U3W1HW-Parsing
//
// Created by C4Q on 11/21/17.
// Copyright © 2017 C4Q . All rights reserved.
//
import UIKit
class ContactDetailViewController: UIViewController {
var contacts: Person?
override func viewDidLoad() {
super.viewDidLoad()
//Example:
//guard let contact = contact else { return }
// contactImageView.image = #imageLiteral(resourceName: "profileImage")
// contactNameLabel.text = contact.name.first.capitalized + " " + contact.name.last.capitalized
// contactEmailLabel.text = contact.email
// contactLocationLabel.text = contact.location.city.capitalized
// }
}
}
|
//
// CollectionViewBase.swift
// WatNi
//
// Created by 홍창남 on 2020/02/16.
// Copyright © 2020 hcn1519. All rights reserved.
//
import Foundation
import UIKit
protocol CollectionViewModelBase {
associatedtype BaseModel
associatedtype ModelCollection: Swift.Collection
associatedtype SectionType: Hashable
/// ViewModel의 Model Collection
var models: ModelCollection { get set }
}
/// CollectionViewModel의 CellModel 정의
protocol HasCellModel where Self: CollectionViewModelBase {
associatedtype CellModel
associatedtype CellModelCollection: Swift.Collection where CellModelCollection.Element == CellModel
/// Cell의 매핑 정보(섹션별 Cell 정보)
var cellModels: CellModelCollection { get set }
/// 바인딩된 CellModel
///
/// - Parameter indexPath: 타겟 indexPath
/// - Returns: CellModel
func cellModel(indexPath: IndexPath) -> CollectionViewCellModel?
}
/// CollectionViewModel의 ReusableViewModel 정의
protocol HasReusableViewModel where Self: CollectionViewModelBase {
associatedtype ReusableViewModel
associatedtype ReusableViewModelCollection: Swift.Collection where ReusableViewModelCollection.Element == ReusableViewModel
/// 섹션별 Header, Footer 정보
var reusableViewModels: ReusableViewModelCollection { get set }
/// 바인딩된 ReusableViewModel
///
/// - Parameter sectionType: 타겟 sectionType
/// - Returns: ReusableViewModel
func reusableViewModel(sectionType: SectionType) -> CollectionViewReusableViewModel?
}
/// CollectionView 공통 CellModel
protocol CollectionViewCellModel {
/// viewModel에 바인딩되는 cell의 type
var cellType: BindableCollectionViewCell.Type { get }
}
/// CollectionView 공통 ReusableViewModel
protocol CollectionViewReusableViewModel {
/// viewModel에 바인딩되는 reusableView의 type
func viewType(kind: String) -> BindableCollectionReusableView.Type?
}
/// CollectionViewCell viewModel 정의 및 viewModel 통한 cell 업데이트 정의
protocol BindableCollectionViewCell: UICollectionViewCell {
var viewModel: CollectionViewCellModel { get set }
func configureCell(viewModel: CollectionViewCellModel)
}
/// CollectionViewReusableView의 viewModel 정의 및 viewModel 통한 ReusableView 업데이트 정의
protocol BindableCollectionReusableView: UICollectionReusableView {
var viewModel: CollectionViewReusableViewModel { get set }
func configureView(viewModel: CollectionViewReusableViewModel)
}
|
//
// SWBAreaTableViewCell.swift
// SweepBright
//
// Created by Kaio Henrique on 1/19/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import UIKit
protocol SWBRoomServiceDelegate {
var service: SWBRoomServiceProtocol {get }
var serviceProperty: SWBProperty { get}
}
class SWBAreaTableViewCell: UITableViewCell {
@IBOutlet weak var areaTextField: UITextField!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var areaLabel: UILabel!
var cellDelegate: SWBRoomServiceDelegate!
var room: SWBRoom! {
didSet {
self.descriptionLabel?.text = "\(room.structure.rawValue.capitalizedString)"
if let areaLabel = self.areaLabel {
areaLabel.text = "\(room.area) sqft"
}
if let areaTextField = self.areaTextField {
areaTextField.text = "\(room.area)"
areaTextField.rac_signalForControlEvents(.EditingDidEnd).subscribeNext({
_ in
self.cellDelegate?.service.setValueForProperty( self.cellDelegate!.serviceProperty.id, op:"replace", path: "/structure/rooms/\(self.room.id)/size", value: self.areaTextField.text!, completionHandler: {
_ in
})
})
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.areaTextField.delegate = self
self.areaTextField.rac_signalForControlEvents(.EditingDidBegin).filter({_ in self.areaTextField.text == "0.0"}).subscribeNext({
_ in
self.areaTextField.text = ""
})
}
}
extension SWBAreaTableViewCell: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
//
// HamburgerMenuController.swift
// AarambhPlus
//
// Created by Santosh Kumar Sahoo on 9/6/18.
// Copyright © 2018 Santosh Dev. All rights reserved.
//
import UIKit
enum HamburgerCellType: Int {
case profile = 0, items
}
class HamburgerMenuController: UIViewController {
@IBOutlet weak private var tableView: UITableView!
var items = ["Dashboard", "Music", "Originals", "Jatra", "Movies", "Log In"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 50
tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !items.contains("Log Out") {
if UserManager.shared.isLoggedIn {
items.remove(at: 5)
items.append("My Favorites")
items.insert("My Profile", at:0)
items.append("Reset Password")
items.append("Log Out")
} else {
for (index, item) in items.enumerated() {
if item == "Log Out" {
items.remove(at: index)
return
}
}
}
}
}
class func controller() -> HamburgerMenuController {
let controller = UIStoryboard(name: "HamburgerMenu", bundle: nil).instantiateViewController(withIdentifier: "\(HamburgerMenuController.self)") as! HamburgerMenuController
controller.modalPresentationStyle = .custom
controller.transitioningDelegate = controller
return controller
}
@IBAction func dismissOnTap(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
extension HamburgerMenuController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 2//HamburgerCellType.allCases.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let type = HamburgerCellType(rawValue: section) {
switch type {
case .profile:
return 1
case .items:
return items.count
}
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let type = HamburgerCellType(rawValue: indexPath.section) {
switch type {
case .profile:
let cell = tableView.dequeueReusableCell(withIdentifier: "HamburgerProfileCell", for: indexPath) as! HamburgerProfileCell
cell.updateUI()
return cell
case .items:
let cell = tableView.dequeueReusableCell(withIdentifier: "HamburgerItemCell", for: indexPath) as! HamburgerItemCell
cell.updateUI(title: items[indexPath.row])
cell.updateUI(imgge: UIImage(named: items[indexPath.row])) //for Menu Image
return cell
}
}
return UITableViewCell()
}
}
extension HamburgerMenuController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == HamburgerCellType.profile.rawValue {
if UserManager.shared.isLoggedIn {
self.performSelector(onMainThread: #selector(pushProfileScreen), with: nil, waitUntilDone: false)
} else {
self.performSelector(onMainThread: #selector(pushLoginScreen), with: nil, waitUntilDone: false)
}
} else {
self.performSelector(onMainThread: #selector(handleHamburgerTap), with: items[indexPath.row], waitUntilDone: false)
}
}
}
private extension HamburgerMenuController {
@objc func pushLoginScreen() {
dismiss(animated: true) {
UIViewController.rootViewController?.navigate(to: LoginController.self, of: .user, presentationType: .push, prepareForNavigation: nil)
}
}
@objc func pushProfileScreen() {
dismiss(animated: true) {
UIViewController.rootViewController?.navigate(to: ProfileDetailViewController.self, of: .user, presentationType: .push, prepareForNavigation: nil)
}
}
@objc func handleHamburgerTap(_ type: String) {
switch type {
case "Dashboard":
dismiss(animated: true) { [weak self] in
self?.switchToTab(.home)
}
case "Music":
dismiss(animated: true) { [weak self] in
self?.switchToTab(.music)
}
case "Originals":
dismiss(animated: true) { [weak self] in
self?.switchToTab(.originals)
}
case "Jatra":
dismiss(animated: true) { [weak self] in
self?.switchToTab(.jatra)
}
case "Movies":
dismiss(animated: true) { [weak self] in
self?.switchToTab(.movies)
}
case "My Profile":
pushProfileScreen()
case "Log In":
pushLoginScreen()
case "Log Out":
logOut()
case "My Favorites":
dismiss(animated: true) { [weak self] in
self?.showFavoriteList()
}
case "Reset Password":
dismiss(animated: true) { [weak self] in
self?.changePassword()
}
default:
break
}
}
func logOut() {
CustomLoader.addLoaderOn(self.view, gradient: false)
UserManager.shared.logoutUser(handler: {[weak self] (success) in
CustomLoader.removeLoaderFrom(self?.view)
if success {
self?.dismiss(animated: true, completion: nil)
} else {
self?.showAlertView("Error!", message: "Unexpected error occure.")
}
})
}
func showFavoriteList() {
UIViewController.rootViewController?.navigate(to: VideoListController.self, of: .home, presentationType: .push, prepareForNavigation: nil)
}
func changePassword() {
UIViewController.rootViewController?.navigate(to: ResetPasswordViewController.self, of: .home, presentationType: .push, prepareForNavigation: nil)
}
}
extension HamburgerMenuController: UIViewControllerTransitioningDelegate {
func animationController(forPresented _: UIViewController, presenting _: UIViewController, source _: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animator = SidePanelCustomTransitionAnimator()
animator.duration = 0.4
return animator
}
func animationController(forDismissed _: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animator = SidePanelCustomTransitionAnimator()
animator.duration = 0.4
return animator
}
}
|
//
// MessageLoading.swift
// Lenna
//
// Created by MacBook Air on 3/9/19.
// Copyright © 2019 sdtech. All rights reserved.
//
import UIKit
import SDWebImage
import Lottie
class MessageLoading: UITableViewCell {
let messageLabel = UILabel()
let bubleBackgroundView = UIImageView()
let loadingChat = SDAnimatedImageView()
let bubbleImage = UIImage(named: "bubble_received2")?
.resizableImage(withCapInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5),
resizingMode: .stretch)
let bubbleImage_dark = UIImage(named: "bubble_received_dark")?
.resizableImage(withCapInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5),
resizingMode: .stretch)
let bubbleImage2 = UIImage(named: "loading")
let loadingImage = UIImage.animatedImageNamed("loading", duration: 1.0)
var leadingConstraint: NSLayoutConstraint!
var trailingConstraint: NSLayoutConstraint!
var dotLoadingIndicator: UIDotLoadingIndicator!
let ss = SDAnimatedImageView()
let animatedImage = SDAnimatedImage(named: "bubble_received2.png")
// lottie
let animationView = AnimationView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let loading_dot = Animation.named("dot_loading")
animationView.animation = loading_dot
animationView.frame = CGRect(x: 10, y: 25, width: 100, height: 30)
print("MessageLoading","" )
backgroundColor = .clear
bubleBackgroundView.backgroundColor = .yellow
bubleBackgroundView.layer.cornerRadius = 12
bubleBackgroundView.translatesAutoresizingMaskIntoConstraints = false
loadingChat.translatesAutoresizingMaskIntoConstraints = false
bubleBackgroundView.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
addSubview(bubleBackgroundView)
addSubview(animationView)
addSubview(loadingChat)
//lets set up some constraints for our label
let constraints = [
loadingChat.topAnchor.constraint(equalTo: topAnchor, constant: 32),
loadingChat.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -32),
loadingChat.widthAnchor.constraint(lessThanOrEqualToConstant: 220),
bubleBackgroundView.topAnchor.constraint(equalTo: loadingChat.topAnchor, constant: -16),
bubleBackgroundView.leadingAnchor.constraint(equalTo: loadingChat.leadingAnchor, constant: -16),
bubleBackgroundView.bottomAnchor.constraint(equalTo: loadingChat.bottomAnchor, constant: 16),
bubleBackgroundView.trailingAnchor.constraint(equalTo: loadingChat.trailingAnchor, constant: 16),
]
NSLayoutConstraint.activate(constraints)
//margin to parent
leadingConstraint = loadingChat.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 32)
leadingConstraint.isActive = false
trailingConstraint = loadingChat.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -32)
trailingConstraint.isActive = true
animationView.loopMode = .loop
animationView.play()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// ViewController.swift
// Cred.Com
//
// Created by IMAC-0025 on 09/01/20.
// Copyright © 2020 IMAC-0025. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//Declare property for table view
@IBOutlet weak var creditCardsListTableView: UITableView!
//View Model for Card data
var cardModel = CardsViewModel()
//View Controller Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
//initial setup
initialiseViewControllerStuff()
// Do any additional setup after loading the view.
}
//MART:- Private Method
func initialiseViewControllerStuff() {
// Navigation Set up
setupNavBar()
//Hey TableView i will help you with data
self.creditCardsListTableView.dataSource = self
self.creditCardsListTableView.delegate = self
//Relaod and animate for Brownie once
self.creditCardsListTableView.reloadData { [weak self] in
//Get first Cell
let oneTimeAnimationCell = self?.creditCardsListTableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! CustomCardsTableViewCell
UIView.animate(withDuration: 0.6, animations: {
oneTimeAnimationCell.cardImageView.transform = CGAffineTransform(translationX: -oneTimeAnimationCell.cardImageView.frame.width/2 , y: 0)
oneTimeAnimationCell.cardOptionsContentView.transform = CGAffineTransform(translationX: oneTimeAnimationCell.cardOptionsContentView.frame.width/2 , y: 0)
}) { (true) in
UIView.animate(withDuration: 0.6, animations: {
oneTimeAnimationCell.cardImageView.transform = CGAffineTransform(translationX: oneTimeAnimationCell.cardImageView.frame.width/2 , y: 0)
oneTimeAnimationCell.cardOptionsContentView.transform = CGAffineTransform(translationX: -oneTimeAnimationCell.cardOptionsContentView.frame.width/2 , y: 0)
}) { (true) in
self?.moveToOriginalPosition(cell: oneTimeAnimationCell)
}
}
}
}
func setupNavBar() {
//Screen Title
self.title = "Cards"
self.navigationController?.navigationBar.prefersLargeTitles = true
//Add New Card button
let rightNavButtonForAddNewCard = UIButton(type: .custom)
rightNavButtonForAddNewCard.setTitle("+Add New", for: .normal)
rightNavButtonForAddNewCard.setTitleColor(getAppTintColor(), for: .normal)
rightNavButtonForAddNewCard.addTarget(self, action: #selector(rightButtonTapped), for: .touchUpInside)
rightNavButtonForAddNewCard.backgroundColor = #colorLiteral(red: 0.1090913936, green: 0.1288402081, blue: 0.1620890796, alpha: 1)
rightNavButtonForAddNewCard.layer.cornerRadius = 10
rightNavButtonForAddNewCard.layer.masksToBounds = true
rightNavButtonForAddNewCard.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
navigationController?.navigationBar.addSubview(rightNavButtonForAddNewCard)
rightNavButtonForAddNewCard.frame = CGRect(x: self.view.frame.width, y: 0, width: 100, height: 40)
let targetView = self.navigationController?.navigationBar
let trailingContraint = NSLayoutConstraint(item: rightNavButtonForAddNewCard, attribute:
.trailingMargin, relatedBy: .equal, toItem: targetView,
attribute: .trailingMargin, multiplier: 1.0, constant: -30)
let bottomConstraint = NSLayoutConstraint(item: rightNavButtonForAddNewCard, attribute: .bottom, relatedBy: .equal,
toItem: targetView, attribute: .bottom, multiplier: 1.0, constant: -6)
rightNavButtonForAddNewCard.widthAnchor.constraint(equalToConstant: 100).isActive = true
rightNavButtonForAddNewCard.heightAnchor.constraint(equalToConstant: 40).isActive = true
rightNavButtonForAddNewCard.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([trailingContraint, bottomConstraint])
}
@objc func rightButtonTapped(button: UIButton) {
alert(title: "Alert!!", message: "Adding New Card")
}
@IBAction func payNowCardButtonTargetAction(_ sender: UIButton ) {
alert(title: "Alert!", message: "Paying at index: \(sender.tag)")
}
@IBAction func viewCardDetailsButtonTargetAction(_ sender: UIButton ) {
alert(title: "Alert!", message: "Viewing card details at index: \(sender.tag)")
}
}
|
//
// SendMessageRoot.swift
// BeeHive
//
// Created by HyperDesign-Gehad on 11/6/18.
// Copyright © 2018 HyperDesign-Gehad. All rights reserved.
//
import Foundation
class SendMessageRoot : Codable
{
var user_message :Message?
var message : String?
}
|
//
// LocalStorage.swift
// owlympics
//
// Created by Martin Zhou on 9/9/15.
// Copyright (c) 2015 Martin Zhou. All rights reserved.
//
import Foundation
func storeToLocal(exercisefile:Exercise) {
// Initialize data storage
// Create user default delegate
let defaults = NSUserDefaults.standardUserDefaults()
if let dictOfExercise = defaults.valueForKey(defaultsKeys.keyDict) as? NSData {
var allExercise = NSKeyedUnarchiver.unarchiveObjectWithData(dictOfExercise) as! [Exercise]
allExercise.append(exercisefile)
// println("there is data in local storage")
// println(allExercise)
let exerciseData = NSKeyedArchiver.archivedDataWithRootObject(allExercise)
defaults.setValue(exerciseData, forKey: defaultsKeys.keyDict)
} else {
var allExercise = [Exercise]()
allExercise.append(exercisefile)
print("there is not data in local storage")
// println(allExercise)
let exerciseData = NSKeyedArchiver.archivedDataWithRootObject(allExercise)
defaults.setValue(exerciseData, forKey: defaultsKeys.keyDict)
}
// println("successfully stored data")
}
func loadFromLocal() -> [Exercise] {
let defaults = NSUserDefaults.standardUserDefaults()
var allExercise: [Exercise] = []
if let dictOfExercise = defaults.valueForKey(defaultsKeys.keyDict) as? NSData {
allExercise = NSKeyedUnarchiver.unarchiveObjectWithData(dictOfExercise) as! [Exercise]
// println("Successfully Loaded Data")
// println(allExercise)
}
// println(allExercise)
return allExercise
}
func durationOfPastSevenDays() -> [Int] {
var durationList = [0, 0, 0, 0, 0, 0, 0]
// Load local data
let exerciseList = loadFromLocal()
// Update the durationList according to localData
for eachExercise:Exercise in exerciseList {
// Get the two times
let exerciseTime = eachExercise.arrivaltime
let currentTime = NSDate()
// Calculate the days between the two times
let daysBetween = calculateDaysBetween(exerciseTime, currentTime)
// Add the duration to that day if it's within six days
if daysBetween < 7 {
let dur:Int! = eachExercise.duration.toInt()
durationList[durationList.count - 1 - daysBetween] += dur
}
}
return durationList
} |
//
// ViewController.swift
// NoteCoreData
//
// Created by Raksmey on 12/20/17.
// Copyright © 2017 admin. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var actionToolbar: UIToolbar!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var appDelegate = UIApplication.shared.delegate as! AppDelegate
var note:[Notes]?
@IBOutlet weak var noteCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Notes"
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
longGesture.minimumPressDuration = 0.5
longGesture.delaysTouchesBegan = false
longGesture.delegate = self
noteCollectionView.addGestureRecognizer(longGesture)
self.note?.reverse()
noteCollectionView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
self.getNoteData()
DispatchQueue.main.async {
self.noteCollectionView.reloadData()
}
}
@IBAction func actionToolbar(_ sender: Any) {
let detail = storyboard?.instantiateViewController(withIdentifier: "detailStoryBoard")
self.navigationController?.pushViewController(detail!, animated: true)
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if note != nil {
return note!.count
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "titleCell", for: indexPath) as! NoteCollectionViewCell
let bcolor : UIColor = UIColor( red: 0.2, green: 0.2, blue:0.2, alpha: 0.3 )
cell.layer.borderColor = UIColor.gray.cgColor
cell.layer.borderWidth = 0.5
cell.layer.cornerRadius = 1
cell.backgroundColor = UIColor.white
// print("color")
cell.descriptionCell.text = "\(note![indexPath.row].desc!)"
cell.titleCell.text = "\(note![indexPath.row].title!)"
// cell.descriptionCell.text = arr[indexPath.row]
cell.bounds.size = CGSize(width: (view.bounds.width / 2) , height: (view.bounds.width / 2 ) - 5)
return cell
}
func getNoteData(){
self.note = try? context.fetch(Notes.fetchRequest())
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let detail = storyboard?.instantiateViewController(withIdentifier: "detailStoryBoard") as! DetailNoteViewController
print(note![indexPath.row].desc!)
print(note![indexPath.row].title!)
detail.desc = note![indexPath.row].desc!
detail.titles = note![indexPath.row].title!
detail.status = "edit"
detail.index = indexPath.row
self.navigationController?.pushViewController(detail, animated: true)
}
@objc func longTap(_ sender: UIGestureRecognizer){
print("Long tap")
if sender.state == .ended {
print("UIGestureRecognizerStateEnded")
//Do Whatever You want on End of Gesture
}
else if sender.state == .began {
print("UIGestureRecognizerStateBegan.")
//Do Whatever You want on Began of Gesture
let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler:
{
(alert: UIAlertAction!) -> Void in
print("Cancelled")
})
let p = sender.location(in: self.noteCollectionView)
if let indexPath = self.noteCollectionView.indexPathForItem(at: p){
print("index cell \(indexPath.row)")
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler:
{
(alert: UIAlertAction!) -> Void in
print("index \(indexPath.row)")
let note = self.note?[indexPath.row]
self.context.delete(note!)
self.appDelegate.saveContext()
self.getNoteData()
self.noteCollectionView.reloadData()
print("delete cell by \(indexPath.row)")
})
optionMenu.addAction(deleteAction)
}
optionMenu.addAction(cancelAction)
self.present(optionMenu, animated: true, completion: nil)
}
}
}
|
//
// IntermineAPIClient.swift
// intermine-ios
//
// Created by Nadia on 4/25/17.
// Copyright © 2017 Nadia. All rights reserved.
//
import Foundation
import Alamofire
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() -> Bool {
if let reachable = NetworkReachabilityManager()?.isReachable {
return reachable
} else {
return false
}
}
}
class Counter: NSObject {
private var currentMineCount = 0
override init() {
super.init()
self.currentMineCount = 0
}
func incrementMineCount() {
self.currentMineCount += 1
}
func resetMineCount() {
self.currentMineCount = 0
}
func getCurrentMineCount() -> Int {
return self.currentMineCount
}
}
class IntermineAPIClient: NSObject {
static let jsonParams = ["format": "json"]
static let manager = Alamofire.SessionManager.default
static let counter = Counter()
static let useDebugServer = false
static var listsRequest: Request?
static var templatesRequest: Request?
// MARK: Private methods
private class func sendJSONRequest(url: String, method: HTTPMethod, params: [String: String]?, timeOutInterval: Double?, shouldUseAuth: Bool, completion: @escaping (_ result: [String: AnyObject]?, _ error: NetworkErrorType?) -> ()) -> Request {
var interval = General.timeoutIntervalForRequest
if !(timeOutInterval == nil) {
interval = timeOutInterval!
}
manager.session.configuration.timeoutIntervalForRequest = interval
var paramsToUse = params
if shouldUseAuth {
paramsToUse = IntermineAPIClient.updateParamsWithAuth(params: params)
}
return manager.request(url, method: method, parameters: paramsToUse)
.responseJSON {
response in
switch (response.result) {
case .success:
if let JSON = response.result.value as? [String: AnyObject] {
completion(JSON, nil)
} else {
completion(nil, nil)
}
break
case .failure(let error):
let errorType = NetworkErrorHandler.processError(error: error)
completion(nil, errorType)
print("\n\nRequest failed with error:\n \(error)")
break
}
}
}
private class func sendStringRequest(url: String, method: HTTPMethod, params: [String: String]?, shouldUseAuth: Bool, completion: @escaping (_ result: String?, _ error: NetworkErrorType?) -> ()) {
manager.session.configuration.timeoutIntervalForRequest = General.timeoutIntervalForRequest
var paramsToUse = params
if shouldUseAuth {
paramsToUse = IntermineAPIClient.updateParamsWithAuth(params: params)
}
manager.request(url, method: method, parameters: paramsToUse)
.responseString {
response in
switch (response.result) {
case .success:
completion(response.value, nil)
break
case .failure(let error):
let errorType = NetworkErrorHandler.processError(error: error)
completion(nil, errorType)
print("\n\nRequest failed with error:\n \(error)")
break
}
}
}
private class func updateParamsWithAuth(params: [String: String]?) -> [String: String]? {
var mineName = ""
if let selectedMine = DefaultsManager.fetchFromDefaults(key: DefaultsKeys.selectedMine) {
mineName = selectedMine
} else {
mineName = General.defaultMine
}
if let mine = CacheDataStore.sharedCacheDataStore.findMineByName(name: mineName), let mineUrl = mine.url {
if let token = DefaultsManager.fetchFromDefaults(key: mineUrl) {
var updatedParams = params
updatedParams?["token"] = token
return updatedParams
}
}
return params
}
private class func fetchIntermineVersion(mineUrl: String, completion: @escaping (_ result: String?, _ error: NetworkErrorType?) -> ()) {
// TODO: - remove method if not needed
let url = mineUrl + Endpoints.intermineVersion
var _ = IntermineAPIClient.sendJSONRequest(url: url, method: .get, params: jsonParams, timeOutInterval: nil, shouldUseAuth: false) { (result, error) in
if let result = result {
if let versionString = result["version"] {
completion("\(versionString)", nil)
}
} else {
completion(nil, error)
}
}
}
private class func fetchReleaseId(mineUrl: String, completion: @escaping (_ result: String?, _ error: NetworkErrorType?) -> ()) {
let url = mineUrl + Endpoints.modelReleased
var _ = IntermineAPIClient.sendJSONRequest(url: url, method: .get, params: jsonParams, timeOutInterval: nil, shouldUseAuth: false) { (result, error) in
if let result = result {
if let releaseString = result["version"] {
completion("\(releaseString)", nil)
} else {
completion(nil, error)
}
} else {
completion(nil, error)
}
}
}
// MARK: Public methods
class func fetchOrganismsForMine(mineUrl: String, completion: @escaping (_ result: [String?], _ error: NetworkErrorType?) -> ()) {
let query = "<query model=\"genomic\" view=\"Organism.shortName\" sortOrder=\"Organism.shortName ASC\"></query>"
let params = ["query": query, "format": "json"]
let urlString = mineUrl + Endpoints.singleList
_ = IntermineAPIClient.sendJSONRequest(url: urlString, method: .get, params: params, timeOutInterval: General.timeoutIntervalForRequest, shouldUseAuth: false) { (result, error) in
var organisms: [String] = []
if let results = result?["results"] as? [[Any]] {
for organism in results {
if organism.count > 0 {
if let o = organism[0] as? String {
organisms.append(o)
}
}
}
}
completion(organisms, error)
}
}
class func cancelAllRequests() {
manager.session.getAllTasks { tasks in
tasks.forEach { $0.cancel() }
}
}
class func cancelListsRequest() {
IntermineAPIClient.listsRequest?.cancel()
}
class func cancelTemplatesRequest() {
IntermineAPIClient.templatesRequest?.cancel()
}
class func makeSearchInMine(mineUrl: String, params: [String: String], completion: @escaping (_ result: SearchResult?, _ facets: FacetList?, _ error: NetworkErrorType?) -> ()) {
let url = mineUrl + Endpoints.search
var _ = IntermineAPIClient.sendJSONRequest(url: url, method: .get, params: params, timeOutInterval: nil, shouldUseAuth: false) { (res, error) in
if let res = res {
var facetList: FacetList?
if let facets = res["facets"] as? [String: AnyObject] {
var categoryFacet: SearchFacet?
if let category = facets["Category"] as? [String: Int] {
categoryFacet = SearchFacet(withType: "Category", contents: category)
}
if let mine = CacheDataStore.sharedCacheDataStore.findMineByUrl(url: mineUrl), let mineName = mine.name, let categoryFacet = categoryFacet {
facetList = FacetList(withMineName: mineName, facet: categoryFacet)
}
}
if let result = res["results"] as? [[String: AnyObject]] {
if result.count == 0 {
completion(nil, nil, nil)
return
}
for r in result {
if let mine = CacheDataStore.sharedCacheDataStore.findMineByUrl(url: mineUrl) {
if let mineName = mine.name {
let resObj = SearchResult(withType: r["type"] as? String, fields: r["fields"] as? [String: AnyObject], mineName: mineName, id: r["id"] as? Int)
completion(resObj, facetList, nil)
}
}
}
} else {
completion(nil, nil, error)
}
} else {
completion(nil, nil, error)
}
}
}
class func makeSearchOverAllMines(params: [String: String], completion: @escaping (_ result: [SearchResult]?, _ facetList: [FacetList]?, _ error: NetworkErrorType?) -> ()) {
guard let registry = CacheDataStore.sharedCacheDataStore.allRegistry() else {
completion(nil, nil, NetworkErrorType.Unknown)
return
}
AppManager.sharedManager.cachedMineIndex = nil
var results: [SearchResult] = []
var facetLists: [FacetList] = []
let totalMineCount = CacheDataStore.sharedCacheDataStore.registrySize()
for mine in registry {
if let mineUrl = mine.url {
IntermineAPIClient.makeSearchInMine(mineUrl: mineUrl, params: params, completion: { (searchResObj, facetList, error) in
IntermineAPIClient.counter.incrementMineCount()
if let resObj = searchResObj {
results.append(resObj)
}
if let facetList = facetList {
facetLists.append(facetList)
}
if IntermineAPIClient.counter.getCurrentMineCount() == totalMineCount {
IntermineAPIClient.counter.resetMineCount()
completion(results, facetLists, nil)
}
})
} else {
completion(nil, nil, NetworkErrorType.Unknown)
}
}
}
class func fetchSingleList(mineUrl: String, queryString: String, completion: @escaping (_ result: [String: AnyObject]?, _ params: [String: String], _ error: NetworkErrorType?) -> ()) {
let url = mineUrl + Endpoints.singleList
let params: [String: String] = ["format": "json", "query": queryString, "start": "0", "size": "15"]
var _ = IntermineAPIClient.sendJSONRequest(url: url, method: .post, params: params, timeOutInterval: nil, shouldUseAuth: true) { (res, error) in
completion(res, params, error)
}
}
class func fetchRegistry(completion: @escaping (_ result: [String: AnyObject]?, _ error: NetworkErrorType?) -> ()) {
if useDebugServer {
// TODO: make changes in debug server
} else {
let url = Endpoints.registryDomain + Endpoints.registryInstances
var _ = IntermineAPIClient.sendJSONRequest(url: url, method: .get, params: nil, timeOutInterval: General.timeoutForRegistryUpdate, shouldUseAuth: false) { (res, error) in
completion(res, error)
}
}
}
class func fetchVersioning(mineUrl: String, completion: @escaping (_ releaseId: String?, _ error: NetworkErrorType?) -> ()) {
// TODO: - check do I need to use version id or release id will change when version id changes?
IntermineAPIClient.fetchReleaseId(mineUrl: mineUrl) { (releaseId, error) in
completion(releaseId, error)
}
}
class func fetchModel(mineUrl: String, completion: @escaping (_ result: String?, _ error: NetworkErrorType?) -> ()) {
let url = mineUrl + Endpoints.modelDescription
IntermineAPIClient.sendStringRequest(url: url, method: .get, params: nil, shouldUseAuth: false) { (xmlString, error) in
completion(xmlString, error)
}
}
class func fetchLists(mineUrl: String, completion: @escaping (_ result: [List]?, _ error: NetworkErrorType?) -> ()) {
let url = mineUrl + Endpoints.lists
IntermineAPIClient.listsRequest = IntermineAPIClient.sendJSONRequest(url: url, method: .get, params: jsonParams, timeOutInterval: nil, shouldUseAuth: true) { (result, error) in
var listObjects: [List] = []
if let result = result {
if let lists = result["lists"] as? [[String: AnyObject]] {
for list in lists {
let listObj = List(withTitle: list["title"] as? String,
info: list["description"] as? String,
size: list["size"] as? Int,
type: list["type"] as? String,
name: list["name"] as? String,
status: list["status"] as? String,
authorized: list["authorized"] as? Bool)
listObjects.append(listObj)
}
completion(listObjects, nil)
}
} else {
completion(nil, error)
}
}
}
class func fetchTemplates(mineUrl: String, completion: @escaping (_ result: TemplatesList?, _ error: NetworkErrorType?) -> ()) {
let url = mineUrl + Endpoints.templates
IntermineAPIClient.templatesRequest = IntermineAPIClient.sendJSONRequest(url: url, method: .get, params: jsonParams, timeOutInterval: nil, shouldUseAuth: true) { (result, error) in
if let result = result {
if let templates = result["templates"] as? [String: AnyObject] {
var templateList: [Template] = []
for (_, template) in templates {
var queryList: [TemplateQuery] = []
if let queries = template["where"] as? [[String: AnyObject]] {
for query in queries {
var valueString = ""
if let value = query["value"] as? String {
valueString = value
}
if let valueArray = query["values"] as? [String] {
valueString = valueArray.joined(separator: ",")
}
let queryObj = TemplateQuery(withValue: valueString, code: query["code"] as? String, op: query["op"] as? String, constraint: query["path"] as? String, editable: query["editable"] as? Bool, extraValue: query["extraValue"] as? String)
if queryObj.getOperation() != nil {
queryList.append(queryObj)
}
}
}
var authd = false
var templateTags: [String] = []
if let tags = template["tags"] as? [String] {
if !tags.contains("im:public") {
authd = true
}
for tag in tags {
if tag.contains("im:aspect") {
let tagElements = tag.components(separatedBy: ":")
if tagElements.count >= 3 {
let tagName = tagElements[2]
templateTags.append(tagName)
}
}
}
}
let templateObj = Template(withTitle: template["title"] as? String, description: template["description"] as? String, queryList: queryList, name: template["name"] as? String, mineUrl: mineUrl, authorized: authd, tags: templateTags)
templateList.append(templateObj)
}
let templatesListObj = TemplatesList(withTemplates: templateList, mine: mineUrl)
completion(templatesListObj, nil)
} else {
completion(nil, error)
}
} else {
completion(nil, error)
}
}
}
class func fetchTemplateResults(mineUrl: String, queryParams: [String: String], completion: @escaping (_ res: [String: AnyObject]?, _ error: NetworkErrorType?) -> ()) {
let url = mineUrl + Endpoints.templateResults
var _ = IntermineAPIClient.sendJSONRequest(url: url, method: .get, params: queryParams, timeOutInterval: nil, shouldUseAuth: true) { (res, error) in
completion(res, error)
}
}
class func getTemplateResultsCount(mineUrl: String, queryParams: [String: String], completion: @escaping (_ res: String?, _ error: NetworkErrorType?) -> ()) {
let url = mineUrl + Endpoints.templateResults
var countParams = queryParams
countParams["format"] = "count"
IntermineAPIClient.sendStringRequest(url: url, method: .get, params: countParams, shouldUseAuth: true) { (res, error) in
completion(res, error)
}
}
class func getToken(mineUrl: String, username: String, password: String, completion: @escaping (_ success: Bool) -> ()) -> () {
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: username, password: password) {
headers[authorizationHeader.key] = authorizationHeader.value
}
Alamofire.request(mineUrl + Endpoints.tokens, headers: headers)
.responseJSON { (response) in
if let JSON = response.result.value as? [String: AnyObject] {
if let successful = JSON["wasSuccessful"] as? Bool {
if successful {
// store token in nsuserdefaults
if let token = JSON["token"] as? String {
DefaultsManager.storeInDefaults(key: mineUrl, value: token)
completion(true)
}
} else {
// create token
self.createToken(mineUrl: mineUrl, username: username, password: password, completion: { (success) in
completion(success)
})
}
} else {
completion(false)
}
} else {
completion(false)
}
}
}
class func createToken(mineUrl: String, username: String, password: String, completion: @escaping (_ success: Bool) -> ()) -> () {
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: username, password: password) {
headers[authorizationHeader.key] = authorizationHeader.value
}
let params = ["type": "perm", "message": "iOS client"]
Alamofire.request(mineUrl + Endpoints.tokens, method: .post, parameters: params, headers: headers)
.responseJSON { (response) in
if let JSON = response.result.value as? [String: AnyObject] {
if let successful = JSON["wasSuccessful"] as? Bool {
if successful {
// store token in nsuserdefaults
if let token = JSON["token"] as? String {
DefaultsManager.storeInDefaults(key: mineUrl, value: token)
completion(true)
}
} else {
// TODO: user is not auth'd, show message
completion(false)
}
} else {
completion(false)
}
} else {
completion(false)
}
}
}
}
|
//
// HourlyModel.swift
// viewtTesting
//
// Created by urjhams on 3/8/18.
// Copyright © 2018 urjhams. All rights reserved.
//
import Foundation
struct HourlyModel {
public let temp: Double
public let icon: String
public let time: Int64
init?(withData data: NSDictionary) {
guard
let temp = data.double(forKeyPath: "temperature"),
let icon = data.string(forKeyPath: "icon"),
let time = data.int64(forKeyPath: "time")
else {
return nil
}
self.temp = temp
self.icon = icon
self.time = time
}
}
|
//
// DiceImageView.swift
// FarkleRedo
//
// Created by Yemi Ajibola on 8/20/16.
// Copyright © 2016 Yemi Ajibola. All rights reserved.
//
import UIKit
protocol DiceImageViewDelegate {
func diceImageViewTapped(die: DiceImageView)
}
class DiceImageView: UIImageView {
var delegate: DiceImageViewDelegate?
var imageName: String!
var origin: CGPoint!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.userInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(DiceImageView.diceImageViewWasTapped))
self.addGestureRecognizer(tapGesture)
origin = self.center
}
func diceImageViewWasTapped() {
delegate?.diceImageViewTapped(self)
}
func roll() {
let imageName = "\(arc4random()%6+1)"
self.image = UIImage(named: imageName)
self.imageName = imageName
}
}
|
//
// ViewControllerDetail.swift
// BeerMe
//
// Created by McClean, Quinnion on 8/21/16.
// Copyright © 2016 generalassembly. All rights reserved.
//
import UIKit
import CoreLocation
class ViewControllerDetail: UIViewController {
@IBAction func beerNearMeButton(sender: AnyObject) {
}
@IBAction func backButton(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
}
|
//
// Coin.swift
// HDWalletKit
//
// Created by Pavlo Boiko on 10/3/18.
// Copyright © 2018 Essentia. All rights reserved.
//
import Foundation
internal enum Coin {
case bitcoin
case ethereum
case litecoin
case bitcoinCash
case dash
//https://github.com/satoshilabs/slips/blob/master/slip-0132.md
internal var privateKeyVersion: UInt32 {
switch self {
case .litecoin:
return 0x019D9CFE
case .bitcoinCash: fallthrough
case .bitcoin:
return 0x0488ADE4
case .dash:
return 0x02FE52CC
default:
fatalError("Not implemented")
}
}
// P2PKH
internal var publicKeyHash: UInt8 {
switch self {
case .litecoin:
return 0x30
case .bitcoinCash: fallthrough
case .bitcoin:
return 0x00
case .dash:
return 0x4C
default:
fatalError("Not implemented")
}
}
// P2SH
internal var scriptHash: UInt8 {
switch self {
case .bitcoinCash: fallthrough
case .litecoin: fallthrough
case .bitcoin:
return 0x05
case .dash:
return 0x10
default:
fatalError("Not implemented")
}
}
//https://www.reddit.com/r/litecoin/comments/6vc8tc/how_do_i_convert_a_raw_private_key_to_wif_for/
internal var wifAddressPrefix: UInt8 {
switch self {
case .bitcoinCash: fallthrough
case .bitcoin:
return 0x80
case .litecoin:
return 0xB0
case .dash:
return 0xCC
default:
fatalError("Not implemented")
}
}
internal var addressPrefix:String {
switch self {
case .ethereum:
return "0x"
default:
return ""
}
}
internal var uncompressedPkSuffix: UInt8 {
return 0x01
}
internal var coinType: UInt32 {
switch self {
case .bitcoin:
return 0
case .litecoin:
return 2
case .dash:
return 5
case .ethereum:
return 60
case .bitcoinCash:
return 145
}
}
internal var scheme: String {
switch self {
case .bitcoin:
return "bitcoin"
case .litecoin:
return "litecoin"
case .bitcoinCash:
return "bitcoincash"
case .dash:
return "dash"
default: return ""
}
}
}
|
//
// clone.swift
// Quark
//
// Created by Lou Knauer on 06.07.16.
// Copyright © 2016 LouK. All rights reserved.
//
import Foundation
extension QError {
func clone() -> QNode {
return self
}
} |
//
// ViewController.swift
// animations
//
// Created by Seo Yoochan on 6/9/15.
// Copyright (c) 2015 Seo Yoochan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var counter = 1
var timer = NSTimer()
var animating = true
@IBOutlet var image: UIImageView!
@IBAction func update(sender: AnyObject) {
if animating == true {
timer.invalidate()
animating = false
} else {
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("doAnimation"), userInfo: nil, repeats: true)
animating = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("doAnimation"), userInfo: nil, repeats: true)
}
func doAnimation() {
if counter == 22 {
counter = 0
} else {
counter++
}
image.image = UIImage(named: "tmp-\(counter).gif")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// init but not shown yet
override func viewDidLayoutSubviews() {
// image.center = CGPointMake(image.center.x - 400, image.center.y)
// image.alpha = 0
// image.frame = CGRectMake(100, 20, 0, 0)
}
override func viewDidAppear(animated: Bool){
UIView.animateWithDuration(1, animations: { () -> Void in
// self.image.center = CGPointMake(self.image.center.x + 400, self.image.center.y)
//
// self.image.alpha = 1
//
// self.image.frame = CGRectMake(100, 20, 100, 200)
})
}
}
|
//
// InstallHistoryVC.swift
// Project
//
// Created by 张凯强 on 2019/8/8.
// Copyright © 2019年 HHCSZGD. All rights reserved.
//
import UIKit
import SDWebImage
class InstallHistoryVC: DDInternalVC, UITableViewDelegate, UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.configUI()
self.loadMore()
// Do any additional setup after loading the view.
}
let table = UITableView.init(frame: CGRect.init(x: 0, y: DDNavigationBarHeight, width: SCREENWIDTH, height: SCREENHEIGHT - DDNavigationBarHeight), style: UITableView.Style.plain)
let maskView = ShopMaskView.init(frame: CGRect.zero, title: "screenInstallNoNUll"|?|)
func configUI() {
self.naviBar.title = "installHistory"|?|
let rightBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 64, height: 44))
rightBtn.setImage(UIImage.init(named: "installBussiness_search_small"), for: .normal)
rightBtn.addTarget(self, action: #selector(rightBtnAction(btn:)), for: UIControl.Event.touchUpInside)
self.naviBar.rightBarButtons = [rightBtn]
self.view.backgroundColor = UIColor.colorWithHexStringSwift("f0f0f0")
self.view.addSubview(self.maskView)
self.maskView.frame = CGRect.init(x: 0, y: (SCREENHEIGHT - 200) / 2.0, width: SCREENWIDTH, height: 200)
self.maskView.isHidden = true
self.view.addSubview(table)
table.contentInset = UIEdgeInsets.init(top: 50, left: 0, bottom: 0, right: 0)
table.delegate = self
table.dataSource = self
table.showsVerticalScrollIndicator = false
table.backgroundColor = UIColor.colorWithHexStringSwift("f0f0f0")
table.register(InstallHistoryCell.self, forCellReuseIdentifier: "InstallHistoryCell")
table.register(InstallHistoryHeader.self, forHeaderFooterViewReuseIdentifier: "InstallHistoryHeader")
table.separatorStyle = .none
table.gdLoadControl = GDLoadControl.init(target: self, selector: #selector(loadMore))
if #available(iOS 11.0, *) {
self.table.contentInsetAdjustmentBehavior = .never
} else {
// Fallback on earlier versions
}
self.refreshBtn.frame = CGRect.init(x: SCREENWIDTH - 60, y: SCREENHEIGHT - DDSliderHeight - 100, width: 44, height: 44)
self.refreshBtn.isHidden = true
self.view.addSubview(self.header)
self.header.frame = CGRect.init(x: 0, y: DDNavigationBarHeight, width: SCREENWIDTH, height: 44)
self.header.button.addTarget(self, action: #selector(calanderTimeAction(btn:)), for: UIControl.Event.touchUpInside)
}
@objc func rightBtnAction(btn: UIButton) {
self.pushVC(vcIdentifier: "ScreenInstallHistorySearchVC", userInfo: nil)
}
var date: String = "" {
didSet{
if date == "" {
self.refreshBtn.isHidden = true
}else {
self.refreshBtn.isHidden = false
self.header.myTitle.text = date
}
}
}
@objc func loadMore() {
let parameter: [String: AnyObject] = ["date": self.date as AnyObject, "page": self.page as AnyObject, "token": (DDAccount.share.token ?? "") as AnyObject, "data_type": "1" as AnyObject]
if self.page == 1 {
self.table.gdLoadControl?.loadStatus = .idle
}
self.page += 1
let router = Router.get("install-history/install", DomainType.api, parameter)
NetWork.manager.requestData(router: router, success: { (response) in
let model = DDJsonCode.decodeAlamofireResponse(ApiModel<[InstallHistoryModel]>.self, from: response)
if let data = model?.data, model?.status == 200 {
self.table.gdLoadControl?.endLoad(result: GDLoadResult.success)
self.analyDate(date: data)
if self.page == 2 {
//第一次加载第一页的数据的时候
self.header.isHidden = false
self.header.myTitle.text = data.first?.month
}
}else {
if self.page == 2 {
self.header.isHidden = true
}
self.table.gdLoadControl?.endLoad(result: GDLoadResult.nomore)
self.table.reloadData()
}
if self.dataArr.count == 0 {
self.table.isHidden = true
self.maskView.isHidden = false
}else {
self.table.isHidden = false
self.maskView.isHidden = true
}
}) {
if self.page == 2 {
self.header.isHidden = true
}
}
}
func analyDate(date: [InstallHistoryModel]) {
// var key: String = ""
// var count: Int = 0
// var fatherArr: [InstallHistoryModel] = [InstallHistoryModel]()
// var originArr: [InstallHistoryModel] = [InstallHistoryModel]()
// self.dataArr.forEach { (arr) in
// arr.forEach({ (model) in
// originArr.append(model)
// })
// }
// originArr.append(contentsOf: date)
// originArr.forEach { (model) in
// if key != model.month {
// key = model.month ?? ""
// count += 1
// fatherArr.append(model)
//
// }
// }
// self.dataArr.removeAll()
// fatherArr.forEach { (superModel) in
// var arr = [InstallHistoryModel]()
// originArr.forEach({ (model) in
// if superModel.month == model.month {
// arr.append(model)
// }
// })
// self.dataArr.append(arr)
//
// }
self.dataArr.append(contentsOf: date)
self.table.reloadData()
}
// func analyDate(date: [InstallHistoryModel]) {
// var fatherArr: [[InstallHistoryModel]] = [[InstallHistoryModel]]()
// var currentIndex = 0
// var currentMonth = ""
// for ( index , model) in date.enumerated() {
// if model.month != currentMonth {
// currentMonth = model.month ?? ""
// currentIndex = index
// fatherArr.append([InstallHistoryModel]())
// }
// fatherArr[currentIndex].append(model)
// }
// self.dataArr.append(fatherArr)
// self.table.reloadData()
// }
lazy var refreshBtn: UIButton = {
let btn = UIButton.init()
btn.setImage(UIImage.init(named: "returnOrigin"), for: UIControl.State.normal)
btn.addTarget(self, action: #selector(refreshBtnClick(btn:)), for: UIControl.Event.touchUpInside)
self.view.addSubview(btn)
return btn
}()
@objc func refreshBtnClick(btn: UIButton) {
self.page = 1
self.date = ""
self.loadMore()
}
let header: InstallHistoryHeader = InstallHistoryHeader.init(reuseIdentifier: "InstallHistoryHeader")
var page: Int = 1
var keyword: String = ""
var dataArr: [InstallHistoryModel] = [InstallHistoryModel]()
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InstallHistoryCell", for: indexPath) as! InstallHistoryCell
// if indexPath.section < (self.dataArr.count) {
// let arr = self.dataArr[indexPath.section]
// if indexPath.row < arr.count {
// cell.model = arr[indexPath.row]
// }
//
// }
cell.bussinessHistoryModel = self.dataArr[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.001
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let arr = self.dataArr[indexPath.section]
let model = self.dataArr[indexPath.row]
let vc = ShopInfoVC()
vc.vcType = .installHistory
vc.userInfo = ["id": model.id, "type": model.type, "shop_type": model.shop_type ?? "1"]
self.navigationController?.pushViewController(vc, animated: true)
}
// func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// if section >= self.dataArr.count {
// return nil
// }
// let arr = self.dataArr[section]
// let model = arr.first
// let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "InstallHistoryHeader") as! InstallHistoryHeader
// header.myTitle.text = model?.month ?? ""
// let cellArr = tableView.visibleCells
// if let cell = cellArr.first, let index = tableView.indexPath(for: cell) {
//
// }
// let index = tableView.indexPath(for: cell!) ?? IndexPath.init(row: 0, section: 0)
// header.button.isHidden = (section == index.section) ? false : true
// header.button.addTarget(self, action: #selector(calanderTimeAction(btn:)), for: UIControl.Event.touchUpInside)
// header.button.isHidden = true
// self.header.myTitle.text = model?.month ?? ""
// self.header.button.addTarget(self, action: #selector(calanderTimeAction(btn:)), for: UIControl.Event.touchUpInside)
// header.myTitle.text = model?.month
// return header
//
// }
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let cell = self.table.visibleCells.first, let index = self.table.indexPath(for: cell) {
let model = self.dataArr[index.row]
self.header.myTitle.text = model.month
}
}
@objc func calanderTimeAction(btn: UIButton) {
let subView = DDCoverView.init(superView: self.view)
self.cover = subView
let selectTime = ScreenHistorySelectTime.init(frame: CGRect.init(x: 0, y: SCREENHEIGHT - 300 - DDSliderHeight, width: SCREENWIDTH, height: 300 + DDSliderHeight))
self.cover?.addSubview(selectTime)
self.cover?.deinitHandle = {
self.cover?.removeFromSuperview()
self.cover = nil
}
let _ = selectTime.sender.subscribe(onNext: { [weak self](title) in
self?.date = title
self?.page = 1
self?.dataArr.removeAll()
self?.loadMore()
}, onError: { (error) in
}, onCompleted: {
self.cover?.removeFromSuperview()
self.cover = nil
}) {
mylog("回收")
}
}
weak var cover: DDCoverView?
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//
class ScreenInstallHistoryModel: GDModel {
var address: String?
var area_name: String?
var create_at: String?
var id: String?
var member_id: String?
var month: String?
var replace_id: String?
var screen_number: String?
var shop_id: String?
var shop_image: String?
var shop_name: String?
var name: String?
var status: String?
}
|
//
// TodoViewModel.swift
// ThingsTodo
//
// Created by Karamjeet Singh on 17/04/18.
// Copyright © 2018 TheSimpleApps@gmail.com. All rights reserved.
//
protocol ToDoItemPresentable {
var id : String? { get }
var textValue : String? { get }
}
class TodoItemViewModel: ToDoItemPresentable {
var id : String? = "0"
var textValue : String?
init(id: String, textValue: String) {
self.id = id
self.textValue = textValue
}
}
protocol TodoViewDelegate {
// Add item
func onToDoItemAdded() -> ()
// Delete item
func onToDoItemDelete(itemId: String)
}
protocol TodoViewPresentable {
var newTodoValue: String? { get }
}
protocol TodoItemViewDelegate {
func onItemSelected() -> (Void)
}
class TodoViewModel: TodoViewPresentable {
weak var view: TodoViewUpdate?
var newTodoValue: String?
var items : [ToDoItemPresentable] = []
init(view: TodoViewUpdate) {
self.view = view
//Create some dummy items if you want
let item1 = TodoItemViewModel(id: "1", textValue: "item 1")
let item2 = TodoItemViewModel(id: "2", textValue: "item 2")
let item3 = TodoItemViewModel(id: "3", textValue: "item 3")
items.append(contentsOf: [item1, item2, item3])
}
}
extension TodoItemViewModel: TodoItemViewDelegate {
func onItemSelected() {
print("item selected id = \(id!) item = \(textValue!)")
}
}
extension TodoViewModel: TodoViewDelegate {
// Delete item
func onToDoItemDelete(itemId: String) {
guard let index = self.items.index(where: {$0.id! == itemId}) else {
print("item index not present")
return
}
self.items.remove(at: index)
self.view?.itemRemoved(at: index)
}
// Add item
func onToDoItemAdded() {
print("New todo value received in view model: \(newTodoValue)")
guard let newTodoValue = newTodoValue else {
print("new value is empty")
return
}
let itemIndex = items.count + 1
let newItem = TodoItemViewModel(id: "\(itemIndex)", textValue: newTodoValue)
self.items.append(newItem)
self.newTodoValue = ""
self.view?.itemInserted()
}
}
|
//
// WeatherList.swift
// WeatherMan
//
// Created by Jesse Tayler on 8/8/19.
// Copyright © 2019 Jesse Tayler. All rights reserved.
//
import SwiftUI
extension Weather {
struct List<T: Codable & Identifiable>: Codable {
var list: [T]
enum CodingKeys: String, CodingKey {
case list = "data"
}
}
}
|
//
// SongsPresenter.swift
// SoundCast
//
// Created by M sreekanth on 09/08/18.
// Copyright © 2018 Green Bird IT Services. All rights reserved.
//
import UIKit
import AlamofireImage
import Alamofire
import AVFoundation
class SongsPresenter:NSObject{
let thumnailFilter = AspectScaledToFillSizeFilter.init(size: CGSize.init(width: 75, height: 75))
let placeholderImage = UIImage.init(named: "sample.png")
let filemanager = FileManager.default
var alamofiremanager:Alamofire.SessionManager?
var isExcecuting:Bool = false
private var songs:[Song] = [Song]()
private let identifier = "Default"
var avAudioPlayer:AVAudioPlayer?
public var userSelectedIndex:Int?
public func registerTableView(_ table:UITableView) {
table.register(SongsCell.self, forCellReuseIdentifier: identifier)
}
func fetchSongs(_ callback: @escaping (()->Void)) {
ApiCall().fetchSongs({songs, error in
if let songs = songs{
self.songs = songs
callback()
}
})
}
func song(_ index:Int) -> Song {
self.userSelectedIndex = index
return self.songs[index]
}
func playSong(at index:Int) -> Song {
if userSelectedIndex == index{
if avAudioPlayer!.isPlaying{
}else{
avAudioPlayer?.play()
}
return self.songs[index]
}else if index < 0{
self.userSelectedIndex = 0
self.playSongWithAudioPlayer(song: self.songs.first!)
return self.songs.first!
}else if index < self.songs.count{
self.userSelectedIndex = index
self.playSongWithAudioPlayer(song: self.songs[index])
return self.songs[index]
}else{
self.userSelectedIndex = self.songs.count - 1
return self.songs.last!
}
}
private func playSongWithAudioPlayer(song:Song){
if avAudioPlayer != nil{
avAudioPlayer = nil
}
if self.checkFilesInDirectory(url: song.link!) {
do{
let directory = self.getPath()
let url = URL.init(string: song.link!)!
let fileURL = directory.appendingPathComponent(url.lastPathComponent)
self.avAudioPlayer = try AVAudioPlayer.init(contentsOf: fileURL)
self.avAudioPlayer?.prepareToPlay()
self.avAudioPlayer?.play()
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}catch{
}
}catch{
print(error)
}
}
}
fileprivate func directoryExistsAtPath(_ path: String) -> Bool {
var isDirectory = ObjCBool(true)
let exists = filemanager.fileExists(atPath: path, isDirectory: &isDirectory)
return exists && isDirectory.boolValue
}
private func getPath() -> URL{
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0] as AnyObject
let directoryPath = URL.init(fileURLWithPath: documentsDirectory as! String).appendingPathComponent("SoundCast", isDirectory: true)
if directoryExistsAtPath(directoryPath.path){
return directoryPath
}
do{
try filemanager.createDirectory(atPath: directoryPath.path, withIntermediateDirectories: false, attributes: nil)
}catch{
print(error.localizedDescription)
}
return directoryPath
}
private func checkFilesInDirectory(url:String) -> Bool{
if let url:URL = URL.init(string: url){
let directoryPath = self.getPath()
let datapath = directoryPath.appendingPathComponent(url.lastPathComponent)
print(datapath)
return filemanager.fileExists(atPath: datapath.path)
}
return false
}
private func downloadSongFromServer(_ urlStr:String, callBack: @escaping () -> Void){
if let audioUrl = URL(string: urlStr) {
let directoryUrl = self.getPath()
let fileUrl = directoryUrl.appendingPathComponent(audioUrl.lastPathComponent)
if filemanager.fileExists(atPath: fileUrl.path) {
print("The file already exists at path")
} else {
// you can use NSURLSession.sharedSession to download the data asynchronously
let destinationUrl : DownloadRequest.DownloadFileDestination = {_ ,_ in
return (fileUrl, [.removePreviousFile])
}
let configuration = URLSessionConfiguration.background(withIdentifier: audioUrl.lastPathComponent)
self.alamofiremanager = Alamofire.SessionManager(configuration: configuration)
alamofiremanager?.download(audioUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil, to: destinationUrl)
.downloadProgress(closure: {progress in
// print("File Size:: %@",progress.fileTotalCount)
})
.responseData(completionHandler: {data in
self.isExcecuting = false
callBack()
})
.response(completionHandler: {response in
if response.response?.statusCode != 200{
self.isExcecuting = false
}
})
}
}
}
}
extension SongsPresenter:UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:SongsCell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! SongsCell
cell.iconView.af_setImage(withURL: URL.init(string: songs[indexPath.row].thumbnail!)!, placeholderImage: placeholderImage, filter: thumnailFilter)
cell.label.text = songs[indexPath.row].title
if userSelectedIndex == indexPath.row{
if (self.avAudioPlayer?.isPlaying)!{
cell.status = SongStatus.downloaded
cell.statusIcon.image = #imageLiteral(resourceName: "pauseIcon").withRenderingMode(.alwaysTemplate)
cell.setupPulsingAnimation()
}else{
cell.status = SongStatus.downloaded
cell.statusIcon.image = #imageLiteral(resourceName: "playIcon").withRenderingMode(.alwaysTemplate)
cell.removePulsingAnimation()
}
}else{
if checkFilesInDirectory(url: songs[indexPath.row].link!){
cell.status = SongStatus.downloaded
cell.statusIcon.image = #imageLiteral(resourceName: "playIcon").withRenderingMode(.alwaysTemplate)
cell.removePulsingAnimation()
}else{
cell.status = SongStatus.notDownloaded
cell.statusIcon.image = #imageLiteral(resourceName: "downloadIcon").withRenderingMode(.alwaysTemplate)
if !isExcecuting {
isExcecuting = true
cell.setupPulsingAnimation()
cell.status = SongStatus.downloading
self.downloadSongFromServer(songs[indexPath.row].link!, callBack: {
DispatchQueue.main.async {
tableView.reloadData()
}
})
}
}
}
cell.selectionStyle = .none
return cell
}
}
|
/*:
[Previous](@previous)
# Demo
## PokeGAN
Thanks to the power of CoreML, we can run a GAN directly on our Apple device.
This model has been trained on pictures of all 802 Pokémon figures. After several training sessions and meticulous adjustments, the generator is able to generate entirely new figures that the discriminator can no longer discern whether are real or fake.
* Experiment:
You'll be the discriminator (detective). Of the nine images, one is a real Pokémon while the remaining eight are generated by the GAN. Your job is to click the one you think is real. Are you unfamiliar with how the real figures look? No worries - so is the GAN.
*/
// The following snippet shows how an image is generated.
import PlaygroundSupport
struct PokeGenerator: ImageGenerator {
/// Model class created by CoreML based on the model
/// exported from the deep learning environment.
let generator = Generator()
func generateImage() -> Image {
// Generate random noise to feed to the generator.
let input = generateInputNoise(size: 100)
// Ask the generator to create an image based on the noise.
let result = try! generator.prediction(input1: input)
// Convert the output to an image.
let image = result.output1.image(offset: 1.0, scale: 255 / 2)
return image!
}
}
let generator = PokeGenerator()
let view = GameView(generator: generator)
PlaygroundPage.current.liveView = view
PlaygroundPage.current.needsIndefiniteExecution = true
/*:
## Robot uprising?
As you'll see, the resoluation of the generated images is not that great. If you squint your eyes and take a few steps back it'll look more convincing. However, take a moment to appreciate that these are images generated out of random noise, and the whole procedure is taught to the machine by itself. There is no drawing code creating these images.
* Callout(Caveats):
GANs are notoriously difficult to train properly and break very easily. There are a lot of knobs to turn and special care must taken to ensure a level playing field between the generator and the discriminator so one does not dominate the other. A lot of research is being put into improving the stability of GANs. I made an attempt to increase the image resolution from 32x32 pixels but couldn't find a set of parameters that would result in meaningful output.
[The End](3%20-%20Acknowledgements)
*/
|
//
// MangaStateMO+CoreDataProperties.swift
// EhPanda
//
// Created by 荒木辰造 on R 3/07/09.
//
import CoreData
extension MangaStateMO: GalleryIdentifiable {
@nonobjc public class func fetchRequest() -> NSFetchRequest<MangaStateMO> {
NSFetchRequest<MangaStateMO>(entityName: "MangaStateMO")
}
@NSManaged public var comments: Data?
@NSManaged public var contents: Data?
@NSManaged public var gid: String
@NSManaged public var previews: Data?
@NSManaged public var readingProgress: Int64
@NSManaged public var tags: Data?
}
|
//
// DexOrderBookHeaderView.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 8/16/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
final class DexOrderBookHeaderView: DexTraderContainerBaseHeaderView, NibOwnerLoadable {
@IBOutlet private weak var labelAmountAssetName: UILabel!
@IBOutlet private weak var labelPriceAssetName: UILabel!
@IBOutlet private weak var labelSumAssetName: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
loadNibContent()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadNibContent()
}
}
//MARK: - SetupUI
extension DexOrderBookHeaderView: ViewConfiguration {
func update(with model: DexOrderBook.ViewModel.Header) {
labelAmountAssetName.text = Localizable.Waves.Dexorderbook.Label.amount + " " + model.amountName
labelPriceAssetName.text = Localizable.Waves.Dexorderbook.Label.price + " " + model.priceName
labelSumAssetName.text = Localizable.Waves.Dexorderbook.Label.sum + " " + model.sumName
}
}
|
// Codecademy gets the credit for prompting this activity
// Classroom appropriate bottle bot songs
// I love the idea of ASCII art as an assignment
print(".------------------------.")
print("|battle bots! 90 min|")
print("| __ ______ __ |")
print("| ( )|).....|( ) |")
print("| (__)|)_____|(__) |")
print("| ________________ |")
print("|___/_._o________o_._\\___|")
// Declaring an array
var mixtape = [String]()
// Adding some songs
mixtape.append("Ankhaten: Act II, Scene 1 Temple - Spotify")
mixtape.append("Antarcticans Thawed - Spotify")
mixtape.append("Du Hast - Spotify")
mixtape.append("The Bridge of Khazadhum - Spotify")
mixtape.append("Dragonaut - Spotify")
mixtape.append("Wind Waker Boss Music - Youtube")
mixtape.append("Halo Theme - Spotify")
mixtape.append("Twilight Princess, All Boss Music - Youtube")
// Practicing removing values from an array
// Du Hast may not be the most school appropriate song
mixtape.remove(at: 2)
// Practicing putting new values in a new position
mixtape.insert("We will rock you", at: 0)
// OUTPUT!
print("")
print("")
print("THE ULTIMATE BATTLE MIXTAPE!!")
print("-----------------------------")
for item in mixtape{
print(item)
}
print("")
print("This mixtape has \(mixtape.count) songs. ENJOY!")
|
//
// WidgetFactory.swift
// UniversalComponent
//
// Created by Igor Shelopaev on 14.05.2021.
//
import SwiftUI
import Data
import Ui
/// Set of widgets for the app
struct WidgetFactory {
/// Get charts
/// - Returns: Chart views
@ViewBuilder
func charts( viewModel: AppViewModel, factory:ItemFactory, count: Int ) -> some View
{
if count == 0 { EmptyView() } else {
ForEach(1...count, id: \.self) { id in
chart(
store: viewModel.getFileJsonStore(from: "user_chart.json"),
content: factory.userAgeBar,
toolBar: ToolBar("Age chart \(id)")
)
}
}
}
/// Get chart
/// - Returns: Chart view
@ViewBuilder
func chart<T, U: Proxy, Content: View, ToolBarContent: View>
(
store: RemoteStore<T,U>,
content: @escaping (T, Bool, CGFloat) -> Content,
toolBar: ToolBarContent
) -> some View
{
BarChart(
store: store,
content: content,
toolBar: toolBar
)
}
/// Get list
/// - Returns: List view
@ViewBuilder
func list<T, U: Proxy, Content: View, ToolBarContent: View>
(
store: RemoteStore<T,U>,
content: @escaping (T, Bool) -> Content,
toolBar: ToolBarContent
) -> some View
{
UniversalList(
store: store,
content: content,
toolBar: toolBar
)
}
}
|
import Cocoa
if let windowInfo = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[ String : Any]] {
for windowDict in windowInfo {
if let windowName = windowDict[kCGWindowName as String] as? String {
print(windowName)
}
}
}
|
//
// File.swift
// SingaporePSITests
//
// Created by Zhang Tianli on 26/1/18.
// Copyright © 2018 tianli. All rights reserved.
//
import XCTest
import GoogleMaps
@testable import Singapore_PSI
class MapViewControllerTests: XCTestCase {
var viewController: MapViewController!
var refreshButton: UIButton!
var timestampLabel: UILabel!
var mapView: GMSMapView!
let storyboard = UIStoryboard(name:"Main", bundle: .main)
override func setUp() {
super.setUp()
viewController = storyboard.instantiateViewController(withIdentifier: "MapViewController") as! MapViewController
let _ = viewController.view
let _ = viewController.viewDidLoad()
refreshButton = viewController.refreshButton
timestampLabel = viewController.timestampLabel
mapView = viewController.mapView
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testShouldLoadUIElement() {
XCTAssertNotNil(mapView, "mapView should not be nil")
XCTAssertNotNil(refreshButton, "refreshButton should not be nil")
XCTAssertNotNil(timestampLabel, "timestampLabel should not be nil")
}
func testShouldShowTimestampCorrectly() {
self.viewController.timestamp = "2018-01-26T21:00:00+08:00"
XCTAssertEqual(viewController.timestampLabel.text, "Updated on: 2018-01-26T21:00:00")
}
func testPerformanceWhenRefresh() {
measure {
self.viewController.refreshData()
}
}
func testPerformanceWhenLoading() {
measure {
self.viewController.viewDidLoad()
}
}
}
|
//
// Post+Mock.swift
// UserDisplayer
//
// Created by Jeremi Kaczmarczyk on 04/02/2017.
// Copyright © 2017 Jeremi Kaczmarczyk. All rights reserved.
//
import Foundation
@testable import UserDisplayer
extension Post {
static var user1MockPost1: Post {
return Post(userId: 1, id: 1, title: "Post 1", body: "This is test body of a post 1")
}
static var user1MockPost2: Post {
return Post(userId: 1, id: 2, title: "Post 2", body: "This is test body of a post 2")
}
}
|
//
// UIWindowsConfig.swift
// UIWindows
//
// Created by Luke Yin on 2019-12-02.
// Copyright © 2019 sinLuke. All rights reserved.
//
import UIKit
public struct UIWindowsConfig {
public static var defaultConfig = UIWindowsConfig(minHeight: 300.0, minWidth: 200.0, tintColor: .systemBlue, cornerAdjustRadius: 20.0, barHeight: 33.0, windowEdgeWidth: 0)
public init(minHeight: CGFloat, minWidth: CGFloat, tintColor: UIColor, cornerAdjustRadius: CGFloat, barHeight: CGFloat, windowEdgeWidth: CGFloat) {
self.minHeight = minHeight
self.minWidth = minWidth
self.tintColor = tintColor
self.cornerResponsRadius = cornerAdjustRadius
self.barHeight = barHeight
self.windowEdgeWidth = windowEdgeWidth
}
let minHeight: CGFloat
let minWidth: CGFloat
let tintColor: UIColor
let cornerResponsRadius: CGFloat
let barHeight: CGFloat
let windowEdgeWidth: CGFloat
}
|
//
// ObjectManager.swift
// GameFramework
//
// Created by 601 on 2020/02/27.
// Copyright © 2020 601. All rights reserved.
//
import UIKit
// 게임에 등장할 모든 오브젝트는 게임 루프에 의해 tick(), render()가 호출되어야 하고
// nil(null)로 인한 에러를 방지하려면 배열에 담아져야 하는데 생성, 소멸시마다 일일이 배열에 담고
// 제거하는 작업이 번거롭기 때문에 아래의 클래스로 코드를 간결하게 처리해 보자
class ObjectManager: NSObject {
// 게임루프에 의해 호출될 대상들을 담게될 배열
// 즉 이 배열에 담아진 객체들은 모두 게임루프에 의해 tick(), render()가 호출됨
var objectArray:Array=Array<GameObject>() // 게임에 등장할 명단
// 화면에 등장할 객체 추가하기 (배열에 담기)
// 객체 등록
func addObject(obj:GameObject){
objectArray.append(obj)
}
// 화면에서 제거될 객체 처리 (배열에서 제거하기)
func removeObject(obj:GameObject){
// 넘겨받은 객체가 배열의 어느 인덱스에 있었는지 조사하자!!
let index = objectArray.firstIndex(of: obj)
if index != nil{
objectArray.remove(at: index!)
}
//print("objectArrray의 길이는", objectArray.count)
}
}
|
//
// URLResponse+Extensions.swift
// Social Messaging
//
// Created by Vũ Quý Đạt on 12/05/2021.
//
import Foundation
extension URLResponse {
// fileprivate var isSuccess: Bool {
var isSuccess: Bool {
guard let response = self as? HTTPURLResponse else { return false }
return (200...299).contains(response.statusCode)
}
}
|
//
// ViewController.swift
// SoESign
//
// Created by Amol Bombe on 11/07/17.
// Copyright © 2017 softcell. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPopoverPresentationControllerDelegate {
var imagePicker: UIImagePickerController?
var filePath = ""
@IBOutlet weak var docImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPDF" {
if let pdfVC = segue.destination as? PdfViewController {
pdfVC.filePath = filePath
}
}
}
@IBAction func takePhotoButtonTapped(_ sender: UIButton) {
imagePicker = UIImagePickerController()
imagePicker?.delegate = self
let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
self.openCamera()
}))
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.openGallary()
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@IBAction func eSignDocumentTapped(_ sender: UIButton) {
performSegue(withIdentifier: "showPDF", sender: self)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
docImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismiss(animated: true, completion: nil)
let image = docImageView.image
var images = [UIImage]()
images.append(image ?? UIImage())
writePdfInFile(images: images)
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
func writePdfInFile(images: [UIImage]) {
var documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
var data = Data()
for img in images {
let imgData = (UIImagePNGRepresentation(img))
data.append(imgData ?? Data())
}
let mutableData = NSMutableData(data: data)
UIGraphicsBeginPDFContextToData(mutableData, CGRect.zero, nil)
let pdfContext = UIGraphicsGetCurrentContext()
if (pdfContext == nil)
{
return
}
var yAxix = 50
for img in images {
UIGraphicsBeginPDFPage()
let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 500, height: 500))
imageView.image = img
imageView.contentMode = .scaleAspectFit
let view = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
view.addSubview(imageView)
view.layer.render(in: pdfContext!)
yAxix = yAxix + 20 + 500
let font = UIFont(name: "Helvetica Bold", size: 14.0)
let textRect = CGRect(x: 20, y: 800 - 60, width: 500, height: 60)
let paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = NSTextAlignment.left
paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
let textColor = UIColor.black
let textFontAttributes = [
NSFontAttributeName: font!,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: paragraphStyle
]
let text:NSString = "eSigned By Amol Bombe \n\(getCurrentDate())" as NSString
text.draw(in: textRect, withAttributes: textFontAttributes)
}
UIGraphicsEndPDFContext()
var objcBool:ObjCBool = true
documentsPath = documentsPath.appending("/GoNoGoPDFs")
let isExist = FileManager.default.fileExists(atPath: documentsPath, isDirectory: &objcBool)
// If the folder with the given path doesn't exist already, create it
if isExist == false {
do{
try FileManager.default.createDirectory(atPath: documentsPath, withIntermediateDirectories: true, attributes: nil)
}catch{
print("Something went wrong while creating a new folder")
}
} else {
do{
try FileManager.default.removeItem(atPath: documentsPath)
}catch{
print("Something went wrong while deleting a new folder")
}
do{
try FileManager.default.createDirectory(atPath: documentsPath, withIntermediateDirectories: true, attributes: nil)
}catch{
print("Something went wrong while creating a new folder")
}
}
let pdfPath = documentsPath.appending("/eSignDoc.pdf")
var objectiveBool:ObjCBool = true
let isPdfExist = FileManager.default.fileExists(atPath: documentsPath, isDirectory: &objectiveBool)
// If the folder with the given path doesn't exist already, create it
if isPdfExist == false{
do{
try FileManager.default.removeItem(atPath: documentsPath)
}catch{
print("Something went wrong while creating a new folder")
}
}
debugPrint(pdfPath, terminator: "")
mutableData.write(toFile: pdfPath, atomically: true)
filePath = pdfPath
}
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
imagePicker?.sourceType = UIImagePickerControllerSourceType.camera
imagePicker?.allowsEditing = true
self.present(imagePicker!, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func openGallary() {
imagePicker?.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker?.allowsEditing = true
self.present(imagePicker!, animated: true, completion: nil)
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) {
}
func getCurrentDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy h:mm:ss a"
let sDate = dateFormatter.string(from: Date())
return sDate
}
}
|
//
// TypesSearch.swift
// ExemploParseJSON
//
// Created by Rodrigo A E Miyashiro on 11/9/15.
// Copyright © 2015 Rodrigo A E Miyashiro. All rights reserved.
//
import Foundation
class TypesSearch {
enum typeSearch: String {
case users
case repositories
}
} |
//
// DetailViewController.swift
// SpendPlan
//
// Created by Gautham Sritharan on 2021-05-24.
//
import Foundation
import UIKit
import CoreData
import EventKit
class DetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - Outlets
@IBOutlet weak var expenseTableView : UITableView! {
didSet {
self.expenseTableView.delegate = self
self.expenseTableView.dataSource = self
}
}
@IBOutlet weak var detailsDisplayView : UIView!
@IBOutlet weak var lblCategoryName : UILabel!
@IBOutlet weak var leftView : UIView!
@IBOutlet weak var pichartView : UIView!
@IBOutlet weak var categoryNameView : UIView!
@IBOutlet weak var pieChartLabelStackView : UIStackView!
@IBOutlet var barBtnRefresh : UIBarButtonItem!
@IBOutlet var barBtnAddExpense : UIBarButtonItem!
@IBOutlet weak var lblSpent : UILabel!
@IBOutlet weak var lblRemaining : UILabel!
@IBOutlet weak var lblBudget : UILabel!
@IBOutlet weak var lblColorOne : UILabel!
@IBOutlet weak var lblColorTwo : UILabel!
@IBOutlet weak var lblColorThree : UILabel!
@IBOutlet weak var lblColorFour : UILabel!
@IBOutlet weak var lblColorFive : UILabel!
@IBOutlet weak var box1View : UIView!
@IBOutlet weak var box2View : UIView!
@IBOutlet weak var box3View : UIView!
@IBOutlet weak var box4View : UIView!
@IBOutlet weak var box5View : UIView!
// MARK : - Variables
let context = (UIApplication.shared.delegate as!
AppDelegate).persistentContainer.viewContext
var managedObjectContext : NSManagedObjectContext? = nil
var expenseTable : UITableView?
let viewPieChart = PieChartView()
var detailViewController : DetailViewController? = nil
var addExpenseVC : AddExpenseVC? = nil
var expense : [Expense]?
var category : Category?
var expensePlaceholder : Expense?
var isEditMode : Bool? = false
let cellIdentifier = "ExpenseTVCell"
let eventStore = EKEventStore()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configUI()
expenseTableView.register(UINib(nibName: "ExpenseTVCell", bundle: nil), forCellReuseIdentifier: "ExpenseTVCell")
countClick()
}
func configUI() {
lblCategoryName.text = "\(category?.name ?? "Category")"
lblBudget.text = "£ \(category?.budget ?? 0.00)"
lblSpent.text = "£ 0.0"
lblRemaining.text = "£ \(category?.budget ?? 0.00)"
let padding: CGFloat = 20
let height = (pichartView.frame.height - padding * 3)
viewPieChart.frame = CGRect(
x: 0, y: padding, width: pichartView.frame.size.width, height: height
)
viewPieChart.segments = [
LabelledSegment(color: #colorLiteral(red: 0.5647058824, green: 0.04705882353, blue: 0.2470588235, alpha: 1), name: "ColorOne", value: 0),
LabelledSegment(color: #colorLiteral(red: 0.7803921569, green: 0, blue: 0.2235294118, alpha: 1), name: "ColorTwo", value: 0),
LabelledSegment(color: #colorLiteral(red: 1, green: 0.3411764706, blue: 0.2, alpha: 1), name: "ColorThree",value: 0),
LabelledSegment(color: #colorLiteral(red: 1, green: 0.7647058824, blue: 0, alpha: 1), name: "ColorFour", value: 0),
LabelledSegment(color: #colorLiteral(red: 0.8549019608, green: 0.968627451, blue: 0.6509803922, alpha: 1), name: "ColorFive", value: 0)
]
if (category === nil){
barBtnAddExpense.isEnabled = false
self.pieChartLabelStackView.isHidden = true
self.pichartView.isHidden = true
}
viewPieChart.segmentLabelFont = .systemFont(ofSize: 10)
pichartView.addSubview(viewPieChart)
categoryNameView.layer.cornerRadius = 5
categoryNameView.layer.borderWidth = 2
categoryNameView.layer.borderColor = #colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1)
box1View.layer.cornerRadius = box1View.bounds.size.width/2
box2View.layer.cornerRadius = box1View.bounds.size.width/2
box3View.layer.cornerRadius = box1View.bounds.size.width/2;
box4View.layer.cornerRadius = box1View.bounds.size.width/2;
box5View.layer.cornerRadius = box1View.bounds.size.width/2;
}
// MARK: - Segue actions
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "sendCategory" {
let controller = segue.destination as! AddExpenseVC
controller.category = self.category
controller.expenseTable = self.expenseTableView
controller.isEditMode = self.isEditMode
controller.expensePlaceholder = self.expensePlaceholder
addExpenseVC = controller
}
}
// MARK: - Refrsh Button click
@IBAction func didTapOnRefreshBtn(_ sender: Any) {
if let e = (self.category?.expense?.allObjects) as? [Expense] {
var totalSpent:Float = 0
for exp in e {
totalSpent += exp.amount
}
lblBudget.text = "£ \(category?.budget ?? 0.0)"
lblSpent.text = "£ \(round(Double(totalSpent) * 100)/100.0)"
lblRemaining.text = "£ \(round((category!.budget - totalSpent) * 100)/100.0)"
addPieChart(exps :e, spentAmount : totalSpent)
}
}
// MARK: - Piechart View
func addPieChart(exps : [Expense], spentAmount : Float){
resetPieChartToDefault()
let expsR = exps.sorted(by: {$0.amount > $1.amount})
var other:Float = 0
var labeltags: [String] = ["N/A", "N/A", "N/A","N/A","N/A"]
for (index, element) in expsR.enumerated() {
if(index < 4){
viewPieChart.segments[index].value = CGFloat(element.amount/spentAmount*100)
labeltags[index] = element.name!
}else{
other += element.amount
}
}
if other > 0 {
viewPieChart.segments[4].value = CGFloat(other/spentAmount*100)
labeltags[4] = "Other"
}
lblColorOne.text = labeltags[0]
lblColorTwo.text = labeltags[1]
lblColorThree.text = labeltags[2]
lblColorFour.text = labeltags[3]
lblColorFive.text = labeltags[4]
}
func resetPieChartToDefault(){
viewPieChart.segments = [
LabelledSegment(color: #colorLiteral(red: 0.5647058824, green: 0.04705882353, blue: 0.2470588235, alpha: 1), name: "ColorOne", value: 0),
LabelledSegment(color: #colorLiteral(red: 0.7803921569, green: 0, blue: 0.2235294118, alpha: 1), name: "ColorTwo", value: 0),
LabelledSegment(color: #colorLiteral(red: 1, green: 0.3411764706, blue: 0.2, alpha: 1), name: "ColorThree",value: 0),
LabelledSegment(color: #colorLiteral(red: 1, green: 0.7647058824, blue: 0, alpha: 1), name: "ColorFour", value: 0),
LabelledSegment(color: #colorLiteral(red: 0.8549019608, green: 0.968627451, blue: 0.6509803922, alpha: 1), name: "ColorFive", value: 0)
]
lblColorOne.text = "N/A"
lblColorTwo.text = "N/A"
lblColorThree.text = "N/A"
lblColorFour.text = "N/A"
lblColorFive.text = "N/A"
}
// MARK: - Counter
func countClick(){
self.category?.setValue(self.category!.clicks + 1, forKey: "clicks")
do {
try self.context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
// MARK: - TableView
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let exps = (self.category?.expense?.allObjects) as? [Expense] {
if exps.count == 0 {
self.pieChartLabelStackView.isHidden = true
self.pichartView.isHidden = true
self.expenseTableView.setEmptyMessage("No expenses added for this category", #colorLiteral(red: 0.05882352963, green: 0.180392161, blue: 0.2470588237, alpha: 1))
} else {
resetPieChartToDefault()
self.pieChartLabelStackView.isHidden = false
self.pichartView.isHidden = false
self.expenseTableView.restore()
}
return exps.count
}
return 0
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = deleteAction(at: indexPath)
let edit = editAction(at: indexPath)
return UISwipeActionsConfiguration(actions: [delete,edit])
}
func editAction (at indexPath: IndexPath) -> UIContextualAction {
let expenseList = (self.category?.expense?.allObjects) as? [Expense]
let action = UIContextualAction(style: .normal, title: "Edit") { (action, view, completion) in
self.isEditMode = true
self.expensePlaceholder = expenseList![indexPath.row]
self.performSegue(withIdentifier: "sendCategory", sender: expenseList![indexPath.row])
self.isEditMode = false
completion(true)
}
action.image = UIImage(named: "edit")
action.image = action.image?.withTintColor(.white)
action.backgroundColor = .systemBlue
return action
}
func deleteAction (at indexPath: IndexPath) -> UIContextualAction {
let expenseList = (self.category?.expense?.allObjects) as? [Expense]
let action = UIContextualAction(style: .normal, title: "Delete") { (action, view, completion) in
Utilities.showConfirmationAlert(title: "Are you sure?", message: "Delete expense: ", yesAction: {
() in
print("expense deleted",expenseList![indexPath.row])
do {
let removingExpense = expenseList![indexPath.row]
_ = self.deleteCalendarEvent(self.eventStore, removingExpense)
self.category?.removeFromExpense(removingExpense)
let context = self.context
try context.save()
self.expenseTableView.reloadData()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}, caller: self)
completion(true)
}
action.image = UIImage(named: "delete")
action.image = action.image?.withTintColor(.white)
action.backgroundColor = .systemRed
return action
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ExpenseTVCell = self.expenseTableView.dequeueReusableCell(withIdentifier: "ExpenseTVCell") as! ExpenseTVCell
if var e = (self.category?.expense?.allObjects) as? [Expense] {
let datapoint = e[indexPath.row]
cell.lblExpenseName.text = datapoint.name
cell.lblBudget.text = "£ \(datapoint.amount)"
cell.lblNote.text = datapoint.notes
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
cell.lblDueDate.text = formatter.string(from: datapoint.dueDate ?? Date())
switch datapoint.occurance {
case 0:
cell.lblOccurance.text = "Off"
case 1:
cell.lblOccurance.text = "Daily"
case 2:
cell.lblOccurance.text = "Weekly"
case 3:
cell.lblOccurance.text = "Monthly"
default:
cell.lblOccurance.text = "Off"
}
if datapoint.remainder == true {
cell.lblRemainder.text = "On"
} else {
cell.lblRemainder.text = "Off"
}
var totalSpent:Float = 0
for exp in e {
totalSpent += exp.amount
}
lblSpent.text = "£ \(round(Double(totalSpent) * 100)/100.0)"
lblRemaining.text = "£ \(round((category!.budget - totalSpent) * 100)/100.0)"
cell.budgetProgressBar.progress = CGFloat(e[indexPath.row].amount/category!.budget)
addPieChart(exps :e, spentAmount : totalSpent)
}
return cell
}
// MARK: - Calendar Event Handler
// Removes an event from the EKEventStore
func deleteCalendarEvent(_ eventStore: EKEventStore, _ expense:Expense) -> Bool {
if let calendarId = expense.calendarId {
let eventToRemove = eventStore.event(withIdentifier: calendarId)
if eventToRemove != nil {
do {
try eventStore.remove(eventToRemove!, span: .thisEvent)
return true
} catch {
return false
}
}
}
return true;
}
}
|
//
// MarvelCharacter.swift
// MarvelCharacters
//
// Created by Alexander Gurzhiev on 07.04.2021.
//
import Foundation
struct MarvelCharacter: Decodable {
let id: Int
let name: String
let description: String
let thumbnail: Image
let comics: MarvelContentList?
let stories: MarvelContentList?
let events: MarvelContentList?
let series: MarvelContentList?
}
struct Image: Decodable {
let path: String
let `extension`: String
}
struct MarvelContentList: Decodable {
let available: Int?
let returned: Int?
let collectionURI: String?
let items: [MarvelContentSummary]?
}
struct MarvelContentSummary: Decodable {
let resourceURI: String
let name: String
let type: String?
}
|
//
// MetalPreviewView.swift
// FastStyleTransferDemo
//
// Created by Arthur Tonelli on 5/8/20.
// Copyright © 2020 Arthur Tonelli. All rights reserved.
//
import CoreMedia
import Metal
import MetalKit
import MetalPerformanceShaders
class MetalPreviewView: MTKView {
var pixelBuffer: CVPixelBuffer? {
didSet {
syncQueue.sync {
internalPixelBuffer = pixelBuffer
}
}
}
private var internalPixelBuffer: CVPixelBuffer?
private let syncQueue = DispatchQueue(label: "PreviewViewSyncQueue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem)
private var textureCache: CVMetalTextureCache?
private var textureWidth: Int = 0
private var textureHeight: Int = 0
private var textureMirroring = false
private var sampler: MTLSamplerState!
private var renderPipelineState: MTLRenderPipelineState!
private var computePipelineState: MTLComputePipelineState
// private let metalDevice = MTLCreateSystemDefaultDevice()!
private var commandQueue: MTLCommandQueue?
// private var vertexCoordBuffer: MTLBuffer!
//
// private var textCoordBuffer: MTLBuffer!
private var internalBounds: CGRect!
private var textureTranform: CGAffineTransform?
var pipelineState: MTLComputePipelineState?
let filter: MPSImageLanczosScale
let url: URL
public var recorder: MetalVideoRecorder
// Prepare output texture
var inW: Int
var inH: Int
var outW: Int
var outH: Int
// lazy var outW = Int(1128)
// lazy var outH = Int(1504)
var sf: Float
lazy var bytesPerPixel = 2
lazy var outP = self.outW * self.bytesPerPixel
var outTextureDescriptor: MTLTextureDescriptor
// Set constants
// lazy var constants = MTLFunctionConstantValues()
// MARK: - Dumb stuf for clipboard/no camera usage
var shouldUseClipboardImage: Bool = false {
didSet {
if shouldUseClipboardImage {
if imageView.superview == nil {
addSubview(imageView)
let constraints = [
NSLayoutConstraint(item: imageView, attribute: .top,
relatedBy: .equal,
toItem: self, attribute: .top,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: imageView, attribute: .leading,
relatedBy: .equal,
toItem: self, attribute: .leading,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: imageView, attribute: .trailing,
relatedBy: .equal,
toItem: self, attribute: .trailing,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: imageView, attribute: .bottom,
relatedBy: .equal,
toItem: self, attribute: .bottom,
multiplier: 1, constant: 0),
]
addConstraints(constraints)
}
} else {
imageView.removeFromSuperview()
}
}
}
lazy private var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
var image: UIImage? {
get {
return imageView.image
}
set {
imageView.image = newValue
}
}
func viewPointForTexture(point: CGPoint) -> CGPoint? {
var result: CGPoint?
guard let transform = textureTranform?.inverted() else {
return result
}
let transformPoint = point.applying(transform)
if internalBounds.contains(transformPoint) {
result = transformPoint
} else {
print("Invalid point \(point) result point \(transformPoint)")
}
return result
}
func flushTextureCache() {
textureCache = nil
}
required init(coder: NSCoder) {
let metalDevice = MTLCreateSystemDefaultDevice()!
let mFilter = MPSImageLanczosScale(device: metalDevice)
let bundle = Bundle.main
let url = bundle.url(forResource: "default", withExtension: "metallib")
let library = try! metalDevice.makeLibrary(filepath: url!.path)
let function = library.makeFunction(name: "colorKernel")!
self.computePipelineState = try! metalDevice.makeComputePipelineState(function: function)
var pinW = Int(375)
var pinH = Int(754)
var poutW = Int(1128)
var poutH = Int(1504)
// poutW = pinW * 2
// poutH = pinH * 2
var psf = Float(poutH) / Float(pinH)
psf = Float(1)
var pbytesPerPixel = 2
var poutP = poutW * pbytesPerPixel
var outTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: MTLPixelFormat.rgba8Unorm, width: poutW, height: poutH, mipmapped: false)
var constants = MTLFunctionConstantValues()
constants.setConstantValue(&psf, type: MTLDataType.float, index: 0)
constants.setConstantValue(&pinW, type: MTLDataType.uint, index: 1)
constants.setConstantValue(&pinH, type: MTLDataType.uint, index: 2)
constants.setConstantValue(&poutW, type: MTLDataType.uint, index: 3)
constants.setConstantValue(&poutH, type: MTLDataType.uint, index: 4)
constants.setConstantValue(&poutP, type: MTLDataType.uint, index: 5)
let sampleMain = try! library.makeFunction(name: "BicubicMain", constantValues: constants)
let pipeline = try! metalDevice.makeComputePipelineState(function: sampleMain)
self.filter = mFilter
self.outTextureDescriptor = outTextureDescriptor
self.inW = pinW
self.inH = pinH
self.outW = poutW
self.outH = poutH
self.sf = psf
// var purl = URL(string: "com/arthur.fst.videos")!
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
var purl = paths[0].appendingPathComponent("output.mp4")
print(purl.absoluteString)
if FileManager.default.fileExists(atPath: purl.path) {
do {
try FileManager.default.removeItem(atPath: purl.path)
} catch {
fatalError("Unable to delete file: \(error) : \(#function).")
}
}
// print(FileManager.default.createFile(atPath: purl.path, contents: nil, attributes: nil))
print(FileManager.default.fileExists(atPath: purl.path))
self.url = purl
self.recorder = MetalVideoRecorder(outputURL: purl, size: CGSize(width: 1080, height: 1920))!
super.init(coder: coder)
self.preferredFramesPerSecond = 15
self.device = metalDevice
print("Should have created Metal Device")
print(self.device)
self.commandQueue = {
return self.device!.makeCommandQueue()
}()
configureMetal()
createTextureCache()
self.pipelineState = pipeline
colorPixelFormat = .bgra8Unorm
self.framebufferOnly = false
self.autoResizeDrawable = true
self.contentMode = .scaleToFill
// self.contentMode = .center
self.contentScaleFactor = UIScreen.main.scale
}
func configureMetal() {
let defaultLibrary = device!.makeDefaultLibrary()!
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineDescriptor.vertexFunction = defaultLibrary.makeFunction(name: "vertexPassThrough")
pipelineDescriptor.fragmentFunction = defaultLibrary.makeFunction(name: "fragmentPassThrough")
// To determine how textures are sampled, create a sampler descriptor to query for a sampler state from the device.
let samplerDescriptor = MTLSamplerDescriptor()
samplerDescriptor.sAddressMode = .clampToZero
samplerDescriptor.tAddressMode = .clampToZero
samplerDescriptor.minFilter = .linear
samplerDescriptor.magFilter = .linear
sampler = device!.makeSamplerState(descriptor: samplerDescriptor)
do {
renderPipelineState = try device!.makeRenderPipelineState(descriptor: pipelineDescriptor)
} catch {
fatalError("Unable to create preview Metal view pipeline state. (\(error))")
}
commandQueue = device!.makeCommandQueue()
}
func createTextureCache() {
var newTextureCache: CVMetalTextureCache?
if CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device!, nil, &newTextureCache) == kCVReturnSuccess {
textureCache = newTextureCache
} else {
assertionFailure("Unable to allocate texture cache")
}
}
/// - Tag: DrawMetalTexture
override func draw(_ rect: CGRect) {
// print(rect)
var pBuffer: CVPixelBuffer?
syncQueue.sync {
pBuffer = internalPixelBuffer
}
guard let drawable = currentDrawable,
let currentRenderPassDescriptor = currentRenderPassDescriptor,
let previewPixelBuffer = pBuffer else {
print("did not get drawable")
return
}
// Create a Metal texture from the image buffer.
let width = CVPixelBufferGetWidth(previewPixelBuffer)
let height = CVPixelBufferGetHeight(previewPixelBuffer)
// let width = Int(self.frame.size.width)
// let height = Int(self.frame.size.height)
if textureCache == nil {
createTextureCache()
}
var cvTextureOut: CVMetalTexture?
guard let ioSurfaceBacked = previewPixelBuffer.copyToMetalCompatible() else {
print("could not back pixel buffer with iosurface")
return
}
let res = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache!,
// previewPixelBuffer,
ioSurfaceBacked,
nil,
.bgra8Unorm,
// outW,
// outH,
width,
height,
0,
&cvTextureOut)
guard let cvTexture = cvTextureOut else {
print("Failed to set cvTexture from - \(cvTextureOut)")
CVMetalTextureCacheFlush(textureCache!, 0)
return
}
guard var texture = CVMetalTextureGetTexture(cvTexture) else {
print("Failed to create preview texture from \(cvTexture)")
CVMetalTextureCacheFlush(textureCache!, 0)
return
}
// print("texuter - w: \(texture.width), h: \(texture.height)")
// Set up command buffer and encoder
guard let commandQueue = commandQueue else {
print("Failed to create Metal command queue")
CVMetalTextureCacheFlush(textureCache!, 0)
return
}
guard let commandBuffer = commandQueue.makeCommandBuffer() else {
print("Failed to create Metal command buffer")
CVMetalTextureCacheFlush(textureCache!, 0)
return
}
guard let sizeCommandBuffer = commandQueue.makeCommandBuffer() else {
print("Failed to create Metal sizer command buffer")
CVMetalTextureCacheFlush(textureCache!, 0)
return
}
guard let computeCommandEncoder = commandBuffer.makeComputeCommandEncoder() else {
print("Falied to make command encoder from command buffer")
return
}
commandBuffer.addCompletedHandler { commandBuffer in
self.recorder.writeFrame(forTexture: texture)
}
// TOGGGLE
// // Set the compute pipeline state for the command encoder.
computeCommandEncoder.setComputePipelineState(computePipelineState)
// Set the compute pipeline state for the command encoder.
// computeCommandEncoder.setComputePipelineState(pipelineState!)
// Set the input and output textures for the compute shader.
// computeCommandEncoder.setTexture(destTexture, index: 0)
computeCommandEncoder.setTexture(texture, index: 0)
computeCommandEncoder.setTexture(drawable.texture, index: 1)
// Encode a threadgroup's execution of a compute function
computeCommandEncoder.dispatchThreadgroups(texture.threadGroups(), threadsPerThreadgroup: texture.threadGroupCount())
// End the encoding of the command.
computeCommandEncoder.endEncoding()
// Draw to the screen.
// print("drawable size: w - \(drawable.texture.width) h - \(drawable.texture.height)")
// let textDesc = texture2DDescriptor(pixelFormat: MTLPixelFormat.bgra8Unorm, width: outW, height: outH, mipmapped: Bool)
commandBuffer.present(drawable)
commandBuffer.commit()
}
}
|
enum TokenProtocol {
case native
case eip20
case bep2
case spl
case unsupported
}
|
//
// JankenViewController.swift
// MVCJankenApp
//
// Created by 大塚周 on 2020/12/18.
//
import UIKit
class JankenViewController: UIViewController {
//ビューの設定
private(set) lazy var jankenView: JankenView = JankenView()
//モデルの設定
var jankenModel: JankenModel? {
didSet {
print("jankenModelの値が変わり、regesterModelが実行された")
registerModel()
}
}
deinit {
jankenModel?.notificationCenter.removeObserver(self)
}
override func loadView() {
view = jankenView
}
override func viewDidLoad() {
print("viewDidLoadした")
view.backgroundColor = .white
super.viewDidLoad()
// Do any additional setup after loading the view.
}
private func registerModel() {
print("registerModelを実行 fromController")
guard let model = jankenModel else { return }
jankenView.jankenLabel.text = model.jankenHand
print("ViewのUILabelにModelのString型の変数を代入した from COntroller")
jankenView.jankenButton.addTarget(self, action: #selector(janken), for: .touchDown)
model.notificationCenter.addObserver(forName: .init(rawValue: "janken"),
object: nil,
queue: nil,
using: { [unowned self] notification in
if let jankenHand = notification.userInfo?["janken"] as? String {
self.jankenView.jankenLabel.text = jankenHand
}
})
print("「janken」というKeyを受け取った時にそのValueをViewのjankenLabelに代入するようにした from Controller")
}
@objc func janken() {
print("ボタンが押されたのでインスタンス化したjankenModelクラスのjanken()を実行するfrom Controller")
jankenModel?.janken()
}
}
|
import UIKit
import SnapKit
import ThemeKit
class DoubleSpendInfoCell: TitleCell {
private let button = ThemeButton()
private var onTap: (() -> ())?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel.font = .subhead2
titleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
contentView.addSubview(button)
button.snp.makeConstraints { maker in
maker.leading.equalTo(titleLabel.snp.trailing).offset(CGFloat.margin4x)
maker.centerY.equalToSuperview()
maker.trailing.equalTo(disclosureImageView.snp.leading)
}
button.apply(style: .secondaryDefault)
button.addTarget(self, action: #selector(onTapButton), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func onTapButton() {
onTap?()
}
func bind(title: String, hash: String?, last: Bool, onTap: (() -> ())? = nil) {
super.bind(titleIcon: nil, title: title, titleColor: .themeGray, last: last)
button.setTitle(hash, for: .normal)
self.onTap = onTap
}
}
|
//
// titleCell.swift
// NewSwift
//
// Created by gail on 2018/1/2.
// Copyright © 2018年 NewSwift. All rights reserved.
//
import UIKit
class titleCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// MenuCardCell.swift
// DevBoostItau-Project1
//
// Created by Gabriel den Hartog on 05/09/20.
// Copyright © 2020 DevBoost-Itau. All rights reserved.
//
import UIKit
class MenuCardCell: UICollectionViewCell {
static let identifier = "MenuCardCell"
let titleLabel: UILabel = {
var label = UILabel(frame: .zero)
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
label.textColor = .white
return label
}()
let subtitleLabel: UILabel = {
var label = UILabel(frame: .zero)
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
label.textColor = .white
return label
}()
let backImage: UIImageView = {
var image = UIImageView(frame: .zero)
image.alpha = 0.5
image.translatesAutoresizingMaskIntoConstraints = false
image.clipsToBounds = true
return image
}()
let containerView: UIView = {
var view = UIView(frame: .zero)
view.backgroundColor = .clear
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
// MARK: - Overrides
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.applyGradient(style: .vertical, colors: [UIColor.itiOrange, UIColor.itiPink])
self.contentView.clipsToBounds = true
self.contentView.layer.cornerRadius = 8
addSubview(containerView)
containerView.addSubview(titleLabel)
containerView.addSubview(subtitleLabel)
containerView.addSubview(backImage)
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Methods
func setupView(cardMenu: CardMenu) {
self.titleLabel.text = cardMenu.title
self.subtitleLabel.text = cardMenu.subtitle
self.backImage.image = cardMenu.image
}
func setupConstraints() {
containerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0).isActive = true
containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true
containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0).isActive = true
containerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 0).isActive = true
subtitleLabel.bottomAnchor.constraint(equalTo: subtitleLabel.superview!.bottomAnchor, constant: -8).isActive = true
subtitleLabel.leadingAnchor.constraint(equalTo: subtitleLabel.superview!.leadingAnchor, constant: 8).isActive = true
subtitleLabel.trailingAnchor.constraint(equalTo: subtitleLabel.superview!.trailingAnchor, constant: 8).isActive = true
titleLabel.bottomAnchor.constraint(equalTo: subtitleLabel.topAnchor, constant: -4).isActive = true
titleLabel.leadingAnchor.constraint(equalTo: subtitleLabel.leadingAnchor, constant: 0).isActive = true
titleLabel.trailingAnchor.constraint(equalTo: titleLabel.superview!.trailingAnchor, constant: 8).isActive = true
backImage.widthAnchor.constraint(equalToConstant: 160).isActive = true
backImage.heightAnchor.constraint(equalToConstant: 148).isActive = true
backImage.trailingAnchor.constraint(equalTo: backImage.superview!.trailingAnchor, constant: 43).isActive = true
backImage.leadingAnchor.constraint(equalTo: backImage.superview!.leadingAnchor, constant: 51).isActive = true
backImage.topAnchor.constraint(equalTo: backImage.superview!.topAnchor, constant: -36.5).isActive = true
}
}
|
//
// TabBarEnviroment.swift
// Timeless-iOS
//
// Created by Lucas Wilkinson on 7/24/20.
// Copyright © 2020 Timeless. All rights reserved.
//
import Foundation
import SwiftUI
class TabBarEnvironment: ObservableObject {
@Published private(set) var visible: Bool = true
func hideTabBar() {
if visible == true {
visible = false
}
}
func showTabBar() {
if visible == false {
visible = true
}
}
}
|
import XCTest
import UIKitFunctionsFeatureTests
var tests = [XCTestCaseEntry]()
tests += UIKitFunctionsFeatureTests.allTests()
XCTMain(tests)
|
//
// TMContactInfoFreeFormCollectionViewCell.swift
// consumer
//
// Created by Vladislav Zagorodnyuk on 9/29/16.
// Copyright © 2016 Human Ventures Co. All rights reserved.
//
import UIKit
class TMContactInfoFreeFormCollectionViewCell: UICollectionViewCell {
// Info label (age/relation)
@IBOutlet weak var infoInput: UITextField!
@IBOutlet weak var pencilIcon: UIImageView!
var gradientBorder = CAGradientLayer()
func addCellGradienBorder() {
guard let sublayers = layer.sublayers else {
return
}
if !sublayers.contains(self.gradientBorder) {
gradientBorder = addGradienBorder()
}
}
func removeGradientLayer() {
gradientBorder.removeFromSuperlayer()
}
}
|
//
// ViewController.swift
// BarChart
//
// Created by Nguyen Vu Nhat Minh on 19/8/17.
// Copyright © 2017 Nguyen Vu Nhat Minh. All rights reserved.
//
import UIKit
class HistoryViewController: UIViewController, Updatable {
var dataChart: BeautifulBarChart!
var isCurved: Bool = true
let formatter: DateFormatter = DateFormatter()
private var dataSource: DataSource?
private let low: UIColor = UIColor(hex: 0xE81123, alpha: 1.0)
private let medium: UIColor = UIColor(hex: 0xFCE100, alpha: 1.0)
private let high: UIColor = UIColor(hex: 0x6BB700, alpha: 1.0)
override func viewDidLoad() {
super.viewDidLoad()
dataSource = LumoManager.instance.getDataSource()
formatter.dateFormat = "d MMM"
isCurved = true
self.view.backgroundColor = UIColor.white
let topOffset = self.navigationController!.navigationBar.frame.height + self.navigationController!.navigationBar.frame.minY
let bottomOffset = self.tabBarController!.tabBar.frame.height
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - bottomOffset - topOffset)
dataChart = BeautifulBarChart(frame: frame)
self.view.addSubview(dataChart)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.title = "History"
// manual update
update()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// automatic update based on lumo manager timer
LumoManager.instance.updateDelegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func update() {
dataSource?.lockData()
defer { dataSource?.unlockData() }
guard let count = dataSource?.posture.count else {
return
}
let formatter = DateFormatter()
formatter.dateFormat = "d MMM"
var result: [BarEntry] = []
for i in 0..<count {
let posture = dataSource!.posture[i]
if posture == 0 {
continue
}
let date = dataSource!.dateFrom(index: i)
let color = UIColor.lerp(colorA: low, colorB: medium, colorC: high, t: CGFloat(posture))
result.append(BarEntry(color: color, height: posture, textValue: "\(Int(posture*100))%", title: formatter.string(from: date)))
}
dataChart.dataEntries = result
}
}
|
//
// for-in.while.continue .swift
// swift.sintax
//
// Created by 鳥嶋晃次 on 2019/09/23.
// Copyright © 2019 鳥嶋晃次. All rights reserved.
//
import UIKit
/* for-in.while.continue
ループ処理
終了値含まない
for 変数 in 開始値 ..< 終了値 {
ステートメント
}
終了値含む
for 変数 in 開始値 ... 終了値 {
ステートメント
}
*/
// 基本
for num in 5 ... 9 {
let value = num * 9
print(value, terminator: ",")
}
//45,54,63,72,81
print("==================================")
// 指定回数を繰り返す 乱数は 、レンジから取らない 15回乱数をとっている
//
for _ in 1 ... 15 {
let number = arc4random_uniform(100)
print(number,terminator: ",")
}
// 7,67,87,44,13,49,36,50,62,12,51,66,73,46,33,
print("==================================")
// for in のネスティング
for i in 0...2 {
for j in 0...2 {
let point = (5*i, 10*j)
print("\(i) - \(j) 回目 \(point)")
}
}
/* 0 - 0 回目 (0, 0)
0 - 1 回目 (0, 10)
0 - 2 回目 (0, 20)
1 - 0 回目 (5, 0)
1 - 1 回目 (5, 10)
1 - 2 回目 (5, 20)
2 - 0 回目 (10, 0)
2 - 1 回目 (10, 10)
2 - 2 回目 (10, 20)
*/
print("==================================")
/* コレクションの値を順に取り出す for in コレクション(配列型、辞書型)
for 変数 in コレクション {
ステートメント
}
*/
// 配列の場合 Array
let numList = [3,2,6,5,8,7,9]
var sum = 0
for num in numList {
sum += num
}
print("合計\(sum)")
// 合計40
print("==================================")
// 辞書の場合 Dictionary
let tokyometoro = ["G":"銀座線","M":"丸ノ内線","H":"日比谷線","T":"東西線","C":"千代田線","Z":"半蔵門線","N":"南北線","F":"副都心線",]
for rosen in tokyometoro {
print(rosen)
}
/* (key: "C", value: "千代田線")
(key: "N", value: "南北線")
(key: "G", value: "銀座線")
(key: "M", value: "丸ノ内線")
(key: "F", value: "副都心線")
(key: "Z", value: "半蔵門線")
(key: "T", value: "東西線")
(key: "H", value: "日比谷線")
*/
print("==================================")
// String から1文字ずつ順に取り出す
let messeage = "おもてなし"
for char in messeage {
print(char)
}
/*
お
も
て
な
し
*/
print("==================================")
/* for in stride() 飛び飛びで取り出す
for 変数 in stride(from: 開始値, to: 終了値, by: 間隔) {
ステートメント
}
*/
for num in stride(from: 10, to: 30, by: 3) { // 10 ~ 30 の中で 3つ飛ばした数を取り出す
print(num, terminator: ",")
}
// 10,13,16,19,22,25,28,
print("==================================")
/************************************************************************************/
/* 条件が満たされている間繰り返す while, repeat - while
while(ループ条件) {
ステートメント
}
*/
var tickets = 5
var power = 30
while (tickets > 0) && (power < 100) {
tickets -= 1
power += 20
}
print("power\(power),残りチケット\(tickets)")
print("==================================")
/* repeat - while
repeat {
ステートメント
} while (ループ条件)
*/
// 例 合計値が21になる3個の数値(1〜13)の組み合わせを探す
var a:UInt32, b:UInt32 ,c:UInt32
var total:UInt32
repeat {
a = arc4random_uniform(13) + 1
b = arc4random_uniform(13) + 1
c = arc4random_uniform(13) + 1
total = a + b + c
} while (total != 21)
print("\(a),\(b),\(c)")
// 5,12,4 合計値が21になる値
print("==================================")
/* 繰り返しのスキップや中断
ループの途中でその処理をスキップしたり、残りの繰り返し処理を中断できる
for, while, repeat - while で使用
*/
//スキップ continue
let vlist = [3,5,-2,6,-8,2]
var goukei = 0
for v in vlist {
// 負の値はスキップする条件
if v < 0 {
continue // 処理を中断して次の値に進む
}
goukei += v
print("\(v),")
}
print("合計:\(goukei)")
print("==================================")
// 繰り返しを中断 break
//下記の処理は無限ループするが break を実行しているので抜ける
var bangou:UInt32 = 0
//無限ループ
while true {
bangou = arc4random_uniform(100)
if bangou > 70 { // 70より大きな値が出たらぶ break する
break
}
}
print(bangou)
print("==================================")
// ループにラベルをつける
//continueやbreak で処理を中断した後につずける位置をラベル指定できる
/* 例 yloopループを中断してxloopループを続ける
for in ループがネスティングされている
外ループはxloop
内ループはyLoop
yloopの中でxがyより小さい時 continue xloop を実行する
この中断で yloopループの残りをスキップしてxloopの続きに戻る
この中断はここにbreakと書いた場合と結果が同じですが、continue xloop と書くことでコードの可能性がか上がる
*/
xloop:for x in 0...3 {
yloop:for y in 0...3 {
if (x<y) {
print("---------")
continue xloop
}
print((x,y))
}
}
// (0, 0)
// ---------
// (1, 0)
// (1, 1)
// ---------
// (2, 0)
// (2, 1)
// (2, 2)
// ---------
// (3, 0)
// (3, 1)
// (3, 2)
// (3, 3)
print("==================================")
/*内側のループから外側のループをブレイクする
例
ネスティングしたfor in を使って二重の配列の値を全て走査し、
マイナスの値が入っていたらそこでループを抜ける
break outloop のように外のループのラベルを指して break しているので
内側のループから外のループにブレイクできる(多次元配列)
*/
let flist:Array = [[4,2],[5],[9,8,10],[6,8,-9],[4,2],[9,3]] // 多次元配列
outloop: for alist in flist {
inloop:for v in alist {
if v < 0 {
print(alist)
break outloop
}
}
}
// [6, 8, -9]
|
//
// RunSetupViewController.swift
// GotHealthy
//
// Created by Josh Rosenzweig on 3/29/17.
// Copyright © 2016 Volt. All rights reserved.
//
import UIKit
import CoreLocation
import AVFoundation
class RunSetupViewController: UIViewController, UIScrollViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate{
@IBOutlet weak var GPSSignalText: UILabel!
@IBOutlet weak var runPickerView: UIPickerView!
@IBOutlet weak var walkPickerView: UIPickerView!
@IBOutlet weak var locationControl: UISegmentedControl!
@IBOutlet weak var runTimeLabel: UILabel!
@IBOutlet weak var cycleAmountButton: UIButton!
@IBOutlet weak var cycleCountLabel: UILabel!
@IBOutlet weak var walkTimeLabel: UILabel!
@IBOutlet weak var correctCycle: UIButton!
@IBOutlet weak var cancelCycle: UIButton!
@IBOutlet weak var cyclePickerView: UIPickerView!
@IBOutlet weak var runWalkRunSwitch: UISwitch!
var locationArr = [CLLocation?]()
let locationManager = CLLocationManager()
var current: CLLocation!
var outdoor = Int()
var switchState = Bool()
let switchKey = "switchState"
var GPSStrength: String = ""
var runWalkRunState = false
var runMinute = 0
var runSecond = 0
var walkMinute = 0
var walkSecond = 0
var cycleChosen = ""
var blurEffectView: UIVisualEffectView!
let pickerData = [
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
"21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39",
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60"],
["00", "15", "20", "30", "40", "45"]
]
let cycleData = ["Unlimited", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
"21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39",
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"]
let totalPages = 5
let sampleBGColors: Array<UIColor> = [UIColor.red, UIColor.yellow, UIColor.green, UIColor.magenta, UIColor.orange]
override func viewDidLoad() {
super.viewDidLoad()
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
startLocationUpdates()
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
GPSSignalText.text = GPSStrength
let font = UIFont.systemFont(ofSize: 20)
locationControl.setTitleTextAttributes([NSFontAttributeName: font],
for: UIControlState())
runTimeLabel.text = "Run Time"
walkTimeLabel.text = "Walk Time"
runPickerView.dataSource = self
runPickerView.delegate = self
walkPickerView.dataSource = self
walkPickerView.delegate = self
cyclePickerView.dataSource = self
cyclePickerView.delegate = self
runWalkRunSwitch.isOn = UserDefaults.standard.bool(forKey: "switchState")
cyclePickerView.isHidden = true
correctCycle.isHidden = true
cancelCycle.isHidden = true
if runWalkRunSwitch.isOn{
runPickerView.isHidden = false
walkPickerView.isHidden = false
runTimeLabel.isHidden = false
walkTimeLabel.isHidden = false
cycleAmountButton.isHidden = false
cycleCountLabel.isHidden = false
runWalkRunState = true
}
else{
runPickerView.isHidden = true
walkPickerView.isHidden = true
runTimeLabel.isHidden = true
walkTimeLabel.isHidden = true
cycleAmountButton.isHidden = true
cycleCountLabel.isHidden = true
runWalkRunState = false
}
}
override func viewDidAppear(_ animated: Bool) {
let runMinsLabel: UILabel = UILabel(frame: CGRect(x: -30 + (runPickerView.frame.size.width / 2), y: runPickerView.frame.size.height / 2 - 15, width: 75, height: 30))
runMinsLabel.text = "min"
runMinsLabel.textColor = UIColor.white
runPickerView.addSubview(runMinsLabel)
let runSecsLabel: UILabel = UILabel(frame: CGRect(x: 54 + (runPickerView.frame.size.width / 2), y: runPickerView.frame.size.height / 2 - 15, width: 75, height: 30))
runSecsLabel.text = "sec"
runSecsLabel.textColor = UIColor.white
runPickerView.addSubview(runSecsLabel)
self.view!.addSubview(runPickerView)
let walkMinsLabel: UILabel = UILabel(frame: CGRect(x: -30 + (walkPickerView.frame.size.width / 2), y: walkPickerView.frame.size.height / 2 - 15, width: 75, height: 30))
walkMinsLabel.text = "min"
walkMinsLabel.textColor = UIColor.white
walkPickerView.addSubview(walkMinsLabel)
let walkSecsLabel: UILabel = UILabel(frame: CGRect(x: 54 + (walkPickerView.frame.size.width / 2), y: walkPickerView.frame.size.height / 2 - 15, width: 75, height: 30))
walkSecsLabel.text = "sec"
walkSecsLabel.textColor = UIColor.white
walkPickerView.addSubview(walkSecsLabel)
self.view!.addSubview(walkPickerView)
}
@IBAction func runWalkRunSwitchPressed(_ sender: AnyObject) {
UserDefaults.standard.set(runWalkRunSwitch.isOn, forKey: "switchState")
if runWalkRunSwitch.isOn == true{
runPickerView.isHidden = false
walkPickerView.isHidden = false
runTimeLabel.isHidden = false
walkTimeLabel.isHidden = false
cycleAmountButton.isHidden = false
cycleCountLabel.isHidden = false
runWalkRunState = true
}
if runWalkRunSwitch.isOn == false{
runPickerView.isHidden = true
walkPickerView.isHidden = true
runTimeLabel.isHidden = true
walkTimeLabel.isHidden = true
cycleAmountButton.isHidden = true
cycleCountLabel.isHidden = true
runWalkRunState = false
}
}
@IBAction func cycleAmountPressed(_ sender: AnyObject) {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)
cyclePickerView.isHidden = false
view.bringSubview(toFront: cyclePickerView)
correctCycle.isHidden = false
view.bringSubview(toFront: correctCycle)
cancelCycle.isHidden = false
view.bringSubview(toFront: cancelCycle)
}
@IBAction func correctCyclePressed(_ sender: AnyObject) {
cyclePickerView.isHidden = true
correctCycle.isHidden = true
cancelCycle.isHidden = true
blurEffectView.removeFromSuperview()
cycleCountLabel.text = cycleChosen
if cyclePickerView.selectedRow(inComponent: 0) == 0 {
cycleCountLabel.text = "Unlimited"
}
}
@IBAction func cancelCyclePressed(_ sender: AnyObject) {
cyclePickerView.isHidden = true
correctCycle.isHidden = true
cancelCycle.isHidden = true
blurEffectView.removeFromSuperview()
}
@IBAction func beginButtonPressed(_ sender: AnyObject) {
if runMinute == 0 && runSecond == 0 {
let runAlert = UIAlertController(title: "Runtime Error", message: "Run Minutes and Run Seconds for Run Walk Run are set to zero. There needs to be at least 15 seconds.", preferredStyle: UIAlertControllerStyle.alert)
runAlert.addAction(UIAlertAction(title: "Change Runtime", style: .default, handler: { (action: UIAlertAction) in
}))
present(runAlert, animated: true, completion:nil)
}
if walkMinute == 0 && walkSecond == 0 {
let alert = UIAlertController(title: "Walktime Error", message: "Walk Minutes and Walk Seconds for Run Walk Run are set to zero. There needs to be at least 15 seconds.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Change Walktime", style: .default, handler: { (action: UIAlertAction) in
}))
present(alert, animated: true, completion:nil)
}
}
func startLocationUpdates() {
// Here, the location manager will be lazily instantiated
locationManager.startUpdatingLocation()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination.isKind(of: NewRunViewController.self) {
if let newRunViewController = segue.destination as? NewRunViewController {
newRunViewController.runWalkStatus = runWalkRunState
if runWalkRunSwitch.isOn{
if runMinute == 0 && runSecond == 0 {
let runAlert = UIAlertController(title: "Runtime Error", message: "Run Minutes and Run Seconds for Run Walk Run are set to zero. There needs to be at least 15 seconds.", preferredStyle: UIAlertControllerStyle.alert)
runAlert.addAction(UIAlertAction(title: "Change Runtime", style: .default, handler: { (action: UIAlertAction) in
}))
present(runAlert, animated: true, completion:nil)
}
if walkMinute == 0 && walkSecond == 0 {
let alert = UIAlertController(title: "Walktime Error", message: "Walk Minutes and Walk Seconds for Run Walk Run are set to zero. There needs to be at least 15 seconds.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Change Walktime", style: .default, handler: { (action: UIAlertAction) in
}))
present(alert, animated: true, completion:nil)
}
newRunViewController.runMinutes = runMinute
newRunViewController.runSeconds = runSecond
newRunViewController.walkMinutes = walkMinute
newRunViewController.walkSeconds = walkSecond
newRunViewController.location = outdoor
newRunViewController.cycleCount = cycleCountLabel.text!
}
}
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
// Store users initial location - necessary for distance traveled
if locationArr.count != 1 {
self.locationArr.append(userLocation)
}
for location in locations {
if location.horizontalAccuracy < 0 {
//update distance
if (location.horizontalAccuracy < 0)
{
GPSSignalText.text = "No Signal"
print("Checking")
}
else if (location.horizontalAccuracy > 163)
{
GPSSignalText.text = "Poor Signal"
}
else if (location.horizontalAccuracy > 48)
{
GPSSignalText.text = "Average Signal"
}
else
{
GPSSignalText.text = "Full Signal"
}
}
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
if pickerView == cyclePickerView{
return 1
}
return pickerData.count
}
func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == cyclePickerView{
cycleChosen = cycleData[row]
}
switch component{
case 0:
if pickerView == runPickerView {
self.runMinute = Int(pickerData[component][row])!
}
if pickerView == walkPickerView {
self.walkMinute = Int(pickerData[component][row])!
}
case 1:
if pickerView == runPickerView {
self.runSecond = Int(pickerData[component][row])!
}
if pickerView == walkPickerView {
self.walkSecond = Int(pickerData[component][row])!
}
default:
print("No components available")
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == cyclePickerView{
return cycleData[row]
}
return pickerData[component][row]
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView
{
let pickerLabel = UILabel()
if pickerView == cyclePickerView{
pickerLabel.textColor = UIColor.white
pickerLabel.text = cycleData[row]
pickerLabel.font = UIFont(name: "Arial-BoldMT", size: 26)
pickerLabel.textAlignment = NSTextAlignment.center
return pickerLabel
}
pickerLabel.textColor = UIColor.white
pickerLabel.text = pickerData[component][row]
// pickerLabel.font = UIFont(name: pickerLabel.font.fontName, size: 15)
pickerLabel.font = UIFont(name: "Arial-BoldMT", size: 18)
pickerLabel.textAlignment = NSTextAlignment.center
return pickerLabel
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == cyclePickerView{
print("Cycle Data 3")
return cycleData.count
}
return pickerData[component].count
}
}
|
//
// PlayerActions.swift
// Little Orion
//
// Created by Thomas Ricouard on 21/01/2017.
// Copyright © 2017 Thomas Ricouard. All rights reserved.
//
import Foundation
import ReSwift
class PlayerActions {
struct Initialize: Action {}
struct StartTimer: Action {
var timer: Timer!
var currentDate: Date!
init() {
self.currentDate = store.state.playerState.currentDate
let speed = store.state.playerState.currentSpeed
var copy = self
self.timer = Timer.scheduledTimer(withTimeInterval: speed.rawValue, repeats: true, block: { (timer) in
if store.state.playerState.isPlaying {
store.dispatch(UpdateTimer(timer: timer))
copy.currentDate = store.state.playerState.currentDate
if Calendar.current.isDate(copy.currentDate, equalTo: copy.endOfMonth(), toGranularity: .day) {
store.dispatch(UpdateTimerMonth(timer: timer))
}
}
})
}
func startOfMonth() -> Date {
return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month],
from: Calendar.current.startOfDay(for:
currentDate)))!
}
func endOfMonth() -> Date {
return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth())!
}
}
struct UpdateSpeed: Action {
let speed: PlayerSpeed
init(speed: PlayerSpeed) {
self.speed = speed
// Hacky workaround to wait for the init to be done so the state is up to date when restarting the timer.
// Will do better later.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
store.dispatch(PauseTimer())
store.dispatch(StartTimer())
}
}
}
struct UpdateTimer: Action {
let timer: Timer
init(timer: Timer) {
self.timer = timer
}
}
struct UpdateTimerMonth: Action {
let timer: Timer
init(timer: Timer) {
self.timer = timer
}
}
struct MoveToPosition: Action {
let movement: PlayerMovementComponent
}
struct UpdatePosition: Action {
let position: CGPoint
}
struct startDiscoveryUniverseEntity: Action {
let entity: UniverseId
}
struct StopMovement: Action {}
struct PauseTimer: Action {
}
}
|
//
// Created by Pavel Sharanda on 10/29/19.
// Copyright © 2019 Jetpack. All rights reserved.
//
import Foundation
@propertyWrapper
public struct Atomic<T> {
private let queue = DispatchQueue(label: "Atomic.queue")
private var _value: T
public init(wrappedValue: T) {
_value = wrappedValue
}
public var wrappedValue: T {
set {
queue.sync { self._value = newValue }
}
get {
return queue.sync { self._value }
}
}
}
|
//
// RandomEnemyGenerator.swift
// Session1
//
// Created by Developer on 11/13/16.
// Copyright © 2016 Developer. All rights reserved.
//
import SpriteKit
import Foundation
class RandomEnemyGenerator {
weak var parent: SKScene!
var hardcoreMode = false {
didSet {
for enemyController in RandomEnemyGenerator.activeEnemyControllers {
(enemyController as? EnemyController)?.isTargetingPlayer = self.hardcoreMode
}
}
}
static var activeEnemyControllers = [PlaneController]()
deinit {
print("bye Random Enemy Generator")
RandomEnemyGenerator.activeEnemyControllers.removeAll()
}
init(parent: SKScene) {
self.parent = parent
}
func generate(interval: Double) {
let add = SKAction.run { [unowned self] in
var enemyController: PlaneController
switch arc4random_uniform(10) {
case 0...2:
enemyController = EnemyController(parent: self.parent)
(enemyController as! EnemyController).set(customTexture: nil)
case 3...5:
enemyController = EnemyDiagonalController(parent: self.parent)
(enemyController as! EnemyDiagonalController).set(isFromLeft: nil)
case 6...8:
enemyController = EnemyAnimatedController(parent: self.parent)
(enemyController as! EnemyAnimatedController).set(customAnimation: nil)
default:
enemyController = GiftPlaneController(parent: self.parent)
(enemyController as! GiftPlaneController).set(customTexture: nil)
}
(enemyController as? EnemyController)?.isTargetingPlayer = self.hardcoreMode
if self.hardcoreMode {
(enemyController as? EnemyController)?.FIRING_INTERVAL = ((enemyController as? EnemyController)?.FIRING_INTERVAL)! / 2
}
enemyController.spawn()
}
let delay = SKAction.wait(forDuration: interval)
parent.run(.repeatForever(.sequence([add, delay])))
}
}
|
//
// MarkdownViewController.swift
// Umbrella
//
// Created by Lucas Correa on 21/09/2018.
// Copyright © 2018 Security First. All rights reserved.
//
import UIKit
import WebKit
import SafariServices
class MarkdownViewController: UIViewController {
//
// MARK: - Properties
lazy var markdownViewModel: MarkdownViewModel = {
let markdownViewModel = MarkdownViewModel()
return markdownViewModel
}()
var isLoading: Bool = false
@IBOutlet weak var markdownWebView: MarkdownWebView!
//
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.markdownWebView.isHidden = true
self.markdownWebView.navigationDelegate = self
}
//
// MARK: - Functions
/// Load Markdown
func loadMarkdown() {
if self.isLoading {
return
}
self.isLoading = true
if let segment = self.markdownViewModel.segment {
self.title = segment.name
if let documentsPathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
var path = documentsPathURL.absoluteString
path.removeLast()
path = path.replacingOccurrences(of: "file://", with: "")
let results = searchForFileString(content: segment.content!)
if let results = results {
for file in results {
if !checkIfExistFile(file: file) {
changeFileToDefaultLanguange(content: &segment.content!, file: file)
}
}
}
segment.content = segment.content?.replacingOccurrences(of: "#DOCUMENTS", with: path)
let html = HTML(nameFile: "index.html", content: segment.content!)
html.prepareHtmlWithStyle()
let export = Export(html)
let url = export.makeExport()
//Load html
self.markdownWebView.loadFileURL(url, allowingReadAccessTo: documentsPathURL)
}
}
}
/// Search for file string in content
///
/// - Parameter content: String
/// - Returns: [String]
fileprivate func searchForFileString(content: String) -> [String]? {
do {
let regex = try NSRegularExpression(pattern:"\\(#DOCUMENTS([^)]+)\\)", options: [])
var results = [String]()
regex.enumerateMatches(in: content, options: [], range: NSRange(location: 0, length: content.utf16.count)) { result, flags, stop in
if let result = result?.range(at: 1), let range = Range(result, in: content) {
results.append(String(content[range]))
}
}
return results
} catch {
print(error)
return nil
}
}
/// Change file string to the default language EN
///
/// - Parameters:
/// - content: String
/// - file: String
fileprivate func changeFileToDefaultLanguange(content: inout String, file: String?) {
if let file = file {
let language = file.components(separatedBy: "/")[1]
content = content.replacingOccurrences(of: file, with: file.replacingOccurrences(of: "/\(language)/", with: "/en/"))
}
}
/// Check if exist file in documents
///
/// - Parameter file: String
/// - Returns: Bool
fileprivate func checkIfExistFile(file: String) -> Bool {
if file.contains("/en/") {
return true
}
let fileManager = FileManager.default
let documentsUrl = fileManager.urls(for: .documentDirectory,
in: .userDomainMask)
guard documentsUrl.count != 0 else {
return false
}
let finalDatabaseURL = documentsUrl.first!.appendingPathComponent(file)
if ( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
return true
}
return false
}
}
extension MarkdownViewController : WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.markdownWebView.isHidden = false
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: ((WKNavigationActionPolicy) -> Void)) {
switch navigationAction.navigationType {
case .linkActivated:
if navigationAction.request.url?.scheme == "umbrella" {
UIApplication.shared.open(navigationAction.request.url!)
} else {
if (navigationAction.request.url?.scheme?.contains("http"))! {
let safariViewController = SFSafariViewController(url: navigationAction.request.url!)
safariViewController.delegate = self
UIApplication.shared.delegate!.window?!.rootViewController!.present(safariViewController, animated: true)
}
decisionHandler(.cancel)
return
}
default:
break
}
decisionHandler(.allow)
}
}
extension MarkdownViewController: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
dismiss(animated: true)
}
}
|
//
// ViewController.swift
// project
//
// Created by Tanatchaya K on 16/10/2563 BE.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
//test 2
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
|
//
// CoordinateTests.swift
// Test
//
// Created by Shawn Veader on 12/6/18.
// Copyright © 2018 Shawn Veader. All rights reserved.
//
import XCTest
class CoordinateTests: XCTestCase {
func testManhattanDistance() {
XCTAssertEqual(10, Coordinate(x: 0, y: 0).distance(to: Coordinate(x: 5, y: 5)))
XCTAssertEqual(10, Coordinate(x: 0, y: 0).distance(to: Coordinate(x: -5, y: 5)))
XCTAssertEqual(10, Coordinate(x: 0, y: 0).distance(to: Coordinate(x: -5, y: -5)))
}
}
|
//
// UChapterCell.swift
// U17
//
// Created by PT iOS Mac on 2020/9/7.
// Copyright © 2020 PT iOS Mac. All rights reserved.
//
import UIKit
import SnapKit
class UChapterCollectionCell: UICollectionViewCell {
lazy var nameLabel: UILabel = {
let nl = UILabel()
nl.font = .systemFont(ofSize: 16)
return nl
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.initSubViews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initSubViews() {
contentView.backgroundColor = UIColor.white
layer.cornerRadius = 5
layer.borderWidth = 1
layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor
layer.masksToBounds = true
contentView.addSubview(nameLabel)
nameLabel.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)) }
}
}
class UChapterCell: UITableViewCell {
var rightBtnBlock :(()->Void)?
var clickItemBlock :(([ChapterListModel],Int)->Void)?
lazy var leftTitle: UILabel = {
let lt = UILabel.init()
lt.font = .systemFont(ofSize: 16)
lt.textColor = .black
return lt
}()
private lazy var rightBtn: UIButton = {
let rt = UIButton.init(type: .custom)
rt.setTitle("全部目录", for: .normal)
rt.setTitleColor(.black, for: .normal)
rt.titleLabel?.font = .systemFont(ofSize: 13)
rt.addTarget(self, action: #selector(clickRightBtn), for: .touchUpInside)
rt.isUserInteractionEnabled = false
return rt
}()
private lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 10)
layout.minimumInteritemSpacing = 5
layout.minimumLineSpacing = 10
layout.itemSize = CGSize(width: floor((screenWidth - 30) / 2), height: 40)
let ct = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
ct.backgroundColor = .white
ct.delegate = self
ct.dataSource = self
ct.register(UChapterCollectionCell.self, forCellWithReuseIdentifier: "UChapterCollectionCell")
return ct
}()
var modelArr :[ChapterListModel] = []{
didSet{
guard modelArr.count > 0 else { return }
self.collectionView.reloadData()
self.rightBtn.isUserInteractionEnabled = true
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initSubViews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initSubViews() {
contentView.addSubview(leftTitle)
contentView.addSubview(rightBtn)
contentView.addSubview(collectionView)
leftTitle.snp.makeConstraints { (make) in
make.left.equalTo(contentView).offset(20)
make.top.equalTo(contentView).offset(10)
}
rightBtn.snp.makeConstraints { (make) in
make.centerY.equalTo(leftTitle)
make.right.equalTo(contentView).offset(-20)
}
collectionView.snp.makeConstraints { (make) in
make.top.equalTo(leftTitle.snp.bottom).offset(10)
make.left.right.equalTo(contentView)
make.height.equalTo(100)
make.bottom.equalTo(contentView)
}
}
@objc func clickRightBtn() {
if let block = self.rightBtnBlock {
block()
}
}
}
extension UChapterCell:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return modelArr.count>4 ?4:modelArr.count
}
// func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
// return CGSize(width: screenWidth, height: 44)
// }
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UChapterCollectionCell", for: indexPath) as! UChapterCollectionCell
cell.nameLabel.text = modelArr[indexPath.item].name
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(modelArr[indexPath.item].name ?? "")
if let block = self.clickItemBlock {
block(modelArr,indexPath.item)
}
}
}
|
//
// SWBPlan.swift
// SweepBright
//
// Created by Kaio Henrique on 1/19/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import Foundation
class SWBPlanClass: NSObject, SWBPlan {
var surfaces: [SWBSurface] = []
var image: UIImage!
init(surfaces: [SWBSurface]=[], image: UIImage?=nil) {
super.init()
self.image = image
self.surfaces = surfaces
}
}
|
//
// GPPhoto.swift
// GPlaceAPI-Swift
//
// Created by Darshan Patel on 7/23/15.
// Copyright (c) 2015 Darshan Patel. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Darshan Patel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class GPPhoto {
var height: Int?
var html_attributions: [String]?
var photo_reference: String?
var width: Int?
var photo_url: String?
init(attributes: Dictionary<String, AnyObject>)
{
if let height = attributes["height"] as? Int
{
self.height = height;
}
if let html_attributions = attributes["html_attributions"] as? Array<String>
{
self.html_attributions = html_attributions;
}
if let photo_reference = attributes["photo_reference"] as? String
{
self.photo_reference = photo_reference;
}
if let width = attributes["width"] as? Int
{
self.width = width;
}
self.photo_url = "\(GPlaceConstants.kAPI_PLACES_URL)photo?maxwidth=\(self.width)&maxheight=\(self.height)&photoreference=\(self.photo_reference)&key=\(GPlaceAPISetup.sharedInstance.getApi_key())"
}
func getPhotoUrl(maxWidth: Int, maxHeight: Int) -> String
{
var url = "\(GPlaceConstants.kAPI_PLACES_URL)photo?maxwidth=\(maxWidth)&maxheight=\(maxHeight)&photoreference=\(self.photo_reference)&key=\(GPlaceAPISetup.sharedInstance.getApi_key())"
return url
}
} |
class Vehicle {
var numberOfWheels: Int?
var color: String?
var doors: Int?
init(numberOfWheels wheels: Int, andColor color: String) {
//ahhhh okay, we dont need to unwrap yet I'm guessing because
//the values havent been set, therefore we give it a value.
//My hypothesis is that if we, in a later function, change the values,
//we still wont have to unwrap the values?
numberOfWheels = wheels
self.color = color
doors = 0
}
init(numberOfWheels wheels: Int, andColor color:String, andDoors doors:Int) {
numberOfWheels = wheels
self.color = color
self.doors = doors
}
func printInfo() {
println("This vehicle has \(numberOfWheels!) wheels and is \(color!) and has \(doors!) doors")
}
func changeProperties(numWheels: Int, color: String, doors: Int) {
numberOfWheels = numWheels
self.color = color
self.doors = doors
}
}
var toyota = Vehicle(numberOfWheels: 0, andColor: "Red", andDoors: 3)
var numberOfDoors: Int? = 4
toyota.changeProperties(1, color: "Blue", doors: numberOfDoors!)
toyota.printInfo()
//OKAY SO HERES WHATS GOING ON:
//when you call initializers, you actually have to list out all the parts of the function (i.e. numberOfWheels:andColor)
//when you call a function, you have to list out the parameter names for all parameters except the first
//Optionals review:
//If you have var varName: someType?,
//you can always assign it a value of someType normally
//you are forced to unwrap only when you are accessing the value,
//so if i wanted to assigned to varName var otherVar: someType?, i couldnt do
//varName = someType <-- because then I'd be assigning an optional. We always want either
//a someType value or nil. So we'd unwrap otherVar.
//additionally, check our printInfo() - we want to print whats within the optionals
//so we unwrap it - to access the value
|
//
// CarListItemViewModel.swift
// CarFun
//
// Created by Andrei Konstantinov on 18/06/2019.
// Copyright © 2019 Test. All rights reserved.
//
struct CarListItemViewModel {
let model: String
let name: String
let licensePlate: String
let fuelLevel: String
let innerCleanliness: String
let imageURL: String
}
|
//
// SearchIndexViewController.swift
// 美团
//
// Created by wxqdev on 15/6/8.
// Copyright (c) 2015年 meituan.iteasysoft.com. All rights reserved.
//
import UIKit
class SearchIndexViewController: WebBaseViewController ,UISearchBarDelegate{
var searchBar = UISearchBar()
override func viewDidLoad() {
url = "http://www.test.com18.cn/grwsj/product.htm"
myWebView = self.webView
super.viewDidLoad()
searchBar.delegate = self
self.navigationItem.titleView = searchBar
searchBar.placeholder = "搜索商品"
var btnSearch = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
btnSearch.frame = CGRectMake(0, 0, 64, 32);
btnSearch.setTitle("搜索", forState: UIControlState.Normal)
//btnSearch.setBackgroundImage(UIImage(named: "fh"), forState: UIControlState.Normal)
btnSearch.addTarget(self, action: "onClickSearch:", forControlEvents: UIControlEvents.TouchUpInside)
var rightBarButtonItem = UIBarButtonItem(customView:btnSearch)
self.navigationItem.rightBarButtonItem = rightBarButtonItem
}
func onClickSearch(sender: UIViewController) {
var txts = searchBar.text
//txts = "百度"
if txts == ""{
url = "http://www.test.com18.cn/grwsj/product.htm"
}
else{
var customAllowedSet = NSCharacterSet.URLQueryAllowedCharacterSet()
if let escapedTxt = txts.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet){
url = "http://www.test.com18.cn/grwwx/search.jsp?w=\(escapedTxt)"
}
else{
url = "http://www.test.com18.cn/grwwx/search.jsp?w=\(txts)"
}
println("\(url)")
// url = NSString(format: "http://www.test.com18.cn/grwwx/search.jsp?w=\(txt)") as String
}
loadurl()
}
@IBOutlet weak var webView: UIWebView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
println("Search btn clicked")
searchBar.resignFirstResponder()
// var searchtext = searchBar.text
// doSearch(searchBar,searchtext:searchtext)
// keyboard.endEditing()
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar){
println("Search btn searchBarTextDidBeginEditing")
// let dvc = self.storyboard?.instantiateViewControllerWithIdentifier("searchindexview") as! SearchIndexViewController
// dvc.navigationController?.title = "搜索"
// dvc.url = "http://i.meituan.com/s/?cevent=imt%2Fhomepage%2Fsearch"
// self.navigationController?.pushViewController(dvc, animated: true)
}
func searchBar(searchBar: UISearchBar,textDidChange searchText: String){
doSearch(searchBar,searchtext:searchText)
}
func doSearch(searchBar: UISearchBar,var searchtext :String){
if searchtext == ""{
url = "http://www.test.com18.cn/grwsj/product.htm"
let requestURL = NSURL(string:url)
let request = NSURLRequest(URL: requestURL!)
webView.loadRequest(request)
}
}
}
|
import Foundation
import Arweave
import KeychainAccess
var keychain: Keychain? = {
guard let appIdPrefix = Bundle.main.infoDictionary!["AppIdentifierPrefix"] as? String else { return nil }
return Keychain(service: "com.reikam.arweave-wallets", accessGroup: "\(appIdPrefix)com.reikam.shared")
}()
private var allWallets: [Wallet] {
let data = keychain?.allKeys().compactMap { try? keychain?.getData($0) } ?? []
return data.compactMap {
try? JSONDecoder().decode(Wallet.self, from: $0)
}.sorted(by: <)
}
extension Wallet: Identifiable {
public var id: String { String(describing: address) }
}
class WalletPersistence: ObservableObject {
@Published private(set) var wallets: [Wallet]
init() {
wallets = allWallets
}
func add(_ wallet: Wallet) throws {
let encoded = try JSONEncoder().encode(wallet)
try keychain?.set(encoded, key: wallet.id)
wallets = allWallets
}
func remove(_ wallet: Wallet) throws {
try keychain?.remove(wallet.id)
wallets = allWallets
}
}
|
//
// MemeCollectionViewCellControllerCollectionViewCell.swift
// MemeMe_2
//
// Created by Apple on 09/12/17.
// Copyright © 2017 Apple. All rights reserved.
//
import UIKit
class MemeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var memeCellImage: UIImageView!
}
|
import Foundation
extension Date {
var isoDateShort: String {
return stringDate(with: "YYYY")
}
private func stringDate(with format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "pt_BR")
dateFormatter.timeZone = TimeZone(abbreviation: "BRST")
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
|
//
// Copyright © 2020 Tasuku Tozawa. All rights reserved.
//
import Combine
/// @mockable
public protocol TagListQuery {
var tags: CurrentValueSubject<[Domain.Tag], Error> { get }
}
|
//
// UserService.swift
// gv24App
//
// Created by Nguyen Duy Duong on 5/22/17.
// Copyright © 2017 HBBs. All rights reserved.
//
import UIKit
import CoreLocation
import SwiftyJSON
import Alamofire
class UserService: APIService {
static let sharedInstance = UserService()
func logIn(userName : String, password: String,device_token:String, completion : @escaping ((User?, String?, String?)->())){
let params : Dictionary<String, String>? = ["username": userName, "password": password,"device_token":device_token]
postMultipart(url: APIPaths().login(), image: nil, name: nil, parameters: params!) { (jsonData, error) in
if error == nil{
let token = jsonData?["token"].string
let user = User(json: (jsonData?["user"])!)
completion(user,token,nil)
}else{
completion(nil, nil, error)
}
}
}
func register(info: Dictionary<String, String>, avatar: UIImage, completion : @escaping ((User?, String?, String?)->())){
let url = "auth/register"
postMultipart(url: url, image: avatar, name: "image", parameters: info) { (jsonData, error) in
if error == nil{
let token = jsonData?["token"].string
let user = User(json: (jsonData?["user"])!)
completion(user,token , nil)
}else{
completion(nil, nil, error)
}
}
}
}
|
//
// FlowManager+Notifications.swift
// CoAssetsApps
//
// Created by Linh NGUYEN on 3/17/16.
// Copyright © 2016 TruongVO07. All rights reserved.
//
import UIKit
extension FlowManager {
func openWebView(urlString url: String, title: String) {
guard let topController = UIApplication.topViewController() else {
return
}
if topController.isKindOfClass(WebViewController) {
(topController as? WebViewController)!.webLink = url
(topController as? WebViewController)!.loadWebView()
} else {
let webView = WebViewController.vc()
webView.webLink = url
webView.title = title
let baseNAV = BaseNavigationController()
baseNAV.viewControllers.append(webView)
UIApplication.topViewController()?.presentViewController(baseNAV, animated: true, completion: { () -> Void in
webView.loadWebView()
})
}
}
func openOfferDetailIfNeeded(offerId: NSInteger) {
if let topView = UIApplication.topViewController() {
if topView.isKindOfClass(WebViewController) {
topView.dismissViewControllerAnimated(true, completion: { () -> Void in
self.menu?.openOfferDetail(offerId)
})
} else {
self.menu?.openOfferDetail(offerId)
}
} else {
self.menu?.openOfferDetail(offerId)
}
}
func showNotificationView(alert: String?, message: String?, args: AnyObject?) {
bannerView.delegate = self
bannerView.textMessage = message
bannerView.textMessage = alert
bannerView.args = args
let tag = UIApplication.sharedApplication().keyWindow?.tag
if tag == BannerViewTag.tagView {
bannerView.delayPerform()
} else {
bannerView.show(isWillShow: nil)
}
}
}
//MARK: CONotificationBannerViewDelegate
extension FlowManager: CONotificationBannerViewDelegate {
func actionTapBannerView(notificationView: CONotificationBannerView, args: AnyObject?) {
print(args)
if let userInfo = args as? [NSObject: AnyObject] {
NotificationsManager.shared.performAppleNotificationAction(userInfo)
}
}
}
|
// DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: WordTagger.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Copyright (c) 2018, Apple Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-3-clause license that can be
// found in LICENSE.txt or at https://opensource.org/licenses/BSD-3-Clause
import Foundation
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: ProtobufAPIVersionCheck {
struct _2: ProtobufAPIVersion_2 {}
typealias Version = _2
}
///*
/// A model which takes a single input string and outputs a
/// sequence of tokens, tags for tokens, along with their
/// locations and lengths, in the original string.
struct CoreML_Specification_CoreMLModels_WordTagger {
// Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
///
/// Stores the resivion number for the model, revision 1 is available on
/// iOS, tvOS 12.0+, macoOS 10.14+
var revision: UInt32 {
get {return _storage._revision}
set {_uniqueStorage()._revision = newValue}
}
///
/// Stores the language of the model, as specified in BCP-47 format,
/// e.g. "en-US". See https://tools.ietf.org/html/bcp47
var language: String {
get {return _storage._language}
set {_uniqueStorage()._language = newValue}
}
///
/// Stores the name of tokens output. The output will be
/// a sequence of strings that contains the tokens in the
/// input string
var tokensOutputFeatureName: String {
get {return _storage._tokensOutputFeatureName}
set {_uniqueStorage()._tokensOutputFeatureName = newValue}
}
///
/// Stores the name of token tags output. The output will be
/// a sequence of strings that contains the tags for each
/// token in the input string
var tokenTagsOutputFeatureName: String {
get {return _storage._tokenTagsOutputFeatureName}
set {_uniqueStorage()._tokenTagsOutputFeatureName = newValue}
}
///
/// Stores the name of token locations output. The output will be
/// a sequence of integers that contains the locations (indices)
/// for each token in the input string, location starts from 0
var tokenLocationsOutputFeatureName: String {
get {return _storage._tokenLocationsOutputFeatureName}
set {_uniqueStorage()._tokenLocationsOutputFeatureName = newValue}
}
///
/// Stores the name of token lengths output. The output will be
/// a sequence of integers that contains the lengths for each
/// token in the input string
var tokenLengthsOutputFeatureName: String {
get {return _storage._tokenLengthsOutputFeatureName}
set {_uniqueStorage()._tokenLengthsOutputFeatureName = newValue}
}
///
/// Stores the byte representation of learned model parameters
var modelParameterData: Data {
get {return _storage._modelParameterData}
set {_uniqueStorage()._modelParameterData = newValue}
}
///
/// Stores the set of output tags
var tags: OneOf_Tags? {
get {return _storage._tags}
set {_uniqueStorage()._tags = newValue}
}
var stringTags: CoreML_Specification_StringVector {
get {
if case .stringTags(let v)? = _storage._tags {return v}
return CoreML_Specification_StringVector()
}
set {_uniqueStorage()._tags = .stringTags(newValue)}
}
var unknownFields = UnknownStorage()
///
/// Stores the set of output tags
enum OneOf_Tags: Equatable {
case stringTags(CoreML_Specification_StringVector)
#if !swift(>=4.1)
static func ==(lhs: CoreML_Specification_CoreMLModels_WordTagger.OneOf_Tags, rhs: CoreML_Specification_CoreMLModels_WordTagger.OneOf_Tags) -> Bool {
switch (lhs, rhs) {
case (.stringTags(let l), .stringTags(let r)): return l == r
}
}
#endif
}
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "CoreML.Specification.CoreMLModels"
extension CoreML_Specification_CoreMLModels_WordTagger: Message, _MessageImplementationBase, _ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".WordTagger"
static let _protobuf_nameMap: _NameMap = [
1: .same(proto: "revision"),
10: .same(proto: "language"),
20: .same(proto: "tokensOutputFeatureName"),
21: .same(proto: "tokenTagsOutputFeatureName"),
22: .same(proto: "tokenLocationsOutputFeatureName"),
23: .same(proto: "tokenLengthsOutputFeatureName"),
100: .same(proto: "modelParameterData"),
200: .same(proto: "stringTags"),
]
fileprivate class _StorageClass {
var _revision: UInt32 = 0
var _language: String = String()
var _tokensOutputFeatureName: String = String()
var _tokenTagsOutputFeatureName: String = String()
var _tokenLocationsOutputFeatureName: String = String()
var _tokenLengthsOutputFeatureName: String = String()
var _modelParameterData: Data = Internal.emptyData
var _tags: CoreML_Specification_CoreMLModels_WordTagger.OneOf_Tags?
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_revision = source._revision
_language = source._language
_tokensOutputFeatureName = source._tokensOutputFeatureName
_tokenTagsOutputFeatureName = source._tokenTagsOutputFeatureName
_tokenLocationsOutputFeatureName = source._tokenLocationsOutputFeatureName
_tokenLengthsOutputFeatureName = source._tokenLengthsOutputFeatureName
_modelParameterData = source._modelParameterData
_tags = source._tags
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularUInt32Field(value: &_storage._revision)
case 10: try decoder.decodeSingularStringField(value: &_storage._language)
case 20: try decoder.decodeSingularStringField(value: &_storage._tokensOutputFeatureName)
case 21: try decoder.decodeSingularStringField(value: &_storage._tokenTagsOutputFeatureName)
case 22: try decoder.decodeSingularStringField(value: &_storage._tokenLocationsOutputFeatureName)
case 23: try decoder.decodeSingularStringField(value: &_storage._tokenLengthsOutputFeatureName)
case 100: try decoder.decodeSingularBytesField(value: &_storage._modelParameterData)
case 200:
var v: CoreML_Specification_StringVector?
if let current = _storage._tags {
try decoder.handleConflictingOneOf()
if case .stringTags(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {_storage._tags = .stringTags(v)}
default: break
}
}
}
}
func traverse<V: Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if _storage._revision != 0 {
try visitor.visitSingularUInt32Field(value: _storage._revision, fieldNumber: 1)
}
if !_storage._language.isEmpty {
try visitor.visitSingularStringField(value: _storage._language, fieldNumber: 10)
}
if !_storage._tokensOutputFeatureName.isEmpty {
try visitor.visitSingularStringField(value: _storage._tokensOutputFeatureName, fieldNumber: 20)
}
if !_storage._tokenTagsOutputFeatureName.isEmpty {
try visitor.visitSingularStringField(value: _storage._tokenTagsOutputFeatureName, fieldNumber: 21)
}
if !_storage._tokenLocationsOutputFeatureName.isEmpty {
try visitor.visitSingularStringField(value: _storage._tokenLocationsOutputFeatureName, fieldNumber: 22)
}
if !_storage._tokenLengthsOutputFeatureName.isEmpty {
try visitor.visitSingularStringField(value: _storage._tokenLengthsOutputFeatureName, fieldNumber: 23)
}
if !_storage._modelParameterData.isEmpty {
try visitor.visitSingularBytesField(value: _storage._modelParameterData, fieldNumber: 100)
}
if case .stringTags(let v)? = _storage._tags {
try visitor.visitSingularMessageField(value: v, fieldNumber: 200)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: CoreML_Specification_CoreMLModels_WordTagger, rhs: CoreML_Specification_CoreMLModels_WordTagger) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._revision != rhs_storage._revision {return false}
if _storage._language != rhs_storage._language {return false}
if _storage._tokensOutputFeatureName != rhs_storage._tokensOutputFeatureName {return false}
if _storage._tokenTagsOutputFeatureName != rhs_storage._tokenTagsOutputFeatureName {return false}
if _storage._tokenLocationsOutputFeatureName != rhs_storage._tokenLocationsOutputFeatureName {return false}
if _storage._tokenLengthsOutputFeatureName != rhs_storage._tokenLengthsOutputFeatureName {return false}
if _storage._modelParameterData != rhs_storage._modelParameterData {return false}
if _storage._tags != rhs_storage._tags {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
|
//
// InforCell.swift
// GV24
//
// Created by HuyNguyen on 5/31/17.
// Copyright © 2017 admin. All rights reserved.
//
import UIKit
import IoniconsSwift
class InforCell: CustomTableViewCell {
var buttons:[UIButton]?
@IBOutlet weak var bottomAge: NSLayoutConstraint!
@IBOutlet weak var topHeightAge: NSLayoutConstraint!
@IBOutlet weak var vViewAge: UIView!
@IBOutlet weak var contraintAge: NSLayoutConstraint!
@IBOutlet weak var lbName: UILabel!
@IBOutlet var btRating: [UIButton]?{
didSet{
getStar()
}
}
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var imageAddress: UIButton!
@IBOutlet weak var imagePhone: UIButton!
@IBOutlet weak var ImageGender: UIButton!
@IBOutlet weak var imageAge: UIButton!
@IBOutlet weak var lbAddress: UILabel!
@IBOutlet weak var lbPhone: UILabel!
@IBOutlet weak var lbAge: UILabel!
@IBOutlet weak var lbGender: UILabel!
@IBOutlet weak var imageProfile: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
avatar.layer.cornerRadius = avatar.frame.size.width/2
avatar.clipsToBounds = true
avatar.layer.borderWidth = 1
avatar.layer.borderColor = UIColor.white.cgColor
lbName.textColor = UIColor.white
DispatchQueue.main.async {
self.avatar.image = UIImage(named: "avatar")
}
let imagegender = Ionicons.transgender.image(32)
ImageGender.setImage(imagegender, for: .normal)
ImageGender.tintColor = AppColor.backButton
let imagephone = Ionicons.androidPhonePortrait.image(32)
imagePhone.setImage(imagephone, for: .normal)
imagePhone.tintColor = AppColor.backButton
let imageage = Ionicons.androidCalendar.image(32)
imageAge.setImage(imageage, for: .normal)
imageAge.tintColor = AppColor.backButton
let imageaddress = Ionicons.iosHome.image(32)
imageAddress.setImage(imageaddress, for: .normal)
imageAddress.tintColor = AppColor.backButton
lbAge.font = fontSize.fontName(name: .regular, size: sizeFive)
lbName.font = fontSize.fontName(name: .regular, size: sizeFive)
lbPhone.font = fontSize.fontName(name: .regular, size: sizeFive)
lbGender.font = fontSize.fontName(name: .regular, size: sizeFive)
lbAddress.font = fontSize.fontName(name: .regular, size: sizeFive)
}
func getStar() {
let image = Ionicons.star.image(32).maskWithColor(color: AppColor.start)
guard let tag = UserDefaultHelper.currentUser?.workInfor?.evaluation_point else{return}
for i in btRating!{
if i.tag <= tag {
i.setImage(image, for: .normal)
}else{
i.setImage(imageFirst, for: .normal)
}
}
}
var workPending: Work? {
didSet{
guard let gender = workPending?.stakeholders?.owner?.gender! else{return}
if gender == 0 {
lbGender.text = "Boy".localize
}else{
lbGender.text = "Girl".localize
}
lbAddress.text = workPending?.stakeholders?.owner?.address?.name
lbPhone.text = workPending?.stakeholders?.owner?.phone
let url = URL(string: (workPending?.stakeholders?.owner?.image)!)
if url == nil {
imageProfile.image = UIImage(named: "avatar")
avatar.image = UIImage(named: "avatar")
}else{
DispatchQueue.main.async {
self.avatar.kf.setImage(with: url)
self.imageProfile.kf.setImage(with: url)
}
}
lbName.text = workPending?.stakeholders?.owner?.name
lbAge.isHidden = true
vViewAge.isHidden = true
contraintAge.constant = 0
imageAge.isHidden = true
}
}
@IBAction func btRatingAction(_ sender: UIButton) {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.