text stringlengths 8 1.32M |
|---|
// RUN: %target-parse-verify-swift
class C {
func f() {}
}
class D : C {
}
class E { }
protocol P { // expected-note{{requirement specified as 'Self.Assoc' : 'C' [with Self = X2]}}
associatedtype Assoc : C
func getAssoc() -> Assoc
}
struct X1 : P {
func getAssoc() -> D { return D() }
}
struct X2 : P { // expected-error{{'P' requires that 'E' inherit from 'C'}}
func getAssoc() -> E { return E() }
}
func testP<T:P>(_ t: T) {
_ = t.getAssoc() as C
t.getAssoc().f()
}
func callTestP(_ x1: X1) {
testP(x1)
}
|
//
// PageTitleView.swift
// douyuzb
//
// Created by 易 on 2017/11/6.
// Copyright © 2017年 易. All rights reserved.
//
import UIKit
let kscrollLineH: CGFloat = 2
let klineH: CGFloat = 1
class PageTitleView: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
// STC: define title attribute 定义titles 属性
private var titles : [String]
//
private var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
// 懒加载属性
private lazy var titleLabels : [UILabel] = [UILabel]()
private lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
// MARK: define a mutated function, 定义构造函数
init(frame: CGRect, titles : [String]) {
self.titles = titles
super.init(frame: frame)
// 设置UI界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
private func setupUI() {
// 1、 添加UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
// 2、添加title 对应的label
setTitleLabels()
// 3、设置底线和滚动的滑块
setupBootMenuAndScrollLine()
}
private func setTitleLabels() {
// 0、预设置某些值
let labelW: CGFloat = frame.width/CGFloat(titles.count)
let labelH: CGFloat = frame.height - kscrollLineH
let labelY: CGFloat = 0
for (index, title) in titles.enumerated() {
//1、 创建 UI label
let label = UILabel()
//2、 set label's 属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor.black
label.textAlignment = .center
//3、 set lebel's frame
let labelX: CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
//4、 将label添加到scrollView中
scrollView.addSubview(label)
titleLabels.append(label)
}
}
private func setupBootMenuAndScrollLine() {
//1、 添加底线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
bottomLine.frame = CGRect(x: 0, y: frame.height - klineH , width: frame.width, height: klineH)
addSubview(bottomLine)
// 2、添加scrollLine
// 2.1、获取第一个label
guard let firstLabel = titleLabels.first else { return }
titleLabels.first?.textColor = UIColor.orange
// 2.2设置scrollView的属性
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kscrollLineH, width: firstLabel.frame.width, height: kscrollLineH)
}
}
|
//
// QuickCache.swift
// QuickKV
//
// Created by zf on 2021/8/29.
//
import Foundation
import MMKV
public final class QuickCache<T> {
let config: QuickCacheConfig
let transformer: Transformer<T>
let mmkv: MMKV
init(mmkv: MMKV, config: QuickCacheConfig, transformer: Transformer<T>) {
self.mmkv = mmkv
self.config = config
self.transformer = transformer
}
public convenience init(config: QuickCacheConfig, transformer: Transformer<T>) throws {
if let mmkv = MMKV(mmapID: config.name, cryptKey: kQuickCache) {
self.init(mmkv: mmkv, config: config, transformer: transformer)
} else {
throw CacheError.initializeFailed
}
}
}
private let kQuickCache: Data? = "QuickCache".data(using: .utf8)
// MARK: Basic operation
public extension QuickCache {
func setObject(_ object: T, forKey key: String, expiry: CacheExpiry? = nil) throws {
let expiry = expiry ?? config.expiry
let data = try transformer.toData(object)
let entry = CacheEntry(data: data, expiry: expiry)
try mmkvSet(entry: entry, key: key, mmkv: mmkv)
}
func getObject(forKey key: String) throws -> T {
let entry = try mmkvGet(forKey: key, mmkv: mmkv)
return try transformer.fromData(entry.data)
}
func getObjectWithExpiry(forKey key: String) throws -> (T, Bool) {
let entry = try mmkvGet(forKey: key, mmkv: mmkv)
let t = try transformer.fromData(entry.data)
return (t, entry.expiry.isExpired)
}
func existsObject(forKey key: String) -> Bool {
return mmkv.contains(key: key)
}
func forEachKeys(_ key: @escaping (String) -> Void) {
return mmkv.enumerateKeys { k, _ in
key(k)
}
}
func removeObject(forKey key: String) {
mmkv.removeValue(forKey: key)
}
func removeObjectIfExpired(forKey key: String) {
if let entry = try? mmkvGet(forKey: key, mmkv: mmkv), entry.expiry.isExpired {
removeObject(forKey: key)
}
}
func removeObjects(forKeys keys: [String]) {
mmkv.removeValues(forKeys: keys)
}
func removeAll() {
mmkv.clearAll()
}
func removeExpiredObjects() {
forEachKeys { k in
self.removeObjectIfExpired(forKey: k)
}
}
func isExpiredObject(forKey key: String) -> Bool {
do {
let entry = try mmkvGet(forKey: key, mmkv: mmkv)
return entry.expiry.isExpired
} catch {
// not found is true
return true
}
}
var totalSize: Int {
return mmkv.totalSize()
}
var count: Int {
return mmkv.count()
}
}
// MARK: Transform
public extension QuickCache {
func transform<U>(transformer: Transformer<U>) -> QuickCache<U> {
return QuickCache<U>(mmkv: mmkv, config: config, transformer: transformer)
}
func transformData() -> QuickCache<Data> {
let storage = transform(transformer: TransformerFactory.forData())
return storage
}
func transformCodable<U: Codable>(ofType: U.Type) -> QuickCache<U> {
let storage = transform(transformer: TransformerFactory.forCodable(ofType: U.self))
return storage
}
}
|
//
// ViewController.swift
// DemoDongHo
//
// Created by Taof on 10/21/19.
// Copyright © 2019 Taof. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var kimGiayView: UIView!
@IBOutlet weak var kimPhutView: UIView!
@IBOutlet weak var kimGioView: UIView!
var timerClock: Timer!
var currentDate = NSDate()
var calendar = NSCalendar.current
override func viewDidLoad() {
super.viewDidLoad()
dongho()
}
func setTime() -> (hour: CGFloat, minute: CGFloat, second: CGFloat){
let hour = calendar.component(.hour, from: currentDate as Date)
let minute = calendar.component(.minute, from: currentDate as Date)
let second = calendar.component(.second, from: currentDate as Date)
print("Giờ: \(hour) phút: \(minute) giây \(second)")
let hourInSecond = hour*60*60 + minute*60 + second
let minuteInSecond = minute*60 + second
print("hourInSecond: \(hourInSecond) minuteInSecond: \(minuteInSecond)")
let firstAlphaHour = CGFloat(Double.pi)*(2*CGFloat(hourInSecond)/12/60/60 - 0.5)
let firstAlphaMinute = CGFloat(Double.pi)*(2*CGFloat(minuteInSecond)/60/60 - 0.5)
let firstAlphaSecond = CGFloat(Double.pi)*(2*CGFloat(second)/60 - 0.5)
print("góc Giờ: \(firstAlphaHour) góc phút: \(firstAlphaMinute) góc giây \(firstAlphaSecond)")
return (firstAlphaHour, firstAlphaMinute, firstAlphaSecond)
}
func dongho(){
getLocation(kimView: kimGiayView, alpha: setTime().second)
getLocation(kimView: kimPhutView, alpha: setTime().minute)
getLocation(kimView: kimGioView, alpha: setTime().hour)
timerClock = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runClock), userInfo: nil, repeats: true)
}
func getLocation(kimView: UIView, alpha: CGFloat){
let r = kimView.bounds.size.height/2
kimView.center = CGPoint(x: view.center.x, y: view.center.y)
kimView.layer.cornerRadius = r
setAnchorPoint(aView: kimView, point: CGPoint(x: kimView.bounds.height/2/kimView.bounds.width, y: 0.5))
kimView.transform = CGAffineTransform(rotationAngle: alpha)
}
@objc func runClock(){
let omegaGiay = CGAffineTransform(rotationAngle: CGFloat.pi*2/60)
kimGiayView.transform = kimGiayView.transform.concatenating(omegaGiay)
let omegaPhut = CGAffineTransform(rotationAngle: CGFloat(Double.pi*2/60/60))
kimPhutView.transform = kimPhutView.transform.concatenating(omegaPhut)
let omegaGio = CGAffineTransform(rotationAngle: CGFloat(Double.pi*2/60/60/12))
kimGioView.transform = kimGioView.transform.concatenating(omegaGio)
}
func setAnchorPoint(aView: UIView, point: CGPoint){
var newPoint = CGPoint(x: aView.bounds.size.width * point.x, y: aView.bounds.size.height * point.y)
var oldPoint = CGPoint(x: aView.bounds.size.width * aView.layer.anchorPoint.x, y: aView.bounds.size.height * aView.layer.anchorPoint.y);
newPoint = newPoint.applying(aView.transform)
oldPoint = oldPoint.applying(aView.transform)
var position = aView.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
aView.layer.position = position
aView.layer.anchorPoint = point
}
}
|
import Foundation
struct Offer: Hashable {
let id: String
}
final class CartEventStore {
}
protocol Event {}
struct OfferAddedEvent: Event {
let offer: Offer
let count: Int
}
struct SomeTask {}
@available(iOS 9999, *)
actor TaskExecutor {
func execute(_ task: SomeTask) async {
await withUnsafeContinuation { c in
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) {
c.resume()
}
}
}
}
actor EventDispatcher {
func dispatch(_ event: Event) async {
}
}
@available(iOS 9999, *)
actor Cart {
private let eventDispatcher: EventDispatcher
private let taskExecutor = TaskExecutor()
init(eventDispatcher: EventDispatcher) {
self.eventDispatcher = eventDispatcher
}
var items: [Offer: Int] = [:]
func add(_ item: Offer, count: Int) async {
let count = (items[item] ?? 0) + count
items[item] = count
await taskExecutor.execute(SomeTask())
let shouldBeTheSameCount = (items[item] ?? 0)
if shouldBeTheSameCount != count {
fatalError("Interleaving side-effect happened")
}
await eventDispatcher.dispatch(OfferAddedEvent(offer: item, count: items[item] ?? 0))
}
}
|
//
// PriceList.swift
// PriceGet
//
// Created by Владимир on 22.12.2019.
// Copyright © 2019 VladCorp. All rights reserved.
//
import Foundation
struct PriceList: Codable{
var priceListUrl: String
init?(priceListUrl: String?){
guard
let priceListUrl = priceListUrl else {return nil}
self.priceListUrl = priceListUrl
}
}
struct PriceListResponse: Decodable{
let priceListUrl:String?
}
|
../../StellarKit/third-party/SHA256.swift |
//
// ItemCell.swift
// LootLogger-BNR
//
// Created by Ting Chen on 7/14/20.
// Copyright © 2020 DukeMobileDevCenter. All rights reserved.
//
import UIKit
class ItemCell: UITableViewCell {
@IBOutlet var nameLabel: UILabel!
@IBOutlet var serialNumberLabel: UILabel!
@IBOutlet var valueLabel: UILabel!
}
|
//: Playground - noun: a place where people can play
// 3. Longest Substring Without Repeating Characters: https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
import Foundation
let str = "WERTYUIOP"
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
for subStrLen in stride(from: s.count, to: 1, by: -1) {
for index in 0...s.count-subStrLen {
let subString = getSubString(forString: s, from: index, to: index+subStrLen)
let characterSet = Set(subString)
if characterSet.count == subStrLen {
return subString.count
}
}
}
return 1
}
func getSubString(forString string:String, from:Int, to:Int) -> String {
let str = string
let startIndex = str.index(str.startIndex, offsetBy: from)
let endIndex = str.index(str.startIndex, offsetBy: to)
return String(str[startIndex..<endIndex])
}
}
let solution = Solution()
solution.lengthOfLongestSubstring(str)
|
//
// DependencyContainer.swift
// Katana
//
// Copyright © 2016 Bending Spoons.
// Distributed under the MIT License.
// See the LICENSE file for more information.
import Foundation
import Katana
class SimpleDependencyContainer: SideEffectDependencyContainer {
let state: AppState?
public required init(state: State, dispatch: @escaping StoreDispatch) {
if let s = state as? AppState {
self.state = s
} else {
self.state = nil
}
}
}
|
//
// AVAsset+Generate.swift
// JYVideoEditor
//
// Created by aha on 2021/2/19.
//
import AVFoundation
import Foundation
import UIKit
//MARK: - 视频资源生成预览图
extension AVAsset {
func generatePreviewImage(interval: TimeInterval, caseSize: CGSize, result: ((UIImage?) -> Void)?) {
generateAllPreviewSnapshop(interval: interval) { (imgs) in
DispatchQueue.main.async {
let img = self.compositionImages(imgs, size: caseSize)
result?(img)
}
}
}
private func compositionImages(_ imgs: [UIImage], size: CGSize) -> UIImage? {
let width: CGFloat = size.width
let height: CGFloat = size.height
let seconds = self.tracks(withMediaType: .video).first?.timeRange.duration.seconds ?? 0.0
let totalSize = CGSize(width: CGFloat(seconds) * width, height: height)
UIGraphicsBeginImageContextWithOptions(totalSize, false, 0)
for i in 0..<imgs.count {
let rect = CGRect.init(x: width * CGFloat(i), y: 0, width: width, height: height)
imgs[i].draw(in: rect)
}
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
private func generateAllPreviewSnapshop(interval: TimeInterval, complete: @escaping ([UIImage]) -> Void) {
guard let videoTrack = tracks(withMediaType: .video).first else {
return
}
let generator = AVAssetImageGenerator(asset: self)
generator.requestedTimeToleranceAfter = .zero
generator.requestedTimeToleranceBefore = .zero
var times = [CMTime]()
let needsImageCount = Int(videoTrack.timeRange.duration.seconds / interval)
for i in 0...needsImageCount {
let time = CMTime(seconds: Double(i) * interval, preferredTimescale: videoTrack.timeRange.duration.timescale)
times.append(time)
}
let results = times.map { NSValue(time: $0) }
var resultImages = [(CMTime, UIImage)]()
let totalCount = needsImageCount
var currentCount = 0
generator.generateCGImagesAsynchronously(forTimes: results) { (_, imgRef, actualTime, result, err) in
currentCount += 1
if result == .succeeded, let imageRef = imgRef {
let img = UIImage(cgImage: imageRef)
resultImages.append((actualTime, img))
} else {
print("generator snapshot failed: \(err)")
}
if currentCount > totalCount {
let resultImgs = resultImages.sorted { (result1, result2) -> Bool in
result1.0 < result2.0
}.map { $0.1 }
complete(resultImgs)
}
}
}
}
//MARK: - 音频资源生成波形图
extension AVAsset {
func generateAudioToWaves(interval: TimeInterval, caseSize: CGSize) -> UIImage? {
guard let track = tracks(withMediaType: .audio).first else {
return nil
}
let duration = CGFloat(track.timeRange.duration.seconds)
let width = caseSize.width * duration / CGFloat(interval)
let imageSize = CGSize.init(width: width, height: caseSize.height)
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
let bgPath = UIBezierPath(rect: .init(origin: .zero, size: imageSize))
context.setFillColor(UIColor.cyan.cgColor)
bgPath.fill()
let path = UIBezierPath()
path.move(to: .init(x: 0, y: caseSize.height/2))
var i: CGFloat = 0.0
repeat {
let pointY = sin(i / 10 * .pi / 2) * caseSize.height / 2 * 0.8 + caseSize.height / 2
i += 10
path.addLine(to: .init(x: i, y: pointY))
}while i < CGFloat(duration * caseSize.width)
context.setStrokeColor((UIColor.white.cgColor))
path.lineWidth = 2
path.stroke()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
|
//
// ClusterAnnotationView.swift
// CafeNomad
//
// Created by Albert on 2018/11/6.
// Copyright © 2018 Albert.C. All rights reserved.
//
import Foundation
import MapKit
class ClusterAnnotationView: MKAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
// displayPriority = .defaultHigh
collisionMode = .circle
canShowCallout = false
centerOffset = CGPoint(x: 0.0, y: -10.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForDisplay() {
super.prepareForDisplay()
if let custer = annotation as? MKClusterAnnotation {
let cafeShopCount = custer.memberAnnotations.count
image = drawCafeShop(count: cafeShopCount)
displayPriority = .defaultLow
canShowCallout = false
}
}
private func drawCafeShop(count: Int) -> UIImage {
return drawRatio(0, whole: count)
}
private func drawRatio(_ fraction: Int, whole: Int) -> UIImage {
let cafeShop = UIGraphicsImageRenderer(size: CGSize(width: 30.0, height: 30.0))
return cafeShop.image { _ in
UIColor(red: 194/255, green: 147/255, blue: 88/255, alpha: 1).setFill()
UIBezierPath(ovalIn: CGRect(x: 0.0, y: 0.0, width: 30.0, height: 30.0)).fill()
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17.0)]
let text = "\(whole)"
let size = text.size(withAttributes: attributes)
let rect = CGRect(x: 15 - size.width / 2, y: 15 - size.height / 2, width: size.width, height: size.height)
text.draw(in: rect, withAttributes: attributes)
}
}
}
|
import Foundation
final class NavigationPresenter {
func createExperiencePresenter(from presenter: InformationPresenter?) -> ExperiencePresenter {
guard let presenter = presenter else {
return ExperiencePresenter()
}
let informationPresenter = ExperiencePresenter()
informationPresenter.setExperience(presenter.getExperiences())
return informationPresenter
}
func createInformationPresenter() -> InformationPresenter {
return InformationPresenter()
}
}
|
//
// LightMode.swift
// yourservice-ios
//
// Created by Игорь Сорокин on 27.10.2020.
// Copyright © 2020 spider. All rights reserved.
//
import AVFoundation
import UIKit
enum LightMode: Int {
case auto
case on
case off
var image: UIImage {
switch self {
case .auto: return Asset.flashAuto.image
case .off: return Asset.flashOff.image
case .on: return Asset.flashOn.image
}
}
var torch: AVCaptureDevice.TorchMode {
switch self {
case .auto: return .auto
case .off: return .off
case .on: return .on
}
}
var flash: AVCaptureDevice.FlashMode {
switch self {
case .auto: return .auto
case .off: return .off
case .on: return .on
}
}
func nextMode() -> LightMode {
let nextRawValue = rawValue + 1
let normallyRawValue = nextRawValue % 3
return LightMode(rawValue: normallyRawValue)!
}
}
|
//
// MainViewController.swift
// Raytracer
//
// Created by Drew Ingebretsen on 12/4/14.
// Copyright (c) 2014 Drew Ingebretsen. All rights reserved.
//
import UIKit
import Metal
import QuartzCore
class MainViewController: UIViewController, RaytracerViewDelegate {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var raytracerView: RaytracerView!
@IBOutlet weak var renderingProgressView: UIProgressView!
@IBOutlet weak var toolbar: UIToolbar!
var helpViewController:UIViewController!
var lightEditViewController:LightEditViewController!
var moreViewController:MoreViewController!
var sceneSelecViewController:SceneSelectViewController!
var sphereEditViewController:SphereEditViewController!
var wallEditViewController:WallEditViewController!
@IBAction func selectPane(_ sender: UIBarButtonItem) {
if (sender.tintColor == UIColor.darkGray) {
switchViewController(viewController: helpViewController)
sender.tintColor = UIColor.lightGray
return
}
switch (sender.tag) {
case 0:
switchViewController(viewController: sceneSelecViewController)
break
case 1:
switchViewController(viewController: lightEditViewController)
lightEditViewController.update()
break
case 2:
switchViewController(viewController: wallEditViewController)
wallEditViewController.update()
break
case 3:
switchViewController(viewController: moreViewController)
break
default: break
}
raytracerView.selectedSphere = -1
toolbar.items?.forEach({ $0.tintColor = ($0 == sender ? UIColor.darkGray : UIColor.lightGray) })
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if raytracerView.rendering == false {
PresetScenes.scene = raytracerView.scene
PresetScenes.selectPresetScene(sceneIndex: 0)
raytracerView.startRendering()
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupChildViewControllers()
raytracerView.delegate = self
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func setupChildViewControllers() {
helpViewController = (storyboard?.instantiateViewController(withIdentifier: "HelpViewController"))!
lightEditViewController = (storyboard?.instantiateViewController(withIdentifier: "LightEditViewController"))! as! LightEditViewController
moreViewController = (storyboard?.instantiateViewController(withIdentifier: "MoreViewController"))! as! MoreViewController
sceneSelecViewController = (storyboard?.instantiateViewController(withIdentifier: "SceneSelectViewController"))! as! SceneSelectViewController
sphereEditViewController = (storyboard?.instantiateViewController(withIdentifier: "SphereEditViewController"))! as! SphereEditViewController
wallEditViewController = (storyboard?.instantiateViewController(withIdentifier: "WallEditViewController"))! as! WallEditViewController
addChildViewController(helpViewController)
addChildViewController(lightEditViewController)
addChildViewController(moreViewController)
addChildViewController(sceneSelecViewController)
addChildViewController(sphereEditViewController)
addChildViewController(wallEditViewController)
lightEditViewController.raytracerView = raytracerView
moreViewController.raytracerView = raytracerView
sceneSelecViewController.raytracerView = raytracerView
sphereEditViewController.raytracerView = raytracerView
wallEditViewController.raytracerView = raytracerView
}
func switchViewController(viewController:UIViewController) {
viewController.view.translatesAutoresizingMaskIntoConstraints = false
containerView.subviews.forEach({ $0.removeFromSuperview() })
containerView.addSubview(viewController.view)
NSLayoutConstraint.activate([
viewController.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 0),
viewController.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 0),
viewController.view.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0),
viewController.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0)
])
viewController.didMove(toParentViewController: self)
}
func raytracerViewDidCreateImage(image: UIImage) {
self.renderingProgressView.setProgress(Float(raytracerView.samples)/2000.0, animated: true)
}
func raytracerViewDidSelectSphere(index:Int) {
if (index > -1){
switchViewController(viewController: sphereEditViewController)
sphereEditViewController.update()
} else {
switchViewController(viewController: helpViewController)
}
toolbar.items?.forEach({ $0.tintColor = UIColor.lightGray })
}
}
|
//
// CategoryViewModel.swift
// NewsApp
//
// Created by Vaibhav Parmar on 09/11/17.
// Copyright © 2017 Vaibhav Parmar. All rights reserved.
//
import Foundation
import FoxAPIKit
import ReactiveSwift
import Model
class CategoryViewModel {
var loading = MutableProperty<Bool>(false)
var cellModels = MutableProperty<[CategoryCellModel]>([])
var disposable = CompositeDisposable([])
deinit {
disposable.dispose()
}
init() {
self.disposable += self.loading <~ self.fetchSourceAction.isExecuting
self.disposable += self.fetchSourceAction.values.observeValues({ (sources) in
self.sources = sources
})
self.disposable += self.fetchSourceAction.errors.observeValues({ (error) in
print("Error: \(error.code) \(error.message)")
})
}
fileprivate(set) public var sources: [Source] = [] {
didSet {
self.cellModels.value = Model.Category.groupCategories(sources: sources).map {
CategoryCellModel.init(category: $0)
}
}
}
fileprivate let fetchSourceAction = Action { () -> SignalProducer<[Source], NewsError> in
return Source.fetchSources()
}
}
extension CategoryViewModel {
func fetchSources() {
self.disposable += self.fetchSourceAction.apply().start()
}
}
|
//
// StickersViewController.swift
// MyMessageStickers
//
// Created by Jeff Ripke on 7/13/17.
// Copyright © 2017 Jeff Ripke. All rights reserved.
//
import Foundation
import Messages
class StickersViewController: MSStickerBrowserViewController {
var stickers = [MSSticker]()
let stickerNames = ["yes", "house", "sun", "car"]
override func viewDidLoad() {
super.viewDidLoad()
populateStickers()
}
override func stickerBrowserView(_ stickerBrowserView: MSStickerBrowserView, stickerAt index: Int) -> MSSticker {
return stickers[index]
}
override func numberOfStickers(in stickerBrowserView: MSStickerBrowserView) -> Int {
return stickers.count
}
private func populateStickers() {
for stickerName in stickerNames {
let path = Bundle.main.url(forResource: stickerName, withExtension: "png")
let sticker = try! MSSticker(contentsOfFileURL: path!, localizedDescription: stickerName)
stickers.append(sticker)
}
stickerBrowserView.reloadData()
}
}
|
//
// ViewController.swift
// MQCompressImageDemo
//
// Created by 120v on 2018/9/21.
// Copyright © 2018年 MQ. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var imageSizeTextField: UITextField!
@IBOutlet weak var imageView: UIImageView!
private var image: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Select image", style: .plain, target: self, action: #selector(selectImage))
}
@objc private func selectImage() {
view.endEditing(true)
let sourceType: UIImagePickerController.SourceType = .photoLibrary
if UIImagePickerController.isSourceTypeAvailable(sourceType) {
let picker: UIImagePickerController = UIImagePickerController()
picker.delegate = self
picker.sourceType = sourceType
present(picker, animated: true, completion: nil)
}
}
@IBAction func compressButtonClicked(_ sender: UIButton) {
view.endEditing(true)
guard let image = image,
let text = imageSizeTextField.text,
let textIntValue = Int(text) else { return }
let imageByte: Int = textIntValue * 1024
switch sender.tag {
case 1000:
imageView.image = ViewController.compressImageQuality(image, toByte: imageByte)
case 1001:
imageView.image = ViewController.compressImageSize(image, toByte: imageByte)
default:
imageView.image = ViewController.compressImage(image, toByte: imageByte)
}
}
static func compressImageQuality(_ image: UIImage, toByte maxLength: Int) -> UIImage {
var compression: CGFloat = 1
guard var data = image.jpegData(compressionQuality: compression),
data.count > maxLength else { return image }
print("Before compressing quality, image size =", data.count / 1024, "KB")
var max: CGFloat = 1
var min: CGFloat = 0
for _ in 0..<6 {
compression = (max + min) / 2
data = image.jpegData(compressionQuality: compression)!
print("Compression =", compression)
print("In compressing quality loop, image size =", data.count / 1024, "KB")
if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
min = compression
} else if data.count > maxLength {
max = compression
} else {
break
}
}
print("After compressing quality, image size =", data.count / 1024, "KB")
return UIImage(data: data)!
}
static func compressImageSize(_ image: UIImage, toByte maxLength: Int) -> UIImage {
guard var data = image.jpegData(compressionQuality: 1) else { return image }
print("Before compressing size, image size =", data.count / 1024, "KB")
var resultImage: UIImage = image
var lastDataLength: Int = 0
while data.count > maxLength, data.count != lastDataLength {
lastDataLength = data.count
let ratio: CGFloat = CGFloat(maxLength) / CGFloat(data.count)
print("Ratio =", ratio)
let size: CGSize = CGSize(width: Int(resultImage.size.width * sqrt(ratio)),
height: Int(resultImage.size.height * sqrt(ratio)))
UIGraphicsBeginImageContext(size)
resultImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
resultImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
data = resultImage.jpegData(compressionQuality: 1)!
print("In compressing size loop, image size =", data.count / 1024, "KB")
}
print("After compressing size loop, image size =", data.count / 1024, "KB")
return resultImage
}
static func compressImage(_ image: UIImage, toByte maxLength: Int) -> UIImage {
var compression: CGFloat = 1
guard var data = image.jpegData(compressionQuality: compression),
data.count > maxLength else { return image }
print("Before compressing quality, image size =", data.count / 1024, "KB")
// Compress by size
var max: CGFloat = 1
var min: CGFloat = 0
for _ in 0..<6 {
compression = (max + min) / 2
data = image.jpegData(compressionQuality: compression)!
print("Compression =", compression)
print("In compressing quality loop, image size =", data.count / 1024, "KB")
if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
min = compression
} else if data.count > maxLength {
max = compression
} else {
break
}
}
print("After compressing quality, image size =", data.count / 1024, "KB")
var resultImage: UIImage = UIImage(data: data)!
if data.count < maxLength { return resultImage }
// Compress by size
var lastDataLength: Int = 0
while data.count > maxLength, data.count != lastDataLength {
lastDataLength = data.count
let ratio: CGFloat = CGFloat(maxLength) / CGFloat(data.count)
print("Ratio =", ratio)
let size: CGSize = CGSize(width: Int(resultImage.size.width * sqrt(ratio)),
height: Int(resultImage.size.height * sqrt(ratio)))
UIGraphicsBeginImageContext(size)
resultImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
resultImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
data = resultImage.jpegData(compressionQuality: compression)!
print("In compressing size loop, image size =", data.count / 1024, "KB")
}
print("After compressing size loop, image size =", data.count / 1024, "KB")
return resultImage
}
// MARK: - UIImagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
imageView.image = image
}
}
|
//
// PropertyModel.swift
// CoreDataJsonParser
//
// Created by Alex Belozierov on 9/8/19.
// Copyright © 2019 Alex Belozierov. All rights reserved.
//
import CoreData
struct PropertyModel {
var property: Property?
var jsonPath: JsonDecoderPath?
func updated(with changes: PropertyModel) -> PropertyModel {
var model = self
changes.property.map { model.property = $0 }
changes.jsonPath.map { model.jsonPath = $0 }
return model
}
mutating func updateStorage(_ updater: (inout JsonDecoderStorage) -> Void) {
guard case .relation(var relation) = property,
case .decoder(var decoder) = relation.entityDecoder else { return }
decoder.entityModel.updateStorage(updater)
relation.entityDecoder = .decoder(decoder)
property = .relation(relation)
}
}
|
//
// Girl.swift
// BigGirl
//
// Created by 罗诗朋 on 2021/8/8.
//
import Foundation
struct GirlList:Decodable {
let data:[Girl]
// let page:Int
// let page_count:Int
// let status:Int
// let total_counts:Int
}
struct Girl: Decodable {
let _id:Int
let author:String
let category:String
let cratedAt:String
let desc:String
let images:[String]
let likeCounts:Int
let publishedAt:String
let stars:Int
let title:String
let type:String
let url: String
let views:Int
}
|
//
// DBModel+Id.swift
//
//
// Created by Guerson Perez on 6/11/21.
//
import Foundation
extension DBModel {
func modelId(idKey: String) -> Any? {
return modelStringValue(for: idKey) ?? modelIntValue(for: idKey)
}
func idEquals(to obj: DBModel, idKey: String) -> Bool {
let selfId = modelId(idKey: idKey)
let objId = obj.modelId(idKey: idKey)
if let selfIdString = selfId as? String,
let objIdString = objId as? String,
selfIdString == objIdString {
return true
} else if let selfIdInt = selfId as? Int,
let objIdInt = objId as? Int,
selfIdInt == objIdInt {
return true
}
return false
}
}
|
//
// PodExecutable.swift
// Terminal
//
// Created by Stijn on 27/02/2019.
//
import Errors
import Foundation
import SignPost
import ZFile
public struct PodExecutable: ArgumentExecutableProtocol
{
private let signPost: SignPostProtocol
private let system: SystemProtocol
public init(
system: SystemProtocol = System.shared,
signPost: SignPostProtocol = SignPost.shared
)
{
self.system = system
self.signPost = signPost
}
public func arguments() throws -> Arguments
{
return Arguments(arrayLiteral: "install")
}
public func executableFile() throws -> FileProtocol
{
var podfile: FileProtocol!
do
{
do
{
let homeFolder = FileSystem.shared.homeFolder
signPost.message(".rbenv setup verification - Searching for pod command in folder \(homeFolder)")
podfile = try homeFolder.file(named: ".rbenv/shims/pod")
}
catch
{
signPost.message("Pod not found, looking in all folders from PATH")
signPost.verbose("PATH \n \(system.pathEnvironmentParser.urls.map { $0.path }.joined(separator: "\n")) \n")
podfile = try system.executable(with: "pod")
}
signPost.message("found pod at \(String(describing: podfile))")
}
catch
{
throw "\(self) \(#function) \(error)"
}
return podfile
}
}
|
//
// SettingsTableViewController.swift
// Meme Maker
//
// Created by Avikant Saini on 4/4/16.
// Copyright © 2016 avikantz. All rights reserved.
//
import UIKit
import CoreData
import SVProgressHUD
import MessageUI
import BWWalkthrough
import Reachability
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class SettingsTableViewController: UITableViewController, MFMailComposeViewControllerDelegate, BWWalkthroughViewControllerDelegate {
@IBOutlet weak var autoDismiss: UISwitch!
@IBOutlet weak var resetSettings: UISwitch!
@IBOutlet weak var contEditing: UISwitch!
@IBOutlet weak var darkMode: UISwitch!
@IBOutlet weak var uploadEnable: UISwitch!
@IBOutlet weak var memesCountLabel: UILabel!
@IBOutlet weak var memesPerRowLabel: UILabel!
@IBOutlet var tableViewCells: [UITableViewCell]!
@IBOutlet var tableViewCellLabels: [UILabel]!
var memes = NSMutableArray()
var fetchedMemes = NSMutableArray()
var quotes = NSMutableArray()
var context: NSManagedObjectContext? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Settings"
autoDismiss.isOn = SettingsManager.sharedManager().getBool(kSettingsAutoDismiss)
resetSettings.isOn = SettingsManager.sharedManager().getBool(kSettingsResetSettingsOnLaunch)
contEditing.isOn = SettingsManager.sharedManager().getBool(kSettingsContinuousEditing)
darkMode.isOn = SettingsManager.sharedManager().getBool(kSettingsDarkMode)
// uploadEnable.on = SettingsManager.sharedManager().getBool(kSettingsUploadMemes)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.managedObjectContext
if let data = try? Data(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "quotes", ofType: "json")!)) {
do {
let jsonData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSArray
quotes = NSMutableArray(array: jsonData)
}
catch _ {}
}
updateCount()
updateViews()
}
override func viewWillAppear(_ animated: Bool) {
self.memesPerRowLabel.text = "\(SettingsManager.sharedManager().getInteger(kSettingsNumberOfElementsInGrid))"
}
func updateViews() -> Void {
self.tableView.backgroundColor = globalBackColor
if isDarkMode() {
self.tableView.separatorColor = UIColor.darkGray
}
else {
self.tableView.separatorColor = UIColor.lightGray
}
for cell in tableViewCells {
cell.backgroundColor = globalBackColor
cell.textLabel?.textColor = globalTintColor
cell.textLabel?.font = UIFont(name: "EtelkaNarrowTextPro", size: 18)
cell.detailTextLabel?.font = UIFont(name: "EtelkaNarrowTextPro", size: 18)
}
for label in tableViewCellLabels {
label.textColor = globalTintColor
label.font = UIFont(name: "EtelkaNarrowTextPro", size: 18)
}
}
// MARK: - Switches
@IBAction func autoDismissSwitchAction(_ sender: AnyObject) {
let swtch = sender as! UISwitch
SettingsManager.sharedManager().setBool(swtch.isOn, key: kSettingsAutoDismiss)
}
@IBAction func resetSettingsOnLaunchSwitchAction(_ sender: AnyObject) {
let swtch = sender as! UISwitch
SettingsManager.sharedManager().setBool(swtch.isOn, key: kSettingsResetSettingsOnLaunch)
}
@IBAction func continuousEditingSwitchAction(_ sender: AnyObject) {
let swtch = sender as! UISwitch
SettingsManager.sharedManager().setBool(swtch.isOn, key: kSettingsContinuousEditing)
}
@IBAction func darkModeSwitchAction(_ sender: AnyObject) {
let swtch = sender as! UISwitch
SettingsManager.sharedManager().setBool(swtch.isOn, key: kSettingsDarkMode)
updateGlobalTheme()
let redrawHelperVC = UIViewController()
redrawHelperVC.modalPresentationStyle = .fullScreen
if (UI_USER_INTERFACE_IDIOM() == .pad) {
self.splitViewController?.present(redrawHelperVC, animated: false, completion: nil)
}
else {
self.tabBarController?.present(redrawHelperVC, animated: false, completion: nil)
}
self.dismiss(animated: false, completion: nil)
if (UI_USER_INTERFACE_IDIOM() == .pad) {
if self.splitViewController?.viewControllers.count > 1 {
let editorVC = self.splitViewController?.viewControllers[1] as? EditorViewController
editorVC?.backgroundImageView.layoutSubviews()
}
}
updateViews()
}
@IBAction func uploadEnableSwitchAction(_ sender: AnyObject) {
let swtch = sender as! UISwitch
SettingsManager.sharedManager().setBool(swtch.isOn, key: kSettingsUploadMemes)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (section == 0) {
return quotes.object(at: Int(arc4random()) % quotes.count) as? String
}
return ""
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
let noos = tableView.numberOfSections
switch section {
case 0:
return "Turning this on will dismiss the editing options as you select any option."
case 1:
return "Enabling this function will reset the text editing settings on launch, i.e. no preservations in settings."
case 2:
return "Turning this off will prevent generation of text on image as you enter it, but may help in saving battery life. If enabled, you need to press return to generate text after editing."
// case 4:
// return "Check this if you want your \"creations\" to be uploaded to the server."
case noos - 4:
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd yyyy, hh:mm a"
let date = SettingsManager.sharedManager().getLastUpdateDate()
return "Last updated: \(formatter.string(from: date))"
case noos - 1:
return "Swipe up to bring up editing options.\n\nSwipe left and right to switch between options.\n\nPinch on top or bottom of the image to set text size.\n\nTwo finger pan on top or bottom half to place top or bottom text, Shake or two finger double tap to reset position.\n\nSwipe right text field to add default text. Swipe left to clear text.\n\nDouble tap to change case.\n\n--------------------------\n\n"
default:
return nil
}
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (indexPath.section == tableView.numberOfSections - 4) {
// Update...
SVProgressHUD.show(withStatus: "Fetching latest memes, Just for you!")
if let reachable = try? Reachability.init().isReachable {
if reachable {
self.fetchedMemes = NSMutableArray()
self.fetchMemes(1)
}
}
}
if (indexPath.section == tableView.numberOfSections - 3) {
let mailComposeViewController = configuredMailComposeViewController()
if (indexPath.row == 0) {
mailComposeViewController.setSubject("Meme Maker Bug Report")
}
else {
mailComposeViewController.setSubject("Meme Maker Feedback")
}
if MFMailComposeViewController.canSendMail() {
self.present(mailComposeViewController, animated: true, completion: nil)
}
else {
self.showSendMailErrorAlert()
}
}
if (indexPath.section == tableView.numberOfSections - 2) {
// Tutorial!
showTutorial()
}
}
func showTutorial() -> Void {
let storyboard = UIStoryboard(name: "Walkthrough", bundle: nil)
let walkthrough = storyboard.instantiateViewController(withIdentifier: "WalkthroughBase") as! BWWalkthroughViewController
let page1 = storyboard.instantiateViewController(withIdentifier: "WalkthroughPage1")
let page2 = storyboard.instantiateViewController(withIdentifier: "WalkthroughPage2")
let page3 = storyboard.instantiateViewController(withIdentifier: "WalkthroughPage3")
let page4 = storyboard.instantiateViewController(withIdentifier: "WalkthroughPage4")
walkthrough.delegate = self
walkthrough.add(viewController: page1)
walkthrough.add(viewController: page2)
walkthrough.add(viewController: page3)
walkthrough.add(viewController: page4)
self.present(walkthrough, animated: true, completion: nil)
}
// MARK: - Walkthrough delegate
func walkthroughCloseButtonPressed() {
self.dismiss(animated: true, completion: nil)
}
// MARK: - Mail things
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["avikantsainidbz@gmail.com"])
mailComposerVC.setMessageBody("\n\n\n-----------Device: \(UIDevice.current.modelName)\nSystem: \(UIDevice.current.systemName)|\(UIDevice.current.systemVersion)", isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let alertController = modalAlertControllerFor("What year is this!", message: "Your device cannot send e-mail. Please check e-mail configuration and try again.")
self.present(alertController, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
// MARK: - Fetch Memes
func updateCount() -> Void {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "XMeme")
do {
let fetchedArray = try self.context?.fetch(request)
memes = NSMutableArray(array: fetchedArray!)
self.memesCountLabel.text = "\(memes.count) Memes"
}
catch _ {
print("Error in fetching.")
}
}
func fetchMemes(_ paging: Int) -> Void {
var request = URLRequest(url: apiMemesPaging(paging))
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if (error != nil) {
print("Error: %@", error?.localizedDescription ?? "nil")
DispatchQueue.main.async(execute: {
SVProgressHUD.showError(withStatus: "No connection!")
})
return
}
if (data != nil) {
do {
let persistentStoreCoordinator = self.context?.persistentStoreCoordinator
let asyncContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
asyncContext.persistentStoreCoordinator = persistentStoreCoordinator
guard let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: AnyObject] else {
print("Unable to parse JSON")
return
}
let code = json["code"] as! Int
if (code == 200) {
let jsonmemes = json["data"] as! NSArray
let memesArray = XMeme.getAllMemesFromArray(jsonmemes, context: asyncContext)!
for meme in memesArray {
self.fetchedMemes.add(meme)
}
try asyncContext.save()
DispatchQueue.main.async(execute: {
self.fetchMemes(paging + 1)
})
}
else {
self.memes = self.fetchedMemes
DispatchQueue.main.async(execute: {
SettingsManager.sharedManager().saveLastUpdateDate()
self.tableView.reloadData()
self.updateCount()
SVProgressHUD.dismiss()
})
return
}
}
catch _ {
print("Unable to parse")
SVProgressHUD.showError(withStatus: "Failed to fetch")
return
}
}
}
task.resume()
}
/*
// 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.
}
*/
}
|
//
// VehiclesTableViewController.swift
// Auto Sales
//
// Created by Mahmoud Aljarrash on 2/16/18.
// Copyright © 2018 Mahmoud Aljarrash. All rights reserved.
//
import UIKit
class VehiclesTableViewController: UITableViewController {
var bodyStyle: String = ""
var cars = [String]()
var inventory = VehiclesInventory()
var vehicles = [Vehicle]()
var fvehicles = [Vehicle]() // filtered inventory
var filteredVehicles = [Vehicle]() // filtered search result
let searchController = UISearchController(searchResultsController: nil)
override func viewWillAppear(_ animated: Bool)
{
print("Welcome to VehiclesTableViewController -> viewWillAppear()")
vehicles = inventory.vehicleList
// getVehicles()
filterInventoryByBodyStyle()
for v in vehicles
{
print(v.model)
}
}
func filterInventoryByBodyStyle()
{
print("filterInventoryByBodyStyle()")
fvehicles = [Vehicle]()
for v in vehicles
{
if String(v.bodyType) == bodyStyle
{
print("adding \(v.make) \(v.model) to the filtered list (fvehicles) ")
fvehicles.append(v)
}
}
}
func getVehicles() {
var i = 0
// filter the cars based on the body style
for car in cars
{
print("current car : ",car)
let carDetails = car.split(separator: ";")
if String(carDetails[0]) != bodyStyle
{
print("remove \(carDetails[1]) because it's not \(bodyStyle)")
print("i = " , i)
cars.remove(at: i)
}
i = i + 1
}
// // add Vehicle objects to the array
// for car in cars
// {
// print(car)
// let carDetails = car.split(separator: ";")
// let v = Vehicle(bodyType: String(carDetails[0]), make: String(carDetails[1]), model: String(carDetails[2]), year: String(carDetails[3]), color: String(carDetails[4]), price: Float(carDetails[5])!, mileage: Int(carDetails[6])! )
// //let v = Vehicle()
// // print(carDetails[5])
// vehicles.append(v)
//
// }
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
print("Welcome to VehiclesTableViewController -> viewDidLoad()")
print("user chose ", bodyStyle)
//getVehicles()
// searchResultsUpdater is a property on UISearchController that conforms to the new protocol UISearchResultsUpdating.
searchController.searchResultsUpdater = self
// the current view will show the results
searchController.obscuresBackgroundDuringPresentation = false
//Set the placeholder
searchController.searchBar.placeholder = "Search a Maker or a Model or a Year"
searchController.searchBar.sizeToFit()
searchController.hidesNavigationBarDuringPresentation = false
//navigationItem.searchController = searchController
tableView.tableHeaderView = searchController.searchBar
//setting definesPresentationContext on your view controller to true, you ensure that the search bar does not remain on the screen if the user navigates to another view controller while the UISearchController is active.
definesPresentationContext = true
}
@IBAction func unwingSegue(_ segue: UIStoryboardSegue)
{
if segue.identifier == "saveSegue"
{
let newVehicleVC = segue.source as! NewVehicleViewController
if newVehicleVC.newVehicle.make != ""
{
let newAddedVehicle = newVehicleVC.newVehicle
inventory.vehicleList.append(newAddedVehicle)
fvehicles.append(newAddedVehicle)
tableView.reloadData()
let newVehicleStr = newAddedVehicle.toString()
print("newVehicleStr -> ", newVehicleStr)
cars.append(newVehicleStr)
for car in cars
{
print("=============== ",car)
}
for vv in fvehicles
{
print("*************** ",vv)
}
}
else
{
// AlertController.showAlert(inViewController: self, title: "Missing Info", message: "Please try again and fill ALL fields")
print("unwingSegue() -> fvehicles.count ",fvehicles.count)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if isFiltering()
{
return filteredVehicles.count
}
return fvehicles.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let v : Vehicle
if isFiltering()
{
v = filteredVehicles[indexPath.row]
}
else
{
v = fvehicles[indexPath.row]
print("fvehicles size is ", fvehicles.count)
}
print("index path = ", indexPath.row)
cell.textLabel?.text = v.make + " " + v.model + " " + v.year
cell.detailTextLabel?.text = String(v.price)
//cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete
{
let vehicleToDelete = fvehicles[indexPath.row]
let vehicleToDeleteIndex = inventory.getIndex(vehicle: vehicleToDelete)
print("commit editingStyle() -> vehicleToDelete ", vehicleToDelete.toString())
print("commit editingStyle() -> inventory.getIndex(vehicle: vehicleToDelete) ", inventory.getIndex(vehicle: vehicleToDelete))
print("commit editingStyle() -> indexPath.row ",indexPath.row)
//cars.remove(at: vehicleToDeleteIndex)
fvehicles.remove(at: indexPath.row)
vehicles.remove(at: vehicleToDeleteIndex)
inventory.vehicleList.remove(at: vehicleToDeleteIndex)
tableView.deleteRows(at: [indexPath], with: .fade)
}
else if editingStyle == .insert
{
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "toVehicleInfoTVC"
{
let vehicleInfoTVC = segue.destination as! VehicleInfoTableViewController
// get the index for tapped cell
let indexPath = tableView.indexPath(for: sender as! UITableViewCell)!
print("indexPath = ", indexPath.row)
print("make =", fvehicles[indexPath.row].make)
print("model =", fvehicles[indexPath.row].model)
vehicleInfoTVC.make = fvehicles[indexPath.row].make
vehicleInfoTVC.model = fvehicles[indexPath.row].model
vehicleInfoTVC.color = fvehicles[indexPath.row].color
vehicleInfoTVC.bodyStyle = fvehicles[indexPath.row].bodyType
vehicleInfoTVC.price = String(fvehicles[indexPath.row].price)
vehicleInfoTVC.mileage = String(fvehicles[indexPath.row].mileage)
vehicleInfoTVC.year = fvehicles[indexPath.row].year
}
else if segue.identifier == "toAddNewVehicleVCSegue"
{
let destinationNavigationController = segue.destination as! UINavigationController
let newVehicleVC = destinationNavigationController.topViewController as! NewVehicleViewController
newVehicleVC.bodyStyle = self.title!
}
}
func searchBarIsEmpty() -> Bool
{
// Returns true if the text is empty or nil
return searchController.searchBar.text?.isEmpty ?? true
}
func filterContentForSearchText(_ searchText: String, scope: String = "All")
{
filteredVehicles = fvehicles.filter({ (v : Vehicle) -> Bool in
return v.make.lowercased().contains(searchText.lowercased())
|| v.model.lowercased().contains(searchText.lowercased())
|| v.year.lowercased().contains(searchText.lowercased())
})
tableView.reloadData()
}
func isFiltering() -> Bool
{
return searchController.isActive && !searchBarIsEmpty()
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension VehiclesTableViewController : UISearchResultsUpdating
{
func updateSearchResults(for searchController: UISearchController)
{
searchController.searchResultsController?.view.isHidden = false
filterContentForSearchText(searchController.searchBar.text!)
}
}
|
//
// DownloadTrainingAvgsBySessionIds.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2018. 02. 20..
// Copyright © 2018. Balazs Vidumanszki. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class DownloadTrainingAvgsBySessionIds: ServerService<[TrainingAvg]> {
private let sessionIds: [Double]
init(sessionIds: [Double]) {
self.sessionIds = sessionIds
}
override func handleServiceCommunication(alamofireRequest: DataRequest) -> [TrainingAvg]? {
var trainingAvgs: [TrainingAvg]?
let response = alamofireRequest.responseJSON()
if let json = response.result.value {
let jsonValue = JSON(json)
if let jsonArray = jsonValue.array {
trainingAvgs = [TrainingAvg]()
for trainingAvgDto in jsonArray {
let trainingAvg = TrainingAvg(json: trainingAvgDto)
if trainingAvg != nil {
trainingAvgs?.append(trainingAvg!)
}
}
}
}
return trainingAvgs
}
override func initUrlTag() -> String {
return "avgtraining/downloadBySessionIds"
}
override func initMethod() -> HTTPMethod {
return .post
}
override func initEncoding() -> ParameterEncoding {
return ArrayEncoding()
}
override func initParameters() -> Parameters? {
return sessionIds.asParameters()
}
override func getManagerType() -> BaseManagerType {
return TrainingManagerType.download_training_avg
}
}
|
//
// MenuView.swift
// AchibanSushi
//
// Created by Ari Supriatna on 08/05/21.
//
import SwiftUI
struct MenuView: View {
let columns: [GridItem] = [
.init(.flexible(minimum: 180)),
.init(.flexible(minimum: 180))
]
var body: some View {
ScrollView {
LazyVStack {
LazyVGrid(columns: columns, spacing: 16) {
ForEach(listMenu) {
MenuItemView(menu: $0)
}
}
}
.padding(16)
}
.navigationTitle(Text("Menu"))
}
}
struct MenuView_Previews: PreviewProvider {
static var previews: some View {
MenuView()
}
}
struct MenuItemView: View {
var menu: Menu
var body: some View {
VStack(spacing: 16) {
Image(menu.image)
.resizable()
.scaledToFit()
.frame(width: 170)
Text(menu.name)
.font(.headline)
Text("Rp \(menu.price)")
#if !APPCLIP
Button {
print("Add item")
} label: {
Text("Add Item")
.font(.system(size: 16, weight: .semibold, design: .rounded))
.foregroundColor(.green)
.frame(width: 150, height: 35)
.overlay(
Capsule().stroke(Color.green, lineWidth: 1)
)
}
#endif
}
.padding(.all)
.frame(width: 180, height: 250)
.background(Color.white)
.mask(RoundedRectangle(cornerRadius: 20))
.shadow(color: .black.opacity(0.2), radius: 10, x: 0, y: 10)
}
}
|
import Foundation
extension String {
var isBlank: Bool {
return trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
var isPresent: Bool {
return !isBlank
}
static func isBlank(_ aString: String) -> Bool {
return aString.isBlank
}
static func isPresent(_ aString: String) -> Bool {
return !isBlank(aString)
}
}
extension Optional where Wrapped == String {
var isBlank: Bool {
if let unwrapped = self {
return unwrapped.isBlank
} else {
return true
}
}
var isPresent: Bool {
return !isBlank
}
static func isBlank(_ anOptional: Optional) -> Bool {
return anOptional.isBlank
}
static func isPresent(_ anOptional: Optional) -> Bool {
return !isBlank(anOptional)
}
}
|
//
// BookListVC.swift
// MVVM+ReactiveSwift
//
// Created by pxh on 2019/2/21.
// Copyright © 2019 pxh. All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
/// book list view controller
class BookListVC: UIViewController {
private let tableview = UITableView()
private lazy var viewModel = {
return BookListVM()
}()
override func viewDidLoad() {
super.viewDidLoad()
deploySubviews()
initialBind()
}
/// 配置子页面
private func deploySubviews(){
self.view.addSubview(tableview)
tableview.tableFooterView = UIView()
tableview.snp.makeConstraints { (make) in
make.top.bottom.left.right.equalTo(0)
}
}
/// 绑定模型
private func initialBind(){
tableview.delegate = viewModel
tableview.dataSource = viewModel
viewModel.bookAction.apply(()).startWithResult { result in
switch result{
case let .success(value):
self.viewModel.models = value
self.tableview.reloadData()
default:
break
}
}
}
}
|
//
// DatabaseServiceTest.swift
// smartWeather
//
// Created by Florian on 07/11/15.
// Copyright © 2015 FH Joanneum. All rights reserved.
//
import Foundation
import XCTest
@testable import smartWeather
class DatabaseServiceTests:XCTestCase {
func testGetLocationFromCityName() {
let s = DatabaseService()
let location = s.getLocationFromCityName("Kapfenberg")
XCTAssertEqual("Kapfenberg",location?.name)
//Standardmäßig 7872257, könnte aber auch 2774773 sein, da beide den Namen Kapfenberg haben
XCTAssertEqual(7872257,location?.cityId)
XCTAssertEqual(47.453991 ,location?.position.lat)
XCTAssertEqual(15.27019,location?.position.long)
}
func testGetLocationsForCityIDs() {
let s = DatabaseService()
let locations = s.getLocationsForCityIDs([7872257,2643743,2778067,7873556]) //[Kapfenberg,London,Graz,Birkfeld]
XCTAssertEqual(4,locations.count)
if locations.count == 4 {
//Sortiert nach Alphabeth
XCTAssertEqual("Birkfeld", locations[0].name)
XCTAssertEqual("Graz", locations[1].name)
XCTAssertEqual("Kapfenberg", locations[2].name)
XCTAssertEqual("London", locations[3].name)
}
}
func testUpdateCitiesList() {
XCTAssertTrue(false,"long running test not active")
return
//let s = DatabaseService()
//s.updateCitiesList()
}
func testReadCitiesList() {
let s = DatabaseService()
s.readCitiesList()
}
} |
//
// WebService.swift
// Seattle Bike Park
//
// Created by Alex Cevallos on 11/5/15.
// Copyright © 2015 Alex Cevallos. All rights reserved.
//
import Foundation
class WebService: ProxyProtocol {
// MARK: TypeAliases
typealias CompletitionHandler = (returnedJSON: AnyObject?, errorMessage: String?) -> Void
// MARK: Member Variables
var urlSessionTask: NSURLSessionTask? // The task (actual action)
var urlSession: NSURLSession // The session of the data transfer
var sessionConfiguration: NSURLSessionConfiguration // Settings of the session
let completitionHandler: CompletitionHandler? // Lets us know when data is returned
// MARK: Initializers
init(completition: CompletitionHandler?) {
// Sets up session
self.sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
self.sessionConfiguration.HTTPAdditionalHeaders = ["X-App-Token" : ""] // Our API key is the value
self.urlSession = NSURLSession(configuration: self.sessionConfiguration)
// We want our completition handler to be used by our WebService class
self.completitionHandler = completition
}
// MARK: HTTP Methods
func GET(urlToGet: NSURL) {
self.urlSessionTask = self.urlSession.dataTaskWithURL(urlToGet, completionHandler: { (data, response, error) -> Void in
self.methodHelper_parseResponse(data, response: response, error: error)
})
self.urlSessionTask?.resume()
}
// MARK: Helper Methods - Parsing
func methodHelper_parseResponse(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void {
var resultingJSON: AnyObject?
var resultingErrorMessage: String?
if let _ = error { // Error establishing a connection
resultingErrorMessage = self.methodHelper_parseError(WebServiceConstants_Errors.GenericError)
} else {
// Check: Do we have an HTTP Response?
if let _ = response as? NSHTTPURLResponse {
// Check: Do we have data returned from the API call ?
if let dataReturned = data {
do {
// Try: JSON parsing
let returnJSON = try NSJSONSerialization.JSONObjectWithData(dataReturned, options: NSJSONReadingOptions.MutableContainers)
do { // We don't want this JSON if there is an error..
try self.methodHelper_isValidJSON(returnJSON)
resultingJSON = returnJSON
print(resultingJSON)
} catch WebServiceConstants_Errors.InvalidJSON {
self.methodHelper_parseError(WebServiceConstants_Errors.InvalidJSON)
}
} catch { // Catch: Was there an error in NSJSONSerialization/ HTTP Status code ?
// Regardless, we fetch the correct error message
resultingErrorMessage = self.methodHelper_parseError(WebServiceConstants_Errors.GenericError)
}
}
}
}
// Let our class completition handler know we are good !
if let completionHandler = self.completitionHandler {
completionHandler(returnedJSON: resultingJSON, errorMessage: resultingErrorMessage)
}
}
func methodHelper_parseError(error: WebServiceConstants_Errors) -> String { // Will handle errors, for now: basic return
return WebServiceConstants_ErrorMessages.DefaultErrorMessage.rawValue
}
// MARK: Helper Methods - Validity
func methodHelper_isValidJSON(json: AnyObject?) throws { // Its fine if it is Dictionary or array
if let _ = json as? NSDictionary {
return
}
if let _ = json as? NSArray {
return
}
throw WebServiceConstants_Errors.InvalidJSON
}
}
|
//
// ListViewController.swift
// test-app-movie
//
// Created by Элина on 19.11.2020.
// Copyright © 2020 Элина. All rights reserved.
//
import UIKit
class ListViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UISearchBarDelegate {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var searchBar: UISearchBar!
let storage = Storage.shared
var movie = false
var search = false
var keyword = ""
override func viewWillAppear(_ animated: Bool) {
collectionView.delegate = self
collectionView.dataSource = self
searchBar.delegate = self
navigationController?.navigationBar.isHidden = true
if !search {
storage.movies.removeAll()
let url = Utilities().formURL(path: .trendingpath, id: nil, parameters: [.apikey:Utilities.apikey])
storage.getMovies(name: nil, id: nil, url: url) { (comp) in
if comp {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
}else {
let url = Utilities().formURL(path: .namepath, id: nil, parameters: [.apikey:Utilities.apikey, .query : keyword])
self.search = true
storage.movies.removeAll()
storage.getMovies(name: keyword, id: nil, url: url) { (comp) in
if comp {
self.movie = true
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
searchBar.delegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return storage.movies.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCollectionViewCell
cell.movie = storage.movies[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let detailVC = storyboard?.instantiateViewController(withIdentifier: "detailVC") as! DetailsViewController
let url = Utilities().formURL(path: .trendingpath, id: nil, parameters: [.apikey:Utilities.apikey])
storage.getMovies(name: nil, id: nil, url: url) { (comp) in
if comp {
let movieid = self.storage.movies[indexPath.row].id
self.storage.movies.removeAll()
let url = Utilities().formURL(path: .detailspath, id: movieid, parameters: [.apikey:Utilities.apikey])
self.storage.getMovies(name: nil, id: movieid, url: url) { (comp) in
if comp {
detailVC.movie = self.storage.movies[0]
DispatchQueue.main.async {
self.navigationController?.show(detailVC, sender: self)
}
}
}
}
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
var keyword = searchBar.text
keyword = keyword?.replacingOccurrences(of: " ", with: "%20")
storage.movies.removeAll()
guard let k = keyword else {
return
}
if k.isEmpty || k.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {return}
self.keyword = k
let url = Utilities().formURL(path: .namepath, id: nil, parameters: [.apikey:Utilities.apikey, .query : k])
self.search = true
storage.getMovies(name: keyword, id: nil, url: url) { (comp) in
if comp {
self.movie = true
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
}
}
|
//
// MoviesViewModel.swift
// MovieApp
//
// Created by Ádám-Krisztián Német on 11.05.2021.
//
import Foundation
class MovieViewModel: ObservableObject {
@Published var movies = [Movie]()
func fetchMovies(searchText : String)
{
MovieService.sharedInstance.fetchPopularMoviesData(searchText: searchText, completion: { result in
self.movies = result
})
}
}
|
//
// DemoFiles.swift
// ashish
//
// Created by Planetinnovative on 9/17/18.
// Copyright © 2018 plan. All rights reserved.
//
import Foundation
class eventslists: NSObject {
var event: String?
var mainimage: String?
var eventDescription:String?
var startDate: String?
var endDate: String?
init(json: NSDictionary) {
event = json["eventName"] as? String
mainimage = json["mainImage"] as? String
eventDescription = json["eventDescription"] as? String
startDate = json["start_date"] as? String
endDate = json["end_date"] as? String
}
override init(){
}
}
|
//
// WeeklyViewController.swift
// Calendar
//
// Created by 정구열 on 03/11/2018.
// Copyright © 2018 guyeol_jeong. All rights reserved.
//
import UIKit
import RealmSwift
class WeeklyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var yearLabel: UILabel!
var selectedIdx = 0
override func viewDidLoad() {
super.viewDidLoad()
yearLabel.text = "\(year) 년"
print(Realm.Configuration.defaultConfiguration.fileURL!)
}
@IBAction func backBtn(_ sender: Any) {
day-=7
if day <= 0 {
month-=1
if month < 0 {
month = 11
year -= 1
}
day = DaysInMonth[month] + day
}
tableView.reloadData()
}
@IBAction func nextBtn(_ sender: Any) {
day+=7
if day > DaysInMonth[month] {
day -= DaysInMonth[month]
month += 1
if month > 11 {
month = 0
year += 1
}
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 7
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ScheduleCell", for: indexPath) as! TableViewCell
if day + indexPath.row > DaysInMonth[month] {
if month + 1 > 11 {
cell.DateLabel?.text = "1 / \(day + indexPath.row - DaysInMonth[11])"
} else {
cell.DateLabel?.text = "\(month + 2) / \(day + indexPath.row - DaysInMonth[month])"
}
} else {
cell.DateLabel?.text = "\(month+1) / \(day + indexPath.row)"
}
cell.TextField?.text = "스케쥴이 없습니다."
return cell
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.tabBarController?.selectedIndex = 2
}
}
|
//
// ValidationViewController.swift
// RegHackTO
//
// Created by Yevhen Kim on 2016-11-25.
// Copyright © 2016 Yevhen Kim. All rights reserved.
//
import Foundation
import UIKit
class ValidationViewController: UIViewController, UIImagePickerControllerDelegate, UITextFieldDelegate, UINavigationControllerDelegate {
@IBOutlet weak var driverLicenseImageView: UIImageView!
@IBOutlet weak var PassportImageView: UIImageView!
@IBOutlet weak var check2: UIImageView!
@IBOutlet weak var check1: UIImageView!
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var dob: UITextField!
@IBOutlet weak var addressField: UITextField!
@IBOutlet weak var reputation: UITextField?
@IBOutlet weak var sinNumber: UITextField!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var creditReportLink: UITextField!
@IBOutlet weak var financialCircumstancesLink: UITextField?
let stylesheet: Styles = Styles.sharedInstance
var imageDL: UIImage?
var imagePass: UIImage?
var isDLTapped = false
var isPassTapped = false
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: false)
toggleNextButton()
setupKeyboardNotification()
//takeDLImage()
setupDL()
takePassImage()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
func takeDLImage() {
let tapGestureRocognizer = UITapGestureRecognizer(target: self, action: #selector(imageDLTapped))
driverLicenseImageView.isUserInteractionEnabled = true
driverLicenseImageView.addGestureRecognizer(tapGestureRocognizer)
}
func takePassImage() {
let tapGestureRocognizer = UITapGestureRecognizer(target: self, action: #selector(imagePassTapped))
PassportImageView.isUserInteractionEnabled = true
PassportImageView.addGestureRecognizer(tapGestureRocognizer)
}
func imageDLTapped() {
self.isDLTapped = true
tap()
}
func imagePassTapped() {
self.isPassTapped = true
tap()
}
func tap() {
let imagePicker:UIImagePickerController = UIImagePickerController.init()
imagePicker.sourceType = .camera
imagePicker.cameraDevice = .front
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: {})
}
func setupKeyboardNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
// MARK: keyboard actions
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y += keyboardSize.height
}
}
}
// change next button state
func toggleNextButton() {
let styleSheet = Styles.sharedInstance
if ((firstName.text?.isEmpty)! || (lastName.text?.isEmpty)! || (dob.text?.isEmpty)! || (addressField.text?.isEmpty)! || (creditReportLink.text?.isEmpty)! || (sinNumber.text?.isEmpty)!) {
saveButton.isEnabled = false
saveButton.backgroundColor = styleSheet.lightgrayColor
}
else {
saveButton.isEnabled = true
saveButton.setTitleColor(styleSheet.whiteColor, for: .normal)
saveButton.backgroundColor = styleSheet.backgroundColor
saveButton.layer.cornerRadius = styleSheet.buttonCornerRadius
}
}
// MARK pragma: Image picker Delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// if (self.isDLTapped) {
// self.driverLicenseImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
// self.driverLicenseImageView.contentMode = .scaleToFill
// self.driverLicenseImageView.layer.masksToBounds = true
// self.driverLicenseImageView.layer.cornerRadius = stylesheet.buttonCornerRadius
// //FIXME: add completion handler to safe image
// self.dismiss(animated: true)
// self.check1.alpha = 1
// self.isDLTapped = false
// }
if (self.isPassTapped) {
self.PassportImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.PassportImageView.contentMode = .scaleToFill
self.PassportImageView.layer.masksToBounds = true
self.PassportImageView.layer.cornerRadius = stylesheet.buttonCornerRadius
//FIXME: add completion handler to safe image
self.dismiss(animated: true)
self.check2.alpha = 1
self.isPassTapped = false
}
}
func setupDL() {
self.driverLicenseImageView.image = UIImage(named: "default.jpg")
self.driverLicenseImageView.contentMode = .scaleToFill
self.driverLicenseImageView.layer.masksToBounds = true
self.driverLicenseImageView.layer.cornerRadius = stylesheet.buttonCornerRadius
self.check1.alpha = 1
}
// MARK pragma: Text Field Delegate
func textFieldDidEndEditing(_ textField: UITextField) {
toggleNextButton()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@IBAction func saveButtonPressed(_ sender: Any) {
if let InstitutionVC = self.storyboard?.instantiateViewController(withIdentifier: "InstitutionVC") {
DispatchQueue.main.async {
self.navigationController?.pushViewController(InstitutionVC, animated: true)
}
}
}
}
|
//
// CustomAlertView.swift
// mytine
//
// Created by 남수김 on 2020/08/04.
// Copyright © 2020 황수빈. All rights reserved.
//
import UIKit
class CustomAlertView: UIView {
private var labelText: String?
private var okCallback: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(text: String, okCallback: (() -> Void)?) {
self.init()
self.labelText = text
self.okCallback = okCallback
alertBulider()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func alertBulider() {
let effect = UIBlurEffect(style: .dark)
let containView = UIVisualEffectView(effect: effect)
containView.alpha = 0.85
containView.frame = UIScreen.main.bounds
containView.isUserInteractionEnabled = false
self.addSubview(containView)
containView.snp.makeConstraints {
$0.top.bottom.right.left.equalTo(self)
}
let alert: UIView = {
let view = UIView()
view.backgroundColor = .white
view.viewRounded(cornerRadius: 12)
self.addSubview(view)
view.snp.makeConstraints {
$0.width.equalTo(312)
$0.height.equalTo(128)
$0.center.equalTo(self.snp.center)
}
return view
}()
let _: UILabel = {
let label = UILabel()
label.text = labelText
label.numberOfLines = 0
label.font = .systemFont(ofSize: 14, weight: .medium)
label.textColor = .mainFont
alert.addSubview(label)
label.snp.makeConstraints {
$0.top.leading.trailing.equalToSuperview().offset(20)
}
return label
}()
let okButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(self.alertOkAction), for: .touchUpInside)
button.setTitle("확인", for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 12, weight: .bold)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .mainBlue
button.viewRounded(cornerRadius: 12)
alert.addSubview(button)
button.snp.makeConstraints {
$0.width.equalTo(55)
$0.height.equalTo(30)
$0.right.equalToSuperview().offset(-20)
$0.bottom.equalToSuperview().offset(-20)
}
return button
}()
let _: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(self.alertCancelAction), for: .touchUpInside)
button.setTitle("취소", for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 12, weight: .bold)
button.setTitleColor(.subFont, for: .normal)
alert.addSubview(button)
button.snp.makeConstraints {
$0.width.equalTo(55)
$0.height.equalTo(30)
$0.right.equalTo(okButton.snp.left).offset(-20)
$0.bottom.equalToSuperview().offset(-20)
}
return button
}()
}
@objc
func alertCancelAction() {
self.removeFromSuperview()
}
@objc
func alertOkAction() {
okCallback?()
self.removeFromSuperview()
}
}
|
protocol optionalProtocol: class {
func done()
}
extension optionalProtocol {
func done() {
print("Optional Protocol")
}
}
class exampleOne: optionalProtocol {
func done() {
print("Conforming to Protocol")
}
}
class exampleTwo: optionalProtocol {
}
let one = exampleOne()
let two = exampleTwo()
one.done()
two.done()
|
//
// Opener.swift
// FormulaE
//
// Created by Antonio Ivcec on 21/10/18.
// Copyright © 2018 Antonio Ivcec. All rights reserved.
//
import UIKit
import FBSDKCoreKit
protocol Opener {
var sourceAppKey: String { get }
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool
}
|
//
// DetailViewController.swift
// WatsonMobileUI
//
// Created by liuke on 16/7/22.
// Copyright © 2016. All rights reserved.
//
import UIKit
import Foundation
class DetailViewController: UIViewController {
var data:Goods?
var mainView:UIView?
var showAddGoodButton:Bool = true
var delegate : RegisterDelegate!
override func viewDidLoad() {
super.viewDidLoad()
//let data = Goods.init(id: "15", name: "CITIZEN TITANIA LINE HAPPY FLIGHT", price: "¥575,000", details: "Citizen Watch Xc Happy Flight Titania Line Eco-drive Eco-drive Type Display Type Needle Receiving Station Multi-radio Clock Kitagawa Keiko Ad Wearing Model Media Model Ec1044-55w Women", imgurl: "http://fs.scene7.com/is/image/flagshop/v_243815_01.jpg?$500$")
print("detailviewcontroller load.")
let screenWidth = UIScreen.mainScreen().bounds.width
let screenHeight = UIScreen.mainScreen().bounds.height
let mainView = UIView(frame:CGRectMake(0, 0, screenWidth, screenHeight))
mainView.backgroundColor = UIColor.whiteColor()
//背景图片
self.view.backgroundColor = UIColor.whiteColor()
//图片
let thumbQueue = NSOperationQueue()
let newImage = UIImage(named:"loading110.png")!
let iconImageView = UIImageView(image:newImage);
iconImageView.frame = CGRectMake(50, 20, self.view.frame.size.width-100, 240)
// 异步加载网络图片
let request = NSURLRequest(URL:NSURL.init(string: data!.imgurl)!)
NSURLConnection.sendAsynchronousRequest(request, queue: thumbQueue, completionHandler: { response, data, error in
if (error != nil) {
print(error)
} else {
let image = UIImage.init(data :data!)
dispatch_async(dispatch_get_main_queue(), {
iconImageView.image = image
iconImageView.frame = CGRectMake(0, 0, self.view.frame.size.width, 280)
})
}
})
iconImageView.contentMode = UIViewContentMode.ScaleAspectFit
mainView.addSubview(iconImageView)
//商品名称
let imgHight:CGFloat = 280
let labelName: UILabel = UILabel()
labelName.frame = CGRect(x:5, y:imgHight, width:(self.view.frame.size.width-10)*0.7, height:30)
labelName.text = data!.name
labelName.font = UIFont(name:"HelveticaNeue", size:20)
labelName.textAlignment = NSTextAlignment.Center
labelName.adjustsFontSizeToFitWidth=true //自适应宽度
mainView.addSubview(labelName)
//价格
let labelPrice: UILabel = UILabel()
labelPrice.frame = CGRect(x:(self.view.frame.size.width-10)*0.7, y:imgHight+25, width:(self.view.frame.size.width-10)*0.3, height:40)
labelPrice.text = data!.price
labelPrice.textAlignment = NSTextAlignment.Center
labelPrice.highlighted = true
labelPrice.font = UIFont(name:"HelveticaNeue", size:25)
labelPrice.adjustsFontSizeToFitWidth=true
labelPrice.textColor=UIColor.redColor()
mainView.addSubview(labelPrice)
//商品详细
let labelDetail: UILabel = UILabel()
labelDetail.frame = CGRect(x:5, y:imgHight+30, width:(self.view.frame.size.width-10)*0.7, height:55)
labelDetail.text = data!.details
labelDetail.backgroundColor = UIColor.whiteColor()
labelDetail.textAlignment = NSTextAlignment.Left
labelDetail.font = UIFont(name:"HelveticaNeue", size:15)
labelDetail.adjustsFontSizeToFitWidth=true //自适应宽度
labelDetail.numberOfLines=0 //多行显示
mainView.addSubview(labelDetail)
//竖线
let verticalLine = UIView()
verticalLine.frame = CGRect(x:10+(self.view.frame.size.width-10)*0.7, y:imgHight+15, width:1, height:60)
verticalLine.backgroundColor = UIColor.grayColor()
mainView.addSubview(verticalLine)
//横线
let horizontalLine = UIView()
horizontalLine.frame = CGRect(x:10, y:imgHight+95, width:self.view.frame.size.width-20, height:1.5)
horizontalLine.backgroundColor = UIColor.purpleColor()
mainView.addSubview(horizontalLine)
//提示文字
let txtLocation: UILabel = UILabel()
txtLocation.frame = CGRect(x:10, y:imgHight+100, width:(self.view.frame.size.width-10), height:20)
txtLocation.text = "Please follow the map below to find this item."
txtLocation.backgroundColor = UIColor.whiteColor()
txtLocation.textAlignment = NSTextAlignment.Left
txtLocation.font = UIFont(name:"HelveticaNeue", size:15)
mainView.addSubview(txtLocation)
//地图
let mapImage:UIImage = UIImage(named:"floor_map.png")!
let mapImageView:UIImageView = UIImageView(image:mapImage)
mapImageView.frame = CGRectMake(20, imgHight+120, self.view.frame.size.width-40, 280)
mapImageView.contentMode = UIViewContentMode.ScaleAspectFit
mainView.addSubview(mapImageView)
//制定位置图片
let locationImage:UIImage = UIImage(named:"google_map.png")!
let locationImageView:UIImageView = UIImageView(image:locationImage)
locationImageView.frame = CGRectMake(95, imgHight+150, 50, 50)
locationImageView.contentMode = UIViewContentMode.ScaleAspectFit
mainView.addSubview(locationImageView)
// 返回按钮
let backImageButton = UIButton(frame:CGRectMake(50,imgHight+410,120,35))
backImageButton.backgroundColor = UIColor.blueColor()
backImageButton.setTitle("Back", forState:UIControlState.Normal)
backImageButton.layer.cornerRadius = 5 //圆角
backImageButton.alpha = 0.4
backImageButton.addTarget(self,action:#selector(tappedDown(_:)),forControlEvents:.TouchDown)
backImageButton.addTarget(self, action:#selector(DetailViewController.backToPrevious) ,
forControlEvents:UIControlEvents.TouchUpInside)
mainView.addSubview(backImageButton)
// 加入购物车按钮,动态显示和隐藏
if self.showAddGoodButton == true {
//创建加入购物车按钮
let button:UIButton = UIButton(frame:CGRectMake(180, imgHight+410, 180, 35))
//设置按钮文字
button.backgroundColor = UIColor.purpleColor()
button.setTitle("Add to shopCart", forState:UIControlState.Normal)
button.layer.cornerRadius = 5 //圆角
button.alpha = 0.6
button.addTarget(self,action:#selector(tappedDown(_:)),forControlEvents:.TouchDown)
button.addTarget(self,action:#selector(tappedUp(_:)),forControlEvents:.TouchUpOutside)
button.addTarget(self,action:#selector(tapped(_:)),forControlEvents:.TouchUpInside)
mainView.addSubview(button)
} else {
//返回按钮居中表示
backImageButton.frame.origin.x = (self.view.frame.size.width - 120) / 2
}
self.view.addSubview(mainView)
}
//隐藏顶部状态栏
override func prefersStatusBarHidden()->Bool{
return true
}
//加入购物车事件
func tapped(button:UIButton){
//print("tapped")
let addGood:Goods = Goods.init(id:data!.id, name: data!.name, price: data!.price, details: data!.details, imgurl: data!.imgurl)
//购物车追加
self.delegate!.registerName(addGood)
self.dismissViewControllerAnimated( true, completion : nil )
}
//按钮按下事件(颜色改变)
func tappedDown(button:UIButton){
button.alpha = 0.2
}
//按钮松开事件(颜色改变)
func tappedUp(button:UIButton){
button.alpha = 0.6
}
//返回按钮
func backToPrevious() {
//print("点击了返回键")
self.dismissViewControllerAnimated( true, completion : nil )
//self.navigationController?.popViewControllerAnimated(true)
}
} |
//
// RootToolBar.swift
// HttpRequestMonitor
//
// Created by Eden on 2021/9/15.
//
import UIKit
#if targetEnvironment(macCatalyst)
private struct TouchBarIdentifier
{
static let startServer: NSTouchBarItem.Identifier = NSTouchBarItem.Identifier(MenuManager.identifier + ".startServer")
static let stopServer: NSTouchBarItem.Identifier = NSTouchBarItem.Identifier(MenuManager.identifier + ".stopServer")
static let allIdentifiers: Array<NSTouchBarItem.Identifier> = [TouchBarIdentifier.startServer, TouchBarIdentifier.stopServer]
}
extension RootViewController: NSTouchBarDelegate
{
override
public func makeTouchBar() -> NSTouchBar? {
let touchBar = NSTouchBar().fluent
.delegate(self)
.defaultItemIdentifiers(TouchBarIdentifier.allIdentifiers)
.subject
return touchBar
}
public func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem?
{
var touchBarItem: NSTouchBarItem? = nil
if identifier == TouchBarIdentifier.startServer,
let image = UIImage(systemName: "arrowtriangle.right.fill") {
touchBarItem = NSButtonTouchBarItem(identifier: identifier, title: "Start server", image: image, target: self, action: Selector(("startServerAction:"))).fluent
.bezelColor(.systemBlue)
.subject
}
if identifier == TouchBarIdentifier.stopServer,
let image = UIImage(systemName: "stop.fill") {
touchBarItem = NSButtonTouchBarItem(identifier: identifier, title: "Stop server", image: image, target: self, action: Selector(("stopServerAction:"))).fluent
.bezelColor(.systemRed)
.subject
}
return touchBarItem
}
}
#endif
|
//Solution goes in Sources
class BeerSong {
var numberOfBeerBottles: Int
init(numberOfBeerBottles: Int) {
self.numberOfBeerBottles = numberOfBeerBottles
}
func generateVersesOfBeerSong() -> String {
var songWords = ""
while numberOfBeerBottles > -1 {
switch numberOfBeerBottles {
case 0:
songWords += "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall."
case 1:
songWords += "1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n\n"
default:
songWords += "\(numberOfBeerBottles) bottles of beer on the wall, \(numberOfBeerBottles) bottles of beer.\nTake one down and pass it around, \(numberOfBeerBottles - 1) bottle\((numberOfBeerBottles - 1 == 1 ? "" : "s")) of beer on the wall.\n\n"
}
numberOfBeerBottles -= 1;
}
return songWords
}
}
|
//
// PhoneKeyPads.swift
// AlgorithmSwift
//
// Created by Liangzan Chen on 7/10/18.
// Copyright © 2018 clz. All rights reserved.
//
import Foundation
func printLettersOfPhoneNumbers(_ numbers: [Int]) {
let table: [[Character]] = [[" "],
[" "],
["A", "B", "C"],
["D", "E", "F"],
["G", "H", "I"],
["J", "K", "L"],
["M", "N", "O"],
["P", "Q", "R", "S"],
["T", "U", "V"],
["W", "X", "Y", "Z"]]
var output = [Character](repeatElement(" ", count: numbers.count))
func printLetters(_ numbers: [Int], _ startIndex: Int) {
if startIndex == numbers.count {
print(output)
return
}
for c in table[numbers[startIndex]] {
output[startIndex] = c
printLetters(numbers, startIndex + 1)
}
}
printLetters(numbers, 0)
}
|
// nef:begin:header
/*
layout: docs
title: Running side effects
*/
// nef:end
// nef:begin:hidden
import Foundation
import Bow
import BowEffects
// nef:end
/*:
# Running side effects
{:.beginner}
beginner
`IO` suspends side effects; i.e. it prevents them from running. But at some point they need to be actually evaluated in order to produce the expected outcome of the program. This section shows the different ways you have to execute an `IO` program.
For the rest of this page, consider the following function from a shopping service that fetches articles from the network, from a given category on a specific page and providing a limit to the number of articles that are received:
*/
// nef:begin:hidden
struct Article {}
enum Category {
case boardgames
case technology
case comics
}
enum APIError: Error {}
// nef:end
func fetchArticles(from category: Category, page: UInt, limit: UInt) -> IO<APIError, [Article]>
// nef:begin:hidden
{ return IO.pure([])^ }
// nef:end
/*:
## Synchronous run
We can run the function above synchronously using the `unsafeRunSync ` method on `IO`:
*/
let articles: [Article] = try fetchArticles(from: .boardgames, page: 1, limit: 30).unsafeRunSync()
/*:
This function will return the array of articles that it fetched if everything went well, or will throw an `APIError` if there was any problem (thus, we need to invoke this function using the `try` keyword). If, for some reason, an error of a different type arises, it will cause a fatal error, as our `IO` will not know how to handle it.
If we prefer, there is a safer version of this method, called `unsafeRunSyncEither`:
*/
let result: Either<APIError, [Article]> = fetchArticles(from: .technology, page: 3, limit: 10).unsafeRunSyncEither()
/*:
This way, the result of the execution will be wrapped in an `Either` value; on the right side, we can find the successful value, and on the left side, the error that may happen.
Both versions will block the execution until the evaluation of the `IO` value finishes.
## Asynchronous run
If we want to avoid blocking the execution, we can run the `IO` value using `unsafePerformAsync` and passing a callback:
*/
fetchArticles(from: .boardgames, page: 4, limit: 15).unsafeRunAsync { (result: Either<APIError, [Article]>) in
// Process result
}
/*:
## Running on a different `DispatchQueue`
By default, all options to run an `IO` will use `DispatchQueue.main` to run. If you want to specify your own queue, you can provide it as a parameter to the call:
*/
// On the background queue
try fetchArticles(from: .comics, page: 10, limit: 25).unsafeRunSync(on: .global(qos: .background))
// On a custom queue
fetchArticles(from: .boardgames, page: 1, limit: 5).unsafeRunSyncEither(on: DispatchQueue(label: "MyQueue"))
// On the main queue, equivalent to omitting the parameter
fetchArticles(from: .technology, page: 8, limit: 10).unsafeRunAsync(on: .main) { result in
// ... Process result ...
}
|
//
// PoseEntity.swift
// Runner
//
// Created by Vladimir on 06.05.2021.
//
import Foundation
struct PoseEntity: Codable {
let landmarks: Array<LandmarkEntity>
}
|
// Copyright 2017, Postnummeruppror.nu
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import MapKit
import CoreLocation
import CoreData
extension Bundle {
var releaseVersionNumber: String? {
return infoDictionary?["CFBundleShortVersionString"] as? String
}
var buildVersionNumber: String? {
return infoDictionary?["CFBundleVersion"] as? String
}
}
class ReportController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var locationManager = CLLocationManager()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
@IBAction func showAboutDialog(_ sender: Any) {
// See https://stackoverflow.com/questions/30874386/how-to-correctly-open-url-from-uialertviewcontrollers-handler for hints on handling link opening from alert
let alert = UIAlertController(title: "Om postnummeruppror", message: "Vi vill skapa en ny postnummerdatabas fri att använda för alla. Samtidigt vill vi visa för politiker att affärsmodellen för postnummer är förlegad. \nEftersom ursprungskällan till postnummer är skyddad måste vi bygga upp en ny databas från grunden. Vi vill göra det med din hjälp. Genom att rapportera in adressinformation med någon av våra appar kan du bidra till databasen.\n(v " + String(describing: Bundle.main.releaseVersionNumber!) + "b" + String(describing: Bundle.main.buildVersionNumber!) + ")" , preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
alert.addAction(UIAlertAction(title: "Läs mer", style: UIAlertActionStyle.default, handler: {
(action) in
UIApplication.shared.open(URL(string: "https://postnummeruppror.nu/")!, options: [:], completionHandler: nil)
NSLog("Opening link")
}))
self.present(alert, animated: true, completion: nil)
}
@IBOutlet weak var mapView: MKMapView!
var tileRenderer: MKTileOverlayRenderer!
@IBOutlet weak var labelIntro: UILabel!
@IBOutlet weak var postalCode: UITextField!
@IBOutlet weak var postalTown: UITextField!
@IBOutlet weak var streetName: UITextField!
@IBOutlet weak var houseNumber: UITextField!
@IBOutlet weak var houseName: UITextField!
@IBOutlet weak var labelValidationResult: UILabel!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var clearButton: UIButton!
@IBOutlet weak var accuracyLabel: UILabel!
var latitude = 0.0
var longitude = 0.0
var accuracy = 0.0
var altitude = 0.0
@IBAction func clearForm(_ sender: Any) {
postalTown.text = ""
postalCode.text = ""
streetName.text = ""
houseNumber.text = ""
houseName.text = ""
}
fileprivate func validate(_ textField: UITextField) -> (Bool, String?) {
guard let text = textField.text else {
return (false, nil)
}
if textField == postalCode {
return (text.count == 5, "Fel antal siffror i postnummer")
}
if textField == postalTown {
return (text.count > 1, "Ange en postort")
}
if textField == streetName {
return (text.count > 3, "Ange ett gatunamn")
}
if textField == houseNumber {
return (text.count > 0, "Ange gatunummer")
}
return (true, "")
}
struct Coordinate: Codable {
let provider: String
let accuracy: Double
let latitude: Double
let longitude: Double
let altitude: Double
}
struct PostalAddress: Codable {
let postalCode: String
let postalTown: String
let streetName: String
let houseNumber: String
let houseName: String
}
struct Report: Codable {
let applicationVersion: String
let application: String
let accountIdentity: String
let coordinate: Coordinate
let postalAddress: PostalAddress
}
@IBAction func sendReport(_ sender: Any) {
// Show modal spinner while sending data
DispatchQueue.main.async { [unowned self] in
LoadingOverlay.shared.showOverlay(view: UIApplication.shared.keyWindow!)
}
// Prepare data
let coordinate = Coordinate(provider: "gps",
accuracy: self.accuracy,
latitude: self.latitude,
longitude: self.longitude,
altitude: self.altitude)
let postalAddress = PostalAddress(postalCode: postalCode.text ?? "",
postalTown: postalTown.text ?? "",
streetName: streetName.text ?? "",
houseNumber: houseNumber.text ?? "",
houseName: houseName.text ?? "")
let report = Report(
applicationVersion: Bundle.main.releaseVersionNumber! + "b" + Bundle.main.buildVersionNumber!,
application: "insamlingsappen-ios",
accountIdentity: Utils.getUUID(),
coordinate: coordinate,
postalAddress: postalAddress
)
let jsonEncoder = JSONEncoder()
let jsonData = try? jsonEncoder.encode(report)
// Debug print it
let jsonstr = String(data: jsonData!, encoding: .utf8)
print(jsonstr)
// Post it
let postURL = URL(string: "https://insamling.postnummeruppror.nu/api/0.0.5/location_sample/create")!
var postRequest = URLRequest(url: postURL, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 60.0)
postRequest.httpMethod = "POST"
postRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
postRequest.setValue("application/json", forHTTPHeaderField: "Accept")
postRequest.httpBody = jsonData
URLSession.shared.dataTask(with: postRequest, completionHandler: { (data, response, error) -> Void in
if error != nil { print("POST Request: Communication error: \(error!)") }
if data != nil {
do {
//Print response
print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue))
if let safeData = data{
print("Response: \(String(describing: String(data:safeData, encoding:.utf8)))")
}
if let resultObject = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
var reportidentity = String(describing: resultObject.value(forKey: "identity")!)
DispatchQueue.main.async(execute: {
// Hide spinner
LoadingOverlay.shared.hideOverlayView()
print("Results from POST:\n\(String(describing: resultObject))")
// Show thank you alert
let alert = UIAlertController(title: "Tack", message: "Tack för din rapport. (nr. " + reportidentity + ")", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
})
}
} catch {
DispatchQueue.main.async(execute: {
// Hide spinner
LoadingOverlay.shared.hideOverlayView()
// show error alert
let alert = UIAlertController(title: "Fel", message: "Kunde inte skapa rapport. Försök senare.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
print("Unable to parse JSON response")
})
}
} else {
DispatchQueue.main.async(execute: {
print("Received empty response.")
})
}
}).resume()
}
// Print out the location to the console
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print(location.coordinate)
self.latitude = location.coordinate.latitude
self.longitude = location.coordinate.longitude
self.accuracy = location.horizontalAccuracy
self.altitude = location.altitude
// Update accuracy label above map
self.accuracyLabel.text = String(Int(self.accuracy))
if self.accuracy > 50.0 {
self.accuracyLabel.textColor = UIColor.red
} else {
self.accuracyLabel.textColor = UIColor.black
}
centerMapOnLocation(location: location)
}
}
// If we have been denied access give the user the option to change it
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if(status == CLAuthorizationStatus.denied) {
showLocationDisabledPopUp()
}
}
// Switch to OSM tile layer
func setupTileRenderer() {
let template = "https://a.tile.openstreetmap.se/osm/{z}/{x}/{y}.png"
let overlay = MKTileOverlay(urlTemplate: template)
overlay.canReplaceMapContent = true
self.mapView.add(overlay, level: .aboveLabels)
tileRenderer = MKTileOverlayRenderer(tileOverlay: overlay)
}
// Set upp OSM tile renderer
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
return tileRenderer
}
// Show popup to the user if we have been denied location
func showLocationDisabledPopUp() {
let alertController = UIAlertController(title: "Platsinformation avstängd",
message: "För att detta ska lira behöver vi få information om din plats. Öppna inställningar och tillåt platsinformation när appen används",
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Avbryt", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
let openAction = UIAlertAction(title: "Inställningar", style: .default) { (action) in
if let url = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
alertController.addAction(openAction)
self.present(alertController, animated: true, completion: nil)
}
// Zoom to 250 m radius
let regionRadius: CLLocationDistance = 250
// Center map
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
setupTileRenderer()
// Ask for location when app is in use
locationManager.requestWhenInUseAuthorization()
// If location services is enabled get the user's location
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
// Start with default location in central Stockholm somewhere
let initialLocation = CLLocation(latitude: 59.342944, longitude: 18.083945)
centerMapOnLocation(location: initialLocation)
mapView.delegate = self
// Is user registered?
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
if result.count == 0 {
// show sSettings view
performSegue(withIdentifier: "showSettings", sender: self)
}
} catch {
print("Failed to load user")
}
// Enable tap outside to dismiss keyboard
let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))
tap.cancelsTouchesInView = false
self.view.addGestureRecognizer(tap)
// Set text field delegate
postalCode.delegate = self
postalTown.delegate = self
streetName.delegate = self
houseNumber.delegate = self
houseName.delegate = self
// Hide validation message container
labelValidationResult.isHidden = true
// Start with send button disabled
sendButton.isEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func isReadyToSubmit() -> Bool {
let result = (self.postalCode.text!.count == 5 && self.postalTown.text!.count > 1 && self.streetName.text!.count > 3 && self.houseNumber.text!.count > 0)
return result
}
}
extension ReportController: UITextFieldDelegate {
func checkValid(_ textField: UITextField, nextField: UITextField) {
let (valid, message) = validate(textField)
if valid {
nextField.becomeFirstResponder()
} else {
self.labelValidationResult.text = message
}
// Toggle validation message
UIView.animate(withDuration: 0.25, animations: {
self.labelValidationResult.isHidden = valid
})
}
func textFieldDidEndEditing(_ textField: UITextField) {
// Check fields using the numeric keyboard here
if(textField == postalCode || textField == houseNumber) {
checkValid(textField, nextField: textField)
}
// Show send button if form is ready for submit
self.sendButton.isEnabled = isReadyToSubmit()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField {
case postalTown:
checkValid(postalTown, nextField: streetName)
case streetName:
checkValid(streetName, nextField: houseNumber)
case houseNumber:
houseName.becomeFirstResponder()
default:
postalCode.resignFirstResponder()
}
return true
}
}
// Show modal while data being sent to server.
// https://stackoverflow.com/questions/27960556/loading-an-overlay-when-running-long-tasks-in-ios
public class LoadingOverlay{
var overlayView = UIView()
var activityIndicator = UIActivityIndicatorView()
var bgView = UIView()
class var shared: LoadingOverlay {
struct Static {
static let instance: LoadingOverlay = LoadingOverlay()
}
return Static.instance
}
public func showOverlay(view: UIView) {
bgView.frame = view.frame
bgView.backgroundColor = UIColor.gray
bgView.addSubview(overlayView)
bgView.autoresizingMask = [.flexibleLeftMargin,.flexibleTopMargin,.flexibleRightMargin,.flexibleBottomMargin,.flexibleHeight, .flexibleWidth]
overlayView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
overlayView.center = view.center
overlayView.autoresizingMask = [.flexibleLeftMargin,.flexibleTopMargin,.flexibleRightMargin,.flexibleBottomMargin]
overlayView.backgroundColor = UIColor.white
overlayView.clipsToBounds = true
overlayView.layer.cornerRadius = 10
activityIndicator.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
activityIndicator.activityIndicatorViewStyle = .gray
activityIndicator.center = CGPoint(x: overlayView.bounds.width / 2, y: overlayView.bounds.height / 2)
overlayView.addSubview(activityIndicator)
view.addSubview(bgView)
self.activityIndicator.startAnimating()
}
public func hideOverlayView() {
activityIndicator.stopAnimating()
bgView.removeFromSuperview()
}
}
|
import Foundation
/**
* Adopters can generate entropy; a random set of bytes.
*/
public protocol EntropyGenerator {
func entropy() -> Result<Data,Error>
}
/**
* Errors relating to `EntropyGenerator`.
*/
public enum EntropyGeneratorError: Swift.Error {
case invalidInput(EntropyGenerator)
}
extension Int: EntropyGenerator {
public func entropy() -> Result<Data, Swift.Error> {
guard (self % 2) == 0, case 4...8 = (self / 32) else {
return .failure(EntropyGeneratorError.invalidInput(self))
}
return Result { try Data.randomBytes(self / 8) }
}
static var wordCounts: [Int] {
[ 12, 15, 18, 21, 24 ]
}
public static var weakest : Int { 128 }
public static var weak : Int { 160 }
public static var medium : Int { 192 }
public static var strong : Int { 224 }
public static var strongest : Int { 256 }
}
extension EntropyGenerator where Self: StringProtocol {
/**
* Interprets `self` as a string of pre-computed _entropy_, at least if its
* of even length, and between 32 & 64 characters.
*
* E.g., "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f".
*/
public func entropy() -> Result<Data, Error> {
guard (count % 2) == 0, case 4...8 = (count / 8) else {
return .failure(EntropyGeneratorError.invalidInput(String(self)))
}
var values = [Int32?]()
for (idx, char) in self.enumerated() {
// Break up `self` into character-pairs, representing a single hex.
if idx % 2 == 1 {
let prevIdx = self.index(before: String.Index(utf16Offset: idx, in: self))
let prevChr = self[prevIdx]
let value = Scanner(string: "\(prevChr)\(char)").scanInt32(representation: .hexadecimal)
values.append(value)
}
}
return .success(Data(values.compactMap { $0 }.map(UInt8.init)))
}
}
extension String: EntropyGenerator { }
extension String.SubSequence: EntropyGenerator { }
|
import UIKit
import MapKit
class VCreateMapPin:MKAnnotationView
{
enum Callout:Int
{
case delete
case move
}
private let kImageWidth:CGFloat = 40
private let kImageHeight:CGFloat = 40
init(annotation:MCreateAnnotation)
{
let reuseIdentifier:String = VCreateMapPin.reusableIdentifier
let offsetY:CGFloat = kImageHeight / -2
let leftCallOut:UIButton = UIButton(frame:CGRect(x: 0, y: 0, width: 30, height: 30))
leftCallOut.setImage(UIImage(named:"mapAnnotationDelete"), for:UIControlState())
leftCallOut.imageView?.contentMode = UIViewContentMode.center
leftCallOut.imageView?.clipsToBounds = true
leftCallOut.tag = Callout.delete.rawValue
let rightCallOut:UIButton = UIButton(frame:CGRect(x: 0, y: 0, width: 30, height: 30))
rightCallOut.setImage(UIImage(named:"mapAnnotationMove"), for:UIControlState())
rightCallOut.imageView?.contentMode = UIViewContentMode.center
rightCallOut.imageView?.clipsToBounds = true
rightCallOut.tag = Callout.move.rawValue
super.init(annotation:annotation, reuseIdentifier:reuseIdentifier)
canShowCallout = true
image = UIImage(named:"mapAnnotation")
centerOffset = CGPoint(x: 0, y: offsetY)
leftCalloutAccessoryView = leftCallOut
rightCalloutAccessoryView = rightCallOut
}
required init?(coder:NSCoder)
{
fatalError()
}
}
|
//
// ViewController.swift
// FavorPay
//
// Created by Daniel Newell on 5/27/17.
// Copyright © 2017 Daniel Newell. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
import Firebase
import GooglePlacePicker
class PerformViewController: UITableViewController {
fileprivate var ref : DatabaseReference?
var entries : [GoodDeed] = []
var myGoodDeeds : [GoodDeed] = []
func toDictionary(vals: GoodDeed) -> NSDictionary {
return [
"id" : vals.id,
"title" : vals.title,
"desc" : vals.desc,
"points" : vals.points,
"timeStamp" : vals.timeStamp,
"longitude" : vals.longitude,
"latitude" : vals.latitude,
"formattedAddress" : vals.formattedAddress
]
}
fileprivate func registerForFireBaseUpdates() {
self.ref!.child("goodDeed").observe(.value, with: {
snapshot in if let postDict = snapshot.value as? [String : AnyObject] {
var tmpItems = [GoodDeed]()
for (_,val) in postDict.enumerated() {
let entry = val.1 as! Dictionary<String,AnyObject>
tmpItems.append(
GoodDeed(
id: entry["id"] as! String,
title: entry["title"] as! String,
desc: entry["desc"] as! String,
points: entry["points"] as! Int,
timeStamp: entry["timeStamp"] as! String,
longitude: entry["longitude"] as! String,
latitude: entry["latitude"] as! String,
formattedAddress: entry["formattedAddress"] as! String
)
)
}
self.entries = tmpItems
self.tableView.reloadData()
}
})
let user = Auth.auth().currentUser
self.ref!.child((user?.uid)!).observe(.value, with: {
snapshot in if let postDict = snapshot.value as? [String : AnyObject] {
var tmpItems = [GoodDeed]()
for (_,val) in postDict.enumerated() {
let entry = val.1 as! Dictionary<String,AnyObject>
tmpItems.append(
GoodDeed(
id: entry["id"] as! String,
title: entry["title"] as! String,
desc: entry["desc"] as! String,
points: entry["points"] as! Int,
timeStamp: entry["timeStamp"] as! String,
longitude: entry["longitude"] as! String,
latitude: entry["latitude"] as! String,
formattedAddress: entry["formattedAddress"] as! String
)
)
}
self.myGoodDeeds = tmpItems
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
self.ref = Database.database().reference()
self.registerForFireBaseUpdates()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.entries.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let goodDeed = self.entries[indexPath.row] as GoodDeed
let uiAlert = UIAlertController(title: goodDeed.title, message: "Are you sure you want to perform this good deed?", preferredStyle: UIAlertControllerStyle.alert)
self.present(uiAlert, animated: true, completion: nil)
uiAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in self.performGoodDeed(goodDeed: goodDeed) }))
uiAlert.addAction(UIAlertAction(title: "Nope", style: .cancel, handler: nil))
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "goodDeedCell", for: indexPath) as! FavorPayTableViewCell
cell.title.text = self.entries[indexPath.row].title
cell.desc.text = self.entries[indexPath.row].desc
cell.points.text = String(self.entries[indexPath.row].points)
return cell
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Hide the keyboard when the user taps outside the text fields
self.view.endEditing(true)
}
func performGoodDeed(goodDeed: GoodDeed) {
var goodDeedPerformed = false
let user = Auth.auth().currentUser
for i in 0 ..< self.myGoodDeeds.count {
if (self.myGoodDeeds[i].id == goodDeed.id) {
goodDeedPerformed = true
}
}
if (user != nil) {
if (goodDeedPerformed != true) {
let entry = GoodDeed(
id: goodDeed.id,
title: goodDeed.title,
desc: goodDeed.desc,
points: goodDeed.points,
timeStamp: goodDeed.timeStamp,
longitude: goodDeed.longitude,
latitude: goodDeed.latitude,
formattedAddress: goodDeed.formattedAddress
)
let newChild = self.ref?.child((user?.uid)!).childByAutoId()
newChild?.setValue(self.toDictionary(vals: entry))
} else {
let message = "You have already performed this Good Deed"
let uiAlert = UIAlertController(title: goodDeed.title, message: message, preferredStyle: UIAlertControllerStyle.alert)
self.present(uiAlert, animated: true, completion: nil)
uiAlert.addAction(UIAlertAction(title: "Okay", style: .cancel, handler: nil))
}
}
}
}
|
//
// LoginVC.swift
// communityApplication
//
// Created by Aravind on 31/01/2021.
//
import UIKit
import FirebaseFirestore
import FirebaseAuth
import GoogleSignIn
import FBSDKLoginKit
class LoginVC: UIViewController {
@IBOutlet weak var emailTF: customUITextField!
@IBOutlet weak var passwordTF: customUITextField!
@IBOutlet weak var googleUB: UIButton!
@IBOutlet weak var loginUB: UIButton!
@IBOutlet weak var facebookUB: UIButton!
let db = Firestore.firestore()
let loginManager = LoginManager()
lazy var presenter = LoginPresenter(with: self)
override func viewDidLoad() {
super.viewDidLoad()
if Auth.auth().currentUser != nil {
self.performSegue(withIdentifier: "goToTabBar", sender: nil)
return
}
googleUB.layer.cornerRadius = googleUB.frame.height / 2.0
loginUB.layer.cornerRadius = loginUB.frame.height / 2.0
facebookUB.layer.cornerRadius = facebookUB.frame.height / 2.0
GIDSignIn.sharedInstance()?.presentingViewController = self
GIDSignIn.sharedInstance()?.delegate = self
}
@IBAction func onTapLoginUB(_ sender: Any) {
let email = emailTF.text!
let password = passwordTF.text!
if !email.emailValidation() {
print("please input validate email.")
return
}
if password.count < 6 {
print("Password must be over 6 digits.")
return
}
AppUtil.onShowProgressView(name: "Login...")
presenter.LoginWithEmailPassword(email: email, password: password)
}
@IBAction func ongTapGoogleUB(_ sender: Any) {
print("On Tapped Google Button")
GIDSignIn.sharedInstance()?.signIn()
}
@IBAction func onTapFacebookUB(_ sender: UIButton) {
print("On Tapped FaceBook Button")
if let _ = AccessToken.current {
loginManager.logOut()
} else {
loginManager.logIn(permissions: ["public_profile", "email"], from: self) { (result, error) in
guard error == nil else {
self.loginError(errorMessage: error!.localizedDescription)
return
}
guard let result = result, !result.isCancelled else {
print("User cancelled login")
return
}
let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)
self.presenter.signInWithCredintial(credential: credential)
}
}
}
}
extension LoginVC: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
AppUtil.onShowProgressView(name: "Loading...")
if error != nil {
AppUtil.onHideProgressView()
print(error.debugDescription)
} else {
guard let authentication = user.authentication else {return}
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
self.presenter.signInWithCredintial(credential: credential)
}
}
}
extension LoginVC: LoginViewPresenter {
func loginError(errorMessage: String) {
self.popupAlert(title: "Error", message: errorMessage, actionTitles: ["Okay"], actions:[{action1 in
self.dismiss(animated: true, completion: nil)
}])
}
func loginSuccessfully() {
self.performSegue(withIdentifier: "goToTabBar", sender: nil)
}
}
|
#if WORKING
// Working
struct MYRNG: RandomNumberGenerator {
private var n: UInt64 = 0
mutating func next() -> UInt64 { return 0 }
}
#else
// TSAN crash
struct MYRNG: RandomNumberGenerator {
mutating func next() -> UInt64 { return 1 }
}
#endif
func returnNext<R: RandomNumberGenerator>(using generator: inout R) -> UInt64 {
return generator.next()
}
func callReturnNext<R: RandomNumberGenerator>(_ array: [Int], using generator: inout R) -> UInt64 {
return returnNext(using: &generator)
}
var g = MYRNG()
_ = callReturnNext([0], using: &g)
|
//
// NewsSnippet.swift
// f26Model
//
// Created by David on 08/12/2017.
// Copyright © 2017 com.smartfoundation. All rights reserved.
//
import SFModel
import SFCore
import f26Core
/// Encapsulates a NewsSnippet model item
public class NewsSnippet: ModelItemBase {
// MARK: - Initializers
private override init() {
super.init()
}
public override init(collection: ProtocolModelItemCollection,
storageDateFormatter: DateFormatter) {
super.init(collection: collection,
storageDateFormatter: storageDateFormatter)
}
// MARK: - Public Methods
let categoryKey: String = "Category"
/// Gets or sets the category
public var category: ArtworkCategoryTypes {
get {
let i = Int(self.getProperty(key: categoryKey)!)!
return ArtworkCategoryTypes(rawValue: i)!
}
set(value) {
let i = value.rawValue
self.setProperty(key: categoryKey, value: String(i), setWhenInvalidYN: false)
}
}
let yearKey: String = "Year"
/// Gets or sets the year
public var year: Int {
get {
return Int(self.getProperty(key: yearKey)!)!
}
set(value) {
self.setProperty(key: yearKey, value: String(value), setWhenInvalidYN: false)
}
}
let textKey: String = "Text"
/// Gets or sets the text
public var text: String {
get {
return self.getProperty(key: textKey)!
}
set(value) {
self.setProperty(key: textKey, value: value, setWhenInvalidYN: false)
}
}
let datepostedKey: String = "DatePosted"
/// Gets or sets the datePosted
public var datePosted: Date {
get {
let dateString = self.getProperty(key: datepostedKey)!
return DateHelper.getDate(fromString: dateString, fromDateFormatter: self.storageDateFormatter!)
}
set(value) {
self.setProperty(key: datepostedKey, value: self.getStorageDateString(fromDate: value), setWhenInvalidYN: false)
}
}
let imagefilenameKey: String = "ImageFileName"
/// Gets or sets the imageFileName
public var imageFileName: String {
get {
return self.getProperty(key: imagefilenameKey)!
}
set(value) {
self.setProperty(key: imagefilenameKey, value: value, setWhenInvalidYN: false)
}
}
public func toWrapper() -> NewsSnippetWrapper {
let wrapper = NewsSnippetWrapper()
wrapper.id = Int.init(self.id)!
wrapper.category = self.category
wrapper.year = self.year
wrapper.text = self.text
wrapper.datePosted = self.datePosted
wrapper.imageFileName = self.imageFileName
return wrapper
}
// MARK: - Override Methods
public override func initialiseDataNode() {
// Setup the node data
self.doSetProperty(key: idKey, value: "0")
self.doSetProperty(key: categoryKey, value: "1")
self.doSetProperty(key: yearKey, value: "1900")
self.doSetProperty(key: textKey, value: "")
self.doSetProperty(key: datepostedKey, value: "1/1/1900")
self.doSetProperty(key: imagefilenameKey, value: "")
}
public override func initialiseDataItem() {
// Setup foreign key dependency helpers
}
public override func initialisePropertyIndexes() {
// Define the range of the properties using the enum values
startEnumIndex = ModelProperties.newsSnippet_id.rawValue
endEnumIndex = ModelProperties.newsSnippet_imageFileName.rawValue
}
public override func initialisePropertyKeys() {
// Populate the dictionary of property keys
keys[idKey] = ModelProperties.newsSnippet_id.rawValue
keys[categoryKey] = ModelProperties.newsSnippet_category.rawValue
keys[yearKey] = ModelProperties.newsSnippet_year.rawValue
keys[textKey] = ModelProperties.newsSnippet_text.rawValue
keys[datepostedKey] = ModelProperties.newsSnippet_datePosted.rawValue
keys[imagefilenameKey] = ModelProperties.newsSnippet_imageFileName.rawValue
}
public override var dataType: String {
get {
return "newsSnippet"
}
}
public override func clone(item: ProtocolModelItem) {
// Validations should not be performed when cloning the item
let doValidationsYN: Bool = self.doValidationsYN
self.doValidationsYN = false
// Copy all properties from the specified item
if let item = item as? NewsSnippet {
self.id = item.id
self.category = item.category
self.year = item.year
self.text = item.text
self.datePosted = item.datePosted
self.imageFileName = item.imageFileName
}
self.doValidationsYN = doValidationsYN
}
public override func isValid(propertyEnum: Int, value: String) -> ValidationResultTypes {
var result: ValidationResultTypes = ValidationResultTypes.passed
// Perform validations for the specified property
switch toProperty(propertyEnum: propertyEnum) {
case .newsSnippet_text:
result = self.isValidText(value: value)
break
default:
break
}
return result
}
// MARK: - Private Methods
fileprivate func toProperty(propertyEnum: Int) -> ModelProperties {
return ModelProperties(rawValue: propertyEnum)!
}
// MARK: - Validations
fileprivate func isValidText(value: String) -> ValidationResultTypes {
var result: ValidationResultTypes = .passed
result = self.checkMaxLength(value: value, maxLength: 250, propertyName: "Text")
return result
}
}
|
//
// TimelineAnimationUIViewExtensions.swift
// TimelineAnimations
//
// Created by Georges Boumis on 19/04/2017.
// Copyright © 2017 AbZorba Games. All rights reserved.
//
import Foundation
public extension UIView {
final public func moveAnimation(from: CGPoint?,
to: CGPoint,
timingFunction tf: TimelineAnimation.TimingFunction = .linear) -> TimelineAnimation {
return Animations.move(self, from: from, to: to, timingFunction: tf)
}
final public func scaleAnimation(from: CGFloat,
to: CGFloat,
timingFunction tf: TimelineAnimation.TimingFunction = .linear) -> TimelineAnimation {
return Animations.scale(self, from: from, to: to, timingFunction: tf)
}
final public func scaleXAnimation(from: CGFloat,
to: CGFloat,
timingFunction tf: TimelineAnimation.TimingFunction = .linear) -> TimelineAnimation {
return Animations.scaleX(self, from: from, to: to, timingFunction: tf)
}
final public func scaleYAnimation(from: CGFloat,
to: CGFloat,
timingFunction tf: TimelineAnimation.TimingFunction = .linear) -> TimelineAnimation {
return Animations.scaleY(self, from: from, to: to, timingFunction: tf)
}
final public func rotateAnimation(from: TimelineAnimation.Radians,
to: TimelineAnimation.Radians,
timingFunction tf: TimelineAnimation.TimingFunction = .linear) -> TimelineAnimation {
return Animations.rotate(self, from: from, to: to, timingFunction: tf)
}
final public func showAnimation(timingFunction tf: TimelineAnimation.TimingFunction = .linear) -> TimelineAnimation {
return Animations.show(self, timingFunction: tf)
}
final public func hideAnimation(timingFunction tf: TimelineAnimation.TimingFunction = .linear) -> TimelineAnimation {
return Animations.hide(self, timingFunction: tf)
}
final public func fadeAnimation(from: CGFloat, to: CGFloat, timingFunction tf: TimelineAnimation.TimingFunction = .linear) -> TimelineAnimation {
return Animations.fade(self, from: from, to: to, timingFunction: tf)
}
final public func blinkAnimation(options: Animations.BlinkOptions) -> TimelineAnimation {
return Animations.blink(self, times: options)
}
public typealias PopPhase = (percentage: RelativeTime, tf: TimelineAnimation.TimingFunction)
public typealias PopOptions = (in: UIView.PopPhase, out: UIView.PopPhase)
final public func popAnimation(withOptions options: PopOptions) -> TimelineAnimation {
let timeline = Animations.oscillate(self, keyPath: AnimationKeyPath.opacity,
percentages: (options.in.percentage, options.out.percentage),
values: (from: 0, to: 1),
timingFunctions: (from: options.in.tf, to: options.out.tf))
timeline.append(name: ".pop")
return timeline
}
final public func scalingPopAnimation(from: CGFloat,
to: CGFloat,
options: UIView.PopOptions = (in: (percentage: RelativeTime(0.4), tf: TimelineAnimation.TimingFunction.linear),
out: (percentage: RelativeTime(0.6), tf: TimelineAnimation.TimingFunction.linear))) -> TimelineAnimation {
let group = GroupTimelineAnimation()
group.append(name: String(describing: type(of: self)) + ".scalingPopAnimation")
let opacity = Animations.oscillate(self, keyPath: AnimationKeyPath.opacity,
percentages: (options.in.percentage, options.out.percentage),
values: (from: 0, to: 1),
timingFunctions: (from: options.in.tf, to: options.out.tf))
opacity.append(name: ".scalingPop")
group.add(opacity)
let scale = Animations.oscillate(self, keyPath: AnimationKeyPath.scale,
percentages: (options.in.percentage, options.out.percentage),
values: (from: from, to: to),
timingFunctions: (from: options.in.tf, to: options.out.tf))
scale.append(name: ".scalingPop")
group.add(scale)
return group
}
final public func scalingBounceAnimation(from: CGFloat,
to: CGFloat,
options: UIView.PopOptions = (in: (percentage: RelativeTime(0.4), tf: TimelineAnimation.TimingFunction.linear),
out: (percentage: RelativeTime(0.6), tf: TimelineAnimation.TimingFunction.linear))) -> TimelineAnimation {
let scale = Animations.oscillate(self, keyPath: AnimationKeyPath.scale,
percentages: (options.in.percentage, options.out.percentage),
values: (from: from, to: to),
timingFunctions: (from: options.in.tf, to: options.out.tf))
scale.append(name: ".scalingBounce")
return scale
}
}
|
//
// ViewController.swift
// KakaoImgSearch_RX
//
// Created by BHJ on 2021/02/24.
//
import UIKit
import RxSwift
import Kingfisher
private let imgReuseIdentifier = "ImageCell"
class MainViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var noResultView: UIView!
@IBOutlet weak var noResultLabel: UILabel!
let disposeBag = DisposeBag()
let viewModel = ResultViewModel()
override func viewDidLoad() {
super.viewDidLoad()
let flowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
collectionView.setCollectionViewLayout(flowLayout, animated: true)
collectionView.delegate = self
collectionView.register(UINib(nibName: "ImageCell", bundle: nil), forCellWithReuseIdentifier: imgReuseIdentifier)
noResultView.isHidden = false
collectionView.isHidden = true
bind()
}
func bind() {
searchBar.rx.text.orEmpty
.map({ text -> String in
return text.trimmingCharacters(in: .whitespacesAndNewlines)
})
.filter({ text -> Bool in
let isEmpty = text.isEmpty
if isEmpty == true {
self.viewModel.clearView()
self.noResultLabel.text = "검색어를 입력하세요."
self.noResultView.isHidden = false
self.collectionView.isHidden = true
}
return true
})
.debounce(.milliseconds(1000), scheduler: MainScheduler())
.distinctUntilChanged({ (str1, str2) -> Bool in
return str1 == str2 ? (str1 == "" ? false : true) : false
})
.subscribe(onNext: { (keyword) in
if(!keyword.isEmpty){
self.viewModel.requestImageSearch(keyword: keyword)
}
})
.disposed(by: disposeBag)
collectionView.rx
.willDisplayCell
.subscribe { cell, indexPath in
self.viewModel.nextRequestImage(indexPath: indexPath)
}
.disposed(by: disposeBag)
viewModel.rowViewModels.bind(to: collectionView.rx.items(cellIdentifier: imgReuseIdentifier, cellType: ImageCell.self)){idx,item,cell in
if item is Documents{
self.noResultView.isHidden = true
self.collectionView.isHidden = false
guard let document = item as? Documents else { return }
cell.imgView.kf.setImage(with: URL(string: document.thumbnail_url), placeholder: UIImage(named: "placeholder"))
}else{
guard let descInfo = item as? NoResults else { return }
self.noResultLabel.text = descInfo.desc
self.noResultView.isHidden = false
self.collectionView.isHidden = true
}
}
.disposed(by: disposeBag)
collectionView.rx
.modelSelected(Documents.self)
.subscribe(onNext: { documentInfo in
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
guard let dvc = storyBoard.instantiateViewController(withIdentifier: "DetailVC") as? DetailViewController else{
return
}
dvc.setViewModel(DetailViewModel(doc: documentInfo))
self.present(dvc, animated: true, completion: nil)
})
.disposed(by: disposeBag)
//output
// 에러 처리
viewModel.outputs.errorMessage
.observe(on: MainScheduler.instance)
.subscribe(onNext: { [weak self] error in
let ac = UIAlertController(title: "\(error)", message: error.errorDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self?.present(ac, animated: true)
})
.disposed(by: disposeBag)
}
}
extension MainViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let numberofItem: CGFloat = 3
let collectionViewWidth = self.collectionView.bounds.width
let extraSpace = (numberofItem - 1) * flowLayout.minimumInteritemSpacing
let inset = flowLayout.sectionInset.right + flowLayout.sectionInset.left
let width = Int((collectionViewWidth - extraSpace - inset) / numberofItem)
return CGSize(width: width, height: width)
}
}
|
//
// YiDaIOSSwiftPracticesTests.swift
// YiDaIOSSwiftPracticesTests
//
// Created by Mudox on 9/8/16.
// Copyright © 2016 Mudox. All rights reserved.
//
import XCTest
@testable import YiDaIOSSwiftPractices
class DataTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testNews() {
let newsList1 = loadNewsUsingSwiftyJSON()
var log = newsList1.reduce("") { (lines, newsItem) -> String in
return lines + "\n\(newsItem.dateString) (\(newsItem.timePassedDescription))"
}
Jack.debug(log)
let newsList2 = loadNewsUsingGloss()
log = newsList2.reduce("") { (lines, newsItem) -> String in
return lines + "\n\(newsItem.dateString) (\(newsItem.timePassedDescription))"
}
Jack.debug(log)
}
func testMenu() {
let menu = Menu.shared
Jack.debug(menu.basicPart[4].headerText)
XCTAssert(menu.basicPart[4].items[0].presenting != nil)
}
func testSwiftyJSONPerformance() {
self.measure {
for _ in 0..<100 {
let _ = loadNewsUsingSwiftyJSON()
}
}
}
func testGlossPerformance() {
self.measure {
for _ in 0..<100 {
let _ = loadNewsUsingGloss()
}
}
}
}
|
import XCTest
import Bow
class PairingTest: XCTestCase {
func testPairingStateStore() {
let w = Store<Int, Int>(0, id)
let s = State<Int, Int>.var()
let actions: State<Int, Void> = binding(
|<-.set(5),
|<-.modify { x in x + 5 },
s <- .get(),
|<-.set(s.get * 3 + 1),
yield: ())^
let w2 = Pairing.pairStateStore().select(actions, w.duplicate())
XCTAssertEqual(w2.extract(), 31)
}
func testPairingWriterTraced() {
let w = Traced<Int, String> { x in Array(repeating: "*", count: x).joined() }
let m = Writer<Int, Int>.var()
let a = Writer<Int, Void>.var()
let actions: Writer<Int, Void> = binding(
(m, a) <- Writer.tell(3).censor { x in 2 * x }.listens(id),
|<-.tell(m.get + 1),
yield: ())^
let w2 = Pairing.pairWriterTraced().select(actions, w.duplicate())
XCTAssertEqual(w2.extract(), "*************")
}
func testPairingReaderEnv() {
let w = Env<Int, Double>(10, .pi)
let e1 = Reader<Int, Int>.var()
let e2 = Reader<Int, Int>.var()
var res = 0
let actions: Reader<Int, Int> = binding(
e1 <- Reader.ask().local { x in 2 * x },
e2 <- Reader.pure(e1.get * 3),
|<-Reader<Int, Void> { _ in
res = e2.get
return Id(())
},
yield: e2.get)^
let _ = Pairing.pairReaderEnv().select(actions, w.duplicate())
XCTAssertEqual(res, 60)
}
func testPairingActionMoore() {
func render(_ n: Int) -> String {
(n % 2 == 0) ?
"\(n) is even" :
"\(n) is odd"
}
func update(_ state: Int, _ action: Input) -> Int {
switch action {
case .increment: return state + 1
case .decrement: return state - 1
}
}
enum Input {
case increment
case decrement
}
let w = Moore<Input, String>.from(initialState: 0, render: render, update: update)
let actions: Action<Input, Void> = binding(
|<-Action.from(.increment),
|<-Action.from(.increment),
|<-Action.from(.decrement),
|<-Action.from(.increment),
|<-Action.from(.increment),
yield: ())^
let w2 = Pairing.pairActionMoore().select(actions, w.duplicate())^
XCTAssertEqual(w2.view, "3 is odd")
}
func testPairingCoSumSum() {
let w = Sum<ForId, ForId, Int>(left: Id(10), right: Id(20))
let actions: CoSum<ForId, ForId, Void> = binding(
|<-CoSum.moveRight(),
|<-CoSum.moveLeft(),
|<-CoSum.moveLeft(),
|<-CoSum.moveRight(),
yield: ()
)^
let w2 = Pairing.pairCoSumSum().select(actions, w.duplicate())^
XCTAssertEqual(w2.extract(), 20)
}
func testPairingCoSumOptSumOpt() {
let w = SumOpt<ForId, Int>(left: Id(0), right: Id(25))
let actions: CoSumOpt<ForId, Void> = binding(
|<-CoSumOpt.show(),
|<-CoSumOpt.hide(),
|<-CoSumOpt.toggle(),
yield: ())^
let w2 = Pairing.pairCoSumOptSumOpt().select(actions, w.duplicate())^
XCTAssertEqual(w2.extract(), 25)
}
func testPairingPullerZipper() {
let w = Zipper(left: [1, 2, 3], focus: 4, right: [5, 6, 7])
let actions: Puller<Void> = binding(
|<-Puller.moveToFirst(),
|<-Puller.moveToLast(),
|<-Puller.moveLeft(),
|<-Puller.moveLeft(),
|<-Puller.moveRight(),
yield: ())^
let w2 = Pairing.pairPullerZipper().select(actions, w.duplicate())^
XCTAssertEqual(w2.extract(), 6)
}
}
|
//
// TMAddCreditCardPaymentCollectionViewCell.swift
// consumer
//
// Created by Gregory Sapienza on 3/10/17.
// Copyright © 2017 Human Ventures Co. All rights reserved.
//
import UIKit
@objc protocol TMAddCreditCardPaymentCollectionViewCellProtocol {
/// Text editing has begun for text field in cell.
///
/// - Parameter indexPath: Index path of cell.
func textEditingBeganForIndexPath(_ indexPath: IndexPath)
/// Next button has been tapped on keyboard when editing the text field.
///
/// - Parameter indexPath: Index path of cell.
func nextButtonTappedForIndexPath(_ indexPath: IndexPath)
/// Text has changed for text field in cell.
///
/// - Parameter indexPath: Index path of cell.
/// - Parameter newString: New string in text field.
func textFieldDidChange(indexPath: IndexPath, newString: String)
/// Checks if other cells are verified based on entered text.
///
/// - Returns: True if all other cells are verified.
func allTextFieldsVerified() -> Bool
/// Save button on top of keyboard was tapped.
func onSaveButton()
/// Determines if it is ok to change characters in the text field.
///
/// - Parameters:
/// - indexPath: Index path of cell.
/// - text: Current text field text.
/// - Returns: True if it is ok to change characters in the text field.
func shouldChangeCharacters(_ indexPath: IndexPath, text: String) -> Bool
}
class TMAddCreditCardPaymentCollectionViewCell: UICollectionViewCell {
// MARK: - Public iVars
/// Payment field represented by cell.
var paymentField: TMAddCreditCardPaymentDataType! {
didSet {
let titleAttributedString = NSMutableAttributedString(string: paymentField.rawValue.uppercased())
titleAttributedString.addAttribute(NSKernAttributeName, value: 0.6, range: NSMakeRange(0, paymentField.rawValue.length))
titleLabel.attributedText = titleAttributedString
textField.placeholder = paymentField.placeholderText()
textField.keyboardType = paymentField.keyboardType()
if let autocapitalizationType = paymentField.autocapitalizationType() {
textField.autocapitalizationType = autocapitalizationType
}
}
}
/// Index path of cell from the colleciton view.
var indexPath: IndexPath!
/// Delegate for text field actions.
var delegate: TMAddCreditCardPaymentCollectionViewCellProtocol?
/// Theme for cell.
var theme: TMAddCreditCardPaymentTheme! {
didSet {
titleLabel.textColor = theme.titleColor()
textField.textColor = theme.textColor()
textField.tintColor = theme.textColor()
textField.keyboardAppearance = self.theme.keyboardAppearance()
textField.attributedPlaceholder = NSAttributedString(string: paymentField.placeholderText(), attributes: [NSForegroundColorAttributeName : theme.placeholderColor()])
}
}
/// Text field for content.
lazy var textField: UITextField = {
let textField = UITextField()
let font = UIFont.ActaBook(18)
textField.font = font
textField.textAlignment = .center
textField.delegate = self
textField.adjustsFontSizeToFitWidth = true
textField.minimumFontSize = font.pointSize / 0.7
textField.autocorrectionType = .no
textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
self.saveButton.frame = CGRect(x: 0, y: 0, w: self.bounds.width, h: 66)
textField.inputAccessoryView = self.saveButton
textField.returnKeyType = .next
return textField
}()
/// Boolean to tell the cell if a right side border should be displayed to use as a seperator.
var displaySideBorder = false
// MARK: - Private iVars
/// Label representing which cell this is.
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.MalloryMedium(12)
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.7
return label
}()
/// Save button above keyboard.
fileprivate lazy var saveButton: UIButton = {
let button = UIButton.button(style: .alternateBlack)
button.setTitle("Save", for: .normal)
button.addTarget(self.delegate, action: #selector(TMAddCreditCardPaymentCollectionViewCellProtocol.onSaveButton), for: .touchUpInside)
return button
}()
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
addSubview(titleLabel)
addSubview(textField)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.setLineWidth(2)
context.setStrokeColor(theme.lineColor().cgColor)
context.move(to: CGPoint(x: 0, y: bounds.height))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
if displaySideBorder {
let sideBorderVerticalSpace: CGFloat = bounds.height / 7.3 //Space between the top and bottom of the border.
context.move(to: CGPoint(x: bounds.width, y: sideBorderVerticalSpace))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height - sideBorderVerticalSpace))
}
context.strokePath()
}
override func layoutSubviews() {
super.layoutSubviews()
var cellLayout = VerticalLayout(contents: [titleLabel, textField], verticalSeperatingSpace: 9).withInsets(top: (bounds.height / 2.75) - 9, bottom: bounds.height / 9.7)
cellLayout.layout(in: bounds)
}
//MARK: - Actions
@objc private func textFieldDidChange() {
guard let delegate = self.delegate else {
return
}
if let text = textField.text {
delegate.textFieldDidChange(indexPath: indexPath, newString: text) //Updates delegate with every character change.
}
saveButton.isEnabled = delegate.allTextFieldsVerified() //Enables save button if all other text fields in the collection view are verfied and ready to be submitted.
}
}
// MARK: - UITextFieldDelegate
extension TMAddCreditCardPaymentCollectionViewCell: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
delegate?.textEditingBeganForIndexPath(indexPath)
guard let delegate = self.delegate else {
return false
}
saveButton.isEnabled = delegate.allTextFieldsVerified() //Enables save button if all other text fields in the collection view are verfied and ready to be submitted.
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//Backspace detection.
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
let backSpaceUnicodeValue: Int32 = -92
guard
let text = textField.text,
let delegate = delegate else {
return true
}
if isBackSpace == backSpaceUnicodeValue { //Checks if backspace was tapped.
return true
} else if !delegate.shouldChangeCharacters(indexPath, text: text) {
return false
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.layoutIfNeeded() //Fixes iOS bug where text field bounces after editing when in a collection view cell. http://stackoverflow.com/questions/9674566/text-in-uitextfield-moves-up-after-editing-center-while-editing
if let text = textField.text {
delegate?.textFieldDidChange(indexPath: indexPath, newString: text)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
delegate?.nextButtonTappedForIndexPath(indexPath) //When next button has been tapped in keyboard.
return true
}
}
|
//
// HomeVC.swift
// Surface
//
// Created by Nandini Yadav on 09/03/18.
// Copyright © 2018 Appinventiv. All rights reserved.
import UIKit
class HomeVC: BaseSurfaceVC {
//MARK:- Properties
var nextCount:Int? = 1
var total_Count:Int?
var post_listArr = [Featured_List]()
var featured_Arr = [Featured_List]()
//MARK:- @IBOutlets
@IBOutlet weak var heightConstraintFeaturedView: NSLayoutConstraint!
@IBOutlet weak var progressView: ASProgressPopUpView!
@IBOutlet weak var thumbnilImageView: UIImageView!
@IBOutlet weak var progressContainerView: UIView!
@IBOutlet weak var progressContainerViewHeight: NSLayoutConstraint!
@IBOutlet weak var retryButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var compressionActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var cancelRetryBackViewWidth: NSLayoutConstraint!
@IBOutlet weak var cancelRetryBackView: UIView!
@IBOutlet weak var uploadStatusLabel: UILabel!
@IBOutlet weak var navigationBarSubView: UIView!
@IBOutlet weak var featuredSubView: UIView!
@IBOutlet weak var navigationTitleLabel: UILabel!
@IBOutlet weak var messageButton: UIButton!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var featuredTitleLabel: UILabel!
@IBOutlet weak var featuredCollectionView: UICollectionView!
@IBOutlet weak var collectionView: UICollectionView!
//MARK:- View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
initialSetup()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
progressView.cornerRadius(radius: progressView.h/2)
thumbnilImageView.cornerRadius(radius: 3.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- Private Methods
private func initialSetup(){
collectionView.backgroundColor = #colorLiteral(red: 0.9607843137, green: 0.9607843137, blue: 0.9607843137, alpha: 1)
self.view.backgroundColor = #colorLiteral(red: 0.9607843137, green: 0.9607843137, blue: 0.9607843137, alpha: 1)
featuredSubView.layer.shadowOffset = CGSize(width: 0, height: 4)
featuredSubView.layer.shadowOpacity = 0.20
featuredSubView.layer.shadowRadius = 3.0
featuredSubView.layer.shadowColor = #colorLiteral(red: 0.2196078431, green: 0.2196078431, blue: 0.2196078431, alpha: 1)
navigationBarSubView.layer.shadowOffset = CGSize(width: 0, height: 4)
navigationBarSubView.layer.shadowOpacity = 0.11
navigationBarSubView.layer.shadowRadius = 4.0
navigationBarSubView.layer.shadowColor = #colorLiteral(red: 0.2196078431, green: 0.2196078431, blue: 0.2196078431, alpha: 1)
collectionView.register(UINib(nibName: AppClassID.feedCell.rawValue , bundle: nil), forCellWithReuseIdentifier: AppClassID.feedCell.cellID)
featuredCollectionView.register(UINib(nibName: AppClassID.featuredCell.rawValue , bundle: nil), forCellWithReuseIdentifier: AppClassID.featuredCell.cellID)
featuredCollectionView.delegate = self
featuredCollectionView.dataSource = self
collectionView.delegate = self
collectionView.dataSource = self
//self.featuredCollectionView.prefetchDataSource = self
self.collectionView.emptyDataSetSource = self
self.collectionView.emptyDataSetDelegate = self
// self.collectionView.prefetchDataSource = self
let refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "", attributes: [NSAttributedStringKey.foregroundColor: #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1) , NSAttributedStringKey.font: AppFonts.regular.withSize(14.0)])
refreshControl.addTarget(self, action: #selector(self.refresh(refreshControl:)), for: UIControlEvents.valueChanged)
self.collectionView.addSubview(refreshControl)
self.uploadingStatus(status: .None)
self.featuredTitleLabel.isHidden = true
self.getPostList(pageNo: 1 , isShowLoader: true)
self.featuredCollectionView.isHidden = true
self.heightConstraintFeaturedView.constant = 0
self.view.layoutIfNeeded()
}
// Refresh Table View Data
@objc private func refresh(refreshControl: UIRefreshControl){
self.view.endEditing(true)
if Global.isNetworkAvailable(){
self.getPostList(pageNo: 1)
} else {
Global.showToast(msg: ConstantString.no_internet.localized)
}
refreshControl.endRefreshing()
}
@objc func editPostButtonTapped(_ sender: UIButton){
guard let index = sender.collectionViewIndexPath(collectionView: self.collectionView) else {
Global.print_Debug("index not found")
return
}
self.addActionSheet(index)
}
//MARK:- @IBActions & Methods
//MARK:- IBActions
//=================
@IBAction func retryButtonTapped(_ sender: UIButton) {
(AlamofireReachability.sharedInstance.isNetworkConnected())
?
self.startUploading(objData: AWS3Controller.shared.dataToUpload)
: Global.showToast(msg: "Please check internet")
}
@IBAction func cancelButtonTapped(_ sender: UIButton) {
AWS3Controller.shared.uploadingStatus = .None
AWS3Controller.shared.totalBytes = 0
AWS3Controller.shared.totalBytesSent = 0
CommonFunctions.clearTempDirectory()
CommonFunctions.removeChahe()
self.uploadingStatus(status : AWS3Controller.shared.uploadingStatus)
}
@IBAction func logoutButtonTapped(_ sender: UIButton) {
self.showLogoutConfirmationAlert()
}
private func showLogoutConfirmationAlert() {
let alert = UIAlertController(title: nil, message: "Are you sure to logout?", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Logout", style: .default, handler: { (action) in
self.logout()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
private func logout() {
WebServices.logout(success: { (result) in
if result != nil{
Global.logOut()
}
}) { (err, code) in
Global.showToast(msg: err)
}
}
@IBAction func searchButtonTapped(_ sender: UIButton) {
Global.showToast(msg: "under development")
}
@IBAction func messageButtonTapped(_ sender: UIButton) {
Global.showToast(msg: "under development")
}
}
//MARK:- UICollection View delegate/ datesource
extension HomeVC: UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView === self.collectionView{
return self.post_listArr.count
}else{
return self.featured_Arr.count
}
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
if collectionView === self.collectionView{
let width = (Global.screenWidth/2)-2.5
let height = width*1.35
return CGSize(width: width , height: height)
}else{
return CGSize(width: 53.5, height: self.featuredCollectionView.bounds.height)
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView === self.collectionView{
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AppClassID.feedCell.cellID, for: indexPath) as? FeedCell else {
fatalError("HomeCollectionCell not found")
}
cell.load_feedCell(index: indexPath.item, data: post_listArr)
cell.sideOptionButton.addTarget(self, action: #selector(self.editPostButtonTapped(_:)), for: .touchUpInside)
return cell
}else{
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AppClassID.featuredCell.cellID, for: indexPath) as? FeaturedCell else {
fatalError("featuredCell not found")
}
cell.load_featuredCell(index: indexPath.item, data: featured_Arr)
return cell
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView === self.collectionView{
show_Post_Details(index: indexPath)
} else {
Global.showToast(msg: "Under Development")
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.view.endEditing(true)
if scrollView == self.collectionView{
let endScrolling = scrollView.contentOffset.y + scrollView.contentSize.height
if endScrolling > scrollView.contentSize.height {
if let count = self.nextCount ,let totalCount = self.total_Count , post_listArr.count < totalCount {
self.getPostList(pageNo:count+1)
}
}
}
}
}
//MARK:- Extension for Empty DataSet For Table viewWillLayoutSubviews
extension HomeVC : DZNEmptyDataSetSource , DZNEmptyDataSetDelegate{
func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
if scrollView === self.collectionView{
return NSAttributedString(string: "No data available", attributes: [NSAttributedStringKey.foregroundColor: #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1) , NSAttributedStringKey.font: AppFonts.semibold.withSize(12.0)])
}else{
return nil
}
}
func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
return true
}
func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
return false
}
func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView) -> Bool {
return true
}
func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat {
return -10
}
}
//MARK:- show Action Sheet
//========================
extension HomeVC {
func addActionSheet(_ index: IndexPath) {
let action_arr = [ConstantString.k_SharetoFacebook.localized , ConstantString.k_SharetoTwitter.localized, ConstantString.k_CopyLink.localized]
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
for action in action_arr {
let actionButton = UIAlertAction(title: action , style: .default, handler: {(alertAction) in
Global.showToast(msg: "Under Development")
})
actionSheet.addAction(actionButton)
}
if let id = self.post_listArr[index.row].user_id , id == currentUser.id{
let actionButton1 = UIAlertAction(title: ConstantString.k_Edit.localized, style: .default, handler: {(alertAction) in
self.edit_UserPost(index)
})
let actionButton2 = UIAlertAction(title: ConstantString.k_Delete.localized, style: .destructive, handler: {(alertAction) in
self.deletePost_Alert(index)
})
actionSheet.addAction(actionButton1)
actionSheet.addAction(actionButton2)
}
else{
let actionButton1 = UIAlertAction(title: ConstantString.k_TurnonPostNotifications.localized, style: .default, handler: {(alertAction) in
Global.showToast(msg: "Under Development")
})
let actionButton2 = UIAlertAction(title: ConstantString.k_Report.localized, style: .destructive, handler: {(alertAction) in
Global.showToast(msg: "Under Development")
})
actionSheet.addAction(actionButton1)
actionSheet.addAction(actionButton2)
}
let actionButtonCancel = UIAlertAction(title: ConstantString.k_Cancel.localized, style: .cancel, handler: nil)
actionSheet.addAction(actionButtonCancel)
self.present(actionSheet, animated: true, completion: nil)
}
func deletePost_Alert(_ index:IndexPath){
self.showAlert(alert: ConstantString.k_Delete_post.localized, msg: ConstantString.k_Delete_post_message.localized, done: ConstantString.k_Yes.localized, cancel: ConstantString.k_No.localized) { (success) in
if success{
self.post_delete(index: index)
}
}
}
func edit_UserPost(_ index :IndexPath){
let addPostScene = AddPostVC.instantiate(fromAppStoryboard: .Home)
addPostScene.editPostData = post_listArr[index.row].media_arr.first
addPostScene.edit_PostType = .edit
addPostScene.post_id = post_listArr[index.row].featured_id
addPostScene.post_descriptin = post_listArr[index.row].desc
addPostScene.mediaType = post_listArr[index.row].media_arr.first?.media_type
addPostScene.delegate = self
self.tabBarController?.navigationController?.pushViewController(addPostScene, animated: true)
}
func show_Post_Details(index:IndexPath){
let postDetailScene = Post_DetailVC.instantiate(fromAppStoryboard: .Home)
postDetailScene.postData = post_listArr[index.row]
postDetailScene.delegate = self
let navigationController = UINavigationController(rootViewController: postDetailScene)
navigationController.isNavigationBarHidden = true
self.present(navigationController, animated: true, completion: nil)
}
}
// MARK:- editPostProtocol
extension HomeVC : editPostProtocol{
func editPost_protocol(isUpdate: Bool) {
if isUpdate{
self.getPostList(pageNo: 1 , isShowLoader: false)
}
}
}
extension HomeVC{
//MARK:- Begin Uploading
//========================
func beginUploading(data : JSONDictionary? , isFromCamera:Bool = false){
guard let objData = data else{ return }
AWS3Controller.shared.dataToUpload = objData
AWS3Controller.shared.isVideoFrom_Camera = isFromCamera
self.startUploading(objData: AWS3Controller.shared.dataToUpload)
}
func startUploading(objData : JSONDictionary){
AWS3Controller.shared.uploadingStatus = .Uploaded
self.uploadingStatus(status: AWS3Controller.shared.uploadingStatus)
if let type = objData["type"] as? String , type == "2"{
guard let strUrl = objData["videoUrl"] as? URL else {
return
}
Global.print_Debug("video url for p[ost :- \(strUrl)")
guard let imgData = strUrl.getDataFromUrl() else{ return }
self.setUploadingThumbNil(imgData: imgData)
let tempDir = NSTemporaryDirectory()
let tmpUrl = URL(fileURLWithPath: tempDir.appending("tmporary.mp4"))
AWS3Controller.shared.compressVideo(inputURL: strUrl, outputURL: tmpUrl, handler: { (seccion) in
AWS3Controller.shared.uploadVideo(url : strUrl)
})
}else{
guard let images = objData["images"] as? JSONDictionary else {
return
}
AWS3Controller.shared.uploadImages(dict: images)
}
}
//MARK:- set uploading thumbnail
//================================
func setUploadingThumbNil(imgData : Data){
Global.getMainQueue {
self.thumbnilImageView.image = UIImage(data: imgData, scale: 1.0) //UIImage(data: imgData)
}
}
//Display uploading status on view
//===================================
func uploadingStatus(status : UploadingStatus){
guard let _ = self.progressContainerViewHeight else { return }
switch status{
case .Compressing:
UIView.animate(withDuration: 0.5, animations: {
self.progressContainerViewHeight.constant = 70
self.cancelRetryBackViewWidth.constant = 0
self.view.layoutIfNeeded()
})
self.retryButton.isHidden = true
self.cancelButton.isHidden = true
self.thumbnilImageView.isHidden = false
self.progressView.isHidden = false
self.uploadStatusLabel.isHidden = false
self.uploadStatusLabel.text = "Compressing"
self.compressionActivityIndicator.isHidden = false
self.compressionActivityIndicator.startAnimating()
case .InProgress :
UIView.animate(withDuration: 0.5, animations: {
self.progressContainerViewHeight.constant = 70
self.cancelRetryBackViewWidth.constant = 0
self.view.layoutIfNeeded()
})
if let data = AWS3Controller.shared.imageUploadingData{ self.setUploadingThumbNil(imgData: data) }
self.retryButton.isHidden = true
self.cancelButton.isHidden = true
self.thumbnilImageView.isHidden = false
self.progressView.trackTintColor = AppColors.progressViewColor
self.progressView.isHidden = false
self.uploadStatusLabel.isHidden = false
self.uploadStatusLabel.text = "Uploading....."
self.compressionActivityIndicator.isHidden = true
self.compressionActivityIndicator.stopAnimating()
case .Posting:
UIView.animate(withDuration: 0.5, animations: {
self.progressContainerViewHeight.constant = 70
self.cancelRetryBackViewWidth.constant = 0
self.view.layoutIfNeeded()
})
self.retryButton.isHidden = true
self.cancelButton.isHidden = true
self.thumbnilImageView.isHidden = false
self.progressView.isHidden = false
self.progressView.trackTintColor = AppColors.postingProgressViewColor
self.uploadStatusLabel.isHidden = false
self.uploadStatusLabel.text = "Posting..."
self.compressionActivityIndicator.isHidden = true
self.compressionActivityIndicator.stopAnimating()
case .Uploaded :
UIView.animate(withDuration: 0.5, animations: {
self.progressContainerViewHeight.constant = 0
self.cancelRetryBackViewWidth.constant = 0
self.view.layoutIfNeeded()
})
self.retryButton.isHidden = true
self.cancelButton.isHidden = true
self.thumbnilImageView.isHidden = true
self.progressView.isHidden = true
self.uploadStatusLabel.isHidden = true
self.compressionActivityIndicator.isHidden = true
self.compressionActivityIndicator.stopAnimating()
// get update Posts
self.getPostList(pageNo: 1)
case .failed :
UIView.animate(withDuration: 0.5, animations: {
self.progressContainerViewHeight.constant = 70
self.cancelRetryBackViewWidth.constant = 100
self.view.layoutIfNeeded()
})
self.retryButton.isHidden = false
self.cancelButton.isHidden = false
self.thumbnilImageView.isHidden = false
self.progressView.isHidden = false
self.uploadStatusLabel.isHidden = true
self.compressionActivityIndicator.isHidden = true
self.compressionActivityIndicator.stopAnimating()
case .None :
self.progressContainerViewHeight.constant = 0
self.cancelRetryBackViewWidth.constant = 0
self.view.layoutIfNeeded()
self.retryButton.isHidden = true
self.cancelButton.isHidden = true
self.thumbnilImageView.isHidden = true
self.progressView.isHidden = true
self.uploadStatusLabel.isHidden = true
self.compressionActivityIndicator.isHidden = true
self.compressionActivityIndicator.stopAnimating()
}
}
}
//MARK:- Services
extension HomeVC {
func getPostList(pageNo:Int , isShowLoader:Bool = false){
let params :JSONDictionary = ["page":pageNo]
WebServices.get_home_postList(params: params, loader: isShowLoader, success: { [weak self] (result) in
guard let data = result?["data"] else {
Global.print_Debug("result not found")
return
}
self?.featuredTitleLabel.isHidden = false
self?.nextCount = pageNo
self?.total_Count = result?["total"].intValue
if pageNo == 1{
self?.post_listArr = []
self?.featured_Arr = []
}
if let arr = data["featured"].array{
for value in arr{
guard let data = Featured_List(json: value) else {return}
self?.featured_Arr.append(data)
}
}
//hide the featured collectionview if no featured posts available
guard let featuredArrayEmpty = self?.featured_Arr.isEmpty else {
return
}
self?.featuredCollectionView.isHidden = featuredArrayEmpty
self?.heightConstraintFeaturedView.constant = featuredArrayEmpty ? 0 : 112
let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
self?.featuredCollectionView.reloadData()
}
if let arr = data["home"].array{
for value in arr{
guard let data = Featured_List(json: value) else {return}
self?.post_listArr.append(data)
}
self?.collectionView.reloadData()
}
if self?.post_listArr.count == 0 {
self?.featuredTitleLabel.isHidden = true
self?.collectionView.reloadEmptyDataSet()
}
}) { [weak self] (error, code) in
if self?.post_listArr.count == 0 {
self?.featuredTitleLabel.isHidden = true
self?.collectionView.reloadEmptyDataSet()
}else {
self?.featuredTitleLabel.isHidden = false
}
guard let featuredArrayEmpty = self?.featured_Arr.isEmpty else {
return
}
self?.featuredCollectionView.isHidden = featuredArrayEmpty
self?.heightConstraintFeaturedView.constant = featuredArrayEmpty ? 0 : 112
Global.showToast(msg: error.localized)
}
}
func post_delete(index :IndexPath){
let params : JSONDictionary = ["id": self.post_listArr[index.row].featured_id ?? ""]
WebServices.delete_userPost(params: params, success: { [weak self] (result) in
if let data = result{
Global.print_Debug(data)
self?.post_listArr.remove(at: index.row)
if self?.post_listArr.count == 0{
self?.collectionView.reloadEmptyDataSet()
}
self?.collectionView.reloadData()
}
}) { (error, code) in
Global.showToast(msg: error.localized)
}
}
}
|
//
// HomeViewController.swift
// VideoApp
//
// Created by Subba Nelakudhiti on 9/29/17.
// Copyright © 2017 Subba Nelakudhiti. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
var userDetail:SignInViewModel!
@IBOutlet weak var searchBar: UISearchBar!
var searchActive : Bool = false
var homeViewModel = HomeViewModel()
@IBOutlet weak var videoCollection:UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Videos"
searchBar.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension HomeViewController:HomeViewModelDelegate
{
func videoFetchSuccess(isSuccess: Bool) {
if isSuccess
{
DispatchQueue.main.async {
self.videoCollection.isHidden = false
self.videoCollection.reloadData()
}
}
else
{
DispatchQueue.main.async {
//self.videoCollection.isHidden = true
}
print("Hide collectionview")
}
}
}
extension HomeViewController:UICollectionViewDataSource,UICollectionViewDelegate
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.homeViewModel.numberOfRowInSection()
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCell", for: indexPath) as! VideoCollectionCell
cell = self.homeViewModel.cellForItemAtIndexPath(cell: cell, indexPath: indexPath)
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : VideoDetailController = storyboard.instantiateViewController(withIdentifier: "VideoDetailController") as! VideoDetailController
vc.selectedVideo = self.homeViewModel.videoList[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
@objc func showProfile()
{
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : ProfileViewController = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
vc.userProfile = self.userDetail.userDetail
self.navigationController?.pushViewController(vc, animated: true)
//ProfileViewController
}
}
extension HomeViewController:UISearchBarDelegate
{
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchActive = false;
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
homeViewModel = HomeViewModel()
homeViewModel.delegate = self
homeViewModel.fetchYoutubeVideo(searchQuery: searchText)
}
}
|
//
// WidthView.swift
// Basics
//
// Created by Venkatnarayansetty, Badarinath on 3/23/20.
// Copyright © 2020 Badarinath Venkatnarayansetty. All rights reserved.
//
import SwiftUI
struct BoundsPreferenceKey: PreferenceKey {
typealias Value = Anchor<CGRect>?
static var defaultValue: Value = nil
static func reduce(value: inout Value, nextValue: () -> Value) {
value = nextValue()
}
}
//struct WidthView: View {
// var body: some View {
// ZStack {
// Text("Balance Transfer")
// .font(.system(size: 11, weight: Font.Weight.medium))
// .anchorPreference(key: BoundsPreferenceKey.self, value: .bounds) { $0 }
// }
// .overlayPreferenceValue(BoundsPreferenceKey.self) { preferences in
// GeometryReader { geometry in
// preferences.map {
// RoundedRectangle(cornerRadius: CGFloat(8))
// .frame(width: geometry[$0].width, height: geometry[$0].width)
// .foregroundColor(Color.white)
// .shadow(color: Color(UIColor.black).opacity(0.03), radius: CGFloat(8), x: 5, y: -5) // this will add shadow towards right top side.
// .padding(.vertical, 8)
// .shadow(color: Color(UIColor.black).opacity(0.03), radius: CGFloat(8), y: 5) // this will add shadow towrads right bottom side
// }
// }
// }
// }
//}
struct FilterBodyView: View {
var name:String
var body: some View {
VStack {
filterImage
filterName
}
}
private var filterImage: some View {
return Image("y1")
.resizable()
.frame(width: 50,height: 50)
.padding(.horizontal, 24)
.padding(.top, 12)
.aspectRatio(contentMode: ContentMode.fit)
}
private var filterName : some View {
return Text(name)
.foregroundColor(Color.gray)
.multilineTextAlignment(TextAlignment.center)
.font(.system(size: 11, weight: Font.Weight.medium))
.padding(.bottom , 16)
.padding(.horizontal, 2)
}
}
struct WidthPreference: PreferenceKey {
static let defaultValue: [Int:CGFloat] = [:]
static func reduce(value: inout Value, nextValue: () -> Value) {
print(value)
value.merge(nextValue(), uniquingKeysWith: max)
print(value.sorted(by:<))
}
}
extension View {
func widthPreference(column: Int) -> some View {
background(GeometryReader { proxy in
Color.clear.preference(key: WidthPreference.self, value: [column: proxy.size.width])
})
}
}
struct WidthView: View {
var cells = [FilterBodyView(name: "Balance Transfer"),FilterBodyView(name: "one"),FilterBodyView(name: "Two"),FilterBodyView(name: "Four"), FilterBodyView(name: "Three") ]
var body: some View {
CarouselView(cells: cells)
}
}
struct CarouselView<Cell:View>: View {
var cells:[Cell]
@State private var columnWidths: [Int: CGFloat] = [:]
var body: some View {
ScrollView(Axis.Set.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(self.cells.indices) { column in
self.cells[column]
//.widthPreference(column: column)
.padding(8)
.background(RoundedRectangle(cornerRadius: 8)
.frame(width: self.columnWidths[column], height: self.columnWidths[column])
.foregroundColor(Color.white)
.shadow(color: Color(UIColor.black).opacity(0.03), radius: CGFloat(8), x: 5, y: -5)
.padding(.vertical, 8)
.shadow(color: Color(UIColor.black).opacity(0.03), radius: CGFloat(8), y: 5))
}
}.padding(.horizontal, 16)
.onPreferenceChange(WidthPreference.self) { self.columnWidths = $0 }
}
}
}
|
//
// ViewController.swift
// DailyHasslesApp1
//
// Created by 山本英明 on 2021/04/02.
//
import UIKit
import Firebase
import FirebaseAuth
class ViewController: UIViewController {
@IBOutlet weak var userNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func signUpAction(_ sender: Any) {
//空判定
if userNameTextField.text?.isEmpty != true {
//FB匿名登録
Auth.auth().signInAnonymously { (result, error) in
//エラー判定
if error != nil {
print(error.debugDescription)
}else{
//アプリ内保存
UserDefaults.standard.setValue(self.userNameTextField.text, forKey: "userName")
//"TabBarController"へ画面遷移
let tabBC = self.storyboard?.instantiateViewController(identifier: "tabBC") as! TabBarController
self.navigationController?.pushViewController(tabBC, animated: true)
}
}
}
}
}
|
// Copyright (c) 2015-2016 David Turnbull
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and/or associated documentation files (the
// "Materials"), to deal in the Materials without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Materials, and to
// permit persons to whom the Materials are 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 Materials.
//
// THE MATERIALS ARE 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
// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
import SwiftGL
import SwiftGLmath
public class Shader {
public private(set) var vertex:GLuint = 0
public private(set) var fragment:GLuint = 0
public private(set) var program:GLuint = 0
public init(vertex:String, fragment:String)
{
self.vertex = glCreateShader(type: GL_VERTEX_SHADER)
if let errorMessage = Shader.compileShader(self.vertex, source: vertex) {
fatalError(errorMessage)
}
self.fragment = glCreateShader(type: GL_FRAGMENT_SHADER)
if let errorMessage = Shader.compileShader(self.fragment, source: fragment) {
fatalError(errorMessage)
}
self.program = glCreateProgram()
if let errorMessage = Shader.linkProgram(program, vertex: self.vertex, fragment: self.fragment) {
fatalError(errorMessage)
}
}
deinit
{
glDeleteProgram(program)
glDeleteShader(fragment)
glDeleteShader(vertex)
}
public func validate()
{
if let errorMessage = Shader.validateProgram(program) {
fatalError(errorMessage)
}
}
public func use()
{
glUseProgram(program)
}
/// get uniform location;
/// set uniform by string:
/// shader["model"] = mat4();
public subscript(uniform:String) -> Any
{
get {
let loc = glGetUniformLocation(program, uniform)
assert(glGetError() == GL_NO_ERROR)
return loc
}
set {
self[self[uniform] as! GLint] = newValue
}
}
/// set uniform by location:
/// let modelLoc = shader["model"] as! GLint;
/// shader[modelLoc] = mat4();
public subscript(uniform:GLint) -> Any
{
get {
return uniform
}
set {
assert(uniform != -1, "uniform not found")
switch newValue {
case is Float:
let value = newValue as! Float
glUniform1f(uniform, value)
case is vec2:
let value = newValue as! vec2
glUniform2f(uniform, value.x, value.y)
case is vec3:
let value = newValue as! vec3
glUniform3f(uniform, value.x, value.y, value.z)
case is vec4:
let value = newValue as! vec4
glUniform4f(uniform, value.x, value.y, value.z, value.w)
case is mat2:
var value = newValue as! mat2
withUnsafePointer(&value, {
glUniformMatrix2fv(uniform, 1, false, UnsafePointer($0))
})
case is mat3:
var value = newValue as! mat3
withUnsafePointer(&value, {
glUniformMatrix3fv(uniform, 1, false, UnsafePointer($0))
})
case is mat4:
var value = newValue as! mat4
withUnsafePointer(&value, {
glUniformMatrix4fv(uniform, 1, false, UnsafePointer($0))
})
default:
preconditionFailure()
}
assert(glGetError() == GL_NO_ERROR)
}
}
static func getShaderInfoLog(shader: GLuint) -> String
{
var logSize:GLint = 0
glGetShaderiv(shader: shader, pname: GL_INFO_LOG_LENGTH, params: &logSize)
if logSize == 0 { return "" }
var infoLog = [GLchar](count: Int(logSize), repeatedValue: 0)
glGetShaderInfoLog(shader: shader, bufSize: logSize, length: nil, infoLog: &infoLog)
return String.fromCString(infoLog)!
}
static func getProgramInfoLog(program: GLuint) -> String
{
var logSize:GLint = 0
glGetProgramiv(program: program, pname: GL_INFO_LOG_LENGTH, params: &logSize)
if logSize == 0 { return "" }
var infoLog = [GLchar](count: Int(logSize), repeatedValue: 0)
glGetProgramInfoLog(program: program, bufSize: logSize, length: nil, infoLog: &infoLog)
return String.fromCString(infoLog)!
}
static func compileShader(shader: GLuint, source: String) -> String?
{
source.withCString {
var s = UnsafePointer<Int8>($0)
glShaderSource(shader: shader, count: 1, string: &s, length: nil)
}
glCompileShader(shader)
var success:GLint = 0
glGetShaderiv(shader, GL_COMPILE_STATUS, &success)
if success != GL_TRUE {
return getShaderInfoLog(shader)
}
return nil
}
static func linkProgram(program: GLuint, vertex: GLuint, fragment: GLuint) -> String?
{
glAttachShader(program, vertex)
glAttachShader(program, fragment)
glLinkProgram(program)
var success:GLint = 0
glGetProgramiv(program, GL_LINK_STATUS, &success)
if success != GL_TRUE {
return getProgramInfoLog(program)
}
return nil
}
static func validateProgram(program: GLuint) -> String?
{
glValidateProgram(program)
var success:GLint = 0
glGetProgramiv(program, GL_VALIDATE_STATUS, &success)
if success != GL_TRUE {
return getProgramInfoLog(program)
}
return nil
}
} |
//
// MainViewController.swift
// xkcrm
//
// Created by 小庆 王 on 15-2-23.
// Copyright (c) 2015年 wangxiaoqing. All rights reserved.
//
import UIKit
class MainViewController: UIViewController,DrawerMenuControllerDelegate {
var currentViewController: UIViewController?
var currentIndex: Int?
var allViewControllers: Array<UIViewController> = Array<UIViewController>()
override func viewDidLoad() {
super.viewDidLoad()
var storyboard = UIStoryboard(name: "Main", bundle: nil)
var v0:UIViewController = storyboard.instantiateViewControllerWithIdentifier("lead") as UIViewController
var v1:UIViewController = storyboard.instantiateViewControllerWithIdentifier("opportunity") as UIViewController
var v2:UIViewController = storyboard.instantiateViewControllerWithIdentifier("partner") as UIViewController
var v3:UIViewController = storyboard.instantiateViewControllerWithIdentifier("phonecall") as UIViewController
allViewControllers.append(v0)
allViewControllers.append(v1)
allViewControllers.append(v2)
allViewControllers.append(v3)
var initSel = 0
self.currentIndex = initSel
self.currentViewController = self.allViewControllers[initSel]
for (var i = 0 ;i < allViewControllers.count ;i++)
{
allViewControllers[i].view.frame = self.view.bounds
addChildViewController(allViewControllers[i])
self.view.addSubview(allViewControllers[i].view)
if( i > 0){
allViewControllers[i].view.hidden = true
}
}
self.allViewControllers[initSel].didMoveToParentViewController(self)
}
override func viewDidLayoutSubviews(){
for (var i = 0 ;i < allViewControllers.count ;i++)
{
allViewControllers[i].view.frame = self.view.bounds
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func swithToIndex(var newIndex:Int) -> Void {
if newIndex != self.currentIndex {
transitionFromOldIndexToNewIndex(self.currentIndex, newIndex: newIndex)
}
}
func transitionFromOldIndexToNewIndex(oldIndex: Int!, newIndex: Int!) -> Void {
let visibleViewController = self.allViewControllers[oldIndex] as UIViewController
let newViewController = self.allViewControllers[newIndex] as UIViewController
visibleViewController.view.hidden = true
newViewController.view.hidden = false
self.currentViewController = newViewController
self.currentIndex = newIndex
}
//DrawerMenuControllerDelegate
func CustomlayoutViewWithOffset(xoffset: CGFloat, menuController: DrawerMenuController) {
println(xoffset)
menuController.mainCurrentViewWithOffset(xoffset)
if xoffset > 0 {
menuController.leftSideView!.frame = CGRectMake( ( -menuController.leftSideView!.frame.size.width + xoffset + xoffset / menuController.leftViewShowWidth * ( menuController.leftSideView!.frame.size.width - xoffset) ) , 0, menuController.leftSideView!.frame.size.width, menuController.leftSideView!.frame.size.height)
menuController.leftSideView!.alpha = xoffset/menuController.leftViewShowWidth
}
}
@IBAction func onClickMenu(sender: AnyObject) {
(UIApplication.sharedApplication().delegate as AppDelegate).menuController?.showLeftViewController(true)
}
@IBAction func onClickAdd(sender: AnyObject) {
}
/*
// 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.
}
*/
}
|
//
// LanguageEnvelope.swift
// LocalizeWiz
//
// Created by John Warmann on 2020-02-15.
// Copyright © 2020 LocalizeWiz. All rights reserved.
//
import Foundation
class LanguageEnvelope: Codable {
var languages: [Language]
}
|
//
// ObatCard.swift
// KindCer
//
// Created by Muhammad Tafani Rabbani on 04/01/20.
// Copyright © 2020 Muhammad Tafani Rabbani. All rights reserved.
//
import SwiftUI
struct ObatCard: View {
@State var obat : ObatType = ObatType(id: StaticModel.id, name: "obat pusing", jadwal: [], jenis: "", aturan: "sesudah makan")
@ObservedObject var mObat : ObatModel
var body: some View {
ZStack{
Rectangle().frame( height: 100).foregroundColor(.white).cornerRadius(10)
HStack{
ZStack {
ProgressCircle(value: getHowMany(),
maxValue: Double(obat.jadwal.count),
style: .line,
foregroundColor: Color("Primary"),
lineWidth: 5)
Text(getValue()).foregroundColor(Color("Primary")).bold()
}.frame(width: 60, height: 60)
.padding()
VStack(alignment: .leading){
Text(obat.name) .font(.system(size: 18)) .fontWeight(.semibold)
Text("")
Text(obat.aturan).font(.system(size: 15)) .fontWeight(.medium).foregroundColor(.gray)
}
Spacer()
VStack{
if isSelesai(){
Text("Selesai").bold().foregroundColor(Color("Primary")).font(.system(size: 22))
}else{
Text("Jam Berikutnya").foregroundColor(.gray).font(.system(size: 12))
Text(getNextTime()).bold().foregroundColor(Color("Primary")).font(.system(size: 22))
}
}.padding(.horizontal)
}
}
}
func isSelesai()->Bool{
let arr = Array(obat.jadwal)
let date = Date()
let calendar = Calendar.current
let cHour = calendar.component(.hour, from: date)
let cMinute = calendar.component(.minute, from: date)
let mTime = cHour*100 + cMinute
for a in arr{
let string = a
if let number = Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) {
if mTime < number{
return false
}
}
}
return true
}
func getNextTime()->String{
let arr = Array(obat.jadwal)
var time = 0
let date = Date()
let calendar = Calendar.current
let cHour = calendar.component(.hour, from: date)
let cMinute = calendar.component(.minute, from: date)
let mTime = cHour*100 + cMinute
var aTime = [Int]()
for a in arr{
if let number = Int(a.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) {
if (time < number) && (number >= mTime){
aTime.append(number)
}
}
}
aTime = aTime.sorted()
time = aTime.first ?? 0
let h = time/100
let m = time%100
return "\(h):\(m==0 ? "00" : String(m))"
}
func getValue()->String{
return "\(Int(getHowMany()))/\(obat.jadwal.count)"
}
func getHowMany()->Double{
let data = mObat.getData(obat: obat.name)
return Double(data.count)
}
}
struct ObatCard_Previews: PreviewProvider {
static var previews: some View {
ObatCard(mObat: ObatModel())
}
}
|
//
// DeliveryCellView.swift
// DeliveryApp
//
// Created by abhisheksingh03 on 10/07/19.
// Copyright © 2019 abhisheksingh03. All rights reserved.
//
import UIKit
class DeliveryItemView: UIView {
struct Constant {
static let size: CGFloat = 70
static let padding: CGFloat = ViewConstant.padding
static let borderWidth: CGFloat = 0.5
static let borderColor: UIColor = ColorConstant.appTheme
static let textColor: UIColor = .black
static let textFont: UIFont = FontConstant.systemRegular
static let cornerRadius: CGFloat = ViewConstant.cornerRadius
}
var deliveryItem: DeliveryViewModel? {
didSet {
self.deliveryItemImage.setImageWith(URL: deliveryItem?.imageURL ?? "")
self.deliveryItemLabel.text = deliveryItem?.description
}
}
private let deliveryItemLabel: UILabel = {
let label = UILabel()
label.textColor = Constant.textColor
label.font = Constant.textFont
label.textAlignment = .left
label.numberOfLines = 0
return label
}()
private let deliveryItemImage: UIImageView = {
let imgView = UIImageView(image: UIImage(named: "placeholder"))
imgView.contentMode = .scaleAspectFill
imgView.clipsToBounds = true
imgView.layer.cornerRadius = Constant.cornerRadius
return imgView
}()
init(item: DeliveryViewModel) {
super.init(frame: CGRect.zero)
self.layer.cornerRadius = Constant.cornerRadius
self.layer.borderColor = Constant.borderColor.cgColor
self.layer.borderWidth = Constant.borderWidth
initializeSubViews()
deliveryItemImage.setImageWith(URL: item.imageURL)
deliveryItemLabel.text = item.description
}
init() {
super.init(frame: CGRect.zero)
initializeSubViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func initializeSubViews() {
self.backgroundColor = .white
self.addSubview(deliveryItemImage)
self.addSubview(deliveryItemLabel)
setupViewConstraints()
}
func setupViewConstraints() {
deliveryItemImage.anchor(top: topAnchor,
left: leftAnchor,
paddingTop: Constant.padding,
paddingLeft: Constant.padding,
widthConstant: Constant.size,
heightConstant: Constant.size)
deliveryItemLabel.anchor(top: topAnchor,
left: deliveryItemImage.rightAnchor,
bottom: bottomAnchor,
right: rightAnchor,
paddingTop: Constant.padding,
paddingLeft: Constant.padding,
paddingBottom: Constant.padding,
paddingRight: Constant.padding)
deliveryItemLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constant.size).isActive = true
}
}
|
import UIKit
class VMainBarCell:UICollectionViewCell
{
weak var image:UIImageView!
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let image:UIImageView = UIImageView()
image.isUserInteractionEnabled = false
image.clipsToBounds = true
image.translatesAutoresizingMaskIntoConstraints = false
image.contentMode = UIViewContentMode.center
self.image = image
addSubview(image)
let views:[String:UIView] = [
"image":image]
let metrics:[String:CGFloat] = [:]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[image]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-20-[image]-0-|",
options:[],
metrics:metrics,
views:views))
}
required init?(coder:NSCoder)
{
fatalError()
}
}
|
import Foundation
//class ComplexGradient: ManualGradient {
// var gradients: [(manualGradient: ManualGradient, length: CGFloat)] = []
// var lastColorVector: ColorVector
//
// init(firstColorVector: ColorVector) {
// self.lastColorVector = firstColorVector
// }
//
// convenience init?(firstColor: NSColor = NSColor.clearColor()) {
// if let firstColorVector = ColorVector(color: firstColor) {
// self.init(firstColorVector: firstColorVector)
// } else {
// return nil
// }
// }
//
//// // Adds linear gradient
//// func addGradientToColor(endColor: NSColor, withLength length: CGFloat) {
//// guard let endColorVector = ColorVector(color: endColor) else {
//// let bla = 4 // add throw
//// }
////
//// var nextGradients = gradients
//// let newLinearGradient = LinearGradient(colorVectors: (lastColorVector, endColorVector))
//// nextGradients.append(manualGradient: newLinearGradient, length: length)
////
//// self.lastColorVector = endColorVector
//// self.gradients = nextGradients
//// }
//
// func colorVectorForPoint(point: CGFloat) -> ColorVector {
// return lastColorVector
// }
//}
|
//
// ContentView.swift
// Reddit Client
//
// Created by Женя on 24.05.2021.
//
import SwiftUI
import CoreData
struct ContentView: View {
@ObservedObject var postListViewModel: PostListViewModel
var body: some View {
NavigationView {
List {
ForEach(postListViewModel.postsVM) { post in
NavigationLink(destination: DetailView(detailVM: DetailViewModel(url: post.url, saveButtonEnable: post.isSavingEnable))) {
PostCell(postVM: post)
}
}
if postListViewModel.fetchingAllowed {
Text("Fetching posts...")
.onAppear(perform: fetchList)
}
}
.navigationBarTitle("Reddit")
}
}
private func fetchList() {
postListViewModel.fetchList()
}
}
struct PostsList_Previews : PreviewProvider {
static var previews: some View {
ContentView(postListViewModel: PostListViewModel(manager: NetworkManager()))
}
}
|
//
// ViewController.swift
// PeopleAndAppleStockPrices
//
// Created by Alex Paul on 12/7/18.
// Copyright © 2018 Pursuit. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var peopleTableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var people = [ResultsWrapper]() {
didSet {
DispatchQueue.main.async {
self.peopleTableView.reloadData()
}
}
}
override func viewDidLoad() {
title = "Random People"
peopleTableView.dataSource = self
searchBar.delegate = self
super.viewDidLoad()
people = loadData()
}
private func searchPeople(keyword: String) {
guard let encodedKeyword = keyword.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {return}
PeopleAPI.getPeople(searchName: encodedKeyword) { (movies, error) in
if error != nil {
print(error as Any)
}
}
}
func loadData() -> [ResultsWrapper] {
var results = [ResultsWrapper]()
if let path = Bundle.main.path(forResource: "userinfo", ofType: "json") {
let myURL = URL.init(fileURLWithPath: path)
if let data = try? Data.init(contentsOf: myURL) {
do {
let people = try JSONDecoder().decode(UserInfo.self,from: data)
results = people.results
results.sort{$0.name.first < $1.name.first}
} catch {
}
}
}
return results
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destination = segue.destination as? PeopleDetailViewController,
let selectedIndexpath = peopleTableView.indexPathForSelectedRow else { return }
let peopleToSend = people[selectedIndexpath.row]
destination.image = PeopleAPI.getImage(url: peopleToSend.picture.large)
destination.people = peopleToSend
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = peopleTableView.dequeueReusableCell(withIdentifier: "peopleCell", for: indexPath)
let peopleinfo = people[indexPath.row]
cell.textLabel?.text = "\(peopleinfo.name.first) \(peopleinfo.name.last)".capitalized
cell.detailTextLabel?.text = "\(peopleinfo.location.city), \(peopleinfo.location.state)"
guard let imageUrl = URL.init(string: peopleinfo.picture.thumbnail) else { return UITableViewCell() }
do {
let data = try Data.init(contentsOf: (imageUrl))
cell.imageView?.image = UIImage.init(data: data)
} catch {
print(error)
}
return cell
}
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
people = loadData()
if searchText == "" {
return
} else {
people = loadData().filter{$0.name.first.lowercased().contains(searchText.lowercased())}
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
if searchBar.text == "" {
people = loadData()
}
}
}
|
//
// ViewController.swift
// PythonServerDemo
//
// Created by 李亚洲 on 16/4/10.
// Copyright © 2016年 angryli. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import SnapKit
class AGLLoginViewController: UIViewController {
@IBOutlet weak var tfPhone: UITextField!
@IBOutlet weak var tfPassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// self.p_buildWquipWidthButtons()
}
@IBAction func action_login(_ sender: UIButton, forEvent event: UIEvent) {
guard tfPassword.text != nil else {
print("请输入手机号码")
return
}
guard tfPassword.text != nil else {
print("请输入密码")
return
}
Alamofire.request(.POST, "http://localhost:8000/login?phone=\(tfPhone.text!)&password=\(tfPassword.text!)", parameters: ["name" :"Liyazhou"], encoding: .json, headers: nil).responseJSON { (response) in
switch response.result {
case .success:
if let value = response.result.value {
let json = JSON(value)
print("JSON: \(json)")
}
case .failure(let error):
print(error)
}
}
}
@IBAction func action_register(_ sender: UIButton, forEvent event: UIEvent) {
guard tfPassword.text != nil else {
print("请输入手机号码")
return
}
guard tfPassword.text != nil else {
print("请输入密码")
return
}
Alamofire.request(.POST, "http://localhost:8000/register?phone=\(tfPhone.text!)&password=\(tfPassword.text!)", parameters: nil, encoding: .json, headers: nil).responseJSON { (response) in
switch response.result {
case .success:
if let value = response.result.value {
let json = JSON(value)
print("JSON: \(json)")
}
case .failure(let error):
print(error)
}
}
}
}
|
import UIKit
protocol Stack {
associatedtype Element
var count: Int { get }
mutating func push(_ element: Element)
mutating func pop() -> Element?
}
struct IntStack: Stack {
private var array: [Int] = []
var count: Int {
return array.count
}
mutating func push(_ element: Int) {
array.append(element)
}
mutating func pop() -> Int? {
array.popLast()
}
}
struct MyStack<Item>: Stack {
private var values: [Item] = []
var count: Int {
return values.count
}
mutating func push(_ element: Item) {
values.append(element)
}
mutating func pop() -> Item? {
values.popLast()
}
}
var myStringStack = MyStack<String>()
myStringStack.push("a")
myStringStack.push("b")
myStringStack.count
myStringStack.pop()
myStringStack.pop()
myStringStack.count
var myIntStack = MyStack<Int>()
myIntStack.push(1)
myIntStack.push(2)
myIntStack.count
myIntStack.pop()
myIntStack.pop()
myIntStack.count
extension Array: Stack {
mutating func push(_ element: Element) {
self.append(element)
}
mutating func pop() -> Element? {
return self.popLast()
}
}
func execeuteOperation<Container: Stack>(container: Container) {
}
print("Hello")
|
//
// ContentView.swift
// PopIt
//
// Created by Dan-Mini on 2021/06/03.
//
import SwiftUI
struct ContentView: View {
@State var colorRed = Color.red
@State var colorOrange = Color.orange
@State var colorYellow = Color.yellow
@State var colorGreen = Color.green
@State var colorBlue = Color.blue
@State var colorPurple = Color.purple
var body: some View {
ZStack{
Image("rainbow")
.resizable()
.edgesIgnoringSafeArea(.all)
VStack{
PopItButton(popColor: $colorRed)
PopItButton(popColor: $colorOrange)
PopItButton(popColor: $colorYellow)
PopItButton(popColor: $colorGreen)
PopItButton(popColor: $colorBlue)
PopItButton(popColor: $colorPurple)
/*
ForEach (1..<7) { index in
PopItButton()
.blendMode(.multiply)
}
*/
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct aButton: View {
@State var upAndDown = true
var body: some View {
Image(upAndDown ? "popUp" : "popDown")
.resizable()
.frame(width: 70, height: 70, alignment: .center)
.onTapGesture {
upAndDown.toggle()
}
}
}
struct PopItButton: View {
@Binding var popColor: Color
var body: some View {
HStack{
ForEach (1..<5) { index in
aButton()
.colorMultiply(popColor)
}
}
}
}
|
//
// PhotosGridController.swift
// FBMIF50
//
// Created by BeInMedia on 3/22/20.
// Copyright © 2020 MIF50. All rights reserved.
//
import UIKit
import SwiftUI
import LBTATools
class PhotosGridController: LBTAListController<PhotoGridCell,String> {
let cellSpacing: CGFloat = 4
override func viewDidLoad() {
super.viewDidLoad()
initCollectionView()
}
private func initCollectionView(){
collectionView.backgroundColor = .lightGray
self.items = ["avatar1","story_photo1","story_photo2","avatar1","avatar1"]
}
}
//MARK:- Collection View Delegate Flow Layout
extension PhotosGridController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if self.items.count == 4 {
// do 4 grid cell layout here
}
if indexPath.item == 0 || indexPath.item == 1 {
let width = (view.frame.width - 3 * cellSpacing) / 2
return .init(width: width, height: width)
} else {
let width = (view.frame.width - 4.1 * cellSpacing) / 3
return .init(width: width, height: width)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return cellSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return cellSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return .init(top: 0, left: cellSpacing, bottom: 0, right: cellSpacing)
}
}
// to preview desing form SwiftUI
struct PhotoPreview: PreviewProvider {
static var previews: some View {
ContainerView().edgesIgnoringSafeArea(.all).previewLayout(.fixed(width: 400, height: 500))
}
struct ContainerView: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<PhotoPreview.ContainerView>) -> UIViewController {
return PhotosGridController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<PhotoPreview.ContainerView>) {
}
}
}
|
import DataSourceController
import Foundation
protocol HomeViewModelDelegate: AnyObject {
func viewModelFailedToFetchData(_: HomeViewModelType)
func viewModel(_: HomeViewModelType, didSelectItemWithViewModel _: TrackDetailsViewModelType)
}
protocol HomeViewModelType {
var dataSource: DataSourceController { get }
var delegate: HomeViewModelDelegate? { get set }
var searchTerm: String { get }
var searchScopeIndex: Int { get }
func updateSearchTerm(_: String?)
func updateSearchScope(_: Int)
}
class HomeViewModel {
private var artists: [Artist] {
didSet {
dataSource.removeAllSections(notify: false)
let rowEntries = artists.map { SearchResultTableCellData(artist: $0, delegate: self) }
dataSource.add(section: Section(rows: rowEntries))
}
}
private let repository: SearchRepositoryType
private var searchScope: SearchRepository.SearchScope = .artist {
didSet { performSearch() }
}
private(set) var searchTerm: String {
didSet { performSearch() }
}
lazy var dataSource: DataSourceController = {
let dataSource = DataSourceController(rows: [])
dataSource.register(
dataController: SearchResultTableViewModel.self,
for: SearchResultTableCellData.self
)
return dataSource
}()
weak var delegate: HomeViewModelDelegate?
init(repository: SearchRepositoryType) {
self.repository = repository
artists = []
searchTerm = ""
}
}
extension HomeViewModel: HomeViewModelType {
var searchScopeIndex: Int {
return searchScope.invValue
}
func performSearch() {
switch searchScope {
case .album:
repository.searchMusicVideos(album: searchTerm) { [weak self] result in
self?.handleSearchResult(result)
}
case .artist:
repository.searchMusicVideos(artist: searchTerm) { [weak self] result in
self?.handleSearchResult(result)
}
case .song:
repository.searchMusicVideos(song: searchTerm) { [weak self] result in
self?.handleSearchResult(result)
}
}
}
func updateSearchTerm(_ term: String?) {
if let term = term {
searchTerm = term
}
}
func updateSearchScope(_ index: Int) {
if let newScope = SearchRepository.SearchScope(intValue: index) {
searchScope = newScope
}
}
}
extension HomeViewModel: SearchResultTableDelegate {
func didSelectTrack(_ track: Track) {
delegate?.viewModel(
self,
didSelectItemWithViewModel: TrackDetailsViewModel(track: track)
)
}
}
private extension HomeViewModel {
func handleSearchResult(_ result: Result<[Artist], Error>) {
switch result {
case .success(let artists):
self.artists = artists.sorted()
case .failure(let error):
delegate?.viewModelFailedToFetchData(self)
print(error)
}
}
}
private extension SearchRepository.SearchScope {
init?(intValue: Int) {
switch intValue {
case 0: self = .artist
case 1: self = .song
case 2: self = .album
default: return nil
}
}
var invValue: Int {
switch self {
case .artist: return 0
case .song: return 1
case .album: return 2
}
}
}
|
//
// CurrencyWithUSDRate.swift
// PaypayCurrencyConverter
//
// Created by Chung Han Hsin on 2021/3/7.
//
import Foundation
struct RateCurrency {
let abbreName: String
let rate: Float
}
|
import NIO
/**
PowerLevelMessage
Message that carries a `Device.PowerLevel` payload.
*/
class PowerLevelMessage: Message {
/**
The `Device.PowerLevel` carried by the message.
*/
let powerLevel: Device.PowerLevel
/**
Initializes a new message with a provided `powerLevel`.
- parameters:
- target: `Target` of the `Message` indicating where the `Message` should be send to.
- requestAcknowledgement: Indicates that a acknowledgement message is required.
- requestResponse: Indicates that a response message is required.
- powerLevel: The `Device.PowerLevel` carried by the message.
*/
init(target: Target,
requestAcknowledgement: Bool,
requestResponse: Bool,
powerLevel: Device.PowerLevel) {
self.powerLevel = powerLevel
super.init(target: target,
requestAcknowledgement: requestAcknowledgement,
requestResponse: requestResponse)
}
/**
Initializes a new message from an encoded payload.
The payload layout of the `payload` must be the following:
[LIFX LAN Docs](https://lan.developer.lifx.com/docs/device-messages#section-setpower-21):
[LIFX LAN Docs](https://lan.developer.lifx.com/docs/device-messages#section-statepower-22):
```
1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| POWER_LEVEL |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
```
- parameters:
- source: Source identifier: unique value set by the client, used by responses.
- target: `Target` of the `Message` indicating where the `Message` should be send to.
- requestAcknowledgement: Indicates that a acknowledgement message is required.
- requestResponse: Indicates that a response message is required.
- sequenceNumber: Wrap around message sequence number.
- payload: The encoded payload of the `PowerLevelMessage`.
*/
init(source: UInt32,
target: Target,
requestAcknowledgement: Bool,
requestResponse: Bool,
sequenceNumber: UInt8,
payload: ByteBuffer) throws {
guard payload.readableBytes >= MemoryLayout<Device.PowerLevel.RawValue>.size else {
throw MessageError.messageFormat
}
self.powerLevel = try payload.getPowerLevel(at: payload.readerIndex).powerLevel
super.init(source: source,
target: target,
requestAcknowledgement: requestAcknowledgement,
requestResponse: requestResponse,
sequenceNumber: sequenceNumber)
}
/*
Payload written in this write function:
```
1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| POWER_LEVEL |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
```
*/
override func writeData(inBuffer buffer: inout ByteBuffer) {
buffer.write(powerLevel: powerLevel)
}
}
|
//
// Anchor.swift
// NiceLayout
//
// Created by Adam Shin on 3/1/20.
// Copyright © 2020 Adam Shin. All rights reserved.
//
import UIKit
// MARK: - Anchor Protocols
public protocol LayoutAnchor {
var attribute: NSLayoutConstraint.Attribute { get }
}
public protocol LayoutCompositeAnchor {
var attributes: [NSLayoutConstraint.Attribute] { get }
}
// MARK: - Anchors
public protocol LayoutEdgeAnchor: LayoutAnchor { }
public enum LayoutXAxisAnchor: LayoutEdgeAnchor {
case leading
case trailing
case left
case right
case centerX
public var attribute: NSLayoutConstraint.Attribute {
switch self {
case .leading: return .leading
case .trailing: return .trailing
case .left: return .left
case .right: return .right
case .centerX: return .centerX
}
}
}
public enum LayoutYAxisAnchor: LayoutEdgeAnchor {
case top
case bottom
case centerY
public var attribute: NSLayoutConstraint.Attribute {
switch self {
case .top: return .top
case .bottom: return .bottom
case .centerY: return .centerY
}
}
}
public enum LayoutSizeAnchor: LayoutAnchor {
case width
case height
public var attribute: NSLayoutConstraint.Attribute {
switch self {
case .width: return .width
case .height: return .height
}
}
}
// MARK: - Composite Anchors
public enum LayoutCompositeEdgeAnchor: LayoutCompositeAnchor {
case edges
case hEdges
case vEdges
case topLeading
case topTrailing
case bottomLeading
case bottomTrailing
case topLeft
case topRight
case bottomLeft
case bottomRight
public var attributes: [NSLayoutConstraint.Attribute] {
switch self {
case .edges: return [.leading, .trailing, .top, .bottom]
case .hEdges: return [.leading, .trailing]
case .vEdges: return [.top, .bottom]
case .topLeading: return [.top, .leading]
case .topTrailing: return [.top, .trailing]
case .bottomLeading: return [.bottom, .leading]
case .bottomTrailing: return [.bottom, .trailing]
case .topLeft: return [.top, .left]
case .topRight: return [.top, .right]
case .bottomLeft: return [.bottom, .left]
case .bottomRight: return [.bottom, .right]
}
}
}
public enum LayoutCompositeCenterAnchor: LayoutCompositeAnchor {
case center
public var attributes: [NSLayoutConstraint.Attribute] {
switch self {
case .center: return [.centerX, .centerY]
}
}
}
public enum LayoutCompositeSizeAnchor: LayoutCompositeAnchor {
case size
public var attributes: [NSLayoutConstraint.Attribute] {
switch self {
case .size: return [.width, .height]
}
}
}
|
//
// LinePropertyStyles.swift
// AahToZzz
//
// Created by David Fierstein on 4/16/18.
// Copyright © 2018 David Fierstein. All rights reserved.
//
import UIKit
struct LineProperties {
var lineWidth: CGFloat
var color: UIColor
}
struct LinePropertyStyles {
// Standard frosted edge, works well with partial blur view
static let frosted: [LineProperties] = [
LineProperties(lineWidth: 11.0, color: Colors.veryLight),
LineProperties(lineWidth: 8.5, color: Colors.veryLight),
LineProperties(lineWidth: 5.5, color: Colors.lightBackground),
LineProperties(lineWidth: 2.25, color: .white),
LineProperties(lineWidth: 1.5, color: Colors.darkBackground)]
// Use for button: Highlight outside dark line gives a sunk into the screen look
static let frostedEdgeHighlight: [LineProperties] = [
LineProperties(lineWidth: 15.5, color: Colors.veryLight),
LineProperties(lineWidth: 13.0, color: Colors.veryLight),
LineProperties(lineWidth: 10.0, color: Colors.lightBackground),
LineProperties(lineWidth: 6.75, color: .white),
LineProperties(lineWidth: 6.0, color: Colors.darkBackground),
LineProperties(lineWidth: 3.0, color: Colors.light_yellow)]
}
enum LinePropertyStyle: Int { case frosted, frostedEdgeHighlight }
|
//
// IntegratedSDKsData.swift
// TestBed-Swift
//
// Created by David Westgate on 9/18/17.
// Copyright © 2017 Branch Metrics. All rights reserved.
//
import Foundation
struct IntegratedSDKsData {
static let userDefaults = UserDefaults.standard
// MARK - Adjust
static func activeAdjustAppToken() -> String? {
if let value = userDefaults.string(forKey: "activeAppToken") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "adjust_app_token") as? String {
userDefaults.setValue(value, forKey: "activeAppToken")
return value
}
return nil
}
static func setActiveAdjustAppToken(_ value: String) {
userDefaults.setValue(value, forKey: "activeAppToken")
}
static func pendingAdjustAppToken() -> String? {
if let value = userDefaults.string(forKey: "pendingAdjustAppToken") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "adjust_app_token") as? String {
userDefaults.setValue(value, forKey: "pendingAdjustAppToken")
return value
}
return nil
}
static func setPendingAdjustAppToken(_ value: String) {
userDefaults.setValue(value, forKey: "pendingAdjustAppToken")
}
static func activeAdjustEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeAdjustEnabled")
}
static func setActiveAdjustEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeAdjustEnabled")
}
static func pendingAdjustEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingAdjustEnabled")
}
static func setPendingAdjustEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingAdjustEnabled")
}
// MARK - Adobe
static func activeAdobeKey() -> String? {
if let value = userDefaults.string(forKey: "activeAdobeKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "adobe_api_key") as? String {
userDefaults.setValue(value, forKey: "activeAdobeKey")
return value
}
return nil
}
static func setActiveAdobeKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeAdobeKey")
}
static func pendingAdobeKey() -> String? {
if let value = userDefaults.string(forKey: "pendingAdobeKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "adobe_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingAdobeKey")
return value
}
return nil
}
static func setPendingAdobeKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingAdobeKey")
}
static func activeAdobeEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeAdobeEnabled")
}
static func setActiveAdobeEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeAdobeEnabled")
}
static func pendingAdobeEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingAdobeEnabled")
}
static func setPendingAdobeEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingAdobeEnabled")
}
// Amplitude
static func activeAmplitudeKey() -> String? {
if let value = userDefaults.string(forKey: "activeAmplitudeKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "amplitude_api_key") as? String{
userDefaults.setValue(value, forKey: "activeAmplitudeKey")
return value
}
return nil
}
static func setActiveAmplitudeKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeAmplitudeKey")
}
static func pendingAmplitudeKey() -> String? {
if let value = userDefaults.string(forKey: "pendingAmplitudeKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "amplitude_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingAmplitudeKey")
return value
}
return nil
}
static func setPendingAmplitudeKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingAmplitudeKey")
}
static func activeAmplitudeEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeAmplitudeEnabled")
}
static func setActiveAmplitudeEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeAmplitudeEnabled")
}
static func pendingAmplitudeEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingAmplitudeEnabled")
}
static func setPendingAmplitudeEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingAmplitudeEnabled")
}
// Mark - Appsflyer
static func activeAppsflyerKey() -> String? {
if let value = userDefaults.string(forKey: "activeAppsflyerKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "appsflyer_api_key") as? String {
userDefaults.setValue(value, forKey: "activeAppsflyerKey")
return value
}
return nil
}
static func setActiveAppsflyerKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeAppsflyerKey")
}
static func pendingAppsflyerKey() -> String? {
if let value = userDefaults.string(forKey: "pendingAppsflyerKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "appsflyer_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingAppsflyerKey")
return value
}
return nil
}
static func setPendingAppsflyerKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingAppsflyerKey")
}
static func activeAppsflyerEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeAppsflyerEnabled")
}
static func setActiveAppsflyerEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeAppsflyerEnabled")
}
static func pendingAppsflyerEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingAppsflyerEnabled")
}
static func setPendingAppsflyerEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingAppsflyerEnabled")
}
// Mark - Google Analytics
static func activeGoogleAnalyticsTrackingID() -> String? {
if let value = userDefaults.string(forKey: "activeGoogleAnalyticsTrackingID") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "google_analytics_tracking_id") as? String {
userDefaults.setValue(value, forKey: "activeGoogleAnalyticsTrackingID")
return value
}
return nil
}
static func setActiveGoogleAnalyticsTrackingID(_ value: String) {
userDefaults.setValue(value, forKey: "activeGoogleAnalyticsTrackingID")
}
static func pendingGoogleAnalyticsTrackingID() -> String? {
if let value = userDefaults.string(forKey: "pendingGoogleAnalyticsTrackingID") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "google_analytics_tracking_id") as? String {
userDefaults.setValue(value, forKey: "pendingGoogleAnalyticsTrackingID")
return value
}
return nil
}
static func setPendingGoogleAnalyticsTrackingID(_ value: String) {
userDefaults.setValue(value, forKey: "pendingGoogleAnalyticsTrackingID")
}
static func activeGoogleAnalyticsEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeGoogleAnalyticsEnabled")
}
static func setActiveGoogleAnalyticsEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeGoogleAnalyticsEnabled")
}
static func pendingGoogleAnalyticsEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingGoogleAnalyticsEnabled")
}
static func setPendingGoogleAnalyticsEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingGoogleAnalyticsEnabled")
}
// Mark - Mixpanel
static func activeMixpanelKey() -> String? {
if let value = userDefaults.string(forKey: "activeMixpanelKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "mixpanel_api_key") as? String {
userDefaults.setValue(value, forKey: "activeMixpanelKey")
return value
}
return nil
}
static func setActiveMixpanelKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeMixpanelKey")
}
static func pendingMixpanelKey() -> String? {
if let value = userDefaults.string(forKey: "pendingMixpanelKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "mixpanel_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingMixpanelKey")
return value
}
return nil
}
static func setPendingMixpanelKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingMixpanelKey")
}
static func activeMixpanelEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeMixpanelEnabled")
}
static func setActiveMixpanelEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeMixpanelEnabled")
}
static func pendingMixpanelEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingMixpanelEnabled")
}
static func setPendingMixpanelEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingMixpanelEnabled")
}
// Mark - Tune
// AdvertisingID
static func activeTuneAdvertisingID() -> String? {
if let value = userDefaults.string(forKey: "activeTuneAdvertisingID") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "tune_advertising_id") as? String {
userDefaults.setValue(value, forKey: "activeTuneAdvertisingID")
return value
}
return nil
}
static func setActiveTuneAdvertisingID(_ value: String) {
userDefaults.setValue(value, forKey: "activeTuneAdvertisingID")
}
static func pendingTuneAdvertisingID() -> String? {
if let value = userDefaults.string(forKey: "pendingTuneAdvertisingID") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "tune_advertising_id") as? String {
userDefaults.setValue(value, forKey: "pendingTuneAdvertisingID")
return value
}
return nil
}
static func setPendingTuneAdvertisingID(_ value: String) {
userDefaults.setValue(value, forKey: "pendingTuneAdvertisingID")
}
// ConversionKey
static func activeTuneConversionKey() -> String? {
if let value = userDefaults.string(forKey: "activeTuneConversionKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "tune_conversion_key") as? String {
userDefaults.setValue(value, forKey: "activeTuneConversionKey")
return value
}
return nil
}
static func setActiveTuneConversionKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeTuneConversionKey")
}
static func pendingTuneConversionKey() -> String? {
if let value = userDefaults.string(forKey: "pendingTuneConversionKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "tune_conversion_key") as? String {
userDefaults.setValue(value, forKey: "pendingTuneConversionKey")
return value
}
return nil
}
static func setPendingTuneConversionKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingTuneConversionKey")
}
static func activeTuneEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeTuneEnabled")
}
static func setActiveTuneEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeTuneEnabled")
}
static func pendingTuneEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingTuneEnabled")
}
static func setPendingTuneEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingTuneEnabled")
}
// Mark - Appboy
static func activeAppboyAPIKey() -> String? {
if let value = userDefaults.string(forKey: "activeAppboyAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "appboy_api_key") as? String {
userDefaults.setValue(value, forKey: "activeAppboyAPIKey")
return value
}
return nil
}
static func setActiveAppboyAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeAppboyAPIKey")
}
static func pendingAppboyAPIKey() -> String? {
if let value = userDefaults.string(forKey: "pendingAppboyAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "appboy_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingAppboyAPIKey")
return value
}
return nil
}
static func setPendingAppboyAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingAppboyAPIKey")
}
static func activeAppboyEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeAppboyEnabled")
}
static func setActiveAppboyEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeAppboyEnabled")
}
static func pendingAppboyEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingAppboyEnabled")
}
static func setPendingAppboyEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingAppboyEnabled")
}
// Mark - AppMetrica
static func activeAppMetricaAPIKey() -> String? {
if let value = userDefaults.string(forKey: "activeAppMetricaAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "appmetrica_api_key") as? String {
userDefaults.setValue(value, forKey: "activeAppMetricaAPIKey")
return value
}
return nil
}
static func setActiveAppMetricaAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeAppMetricaAPIKey")
}
static func pendingAppMetricaAPIKey() -> String? {
if let value = userDefaults.string(forKey: "pendingAppMetricaAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "appmetrica_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingAppMetricaAPIKey")
return value
}
return nil
}
static func setPendingAppMetricaAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingAppMetricaAPIKey")
}
static func activeAppMetricaEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeAppMetricaEnabled")
}
static func setActiveAppMetricaEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeAppMetricaEnabled")
}
static func pendingAppMetricaEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingAppMetricaEnabled")
}
static func setPendingAppMetricaEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingAppMetricaEnabled")
}
// Mark - ClearTap
static func activeClearTapAPIKey() -> String? {
if let value = userDefaults.string(forKey: "activeClearTapAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "clevertap_api_key") as? String {
userDefaults.setValue(value, forKey: "activeClearTapAPIKey")
return value
}
return nil
}
static func setActiveClearTapAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeClearTapAPIKey")
}
static func pendingClearTapAPIKey() -> String? {
if let value = userDefaults.string(forKey: "pendingClearTapAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "clevertap_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingClearTapAPIKey")
return value
}
return nil
}
static func setPendingClearTapAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingClearTapAPIKey")
}
static func activeClearTapEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeClearTapEnabled")
}
static func setActiveClearTapEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeClearTapEnabled")
}
static func pendingClearTapEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingClearTapEnabled")
}
static func setPendingClearTapEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingClearTapEnabled")
}
// Mark - Convertro
static func activeConvertroAPIKey() -> String? {
if let value = userDefaults.string(forKey: "activeConvertroAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "convertro_api_key") as? String {
userDefaults.setValue(value, forKey: "activeConvertroAPIKey")
return value
}
return nil
}
static func setActiveConvertroAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeConvertroAPIKey")
}
static func pendingConvertroAPIKey() -> String? {
if let value = userDefaults.string(forKey: "pendingConvertroAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "convertro_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingConvertroAPIKey")
return value
}
return nil
}
static func setPendingConvertroAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingConvertroAPIKey")
}
static func activeConvertroEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeConvertroEnabled")
}
static func setActiveConvertroEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeConvertroEnabled")
}
static func pendingConvertroEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingConvertroEnabled")
}
static func setPendingConvertroEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingConvertroEnabled")
}
// Mark - Kochava
static func activeKochavaAPIKey() -> String? {
if let value = userDefaults.string(forKey: "activeKochavaAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "kochava_api_key") as? String {
userDefaults.setValue(value, forKey: "activeKochavaAPIKey")
return value
}
return nil
}
static func setActiveKochavaAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeKochavaAPIKey")
}
static func pendingKochavaAPIKey() -> String? {
if let value = userDefaults.string(forKey: "pendingKochavaAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "kochava_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingKochavaAPIKey")
return value
}
return nil
}
static func setPendingKochavaAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingKochavaAPIKey")
}
static func activeKochavaEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeKochavaEnabled")
}
static func setActiveKochavaEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeKochavaEnabled")
}
static func pendingKochavaEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingKochavaEnabled")
}
static func setPendingKochavaEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingKochavaEnabled")
}
// Mark - Localytics
static func activeLocalyticsAppKey() -> String? {
if let value = userDefaults.string(forKey: "activeLocalyticsAppKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "localytics_app_key") as? String {
userDefaults.setValue(value, forKey: "activeLocalyticsAppKey")
return value
}
return nil
}
static func setActiveLocalyticsAppKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeLocalyticsAppKey")
}
static func pendingLocalyticsAppKey() -> String? {
if let value = userDefaults.string(forKey: "pendingLocalyticsAppKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "localytics_app_key") as? String {
userDefaults.setValue(value, forKey: "pendingLocalyticsAppKey")
return value
}
return nil
}
static func setPendingLocalyticsAppKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingLocalyticsAppKey")
}
static func activeLocalyticsEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeLocalyticsEnabled")
}
static func setActiveLocalyticsEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeLocalyticsEnabled")
}
static func pendingLocalyticsEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingLocalyticsEnabled")
}
static func setPendingLocalyticsEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingLocalyticsEnabled")
}
// Mark - mParticle
static func activemParticleAppKey() -> String? {
if let value = userDefaults.string(forKey: "activemParticleAppKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "mparticle_app_key") as? String {
userDefaults.setValue(value, forKey: "activemParticleAppKey")
return value
}
return nil
}
static func setActivemParticleAppKey(_ value: String) {
userDefaults.setValue(value, forKey: "activemParticleAppKey")
}
static func pendingmParticleAppKey() -> String? {
if let value = userDefaults.string(forKey: "pendingmParticleAppKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "mparticle_app_key") as? String {
userDefaults.setValue(value, forKey: "pendingmParticleAppKey")
return value
}
return nil
}
static func setPendingmParticleAppKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingmParticleAppKey")
}
static func activemParticleAppSecret() -> String? {
if let value = userDefaults.string(forKey: "activemParticleAppSecret") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "mparticle_app_secret") as? String {
userDefaults.setValue(value, forKey: "activemParticleAppSecret")
return value
}
return nil
}
static func setActivemParticleAppSecret(_ value: String) {
userDefaults.setValue(value, forKey: "activemParticleAppSecret")
}
static func pendingmParticleAppSecret() -> String? {
if let value = userDefaults.string(forKey: "pendingmParticleAppSecret") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "mparticle_app_secret") as? String {
userDefaults.setValue(value, forKey: "pendingmParticleAppSecret")
return value
}
return nil
}
static func setPendingmParticleAppSecret(_ value: String) {
userDefaults.setValue(value, forKey: "pendingmParticleAppSecret")
}
static func activemParticleEnabled() -> Bool? {
return userDefaults.bool(forKey: "activemParticleEnabled")
}
static func setActivemParticleEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activemParticleEnabled")
}
static func pendingmParticleEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingmParticleEnabled")
}
static func setPendingmParticleEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingmParticleEnabled")
}
// Mark - Segment
static func activeSegmentAPIKey() -> String? {
if let value = userDefaults.string(forKey: "activeSegmentAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "segment_api_key") as? String {
userDefaults.setValue(value, forKey: "activeSegmentAPIKey")
return value
}
return nil
}
static func setActiveSegmentAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeSegmentAPIKey")
}
static func pendingSegmentAPIKey() -> String? {
if let value = userDefaults.string(forKey: "pendingSegmentAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "segment_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingSegmentAPIKey")
return value
}
return nil
}
static func setPendingSegmentAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingSegmentAPIKey")
}
static func activeSegmentEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeSegmentEnabled")
}
static func setActiveSegmentEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeSegmentEnabled")
}
static func pendingSegmentEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingSegmentEnabled")
}
static func setPendingSegmentEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingSegmentEnabled")
}
// Mark - Singular
static func activeSingularAPIKey() -> String? {
if let value = userDefaults.string(forKey: "activeSingularAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "singular_api_key") as? String {
userDefaults.setValue(value, forKey: "activeSingularAPIKey")
return value
}
return nil
}
static func setActiveSingularAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeSingularAPIKey")
}
static func pendingSingularAPIKey() -> String? {
if let value = userDefaults.string(forKey: "pendingSingularAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "singular_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingSingularAPIKey")
return value
}
return nil
}
static func setPendingSingularAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingSingularAPIKey")
}
static func activeSingularEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeSingularEnabled")
}
static func setActiveSingularEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeSingularEnabled")
}
static func pendingSingularEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingSingularEnabled")
}
static func setPendingSingularEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingSingularEnabled")
}
// Mark - Stitch
static func activeStitchAPIKey() -> String? {
if let value = userDefaults.string(forKey: "activeStitchAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "stitch_api_key") as? String {
userDefaults.setValue(value, forKey: "activeStitchAPIKey")
return value
}
return nil
}
static func setActiveStitchAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "activeStitchAPIKey")
}
static func pendingStitchAPIKey() -> String? {
if let value = userDefaults.string(forKey: "pendingStitchAPIKey") {
if value.count > 0 {
return value
}
}
if let value = Bundle.main.object(forInfoDictionaryKey: "stitch_api_key") as? String {
userDefaults.setValue(value, forKey: "pendingStitchAPIKey")
return value
}
return nil
}
static func setPendingStitchAPIKey(_ value: String) {
userDefaults.setValue(value, forKey: "pendingStitchAPIKey")
}
static func activeStitchEnabled() -> Bool? {
return userDefaults.bool(forKey: "activeStitchEnabled")
}
static func setActiveStitchEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "activeStitchEnabled")
}
static func pendingStitchEnabled() -> Bool? {
return userDefaults.bool(forKey: "pendingStitchEnabled")
}
static func setPendingStitchEnabled(_ value: Bool) {
userDefaults.setValue(value, forKey: "pendingStitchEnabled")
}
}
|
//===--- GlobalClass.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Test inline cache with a global class. Make sure the retain|release pair
// for the fast path is removed in the loop.
import TestsUtils
class A
{
func f(_ a: Int) -> Int
{
return a + 1
}
}
var x = 0
var a = A()
@inline(never)
public func run_GlobalClass(_ N: Int) {
for _ in 0..<N
{
x = a.f(x)
}
}
|
//
// KaleidoscopeViewController.swift
// Atk_Rnd_VisualToys
//
// Created by Rick Boykin on 8/4/14.
// Copyright (c) 2014 Asymptotik Limited. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
import SceneKit
import Darwin
import GLKit
import OpenGLES
import AVFoundation
import CoreVideo
import CoreMedia
enum MirrorTextureSoure {
case Image, Color, Video
}
enum RecordingStatus {
case Stopped, Finishing, FinishRequested, Recording
}
class KaleidoscopeViewController: UIViewController, SCNSceneRendererDelegate, SCNProgramDelegate, UIGestureRecognizerDelegate {
@IBOutlet weak var settingsOffsetConstraint: NSLayoutConstraint!
@IBOutlet weak var settingsWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var settingsButton: UIButton!
@IBOutlet weak var settingsContainerView: UIView!
@IBOutlet weak var videoButton: UIButton!
@IBOutlet weak var imageRecording: UIImageView!
var textureSource = MirrorTextureSoure.Video
var hasMirror = false
var videoCapture = VideoCaptureBuffer()
var videoRecorder:FrameBufferVideoRecorder?
var videoRecordingTmpUrl: NSURL!;
var recordingStatus = RecordingStatus.Stopped;
var defaultFBO:GLint = 0
var snapshotRequested = false;
private weak var settingsViewController:KaleidoscopeSettingsViewController? = nil
var textureRotation:GLfloat = 0.0
var textureRotationSpeed:GLfloat = 0.1
var rotateTexture = false
var screenTexture:ScreenTextureQuad?
override func viewDidLoad() {
super.viewDidLoad()
// create a new scene
let scene = SCNScene()
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = false
// configure the view
scnView.backgroundColor = UIColor.blackColor()
// Anti alias
scnView.antialiasingMode = SCNAntialiasingMode.Multisampling4X
// delegate to self
scnView.delegate = self
scene.rootNode.runAction(SCNAction.customActionWithDuration(5, actionBlock:{
(triNode:SCNNode, elapsedTime:CGFloat) -> Void in
}))
// create and add a camera to the scene
let cameraNode = SCNNode()
let camera = SCNCamera()
//camera.usesOrthographicProjection = true
cameraNode.camera = camera
scene.rootNode.addChildNode(cameraNode)
scnView.pointOfView = cameraNode;
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
cameraNode.pivot = SCNMatrix4MakeTranslation(0, 0, 0)
// add a tap gesture recognizer
//let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
//let pinchGesture = UIPinchGestureRecognizer(target: self, action: "handlePinch:")
//let panGesture = UIPanGestureRecognizer(target: self, action: "handlePan:")
//var gestureRecognizers:[AnyObject] = [tapGesture, pinchGesture, panGesture]
//if let recognizers = scnView.gestureRecognizers {
// gestureRecognizers += recognizers
//}
//scnView.gestureRecognizers = gestureRecognizers
for controller in self.childViewControllers {
if controller.isKindOfClass(KaleidoscopeSettingsViewController) {
let settingsViewController = controller as! KaleidoscopeSettingsViewController
settingsViewController.kaleidoscopeViewController = self
self.settingsViewController = settingsViewController
}
}
self.videoRecordingTmpUrl = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("video.mov")
self.screenTexture = ScreenTextureQuad()
self.screenTexture!.initialize()
OpenGlUtils.checkError("init")
}
override func viewWillLayoutSubviews() {
let viewFrame = self.view.frame
if(self.settingsViewController?.view.frame.width > viewFrame.width) {
var frame = self.settingsViewController!.view.frame
frame.size.width = viewFrame.width
self.settingsOffsetConstraint.constant = -frame.size.width
self.settingsWidthConstraint.constant = frame.size.width
}
}
func createSphereNode(color:UIColor) -> SCNNode {
let sphere = SCNSphere()
let material = SCNMaterial()
material.diffuse.contents = color
sphere.materials = [material];
let sphereNode = SCNNode()
sphereNode.geometry = sphere
sphereNode.scale = SCNVector3Make(0.25, 0.25, 0.25)
return sphereNode
}
func createCorners() {
let scnView = self.view as! SCNView
let extents = scnView.getExtents()
let minEx = extents.min
let maxEx = extents.max
let scene = scnView.scene!
let sphereCenterNode = createSphereNode(UIColor.redColor())
sphereCenterNode.position = SCNVector3Make(0.0, 0.0, 0.0)
scene.rootNode.addChildNode(sphereCenterNode)
let sphereLLNode = createSphereNode(UIColor.blueColor())
sphereLLNode.position = SCNVector3Make(minEx.x, minEx.y, 0.0)
scene.rootNode.addChildNode(sphereLLNode)
let sphereURNode = createSphereNode(UIColor.greenColor())
sphereURNode.position = SCNVector3Make(maxEx.x, maxEx.y, 0.0)
scene.rootNode.addChildNode(sphereURNode)
}
private var _videoActionRate = FrequencyCounter();
func createMirror() -> Bool {
var ret:Bool = false
if !hasMirror {
//createCorners()
let scnView:SCNView = self.view as! SCNView
let scene = scnView.scene!
let triNode = SCNNode()
//let geometry = Geometry.createKaleidoscopeMirrorWithEquilateralTriangles(scnView)
let geometry = Geometry.createKaleidoscopeMirrorWithIsoscelesTriangles(scnView)
//var geometry = Geometry.createSquare(scnView)
triNode.geometry = geometry
triNode.position = SCNVector3(x: 0, y: 0, z: 0)
if(self.textureSource == .Video) {
geometry.materials = [self.createVideoTextureMaterial()]
}
else if(self.textureSource == .Color) {
let material = SCNMaterial()
material.diffuse.contents = UIColor.randomColor()
geometry.materials = [material]
}
else if(self.textureSource == .Image) {
let me = UIImage(named: "me2")
let material = SCNMaterial()
material.diffuse.contents = me
geometry.materials = [material]
}
//triNode.scale = SCNVector3(x: 0.5, y: 0.5, z: 0.5)
triNode.name = "mirrors"
let videoAction = SCNAction.customActionWithDuration(10000000000, actionBlock:{
(triNode:SCNNode, elapsedTime:CGFloat) -> Void in
//NSLog("Running action: processNextVideoTexture")
if self._videoActionRate.count == 0 {
self._videoActionRate.start()
}
self._videoActionRate.increment()
if self._videoActionRate.count % 30 == 0 {
//NSLog("Video Action Rate: \(self._videoActionRate.frequency)/sec")
}
self.videoCapture.processNextVideoTexture()
})
/*
var swellAction = SCNAction.repeatActionForever(SCNAction.sequence(
[
SCNAction.scaleTo(1.01, duration: 1),
SCNAction.scaleTo(1.0, duration: 1),
]))
*/
let actions = SCNAction.group([videoAction])
triNode.runAction(actions)
scene.rootNode.addChildNode(triNode)
hasMirror = true
ret = true
}
return ret;
}
func createVideoTextureMaterial() -> SCNMaterial {
let material = SCNMaterial()
let program = SCNProgram()
let vertexShaderURL = NSBundle.mainBundle().URLForResource("Shader", withExtension: "vsh")
let fragmentShaderURL = NSBundle.mainBundle().URLForResource("Shader", withExtension: "fsh")
var vertexShaderSource: NSString?
do {
vertexShaderSource = try NSString(contentsOfURL: vertexShaderURL!, encoding: NSUTF8StringEncoding)
} catch _ {
vertexShaderSource = nil
}
var fragmentShaderSource: NSString?
do {
fragmentShaderSource = try NSString(contentsOfURL: fragmentShaderURL!, encoding: NSUTF8StringEncoding)
} catch _ {
fragmentShaderSource = nil
}
program.vertexShader = vertexShaderSource as? String
program.fragmentShader = fragmentShaderSource as? String
// Bind the position of the geometry and the model view projection
// you would do the same for other geometry properties like normals
// and other geometry properties/transforms.
//
// The attributes and uniforms in the shaders are defined as:
// attribute vec4 position;
// attribute vec2 textureCoordinate;
// uniform mat4 modelViewProjection;
program.setSemantic(SCNGeometrySourceSemanticVertex, forSymbol: "position", options: nil)
program.setSemantic(SCNGeometrySourceSemanticTexcoord, forSymbol: "textureCoordinate", options: nil)
program.setSemantic(SCNModelViewProjectionTransform, forSymbol: "modelViewProjection", options: nil)
program.delegate = self
material.program = program
material.doubleSided = true
material.handleBindingOfSymbol("SamplerY", usingBlock: {
(programId:UInt32, location:UInt32, node:SCNNode!, renderer:SCNRenderer!) -> Void in
glUniform1i(GLint(location), 0)
}
)
material.handleBindingOfSymbol("SamplerUV", usingBlock: {
(programId:UInt32, location:UInt32, node:SCNNode!, renderer:SCNRenderer!) -> Void in
glUniform1i(GLint(location), 1)
}
)
material.handleBindingOfSymbol("TexRotation", usingBlock: {
(programId:UInt32, location:UInt32, node:SCNNode!, renderer:SCNRenderer!) -> Void in
glUniform1f(GLint(location), self.textureRotation)
}
)
return material
}
// SCNProgramDelegate
func program(program: SCNProgram, handleError error: NSError) {
NSLog("%@", error)
}
func renderer(aRenderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: NSTimeInterval) {
if _renderCount >= 1 && self.recordingStatus == RecordingStatus.Recording {
if self.videoRecorder != nil{
self.videoRecorder!.bindRenderTextureFramebuffer()
}
}
//self.videoRecorder!.bindRenderTextureFramebuffer()
}
// SCNSceneRendererDelegate
private var _renderCount = 0
func renderer(aRenderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: NSTimeInterval) {
if _renderCount == 1 {
self.createMirror()
if(self.textureSource == .Video) {
if let scnView:SCNView = self.view as? SCNView where scnView.eaglContext != nil {
self.videoCapture.initVideoCapture(scnView.eaglContext!)
}
}
glGetIntegerv(GLenum(GL_FRAMEBUFFER_BINDING), &self.defaultFBO)
NSLog("Default framebuffer: %d", self.defaultFBO)
}
if _renderCount >= 1 {
if self.snapshotRequested {
self.takeShot()
self.snapshotRequested = false
}
if self.recordingStatus == RecordingStatus.Recording {
// var scnView = self.view as! SCNView
glFlush()
glFinish()
if self.videoRecorder != nil{
self.videoRecorder!.grabFrameFromRenderTexture(time)
// Works here
glBindFramebuffer(GLenum(GL_FRAMEBUFFER), GLuint(self.defaultFBO))
self.screenTexture!.draw(self.videoRecorder!.target, name: self.videoRecorder!.name)
}
} else if self.recordingStatus == RecordingStatus.FinishRequested {
self.recordingStatus = RecordingStatus.Finishing
Async.background({ () -> Void in
self.finishRecording()
})
}
//glFinish()
//glBindFramebuffer(GLenum(GL_FRAMEBUFFER), GLuint(self.defaultFBO))
//self.screenTexture!.draw(self.videoRecorder!.target, name: self.videoRecorder!.name)
}
_renderCount++;
/*
let scnView:SCNView = self.view as SCNView
var camera = scnView.pointOfView!.camera
slideVelocity = Rotation.rotateCamera(scnView.pointOfView!, velocity: slideVelocity)
*/
}
private var _lastRenderTime: NSTimeInterval = 0.0
func renderer(aRenderer: SCNSceneRenderer, updateAtTime time: NSTimeInterval) {
if(_lastRenderTime > 0.0) {
if self.rotateTexture {
self.textureRotation += self.textureRotationSpeed * Float(time - _lastRenderTime)
}
else {
self.textureRotation = 0.0
}
}
_lastRenderTime = time;
}
func handleTap(recognizer: UIGestureRecognizer) {
// retrieve the SCNView
let scnView:SCNView = self.view as! SCNView
// check what nodes are tapped
let viewPoint = recognizer.locationInView(scnView)
for var node:SCNNode? = scnView.pointOfView; node != nil; node = node?.parentNode {
NSLog("Node: " + node!.description)
NSLog("Node pivot: " + node!.pivot.description)
NSLog("Node constraints: \(node!.constraints?.description)")
}
let projectedOrigin = scnView.projectPoint(SCNVector3Zero)
let vpWithZ = SCNVector3Make(Float(viewPoint.x), Float(viewPoint.y), projectedOrigin.z)
let scenePoint = scnView.unprojectPoint(vpWithZ)
print("tapPoint: (\(viewPoint.x), \(viewPoint.y)) scenePoint: (\(scenePoint.x), \(scenePoint.y), \(scenePoint.z))")
}
private var currentScale:Float = 1.0
private var lastScale:CGFloat = 1.0
func handlePinch(recognizer: UIPinchGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
lastScale = recognizer.scale
} else if recognizer.state == UIGestureRecognizerState.Changed {
let scnView:SCNView = self.view as! SCNView
let cameraNode = scnView.pointOfView!
let position = cameraNode.position
var scale:Float = 1.0 - Float(recognizer.scale - lastScale)
scale = min(scale, 40.0 / currentScale)
scale = max(scale, 0.1 / currentScale)
currentScale = scale
lastScale = recognizer.scale
let z = max(0.02, position.z * scale)
cameraNode.position.z = z
}
}
var slideVelocity = CGPointMake(0.0, 0.0)
var cameraRot = CGPointMake(0.0, 0.0)
var panPoint = CGPointMake(0.0, 0.0)
func handlePan(recognizer: UIPanGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
panPoint = recognizer.locationInView(self.view)
} else if recognizer.state == UIGestureRecognizerState.Changed {
let pt = recognizer.locationInView(self.view)
cameraRot.x += (pt.x - panPoint.x) * CGFloat(M_PI / 180.0)
cameraRot.y += (pt.y - panPoint.y) * CGFloat(M_PI / 180.0)
panPoint = pt
}
let x = Float(15 * sin(cameraRot.x))
let z = Float(15 * cos(cameraRot.x))
slideVelocity = recognizer.velocityInView(self.view)
let scnView:SCNView = self.view as! SCNView
let cameraNode = scnView.pointOfView!
cameraNode.position = SCNVector3Make(x, 0, z)
var vect = SCNVector3Make(0, 0, 0) - cameraNode.position
vect.normalize()
let at1 = atan2(vect.x, vect.z)
let at2 = Float(atan2(0.0, -1.0))
let angle = at1 - at2
NSLog("Angle: %f", angle)
cameraNode.rotation = SCNVector4Make(0, 1, 0, angle)
}
//
// Settings
//
func startBreathing(depth:CGFloat, duration:NSTimeInterval) {
self.stopBreathing()
let scnView:SCNView = self.view as! SCNView
let mirrorNode = scnView.scene?.rootNode.childNodeWithName("mirrors", recursively: false)
if let mirrorNode = mirrorNode {
let breatheAction = SCNAction.repeatActionForever(SCNAction.sequence(
[
SCNAction.scaleTo(depth, duration: duration/2.0),
SCNAction.scaleTo(1.0, duration: duration/2.0),
]))
mirrorNode.runAction(breatheAction, forKey: "breatheAction")
}
}
func stopBreathing() {
let scnView = self.view as! SCNView
let mirrorNode = scnView.scene?.rootNode.childNodeWithName("mirrors", recursively: false)
if let mirrorNode = mirrorNode {
mirrorNode.removeActionForKey("breatheAction")
}
}
var isUsingFrontFacingCamera:Bool {
get {
return self.videoCapture.isUsingFrontFacingCamera
}
set {
if newValue != self.videoCapture.isUsingFrontFacingCamera {
self.videoCapture.switchCameras()
}
}
}
var maxZoom:CGFloat {
get {
return self.videoCapture.maxZoom
}
}
var zoom:CGFloat {
get {
return self.videoCapture.zoom
}
set {
self.videoCapture.zoom = newValue
}
}
var isSettingsOpen = false
@IBAction func settingsButtonFired(sender: UIButton) {
if !self.isSettingsOpen {
self.settingsViewController!.settingsWillOpen()
}
self.view.layoutIfNeeded()
let offset = (self.isSettingsOpen ? -(self.settingsWidthConstraint.constant) : 0)
UIView.animateWithDuration(0.6, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: ({
self.settingsOffsetConstraint.constant = offset
self.view.layoutIfNeeded()
}), completion: {
(finished:Bool) -> Void in
self.isSettingsOpen = !self.isSettingsOpen
let scnView = self.view as! SCNView
scnView.allowsCameraControl = !self.isSettingsOpen
if !self.isSettingsOpen {
self.settingsViewController!.settingsDidClose()
}
})
}
@IBAction func videoButtonFired(sender: UIButton) {
if self.recordingStatus == RecordingStatus.Stopped {
self.setupVideoRecorderRecording()
self.recordingStatus = RecordingStatus.Recording;
self.imageRecording.hidden = false
}
else if self.recordingStatus == RecordingStatus.Recording {
self.imageRecording.hidden = true
self.stopRecording()
}
}
private func setupVideoRecorderRecording() {
self.deleteFile(self.videoRecordingTmpUrl)
if(self.videoRecorder == nil) {
// retrieve the SCNView
if let scnView = self.view as? SCNView where scnView.eaglContext != nil {
let width:GLsizei = GLsizei(scnView.bounds.size.width * UIScreen.mainScreen().scale)
let height:GLsizei = GLsizei(scnView.bounds.size.height * UIScreen.mainScreen().scale)
self.videoRecorder = FrameBufferVideoRecorder(movieUrl: self.videoRecordingTmpUrl,
width: width,
height: height)
self.videoRecorder!.initVideoRecorder(scnView.eaglContext!)
self.videoRecorder!.generateFramebuffer(scnView.eaglContext!)
}
}
}
private func stopRecording() {
if self.recordingStatus == RecordingStatus.Recording {
self.recordingStatus = RecordingStatus.FinishRequested;
}
}
private func finishRecording() {
self.videoRecorder?.finish({ (status:FrameBufferVideoRecorderStatus) -> Void in
NSLog("Video recorder finished with status: " + status.description);
if(status == FrameBufferVideoRecorderStatus.Completed) {
let fileManager: NSFileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(self.videoRecordingTmpUrl.path!) {
UISaveVideoAtPathToSavedPhotosAlbum(self.videoRecordingTmpUrl.path!, self, "video:didFinishSavingWithError:contextInfo:", nil)
}
else {
NSLog("File does not exist: " + self.videoRecordingTmpUrl.path!);
}
}
})
}
func video(videoPath:NSString, didFinishSavingWithError error:NSErrorPointer, contextInfo:UnsafeMutablePointer<Void>) {
NSLog("Finished saving video")
self.videoRecorder = nil;
self.recordingStatus = RecordingStatus.Stopped
self.deleteFile(self.videoRecordingTmpUrl)
}
func deleteFile(fileUrl:NSURL) {
let fileManager: NSFileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(fileUrl.path!) {
var error:NSError? = nil;
do {
try fileManager.removeItemAtURL(fileUrl)
} catch let error1 as NSError {
error = error1
}
if(error != nil) {
NSLog("Error deleing file: %@ Error: %@", fileUrl, error!)
}
}
}
func takeShot() {
let image = self.imageFromSceneKitView(self.view as! SCNView)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
func imageFromSceneKitView(sceneKitView:SCNView) -> UIImage {
let w:Int = Int(sceneKitView.bounds.size.width * UIScreen.mainScreen().scale)
let h:Int = Int(sceneKitView.bounds.size.height * UIScreen.mainScreen().scale)
let myDataLength:Int = w * h * Int(4)
let buffer = UnsafeMutablePointer<CGFloat>(calloc(myDataLength, Int(sizeof(CUnsignedChar))))
glReadPixels(0, 0, GLint(w), GLint(h), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), buffer)
let provider = CGDataProviderCreateWithData(nil, buffer, Int(myDataLength), nil)
let bitsPerComponent:Int = 8
let bitsPerPixel:Int = 32
let bytesPerRow:Int = 4 * w
let colorSpaceRef = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo.ByteOrderDefault
let renderingIntent = CGColorRenderingIntent.RenderingIntentDefault
// make the cgimage
let decode:UnsafePointer<CGFloat> = nil;
let cgImage = CGImageCreate(w, h, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, decode, false, renderingIntent)
return UIImage(CGImage: cgImage!)
}
//
// UIViewControlle overrides
//
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.AllButUpsideDown
} else {
return UIInterfaceOrientationMask.All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// Wikipedia.swift
// Goalscorer
//
// Created by tichinose1 on 2019/01/03.
// Copyright © 2019 example.com. All rights reserved.
//
import Foundation
struct Wikipedia: Decodable {
let query: Query
struct Query: Decodable {
let pages: Pages
typealias Pages = [String: Page]
struct Page: Decodable {
let revisions: [Revision]
struct Revision: Decodable {
let timestamp: Date
}
}
}
}
|
//
// CalenerTableViewCell.swift
// TrainingNote
//
// Created by Mizuki Kubota on 2020/02/28.
// Copyright © 2020 MizukiKubota. All rights reserved.
//
import UIKit
class CalenerTableViewCell: UITableViewCell {
@IBOutlet weak var testLabel: 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
}
}
|
//
// cardCollectionViewCell.swift
// BlackStarWearProject
//
// Created by Владислав Вишняков on 12.07.2021.
//
import UIKit
class cardCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var cardImage: UIImageView!
}
|
//
// File.swift
//
//
// Created by Mason Phillips on 6/13/20.
//
import Foundation
public struct PeopleTVCreditsModel: Decodable {
public let id: Int
public let cast: Array<Cast>
public let crew: Array<Crew>
public struct Cast: Decodable {
public let character: String
public let credit_id: String
public let release_date: String
public let vote_count: Int
public let video: Bool
public let adult: Bool
public let vote_average: Float
public let title: String
public let genre_ids: Array<Int>
public let original_language: String
public let original_title: String
public let popularity: Float
public let id: Int
public let backdrop_path: String?
public let overview: String
public let poster_path: String?
}
public struct Crew: Decodable {
public let id: Int
public let department: String
public let original_language: String
public let original_title: String
public let job: String
public let overview: String
public let vote_count: Int
public let video: Bool
public let poster_path: String?
public let backdrop_path: String?
public let title: String
public let popularity: Int
public let genre_ids: Array<Int>
public let vote_average: Float
public let adult: Bool
public let release_date: String
public let credit_id: String
}
}
|
//
// API.swift
// appstoreSearch
//
// Created by Elon on 17/03/2019.
// Copyright © 2019 Elon. All rights reserved.
//
import Foundation
import RxSwift
enum HTTP: String {
case get = "GET"
case post = "POST"
}
final class API {
static var shared = API()
let hostURL = "https://itunes.apple.com"
let endpoint = "/search"
private init() {}
private func requsetURL(_ urlString: String, with parameters: [String : String]? = nil) -> URL? {
var urlComponents = URLComponents(string: urlString)
if let _parameters = parameters {
let query = _parameters.map {
URLQueryItem(name: $0.key, value: $0.value)
}
urlComponents?.queryItems = query
}
return urlComponents?.url
}
func searchAppsotre(by keyword: String) -> Observable<Result> {
let parameter = [
"term" : keyword,
"media" : "software",
"entity" : "software",
"limit" : "5",
"lang" : "ko_kr",
"country" : "kr"
]
let url = requsetURL(hostURL + endpoint, with: parameter)
return requestSearchResult(by: url)
}
private func requestSearchResult(by requsetURL: URL?) -> Observable<Result> {
return Observable.create { [unowned self] observer in
guard let url = requsetURL else {
observer.onError(APIError.url)
return Disposables.create()
}
let task = self.request(with: url, method: .get) { data, requsetError in
if let error = requsetError {
observer.onError(error)
} else {
do {
let result = try Result(data: data)
observer.onNext(result)
observer.onCompleted()
} catch {
observer.onError(error)
}
}
}
return Disposables.create(with: task.cancel)
}
}
func requestImage(urlString: String) -> Observable<Data> {
return Observable.create { [unowned self] observer in
guard let url = self.requsetURL(urlString) else {
observer.onError(APIError.url)
return Disposables.create()
}
let task = self.request(with: url, method: .get) { responseData, requsetError in
if let error = requsetError {
observer.onError(error)
} else if let data = responseData {
observer.onNext(data)
observer.onCompleted()
} else {
observer.onError(APIError.responseData)
}
}
return Disposables.create(with: task.cancel)
}
}
private func request(with url: URL, method: HTTP, completion: @escaping (Data?, Error?) -> Void) -> URLSessionDataTask {
var request = URLRequest(url: url, timeoutInterval: 30)
request.httpMethod = method.rawValue
URLSession.shared.configuration.waitsForConnectivity = true
let task = URLSession.shared.dataTask(with: request) { responseData, urlResponse, requsetError in
var error: Error? = nil
defer {
completion(responseData, error)
}
guard requsetError == nil else {
error = requsetError
return
}
guard let response = urlResponse as? HTTPURLResponse else {
error = APIError.response
return
}
guard response.statusCode >= 200 && response.statusCode < 300 else {
error = APIError.statusCode(response.statusCode)
return
}
}
task.resume()
return task
}
}
|
//
// FluentInterface.swift
// DTTest
//
// Created by Darktt on 21/9/3.
// Copyright © 2021 Darktt. All rights reserved.
//
import UIKit
/// Implement fluent interface.
///
/// Idea from: [利用 Swift 5.1 新功能實作 Fluent Interface 讓程式碼更易讀流暢!](https://www.appcoda.com.tw/fluent-interface/)
/// Usage:
/// ```swift
/// FluentInterface(subject: UIView())
/// .frame(CGRect(x: 0, y: 0, width: 100, height: 100))
/// .backgroundColor(.white)
/// .alpha(0.5)
/// .subject
/// ```
@dynamicMemberLookup
public struct FluentInterface<Subject>
{
// MARK: - Properties -
public let subject: Subject
public let discardResult: Void = ()
// MARK: - Methods -
public subscript<Value>(dynamicMember keyPath: WritableKeyPath<Subject, Value>) -> FluentCaller<Subject, Value>
{
let caller = FluentCaller(subject: self.subject, keyPath: keyPath)
return caller
}
}
@dynamicCallable
public struct FluentCaller<Subject, Value>
{
// MARK: - Properties -
fileprivate let subject: Subject
fileprivate let keyPath: WritableKeyPath<Subject, Value>
// MARK: - Methods -
// MARK: Initial Method
func dynamicallyCall(withArguments arguments: Array<Value>) -> FluentInterface<Subject>
{
guard let value: Value = arguments.first else {
return FluentInterface(subject: self.subject)
}
var subject: Subject = self.subject
subject[keyPath: self.keyPath] = value
let fluentInterface = FluentInterface(subject: subject)
return fluentInterface
}
}
// MARK: - FluentCompatible -
public protocol FluentCompatible { }
extension FluentCompatible
{
var fluent: FluentInterface<Self> {
FluentInterface(subject: self)
}
}
extension UIBarItem: FluentCompatible { }
extension UIGestureRecognizer: FluentCompatible { }
extension UIResponder: FluentCompatible { }
#if targetEnvironment(macCatalyst)
extension NSTouchBar: FluentCompatible { }
extension NSTouchBarItem: FluentCompatible { }
#endif
|
//
// NetworkProxy.swift
// EmpireMobileApp
//
// Created by Rodrigo Nunes on 12/10/19.
// Copyright © 2019 Rodrigo Nunes Gil. All rights reserved.
//
import Foundation
class NetworkProxy {
func process<T: Decodable>( networkRequest: NetworkRequest, completion: @escaping(T?, Error?) -> Void) {
Network.shared.requestObject(networkRequest: networkRequest) { (object: T?, error) in
if let error = error {
completion(nil, error)
} else {
completion(object, nil)
}
}
}
func processArray<T: Decodable>( networkRequest: NetworkRequest, completion: @escaping([T]?, Error?) -> Void) {
Network.shared.requestArray(networkRequest: networkRequest) { (objectArray: [T]?, error) in
if let error = error {
completion(nil, error)
} else {
completion(objectArray, nil)
}
}
}
}
|
//
// HKVieweController.swift
// fitBit
//
// Created by KAIZER WEB DESIGN on 22/11/2019.
// Copyright © 2019 kaizer. All rights reserved.
//
import UIKit
import HealthKit
class HKHistoryController: UITableViewController {
var sessions: [workoutSession] = []
let healthkitStore = HKHealthStore()
override func viewDidLoad() {
super.viewDidLoad()
readSessions()
super.tableView.delegate = self
super.tableView.dataSource = self
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
func readSessions(){
WorkoutDataStore.loadPrancerciseWorkouts { ( collection, error) in
for work in collection!{
let id = 12
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let start = work.startDate
let stop = work.endDate
let begin = df.string(from: start)
let end = df.string(from: stop)
let duration = Int(work.duration)
let distance : Double = (work.totalDistance?.doubleValue(for: HKUnit.meter()))!
let session = workoutSession(id: Int32(id), startTime: begin, endTime: end, duration: duration, distance: distance, sourLat: 0, sourLong: 0, destLat: 0, destLong: 0)
self.sessions.append(session)
super.tableView.reloadData()
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
print(self.sessions)
return self.sessions.count //count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(58)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("populate !")
let session = sessions[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "HKCell") as! HKCell
cell.setSessionCell(session: session)
return cell
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// SingalImageViewController.swift
// 2019_ios_final
//
// Created by 王心妤 on 2019/6/1.
// Copyright © 2019 river. All rights reserved.
//
import UIKit
class SingalImageViewController: UIViewController {
var tmpImage: UIImage = UIImage()
var receiver: Friend = Friend(propic: "test", name: "", id: "", status: "")
@IBOutlet weak var nameLabel: UINavigationItem!
@IBOutlet weak var singalImage: UIImageView!
@IBAction func showAllImages(_ sender: Any) {
self.performSegue(withIdentifier: "showAllImages", sender: "")
}
@IBAction func download(_ sender: Any) {
if let image = singalImage.image{
let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
singalImage.image = tmpImage
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showAllImages" {
let controller = segue.destination as! AllImagesViewController
controller.receiver = receiver
}
}
}
|
//
// CodableResponse.swift
// ShopPickup
//
// Created by Thanathip on 5/10/2563 BE.
//
import Foundation
struct PickupResponse<T: Codable>: Codable {
let pickup: [T]
}
struct PickupResult<T: Codable>: Codable {
let pickup: [T]
}
|
//
// marchandoController.swift
// PizzaWatch
//
// Created by Jesús de Villar on 23/4/16.
// Copyright © 2016 JdeVillar. All rights reserved.
//
import WatchKit
import Foundation
class marchandoController: WKInterfaceController {
@IBAction func MavegaAInicio() {
pushControllerWithName("inicio", context:nil)
}
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
|
//
// Utils.swift
//
import Foundation
import UIKit
let sharedUtils : Utils = Utils()
class Utils:NSObject
{
//MARK:-Initialization
override init()
{
super.init();
}
class var sharedInstance : Utils {
return sharedUtils
}
//String encoding UTF8
class func encodeString(_ str: String) -> String
{
let parsedStr = CFURLCreateStringByAddingPercentEscapes(
nil,
str as CFString!,
nil,
"!*'();:@&=+$,/?%#[]" as CFString!, //you can add another special characters
CFStringBuiltInEncodings.UTF8.rawValue
);
return parsedStr as! String;
}
//MARK:- Validations
//Check email vaildity
class func isValidEmail(_ testStr:String) -> Bool {
let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
class func numberOfDaysLeft(oldDate: String) -> Int {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let couponCreatedDate: Date = dateFormatter.date(from: oldDate)!
let currentDateStr: String = dateFormatter.string(from: Date())
let currentDate: Date = dateFormatter.date(from: currentDateStr)!
let calendar = NSCalendar.current
let date1 = calendar.startOfDay(for: couponCreatedDate)
let date2 = calendar.startOfDay(for: currentDate)
let components = calendar.dateComponents([.day], from: date1, to: date2)
print(components.day!)
return 30 - components.day!
}
//Check username validation
func isValidInput(Input:String) -> Bool {
let RegEx = "\\A\\w{7,18}\\z"
let Test = NSPredicate(format:"SELF MATCHES %@", RegEx)
return Test.evaluate(with: Input)
}
}
|
// specification file parser
import Foundation
struct Parser {
struct ParseError: ErrorType {
var pos: Position
var reason: String
}
enum Error: ErrorType {
case ParseError(pos: Int, reason: String)
}
enum Declaration {
case SwiftCode(pos: Int, code: String)
case Token(pos: Int, swiftType: String?, tokens: [String])
case Nonassoc([String])
case Left([String])
case Right([String])
case Type(pos: Int, swiftType: String, rules: [String])
case StartRules(pos: Int, swiftType: String?, rules: [String])
}
var path: String
var package: String
var src: String
var buf: NSScanner
var pinnedPos: Int?
init(path: String, src: String) {
self.path = path
self.src = src
self.package = path // TODO
self.buf = NSScanner(string: src)
self.buf.charactersToBeSkipped = nil
self.pinnedPos = nil
}
static func parse(path: String) throws -> Result<Grammar, ParseError> {
// TODO
let data = NSFileManager.defaultManager().contentsAtPath(path)
let src = String(data: data!, encoding: NSUTF8StringEncoding)
return try Parser.parse(path, src: src!)
}
// -> Result<Grammar, ParseError>
static func parse(path: String, src: String) throws -> Result<Grammar, ParseError> {
var p = Parser(path: path, src: src)
do {
return .Success(try p.parse())
} catch Error.ParseError(let pos, let reason) {
let pos = Position(offset: pos, string: src)
return .Failure(ParseError(pos: pos, reason: reason))
} catch {
print("unknown error")
throw error
}
}
mutating func parse() throws -> Grammar {
// decls
var decls = [Declaration]()
while let decl = try self.parseDecl() {
decls.append(decl)
}
// check unknown decls
self.scanSpace()
self.pinPos()
if self.scanString("%") {
if let id = self.scanId() {
try self.parseError("unknown declaration: %\(id)")
}
}
self.revertPos()
// rules
self.scanSpace()
if !self.scanString("%%") {
try self.parseError("'%%' expected")
}
var rules: [Grammar.Rule] = []
while let rule = try self.parseRule() {
rules.append(rule)
}
// Swift code
var code: Grammar.SwiftCode?
self.scanSpace()
if self.scanString("%%") {
let pos = self.buf.scanLocation
let codeStr = self.buf.string.substringFromIndex(
self.buf.string.startIndex.advancedBy(self.buf.scanLocation))
code = Grammar.SwiftCode(pos: pos, code: codeStr)
}
return self.generateGrammar(decls, rules: rules, code: code)
}
func parseError(reason: String) throws {
throw Error.ParseError(pos: self.buf.scanLocation,
reason: reason)
}
mutating func parseDecl() throws -> Declaration? {
if let decl = try self.parseSwiftDecl() {
return decl
} else if let decl = try self.parseTokenDecl() {
return decl
} else if let decl = try self.parseLeftDecl() {
return decl
} else if let decl = try self.parseRightDecl() {
return decl
} else if let decl = try self.parseNonassocDecl() {
return decl
} else if let decl = try self.parseStartDecl() {
return decl
} else {
return nil
}
}
mutating func parseSwiftDecl() throws -> Declaration? {
self.scanSpace()
if !self.scanString("%{") {
return nil
}
print("parse swift decl")
if let code = try self.scanSwiftCodeUpToString("%}") {
print("swift decl: ", code)
return Declaration.SwiftCode(pos: self.buf.scanLocation,
code: code)
} else {
print("expected %}")
throw Error.ParseError(pos: self.buf.scanLocation,
reason: "expected \"%}\"")
}
}
mutating func parseTokenDecl() throws -> Declaration? {
print("begin parse token")
self.scanSpace()
let pos = self.buf.scanLocation
if !self.scanWordString("%token") {
print("not token")
return nil
}
print("parse token")
// swift type
print("parse swift type")
let swiftType = try self.parseSwiftTypeSpec()
self.scanSpace()
let list = self.scanUpperIdList()
if list.isEmpty {
try self.parseError("need lower identifier list")
return nil
}
return Declaration.Token(pos: pos, swiftType: swiftType, tokens: list)
}
mutating func parseSwiftTypeSpec() throws -> String? {
var swiftType: String? = nil
self.scanSpace()
if self.scanString("<") {
print("begin scan swift type")
self.scanSpace()
if let s = try self.scanSwiftType() {
swiftType = s
} else {
throw Error.ParseError(pos: self.buf.scanLocation,
reason: "expected Swift type")
}
self.scanSpace()
if !self.scanString(">") {
throw Error.ParseError(pos: self.buf.scanLocation,
reason: "expected \">\"")
}
}
return swiftType
}
mutating func parseLeftDecl() throws -> Declaration? {
self.scanSpace()
if !self.scanWordString("%left") {
return nil
}
self.scanSpace()
let list = self.scanUpperIdList()
if list.isEmpty {
try self.parseError("need upper identifier list")
return nil
}
return Declaration.Left(list)
}
mutating func parseRightDecl() throws -> Declaration? {
self.scanSpace()
if !self.scanWordString("%right") {
return nil
}
self.scanSpace()
let list = self.scanUpperIdList()
if list.isEmpty {
try self.parseError("need upper identifier list")
return nil
}
return Declaration.Right(list)
}
mutating func parseNonassocDecl() throws -> Declaration? {
self.scanSpace()
if !self.scanWordString("%nonassoc") {
return nil
}
self.scanSpace()
let list = self.scanUpperIdList()
if list.isEmpty {
try self.parseError("need upper identifier list")
return nil
}
return Declaration.Nonassoc(list)
}
mutating func parseStartDecl() throws -> Declaration? {
print("begin parse %start")
self.scanSpace()
let pos = self.buf.scanLocation
if !self.scanWordString("%start") {
return nil
}
let swiftType = try self.parseSwiftTypeSpec()
self.scanSpace()
let list = self.scanLowerIdList()
if list.isEmpty {
try self.parseError("need lower identifier list")
return nil
}
return Declaration.Token(pos: pos, swiftType: swiftType, tokens: list)
}
mutating func parseRule() throws -> Grammar.Rule? {
print("parse rule")
self.scanSpace()
let name = self.scanId()
if name == nil {
return nil
}
print(name)
self.scanSpace()
if !self.scanString(":") {
try self.parseError("rule: ':' expected")
return nil
}
// option
self.scanSpace()
self.scanString("|")
var groups: [Grammar.Group] = []
if let fst = try self.parseGroup() {
groups.append(fst)
}
self.scanSpace()
while self.scanString("|") {
if let group = try self.parseGroup() {
groups.append(group)
} else {
try self.parseError("group expected")
return nil
}
}
return Grammar.Rule(name: name!, groups: groups, priority: Grammar.Priority.Nonassoc)
}
mutating func parseGroup() throws -> Grammar.Group? {
print("parse group")
var prods: [Grammar.Production] = []
while let prod = try self.parseProduction() {
prods.append(prod)
}
if prods.isEmpty {
return nil
}
// Swift code
self.scanSpace()
if !self.scanString("{") {
try self.parseError("need \"{\"")
return nil
}
if let code = try self.scanSwiftCodeUpToString("}") {
return Grammar.Group(products: prods, code: code)
} else {
try self.parseError("need \"}\"")
return nil
}
}
mutating func parseProduction() throws -> Grammar.Production? {
print("parse production")
self.scanSpace()
let pos = self.buf.scanLocation
var producers: [Grammar.Producer] = []
while let prod = try self.parseProducer() {
producers.append(prod)
}
if producers.isEmpty {
return nil
}
let prec = try self.parsePrec()
return Grammar.Production(pos: pos, producers: producers, prec: prec)
}
mutating func parseProducer() throws -> Grammar.Producer? {
print("parse producer")
self.scanSpace()
let pos = self.buf.scanLocation
var alias: String? = nil
if let id = self.scanLowerId() {
alias = id
self.scanSpace()
if !self.scanString("=") {
try self.parseError("`=' expected")
return nil
}
}
self.scanSpace()
if let actual = self.scanId() {
return Grammar.Producer(pos: pos, alias: alias, actual: actual)
} else if alias != nil {
try self.parseError("need id")
return nil
} else {
return nil
}
}
mutating func parsePrec() throws -> String? {
if !self.scanWordString("%prec") {
return nil
}
if let id = self.scanId() {
return id
} else {
try self.parseError("no precedure identifier")
return nil
}
}
func parseSwiftCode() {
// TODO
}
mutating func pinPos() {
self.pinnedPos = self.buf.scanLocation
}
mutating func revertPos() {
self.buf.scanLocation = self.pinnedPos!
self.pinnedPos = nil
}
// whitespace and newline
mutating func scanSpace() -> String? {
var scanBuf: NSString? = nil
self.buf.scanCharactersFromSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet(),
intoString: &scanBuf)
return scanBuf as String?
}
mutating func scanString(s: String) -> Bool {
return self.buf.scanString(s, intoString: nil)
}
mutating func scanUpToString(upTo: String) -> String? {
var buf: NSString? = nil
self.buf.scanUpToString(upTo, intoString: &buf)
return buf as String?
}
mutating func scanCharactersFromSet(charSet: NSCharacterSet) -> String? {
var buf: NSString? = nil
self.buf.scanCharactersFromSet(charSet, intoString: &buf)
return buf as String?
}
static let strChar = NSCharacterSet(charactersInString: "\\\"").invertedSet
mutating func scanStringLiteral() throws -> String? {
if !self.buf.scanString("\"", intoString: nil) {
return nil
}
var strBuf = ""
var scanBuf: NSString? = nil
while !self.buf.atEnd {
if self.scanString("\\\\") {
strBuf.appendContentsOf("\\\\")
} else if self.scanString("\\\"") {
strBuf.appendContentsOf("\\\"")
} else if self.buf.scanCharactersFromSet(Parser.strChar, intoString: &scanBuf) {
strBuf.appendContentsOf(scanBuf as! String)
} else {
throw Error.ParseError(pos: self.buf.scanLocation,
reason: "string is not enclosed")
}
}
assertionFailure("unexpected error")
return nil
}
mutating func scanSwiftCodeUpToString(upTo: String) throws -> String? {
let pos = self.buf.scanLocation
let codeChar = NSCharacterSet(charactersInString: upTo + "\"").invertedSet
let upToChar = NSCharacterSet(charactersInString: upTo)
var strBuf = ""
while !self.buf.atEnd {
if self.scanString(upTo) {
return strBuf
} else if let s = try self.scanStringLiteral() {
strBuf.appendContentsOf(s)
} else if let s = self.scanCharactersFromSet(codeChar) {
strBuf.appendContentsOf(s)
} else if let s = self.scanCharactersFromSet(upToChar) {
strBuf.appendContentsOf(s)
} else if !self.buf.atEnd {
assertionFailure("unexpected error")
}
}
self.buf.scanLocation = pos
return nil
}
mutating func scanId() -> String? {
let charSet = NSMutableCharacterSet.alphanumericCharacterSet()
charSet.addCharactersInString("_")
return self.scanCharactersFromSet(charSet)
}
mutating func scanUpperId() -> String? {
var buf = ""
// first character
if let s = self.scanCharactersFromSet(NSCharacterSet.uppercaseLetterCharacterSet()) {
buf.appendContentsOf(s)
} else {
return nil
}
// rest characters
if let s = self.scanId() {
buf.appendContentsOf(s)
}
return buf
}
mutating func scanLowerId() -> String? {
var buf = ""
// first character
if let s = self.scanCharactersFromSet(NSCharacterSet.lowercaseLetterCharacterSet()) {
buf.appendContentsOf(s)
} else {
return nil
}
// rest characters
if let s = self.scanId() {
buf.appendContentsOf(s)
}
return buf
}
mutating func scanUpperIdList() -> [String] {
var list = [String]()
while let id = self.scanUpperId() {
print("scan id = '\(id)'")
list.append(id)
self.scanSpace()
}
return list
}
mutating func scanLowerIdList() -> [String] {
var list = [String]()
while let id = self.scanLowerId() {
list.append(id)
self.scanSpace()
}
return list
}
mutating func scanIdList() -> [String] {
var list = [String]()
while let id = self.scanId() {
list.append(id)
self.scanSpace()
}
return list
}
mutating func scanWordString(s: String) -> Bool {
self.pinPos()
if !self.scanString(s) {
return false
}
let charSet = NSMutableCharacterSet.alphanumericCharacterSet()
charSet.addCharactersInString("_")
if self.buf.scanCharactersFromSet(charSet, intoString: nil) {
self.revertPos()
return false
} else {
return true
}
}
mutating func scanSwiftType() throws -> String? {
enum Pair {
case Paren // "("
case Brack // "["
case Brace // "{"
case Sign // "<"
}
self.pinPos()
var state = [Pair]()
var buf = ""
let idCharSet = NSCharacterSet(charactersInString: "()[]{}<>").invertedSet
let open = ["(":Pair.Paren, "[":Pair.Brack, "{":Pair.Brack, "<":Pair.Sign]
let close = [Pair.Paren:")", Pair.Brack:"]", Pair.Brace:"}", Pair.Sign:">"]
repeat {
self.scanSpace()
var next = true
for (s, pair) in open {
if self.scanString(s) {
buf.appendContentsOf(s)
state.append(pair)
next = false
break
}
}
if !next {
continue
}
var scanBuf: NSString? = nil
if let last = state.last {
let s = close[last]!
if self.scanString(s) {
buf.appendContentsOf(s)
state.popLast()
continue
}
}
if self.scanString("->") {
buf.appendContentsOf("->")
} else if self.buf.scanCharactersFromSet(idCharSet, intoString: &scanBuf) {
print("scan id")
buf.appendContentsOf(scanBuf as! String)
} else {
print("return scan id")
return buf as String?
}
} while !self.buf.atEnd
self.revertPos()
return nil
}
func generateGrammar(decls: [Declaration],
rules: [Grammar.Rule],
code: Grammar.SwiftCode?) -> Grammar {
var swiftDecls: [Grammar.SwiftCode] = []
var tokens: [Grammar.Token] = []
var prios: [String: Grammar.Priority] = [:]
var startRules: [String] = []
var startSwiftType: String? = nil
for decl in decls {
switch decl {
case .SwiftCode(pos: let pos, code: let code):
swiftDecls.append(Grammar.SwiftCode(pos: pos, code: code))
case .Token(pos: let pos, swiftType: let type, tokens: let tokNames):
for tokName in tokNames {
let tok = Grammar.Token(pos: pos, name: tokName, swiftType: type, priority: Grammar.Priority.Nonassoc)
tokens.append(tok)
}
case .Type(pos: let pos, swiftType: let type, rules: let rules):
// TODO
break
case .Nonassoc(let ruleNames):
for ruleName in ruleNames {
prios[ruleName] = Grammar.Priority.Nonassoc
}
case .Left(let ruleNames):
for ruleName in ruleNames {
prios[ruleName] = Grammar.Priority.Left
}
case .Right(let ruleNames):
for ruleName in ruleNames {
prios[ruleName] = Grammar.Priority.Right
}
case .StartRules(pos: _, swiftType: let type, rules: let rules):
startRules = rules
startSwiftType = type
}
}
prio: for (ruleName, prio) in prios {
// token
for var tok in tokens {
if tok.name == ruleName {
tok.priority = prio
break prio
}
}
// rule
for var rule in rules {
if rule.name == ruleName {
rule.priority = prio
break prio
}
}
// TODO: not found error
}
return Grammar(path: self.path,
package: self.package,
swiftDecls: swiftDecls,
swiftCode: code,
tokens: tokens,
rules: rules,
startRules: startRules,
startSwiftType: startSwiftType)
}
} |
//
// RDScrollView.swift
// GliderSample
//
// Created by Guillermo Delgado on 25/04/2017.
// Copyright © 2017 Guillermo Delgado. All rights reserved.
//
// swiftlint:disable function_body_length type_body_length file_length
import UIKit
@objc public enum RDScrollViewOrientationType: Int {
case RDScrollViewOrientationUnknown
case RDScrollViewOrientationLeftToRight
case RDScrollViewOrientationBottomToTop
case RDScrollViewOrientationRightToLeft
case RDScrollViewOrientationTopToBottom
}
@objc public class RDScrollView: UIScrollView {
/**
Draggable content
*/
var content: UIView? {
didSet {
self.addContent(content: self.content!)
}
}
/**
Orientation for draggable container.
Default value: RDScrollViewOrientationLeftToRight
*/
public var orientationType: RDScrollViewOrientationType = .RDScrollViewOrientationRightToLeft
/**
Expandable offset in % of content view. from 0 to 1.
*/
private var _offsets: [NSNumber] = []
public var offsets: [NSNumber] {
set {
if newValue.count == 0 {
NSException(name: NSExceptionName(rawValue: "Invalid offset array"),
reason:"offsets array cannot be nil nor empty").raise()
}
let clearOffsets: [NSNumber] = (NSOrderedSet.init(array: newValue).array as? [NSNumber])!
var reversedOffsets = [NSNumber]()
for number: NSNumber in clearOffsets {
if number.floatValue < 0.0 || 1.0 < number.floatValue {
let m = "offset represents a %% of content to be shown, 0.5 of a content of 100px will show 50px"
NSException(name: NSExceptionName(rawValue: "Invalid offset value"), reason: m).raise()
}
if self.orientationType == .RDScrollViewOrientationTopToBottom ||
self.orientationType == .RDScrollViewOrientationLeftToRight {
reversedOffsets.append(NSNumber.init(value: Float(1 - number.floatValue)))
}
}
var newOffsets: [NSNumber] = clearOffsets.sorted { $0.floatValue < $1.floatValue }
if reversedOffsets.count > 0 {
newOffsets = reversedOffsets
newOffsets = newOffsets.sorted { $0.floatValue < $1.floatValue }.reversed()
}
_offsets = newOffsets
self.recalculateContentSize()
}
get {
return _offsets
}
}
/**
Determines whether the element's offset is different than % 0.
*/
public private(set) var isOpen: Bool = false
/**
Returns the position of open Offsets.
*/
public private(set) var offsetIndex: Int = 0
/**
Margin of elastic animation default is 20px.
*/
private var _margin: Float = 20
var margin: Float {
set {
_margin = newValue
if self.orientationType == .RDScrollViewOrientationTopToBottom {
self.topToBottomTopContraint?.constant = CGFloat(_margin)
} else if self.orientationType == .RDScrollViewOrientationLeftToRight {
self.leftToRightLeadingContraint?.constant = CGFloat(_margin)
}
self.recalculateContentSize()
}
get {
return _margin
}
}
/**
Consider subviews of the content as part of the content, used when dragging.
Default Value is False
*/
var selectContentSubViews: Bool = false
/**
Duration of animation for changing offset, default vaule is 0.3
*/
var duration: Float = 0.3
/**
Delay of animation for changing offset, default vaule is 0.0
*/
var delay: Float = 0.0
/**
Damping of animation for changing offset, default vaule is 0.7
*/
var damping: Float = 0.7
/**
Damping of animation for changing offset, default vaule is 0.6
*/
var velocity: Float = 0.6
private var leftToRightLeadingContraint: NSLayoutConstraint?
private var topToBottomTopContraint: NSLayoutConstraint?
// Only available init
override init(frame: CGRect) {
super.init(frame: frame)
self.initializeByDefault()
}
// Disabled implementation use instead init(frame: CGRect)
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Call this method to force recalculation of contentSize in ScrollView, i.e. when content changes.
*/
func recalculateContentSize() {
if self.content == nil || self.offsets.isEmpty {
return
}
var size: CGSize = CGSize.zero
if self.orientationType == .RDScrollViewOrientationBottomToTop {
size.height = self.frame.height + (self.content!.frame.height * CGFloat(self.offsets.last!.floatValue)) +
CGFloat(self.margin)
} else if self.orientationType == .RDScrollViewOrientationTopToBottom {
size.height = self.frame.height + (self.content!.frame.height * CGFloat(self.offsets.first!.floatValue)) +
CGFloat(self.margin)
} else if self.orientationType == .RDScrollViewOrientationRightToLeft {
size.width = self.frame.width + (self.content!.frame.width * CGFloat(self.offsets.last!.floatValue)) +
CGFloat(self.margin)
} else if self.orientationType == .RDScrollViewOrientationLeftToRight {
size.width = self.frame.width + (self.content!.frame.width * CGFloat(self.offsets.first!.floatValue)) +
CGFloat(self.margin)
}
self.contentSize = size
self.layoutIfNeeded()
DispatchQueue.main.async {
self.changeOffsetTo(offsetIndex: self.offsetIndex, animated: false, completion: nil)
}
}
// Methods to Increase or decrease offset of content within RDScrollView.
func changeOffsetTo(offsetIndex: Int, animated: Bool, completion: ((Bool) -> Void)?) {
panGestureRecognizer.isEnabled = false
UIView.animate(withDuration: TimeInterval(self.duration),
delay: TimeInterval(self.delay),
usingSpringWithDamping: CGFloat(self.damping),
initialSpringVelocity: CGFloat(self.velocity),
options: .curveEaseOut,
animations: {() -> Void in
if self.content == nil || self.offsets.count == 0 {
self.setContentOffset(CGPoint.zero, animated: animated)
} else {
self.content?.isHidden = false
if self.orientationType == .RDScrollViewOrientationLeftToRight {
let margin: Float = (offsetIndex == 0 || offsetIndex == Int(self.offsets.count - 1)) ?
self.margin: Float(0.0)
self.setContentOffset(CGPoint.init(x: ((CGFloat(self.offsets[Int(offsetIndex)]) *
self.content!.frame.width) + CGFloat(margin)),
y: CGFloat(self.contentOffset.y)), animated: animated)
} else if self.orientationType == .RDScrollViewOrientationRightToLeft {
self.setContentOffset(CGPoint(x: CGFloat(self.offsets[Int(offsetIndex)]) *
self.content!.frame.width, y: CGFloat(self.contentOffset.y)), animated: animated)
} else if self.orientationType == .RDScrollViewOrientationBottomToTop {
self.setContentOffset(CGPoint(x: CGFloat(self.contentOffset.x),
y: (CGFloat(self.offsets[Int(offsetIndex)]) *
CGFloat(self.content!.frame.height))),
animated: animated)
} else if self.orientationType == .RDScrollViewOrientationTopToBottom {
let margin: Float = (offsetIndex == 0 || Int(offsetIndex) == self.offsets.count - 1) ?
self.margin: Float(0.0)
self.setContentOffset(CGPoint(x: CGFloat(self.contentOffset.x),
y: (CGFloat(self.offsets[Int(offsetIndex)]) *
CGFloat(self.content!.frame.height)) + CGFloat(margin)),
animated: animated)
}
}
}, completion: {(_ finished: Bool) -> Void in
self.offsetIndex = offsetIndex
if self.orientationType == .RDScrollViewOrientationLeftToRight ||
self.orientationType == .RDScrollViewOrientationTopToBottom {
self.isOpen = self.offsets[Int(offsetIndex)].floatValue == 1 ? false: true
} else {
self.isOpen = self.offsets[Int(offsetIndex)].floatValue == 0 ? false: true
}
self.content?.isHidden = !self.isOpen
self.panGestureRecognizer.isEnabled = true
completion?(finished)
})
}
func expandWithCompletion(completion: ((Bool) -> Void)?) {
let nextIndex: Int = self.offsetIndex + 1 < Int(self.offsets.count) ? self.offsetIndex + 1: self.offsetIndex
self.changeOffsetTo(offsetIndex: nextIndex, animated: false, completion: completion)
}
func collapseWithCompletion(completion: ((Bool) -> Void)?) {
let nextIndex: Int = self.offsetIndex == 0 ? 0: self.offsetIndex - 1
self.changeOffsetTo(offsetIndex: nextIndex, animated: false, completion: completion)
}
func closeWithCompletion(completion: ((Bool) -> Void)?) {
self.changeOffsetTo(offsetIndex: 0, animated: false, completion: completion)
}
// MARK: - private methods
private func initializeByDefault() {
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.showsVerticalScrollIndicator = false
self.showsHorizontalScrollIndicator = false
self.bounces = false
self.isDirectionalLockEnabled = false
self.scrollsToTop = false
self.isPagingEnabled = false
self.contentInset = UIEdgeInsets.zero
self.decelerationRate = UIScrollViewDecelerationRateFast
}
private func addContent(content: UIView) {
if content.frame.isNull {
return
}
self.subviews.forEach { $0.removeFromSuperview() }
let container: UIView = UIView.init()
container.addSubview(content)
self.addSubview(container)
container.translatesAutoresizingMaskIntoConstraints = false
content.translatesAutoresizingMaskIntoConstraints = false
if self.orientationType == .RDScrollViewOrientationRightToLeft {
container.addConstraints([NSLayoutConstraint(item: content, attribute: .top, relatedBy: .equal,
toItem: container, attribute: .top, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: content, attribute: .bottom, relatedBy: .equal,
toItem: container, attribute: .bottom, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: content, attribute: .trailing, relatedBy: .equal,
toItem: container, attribute: .trailing, multiplier: 1.0,
constant: 0.0)])
self.addConstraints([NSLayoutConstraint(item: container, attribute: .leading, relatedBy: .equal,
toItem: self, attribute: .leading, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .top, relatedBy: .equal,
toItem: self, attribute: .top, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .height, relatedBy: .equal,
toItem: self, attribute: .height, multiplier: 1.0,
constant: 0.0)])
if content.frame.isEmpty {
self.addConstraints([NSLayoutConstraint(item: content, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width, multiplier: 2.0,
constant: 0.0)])
} else {
container.addConstraints([NSLayoutConstraint(item: content, attribute: .width, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1.0,
constant: content.frame.width)])
self.addConstraints([NSLayoutConstraint(item: container, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width, multiplier: 1.0,
constant: content.frame.width)])
}
} else if self.orientationType == .RDScrollViewOrientationLeftToRight {
self.leftToRightLeadingContraint = NSLayoutConstraint(item: content, attribute: .leading, relatedBy: .equal,
toItem: container, attribute: .leading, multiplier: 1.0,
constant: CGFloat(self.margin))
container.addConstraints([NSLayoutConstraint(item: content, attribute: .top, relatedBy: .equal,
toItem: container, attribute: .top, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: content, attribute: .bottom, relatedBy: .equal,
toItem: container, attribute: .bottom, multiplier: 1.0,
constant:0.0),
self.leftToRightLeadingContraint!])
self.addConstraints([NSLayoutConstraint(item: container, attribute: .leading, relatedBy: .equal,
toItem: self, attribute: .leading, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .top, relatedBy: .equal,
toItem: self, attribute: .top, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .height, relatedBy: .equal,
toItem: self, attribute: .height, multiplier: 1.0,
constant: 0.0)])
if content.frame.isEmpty {
self.addConstraints([NSLayoutConstraint(item: content, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width, multiplier: 2.0,
constant: 0.0)])
} else {
container.addConstraints([NSLayoutConstraint(item: content, attribute: .width, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1.0,
constant: content.frame.width)])
self.addConstraints([NSLayoutConstraint(item: container, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width, multiplier: 1.0,
constant: content.frame.width)])
}
} else if self.orientationType == .RDScrollViewOrientationBottomToTop {
container.addConstraints([NSLayoutConstraint(item: content, attribute: .leading, relatedBy: .equal,
toItem: container, attribute: .leading, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: content, attribute: .trailing, relatedBy: .equal,
toItem: container, attribute: .trailing, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: content, attribute: .bottom, relatedBy: .equal,
toItem: container, attribute: .bottom, multiplier: 1.0,
constant: 0.0)])
self.addConstraints([NSLayoutConstraint(item: container, attribute: .leading, relatedBy: .equal,
toItem: self, attribute: .leading, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .top, relatedBy: .equal,
toItem: self, attribute: .top, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width, multiplier: 1.0,
constant: 0.0)])
if content.frame.isEmpty {
self.addConstraints([NSLayoutConstraint(item: content, attribute: .height, relatedBy: .equal,
toItem: self, attribute: .height, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .height, relatedBy: .equal,
toItem: self, attribute: .height, multiplier: 2.0,
constant: 0.0)])
} else {
container.addConstraints([NSLayoutConstraint(item: content, attribute: .height, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1.0,
constant: content.frame.height)])
self.addConstraints([NSLayoutConstraint(item: container, attribute: .height, relatedBy: .equal,
toItem: self, attribute: .height, multiplier: 1.0,
constant: content.frame.height)])
}
} else if self.orientationType == .RDScrollViewOrientationTopToBottom {
self.topToBottomTopContraint = NSLayoutConstraint(item: content, attribute: .top, relatedBy: .equal,
toItem: container, attribute: .top, multiplier: 1.0,
constant: CGFloat(self.margin))
container.addConstraints([NSLayoutConstraint(item: content, attribute: .leading, relatedBy: .equal,
toItem: container, attribute: .leading, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: content, attribute: .trailing, relatedBy: .equal,
toItem: container, attribute: .trailing, multiplier: 1.0,
constant:0.0),
self.topToBottomTopContraint!])
self.addConstraints([NSLayoutConstraint(item: container, attribute: .leading, relatedBy: .equal,
toItem: self, attribute: .leading, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .top, relatedBy: .equal,
toItem: self, attribute: .top, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width, multiplier: 1.0,
constant: 0.0)])
if content.frame.isEmpty {
self.addConstraints([NSLayoutConstraint(item: content, attribute: .height, relatedBy: .equal,
toItem: self, attribute: .height, multiplier: 1.0,
constant: 0.0),
NSLayoutConstraint(item: container, attribute: .height, relatedBy: .equal,
toItem: self, attribute: .height, multiplier: 2.0,
constant: 0.0)])
} else {
container.addConstraints([NSLayoutConstraint(item: content, attribute: .height, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute,
multiplier: 1.0, constant: content.frame.height)])
self.addConstraints([NSLayoutConstraint(item: container, attribute: .height, relatedBy: .equal,
toItem: self, attribute: .height,
multiplier: 1.0, constant: content.frame.height)])
}
}
self.layoutIfNeeded()
self.recalculateContentSize()
}
private func viewContainsPoint(point: CGPoint, inView view: UIView) -> Bool {
if self.content != nil && self.content!.frame.contains(point) {
return true
}
if self.selectContentSubViews {
for subView in view.subviews {
if subView.frame.contains(point) {
return true
}
}
}
return false
}
// MARK: - touch handlers
override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if !self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01 {
return nil
}
if (self.content != nil) && self.viewContainsPoint(point: point, inView: self.content!) {
for subview in self.subviews.reversed() {
let pt: CGPoint = CGPoint.init(x:CGFloat(fabs(point.x)), y:CGFloat(fabs(point.y)))
let convertedPoint: CGPoint = subview.convert(pt, from: self)
let hitTestView: UIView? = subview.hitTest(convertedPoint, with: event)
if hitTestView != nil {
return hitTestView
}
}
}
return nil
}
}
|
import UIKit
protocol StoryboardEmbeddableTransition {
func embed(viewController: UIViewController, inViewController: UIViewController, inView: UIView, completion:(()->())?)
func deEmbed(viewController: UIViewController, fromViewController: UIViewController, completion: (()->())?)
}
|
//
// ChatViewController.swift
// Chatter
//
import UIKit
class ChatViewController: UIViewController {
private enum Keys: String {
case userStoppedTyping = "stopType"
case userStartedTyping = "startType"
}
private var isTyping = false
@IBOutlet weak var messageTextView: UITextView!
@IBOutlet weak var messageTexrViewWithoutScrollConstraint: NSLayoutConstraint!
@IBOutlet weak var messageTextViewWithScrollConstraint: NSLayoutConstraint!
@IBOutlet weak var messagePlaceholder: UILabel!
@IBOutlet weak var menuButton: UIButton!
@IBOutlet weak var channelNameLabel: UILabel!
@IBOutlet weak var messageTableView: UITableView!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var typingUsersLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupSockets()
setupDelegate()
setupTableView()
setupBehaviour()
setupNotifications()
}
func updateWithChannel() {
let channelName = MessageService.instance.channelSelected?.name ?? ""
channelNameLabel.text = "#\(channelName)"
messagePlaceholder.isHidden = false
getMessages()
}
func onLoginGetMessages() {
MessageService.instance.findAllChannels { success in
guard success else { return }
if MessageService.instance.channels.count > 0 {
MessageService.instance.channelSelected = MessageService.instance.channels[0]
self.updateWithChannel()
} else {
self.channelNameLabel.text = "No channels added yet!"
}
}
}
func getMessages() {
guard let channelId = MessageService.instance.channelSelected?.identifier else { return }
MessageService.instance.findAllMessagesForChannel(channelId: channelId) { [weak self] success in
guard success else {
print("Error getting messages for channel with id: \(channelId)")
return
}
self?.messageTableView.reloadData()
guard !MessageService.instance.messages.isEmpty else { return }
let indexPath = IndexPath(row: MessageService.instance.messages.count - 1, section: 0)
self?.messageTableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
}
}
@objc func handleTap() {
view.endEditing(true)
}
@objc func keyboardDidChange(_ notification: Notification) {
guard !MessageService.instance.messages.isEmpty else { return }
let indexPath = IndexPath(row: MessageService.instance.messages.count - 1, section: 0)
messageTableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
@objc func userDataDidChange() {
if AuthenticationService.instance.isLoggedIn {
onLoginGetMessages()
} else {
messagePlaceholder.isHidden = true
channelNameLabel.text = "Please Log In"
messageTableView.reloadData()
}
}
@objc func channelSelected() {
updateWithChannel()
}
private func setupView() {
if !AuthenticationService.instance.isLoggedIn {
channelNameLabel.text = "Please log in"
messagePlaceholder.isHidden = true
}
sendButton.isHidden = true
menuButton.addTarget(
self.revealViewController(),
action: #selector(SWRevealViewController.revealToggle(_:)),
for: .touchUpInside)
messageTextView
.bottomAnchor
.constraint(equalTo: view.keyboardLayoutGuide.topAnchor, constant: -8)
.isActive = true
view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
}
private func setupTableView() {
messageTableView.estimatedRowHeight = 80
messageTableView.rowHeight = UITableView.automaticDimension
}
private func setupDelegate() {
messageTextView.delegate = self
messageTableView.delegate = self
messageTableView.dataSource = self
revealViewController()?.delegate = self
}
private func setupBehaviour() {
view.addGestureRecognizer(
UITapGestureRecognizer(
target: self,
action: #selector(ChatViewController.handleTap)))
}
private func setupSockets() {
SocketService.instance.getChatMessage { [weak self] newMessage in
guard
newMessage.channelId == MessageService.instance.channelSelected?.identifier,
AuthenticationService.instance.isLoggedIn
else {
return
}
MessageService.instance.messages.append(newMessage)
self?.messageTableView.reloadData()
guard !MessageService.instance.messages.isEmpty else { return }
let indexPath = IndexPath(row: MessageService.instance.messages.count - 1, section: 0)
self?.messageTableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
SocketService.instance.getTypingUsers { [weak self] typingUsers in
guard let channelId = MessageService.instance.channelSelected?.identifier else { return }
var names = ""
var numberOfTypers = 0
for (typingUser, channel) in typingUsers {
if typingUser != UserDataService.instance.name && channel == channelId {
if names.isEmpty {
names = typingUser
} else {
names += ", \(typingUser)"
}
numberOfTypers += 1
}
}
if numberOfTypers > 0, AuthenticationService.instance.isLoggedIn {
var verb = "is"
if numberOfTypers > 1 {
verb = "are"
}
self?.typingUsersLabel.text = "\(names) \(verb) typing a message"
} else {
self?.typingUsersLabel.text = ""
}
}
}
private func setupNotifications() {
if AuthenticationService.instance.isLoggedIn {
AuthenticationService.instance.findUserByEmail { success in
guard success else { return }
NotificationCenter.default.post(name: .userDataDidChange, object: nil)
}
}
NotificationCenter.default.addObserver(
self,
selector: #selector(ChatViewController.userDataDidChange),
name: .userDataDidChange,
object: nil)
NotificationCenter.default.addObserver(
self, selector:
#selector(ChatViewController.channelSelected),
name: .channelSelected,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(ChatViewController.keyboardDidChange(_:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil)
}
@IBAction func sendMessageButtonPressed(_ sender: Any) {
guard
AuthenticationService.instance.isLoggedIn,
let channelId = MessageService.instance.channelSelected?.identifier,
let message = messageTextView.text
else {
return
}
SocketService.instance.addMessage(
messageBody: message,
userId: UserDataService.instance.userId,
channelId: channelId
) { success in
guard success else { return }
self.messageTextView.text = ""
self.sendButton.isHidden = true
self.messagePlaceholder.isHidden = false
SocketService.instance.socket.emit(
Keys.userStoppedTyping.rawValue,
UserDataService.instance.name,
channelId)
}
}
}
extension ChatViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return MessageService.instance.messages.count
}
func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(
withIdentifier: Cell.messageCell.rawValue,
for: indexPath) as? MessageCell
else {
return UITableViewCell()
}
let message = MessageService.instance.messages[indexPath.row]
cell.configureCell(message: message)
return cell
}
}
extension ChatViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
if textView.text != nil, textView.text != "" {
sendButton.isHidden = false
messagePlaceholder.isHidden = true
} else {
sendButton.isHidden = true
messagePlaceholder.isHidden = false
}
if let lineHeight = textView.font?.lineHeight {
let numberOfLines = Int(textView.contentSize.height / lineHeight)
if numberOfLines >= 3 {
messageTexrViewWithoutScrollConstraint.isActive = false
messageTextViewWithScrollConstraint.constant = textView.frame.height
messageTextViewWithScrollConstraint.isActive = true
textView.isScrollEnabled = true
} else {
messageTexrViewWithoutScrollConstraint.isActive = true
messageTextViewWithScrollConstraint.isActive = false
textView.isScrollEnabled = false
}
}
guard !MessageService.instance.messages.isEmpty else { return }
let indexPath = IndexPath(row: MessageService.instance.messages.count - 1, section: 0)
self.messageTableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
guard let channelId = MessageService.instance.channelSelected?.identifier else { return }
if messageTextView.text.isEmpty {
isTyping = false
sendButton.isHidden = true
SocketService.instance.socket.emit(
Keys.userStoppedTyping.rawValue,
UserDataService.instance.name,
channelId)
} else {
if isTyping == false {
SocketService.instance.socket.emit(
Keys.userStartedTyping.rawValue,
UserDataService.instance.name,
channelId)
sendButton.isHidden = false
}
isTyping = true
}
}
}
extension ChatViewController: SWRevealViewControllerDelegate {
func revealController(
_ revealController: SWRevealViewController!,
willMoveTo position: FrontViewPosition
) {
if messageTextView.isFirstResponder {
messageTextView.resignFirstResponder()
}
}
}
|
//
// KVObserver.swift
// https://github.com/xinyzhao/ZXToolboxSwift
//
// Copyright (c) 2019-2020 Zhao Xin
//
// 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
public class KVObserver<T>: NSObject {
public typealias KVObserveValue<T> = (_ value: T) -> Void
private var object: NSObject?
private var keyPath: String?
private var options: NSKeyValueObservingOptions?
private var observeValue: KVObserveValue<T>?
public func addObserver(_ object: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions, observeValue: KVObserveValue<T>?) {
removeObserver()
self.object = object
self.keyPath = keyPath
self.options = options
self.observeValue = observeValue
addObserver()
}
private func addObserver() {
if let object = object, let keyPath = keyPath, let options = options {
object.addObserver(self, forKeyPath: keyPath, options: options, context: nil)
}
}
public func removeObserver() {
if let object = object, let keyPath = keyPath {
object.removeObserver(self, forKeyPath: keyPath)
}
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == self.keyPath, let change = change, let observeValue = observeValue {
for (_, value) in change {
if let v = value as? T {
observeValue(v)
}
}
}
}
}
|
//
// SettingsView.swift
// RunWalkPro
//
// Created by Marc Mendoza on 2/17/21.
//
import SwiftUI
struct SettingsView: View {
var body: some View {
Text("Settings")
.navigationTitle("Settings")
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
|
/* Copyright Airship and Contributors */
import Foundation
import SwiftUI
@available(iOS 13.0.0, tvOS 13.0, *)
struct RadioInput : View {
let model: RadioInputModel
let constraints: ViewConstraints
@EnvironmentObject var formState: FormState
@EnvironmentObject var radioInputState: RadioInputState
@Environment(\.colorScheme) var colorScheme
@ViewBuilder
private func createToggle() -> some View {
let isOn = Binding<Bool>(
get: { self.radioInputState.selectedItem == self.model.value },
set: {
if ($0) {
self.radioInputState.updateSelectedItem(self.model)
}
}
)
let toggle = Toggle(isOn: isOn.animation()) {}
switch (self.model.style) {
case .checkboxStyle(let style):
toggle.toggleStyle(AirshipCheckboxToggleStyle(viewConstraints: self.constraints,
model: style,
colorScheme: colorScheme))
case .switchStyle(let style):
toggle.toggleStyle(AirshipSwitchToggleStyle(model: style, colorScheme: colorScheme))
}
}
@ViewBuilder
var body: some View {
createToggle()
.constraints(constraints)
.background(model.backgroundColor)
.border(model.border)
.common(self.model)
.formElement()
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.