text stringlengths 8 1.32M |
|---|
// CGColorExtensionsTests.swift - Copyright 2020 SwifterSwift
@testable import SwifterSwift
import XCTest
#if canImport(CoreGraphics)
import CoreGraphics
#if os(macOS)
import AppKit
#else
import UIKit
#endif
final class CGColorExtensionsTests: XCTestCase {
#if !os(macOS)
func testUIColor() {
let red = UIColor.red
let cgRed = red.cgColor
XCTAssertEqual(cgRed.uiColor, red)
}
#endif
#if os(macOS)
func testNSColor() {
let red = NSColor.red
let cgRed = red.cgColor
XCTAssertEqual(cgRed.nsColor, red)
}
#endif
}
#endif
|
//
// DateData.swift
// Video Club App
//
// Created by Rodrigo Camargo on 5/5/21.
//
import Foundation
import RealmSwift
class DateData: Object {
@objc dynamic var date: String = ""
func dateToString(_ date: Date) -> String {
let calendar = Calendar.current
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let year = calendar.component(.year, from: date)
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let datetime = "\(day)/\(month)/\(year) \(hour):\(minutes)"
return datetime
}
func stringToDate(_ date: String) -> Date {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
let newDate = formatter.date(from: date)
return newDate!
}
}
|
//
// ViewController.swift
// material-test
//
// Created by Phyo Htet Arkar on 4/30/20.
// Copyright © 2020 Phyo Htet Arkar. All rights reserved.
//
import UIKit
import MaterialComponents
class ViewController: UIViewController {
@IBOutlet weak var filledTextField: MDCFilledTextField!
@IBOutlet weak var outlineTextField: MDCOutlinedTextField!
override func viewDidLoad() {
super.viewDidLoad()
let scheme = MDCContainerScheme()
scheme.colorScheme.primaryColor = .systemPurple
filledTextField.applyTheme(withScheme: scheme)
filledTextField.label.text = "Filled"
filledTextField.leadingAssistiveLabel.text = "Helper text."
outlineTextField.applyTheme(withScheme: scheme)
outlineTextField.label.text = "Outline"
outlineTextField.leadingAssistiveLabel.text = "Helper text."
}
}
|
//
// ReminderManager.swift
// schedule
//
// Created by zj-db0548 on 2017/6/21.
// Copyright © 2017年 魔方. All rights reserved.
//
import Foundation
import NotificationCenter
import EventKit
func addalarmEvent(date:NSDate!, message:String!)-> Void {
let eventDB = EKEventStore()
eventDB.requestAccess(to: EKEntityType.event) { (granted, error) in
if !granted {
return
}
print("request")
let alarmStarDate = Date(timeIntervalSinceNow: 10)
// let alarmEndDate = Date(timeIntervalSinceNow: 30)
let event = EKEvent(eventStore: eventDB)
event.title = message
event.startDate = alarmStarDate
event.endDate = alarmStarDate
let alarm = EKAlarm(absoluteDate: alarmStarDate)
event.addAlarm(alarm)
event.calendar = eventDB.defaultCalendarForNewEvents
do {
try eventDB.save(event, span: EKSpan.thisEvent)
}catch {
}
}
}
//闹钟
func addAlarmClock() -> Void {
let notification = UILocalNotification()
notification.fireDate = Date(timeIntervalSinceNow: 10)
notification.repeatInterval = NSCalendar.Unit.minute
notification.timeZone = NSTimeZone.default
notification.soundName = "test.caf"
notification.alertBody = "哈哈哈"
notification.alertAction = "ds"
notification.userInfo = ["us":"d"]
notification.applicationIconBadgeNumber = notification.applicationIconBadgeNumber + 1
UIApplication.shared.scheduleLocalNotification(notification)
}
//添加提醒
func addReminder(message:String!) {
let eventDB = EKEventStore()
eventDB.requestAccess(to: EKEntityType.reminder) { (granted, error) in
if !granted {
return
}
let alarmStarDate = Date(timeIntervalSinceNow: 10)
let alarmEndDate = Date(timeIntervalSinceNow: 30)
let reminder = EKReminder(eventStore: eventDB)
reminder.title = message
reminder.calendar = eventDB.defaultCalendarForNewReminders()
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.system
var flags = Set<Calendar.Component>()
flags.insert(Calendar.Component.year)
flags.insert(Calendar.Component.month)
flags.insert(Calendar.Component.day)
flags.insert(Calendar.Component.hour)
flags.insert(Calendar.Component.minute)
flags.insert(Calendar.Component.second)
let dateCmp = calendar.dateComponents(flags, from: alarmStarDate)
let endDateCmp = calendar.dateComponents(flags, from: alarmEndDate)
reminder.startDateComponents = dateCmp
reminder.dueDateComponents = endDateCmp
reminder.priority = 1
let alarm = EKAlarm(absoluteDate: alarmStarDate)
reminder.addAlarm(alarm)
do {
try eventDB.save(reminder, commit: true)
}catch {
}
}
}
|
import Foundation
@objcMembers public class USStreetAnalysis: NSObject, Codable {
// See "https://smartystreets.com/docs/cloud/us-street-api#analysis"
public var dpvMatchCode:String?
public var dpvFootnotes:String?
public var cmra:String?
public var vacant:String?
public var noStat:String?
public var active:String?
public var footnotes:String?
public var lacsLinkCode:String?
public var lacsLinkIndicator:String?
public var isSuiteLinkMatch:Bool?
public var enhancedMatch:String?
public var objcIsSuiteLinkMatch:NSNumber? {
get {
return isSuiteLinkMatch as NSNumber?
}
}
enum CodingKeys: String, CodingKey {
case dpvMatchCode = "dpv_match_code"
case dpvFootnotes = "dpv_footnotes"
case cmra = "dpv_cmra"
case vacant = "dpv_vacant"
case noStat = "dpv_no_stat"
case active = "active"
case footnotes = "footnotes"
case lacsLinkCode = "lacslink_code"
case lacsLinkIndicator = "lacslink_indicator"
case isSuiteLinkMatch = "suitelink_match"
case enhancedMatch = "enhanced_match"
}
init(dictionary: NSDictionary) {
self.dpvMatchCode = dictionary["dpv_match_code"] as? String
self.dpvFootnotes = dictionary["dpv_footnotes"] as? String
self.cmra = dictionary["dpv_cmra"] as? String
self.vacant = dictionary["dpv_vacant"] as? String
self.noStat = dictionary["dpv_no_stat"] as? String
self.active = dictionary["active"] as? String
self.footnotes = dictionary["footnotes"] as? String
self.lacsLinkCode = dictionary["lacslink_code"] as? String
self.lacsLinkIndicator = dictionary["lacslink_indicator"] as? String
self.isSuiteLinkMatch = dictionary["suitelink_match"] as? Bool
self.enhancedMatch = dictionary["enhanced_match"] as? String
}
}
|
//
// Int+Random.swift
// Ubud-Example
//
// Created by Luqman Fauzi on 10/12/2017.
// Copyright © 2017 Luqman Fauzi. All rights reserved.
//
import Foundation
extension Int {
static func random(upper: Int = 10) -> Int {
let randomNumber: UInt32 = arc4random_uniform(UInt32(upper))
return Int(randomNumber)
}
}
|
//
// TransactionService.swift
// mOOOnWallet
//
// Created by 조현호 on 2018. 1. 15..
// Copyright © 2018년 mOOOn. All rights reserved.
//
import Geth
import Alamofire
class TransactionService: TransactionServiceProtocol {
private let context: GethContext
private let client: GethEthereumClient
private let keystore: KeystoreService
private let chain: Chain
init(core: Ethereum, keystore: KeystoreService) {
// TODO: Check objects
self.context = core.context
self.client = core.client
self.chain = core.chain
self.keystore = keystore
}
func sendTransaction(amountHex: String, to: String, gasLimitHex: String, passphrase: String, result: @escaping (Result<GethTransaction>) -> Void) {
Ethereum.syncQueue.async {
do {
let account = try self.keystore.getAccount(at: 0)
let transaction = try self.createTransaction(amountHex: amountHex, to: to, gasLimitHex: gasLimitHex, account: account)
let signedTransaction = try self.keystore.signTransaction(transaction, account: account, passphrase: passphrase, chainId: self.chain.chainId)
try self.sendTransaction(signedTransaction)
DispatchQueue.main.async {
result(.success(signedTransaction))
}
} catch {
DispatchQueue.main.async {
result(.failure(error))
}
}
}
}
func sendTokenTransaction(contractAddress: String, to: String, amountHex: String, passphrase: String, result: @escaping (Result<GethTransaction>) -> Void) {
Ethereum.syncQueue.async {
do {
let account = try self.keystore.getAccount(at: 0)
let transaction = try self.createTokenTransaction(contractAddress: contractAddress, to: to, amountHex: amountHex)
let signedTransaction = try self.keystore.signTransaction(transaction, account: account, passphrase: passphrase, chainId: self.chain.chainId)
try self.sendTransaction(signedTransaction)
DispatchQueue.main.async {
result(.success(signedTransaction))
}
} catch {
DispatchQueue.main.async {
result(.failure(error))
}
}
}
}
private func createTransaction(amountHex: String, to: String, gasLimitHex: String, account: GethAccount) throws -> GethTransaction {
var error: NSError?
let gethAddress = GethNewAddressFromHex(to, &error)
var noncePointer: Int64 = 0
try client.getNonceAt(context, account: account.getAddress(), number: -1, nonce: &noncePointer)
let intAmount = GethNewBigInt(0)
intAmount?.setString(amountHex, base: 16)
let gasLimit = GethNewBigInt(0)
gasLimit?.setString(gasLimitHex, base: 16)
let gasPrice = try client.suggestGasPrice(context)
return GethNewTransaction(noncePointer, gethAddress, intAmount, gasLimit, gasPrice, nil)
}
private func createTokenTransaction(contractAddress: String, to: String, amountHex: String) throws -> GethTransaction {
var error: NSError?
let gethAddress = GethNewAddressFromHex(to, &error)
guard let contract = GethBindContract(gethAddress, "", client, &error) else {
throw TransactionServiceError.wrongContractAddress
}
let transactOpts = GethTransactOpts()
let method = "{\"constant\": false, \"inputs\": [ { \"name\": \"_to\", \"type\": \"address\" }, { \"name\": \"_value\", \"type\": \"uint256\" } ], \"name\": \"transfer\", \"outputs\": [ { \"name\": \"success\", \"type\": \"bool\" } ], \"type\": \"function\"}"
let addresInterface = GethInterface()!
addresInterface.setString(to)
let amountInterface = GethInterface()!
let intAmount = GethNewBigInt(0)!
intAmount.setString(amountHex, base: 16)
amountInterface.setUint64(intAmount)
let interfaces = GethInterfaces(2)!
try interfaces.set(0, object: addresInterface)
try interfaces.set(1, object: amountInterface)
return try contract.transact(transactOpts, method: method, args: interfaces)
}
private func sendTransaction(_ signedTransaction: GethTransaction) throws {
try client.sendTransaction(context, tx: signedTransaction)
}
}
enum TransactionServiceError: Error {
case wrongContractAddress
}
|
import UIKit
private let space: CGFloat = 20
private let ratio: CGFloat = 1.2
// swiftlint:disable anyobject_protocol
protocol RecipesCollectionProviderDelegate: class {
var collectionView: UICollectionView! { get }
func provider(_ provider: RecipesCollectionProvider, didSelectRecipeWithIdentifier identifier: String)
func providerWillDisplayLastRecipe(_ provider: RecipesCollectionProvider)
}
// swiftlint:enable anyobject_protocol
class RecipesCollectionProvider: NSObject,
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout {
weak var delegate: RecipesCollectionProviderDelegate?
private var recipes = [Recipe]()
func set(_ recipes: [Recipe]) {
self.recipes = recipes
delegate?.collectionView.reloadData()
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return recipes.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let recipe = recipes[indexPath.row]
let cell: RecipeCollectionViewCell = collectionView.dequeueReusableCellForIndexPath(indexPath)
cell.populate(with: recipe)
return cell
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let recipe = recipes[indexPath.row]
delegate?.provider(self, didSelectRecipeWithIdentifier: recipe.identifier)
}
func collectionView(_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
if indexPath.item == recipes.count - 1 {
delegate?.providerWillDisplayLastRecipe(self)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let widthOfContent = delegate?.collectionView.bounds.size.width ?? UIScreen.main.bounds.size.width
let numberOfColumns: CGFloat = UIDevice.current.userInterfaceIdiom == .phone ? 1 : 2
let spacing = (numberOfColumns + 1) * space
let width = (widthOfContent - spacing) / numberOfColumns
let height = Float(width * ratio)
let roundedHeight = CGFloat(lroundf(height))
return CGSize(width: width, height: roundedHeight)
}
}
|
import WebRTC
class ARDSDPUtils {
class func description(for description: RTCSessionDescription, preferredVideoCodec codec: String) -> RTCSessionDescription {
let sdpString: String = description.sdp
let lineSeparator = "\n"
let mLineSeparator = " "
// Copied from PeerConnectionClient.java.
// TODO(tkchin): Move this to a shared C++ file.
var lines = sdpString.components(separatedBy: lineSeparator)
// Find the line starting with "m=video".
var mLineIndex: Int = -1
for i in 0..<lines.count {
if lines[i].hasPrefix("m=video") {
mLineIndex = i
break
}
}
if mLineIndex == -1 {
print("No m=video line, so can't prefer \(codec)")
return description
}
// An array with all payload types with name |codec|. The payload types are
// integers in the range 96-127, but they are stored as strings here.
var codecPayloadTypes = [String]()
// a=rtpmap:<payload type> <encoding name>/<clock rate>
// [/<encoding parameters>]
let pattern = "^a=rtpmap:(\\d+) \(codec)(/\\d+)+[\r]?$"
for line: String in lines {
if line.range(of:pattern, options: .regularExpression) != nil {
codecPayloadTypes.append(String(line.components(separatedBy: mLineSeparator)[0].components(separatedBy: ":")[1]))
}
}
if codecPayloadTypes.count == 0 {
print("No payload types with name \(codec)")
return description
}
let origMLineParts = lines[mLineIndex].components(separatedBy: mLineSeparator)
// The format of ML should be: m=<media> <port> <proto> <fmt> ...
let kHeaderLength: Int = 3
if origMLineParts.count <= kHeaderLength {
print("Wrong SDP media description format: \(lines[mLineIndex])")
return description
}
// Split the line into header and payloadTypes.
let header = origMLineParts[0...kHeaderLength-1]
var payloadTypes = origMLineParts[kHeaderLength...origMLineParts.count-1]
// Reconstruct the line with |codecPayloadTypes| moved to the beginning of the
// payload types.
var newMLineParts = [String]() /* TODO: .reserveCapacity(origMLineParts.count) */
newMLineParts.append(contentsOf: header)
newMLineParts.append(contentsOf: codecPayloadTypes)
payloadTypes = payloadTypes.filter({ !codecPayloadTypes.contains($0) })
newMLineParts.append(contentsOf: payloadTypes )
let newMLine: String = newMLineParts.joined(separator: mLineSeparator)
lines[mLineIndex] = newMLine
let mangledSdpString: String = lines.joined(separator: lineSeparator)
return RTCSessionDescription(type: description.type, sdp: mangledSdpString)
}
}
|
import PackageDescription
let package = Package(
name: "StencilViewEngine",
dependencies: [
.Package(url: "https://github.com/noppoMan/Suv.git", majorVersion: 0, minor: 14),
.Package(url: "https://github.com/slimane-swift/HTTPCore.git", majorVersion: 0, minor: 1),
.Package(url: "https://github.com/kylef/Stencil.git", majorVersion: 0, minor: 6)
]
)
|
//
// TopScrollView.swift
// Cashbook
//
// Created by 王越 on 2019/1/16.
// Copyright © 2019 王越. All rights reserved.
//
import UIKit
class TopScrollView: UIScrollView {
// let incomeModels = TypeModel.getTypeModels()
// let expendModels = TypeModel.getTypeModels2()
var returnCount:((Int)->())?
let opts = UIView.AnimationOptions.curveEaseIn
var buttons = [UIButton]()
var models:[String]?{
didSet{
for view in subviews{
view.removeFromSuperview()
}
buttons.removeAll()
for i in 0..<(models?.count)!{
let button = UIButton()
button.setTitle(models![i], for: UIControl.State.normal)
// button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(click(_:)), for: UIControl.Event.touchUpInside)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0)
// button.titleLabel?.textAlignment = .left
button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .bottom
button.tag = i
button.setTitleColor(UIColor.gray, for: UIControl.State.normal)
buttons.append(button)
self.addSubview(button)
}
currentNum = 0
}
}
var currentNum:Int? = 0{
didSet{
UIView.animate(withDuration: 1, delay: 0, options: opts, animations: {
self.buttons[self.currentNum!].titleLabel?.font = UIFont.boldSystemFont(ofSize: 30)
self.buttons[self.currentNum!].setTitleColor(UIColor.black, for: UIControl.State.normal)
}, completion: nil)
// buttons[currentNum!].titleLabel?.font = UIFont.boldSystemFont(ofSize: 30)
// buttons[currentNum!].setTitleColor(UIColor.black, for: UIControl.State.normal)
}
willSet{
UIView.animate(withDuration: 1, delay: 0, options: opts, animations: {
self.buttons[self.currentNum!].titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
self.buttons[self.currentNum!].setTitleColor(UIColor.gray, for: UIControl.State.normal)
}, completion: nil)
// buttons[currentNum!].titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
// buttons[currentNum!].setTitleColor(UIColor.gray, for: UIControl.State.normal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
if buttons.count != 0{
for i in 0..<buttons.count{
buttons[i].frame = CGRect(x: CGFloat(i) * 70 + 15, y: 0, width: 70, height: 50)
// self.contentSize = CGSize(width: (Int(self.frame.width) * 3 / 20) * views.count, height: 0)
}
}
}
}
extension TopScrollView{
@objc func click(_ sender:UIButton){
if sender.tag != currentNum!{
buttons[currentNum!].titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
buttons[currentNum!].setTitleColor(UIColor.gray, for: UIControl.State.normal)
currentNum = sender.tag
if returnCount != nil{
returnCount!(sender.tag)
}
}
}
}
|
//
// LaunchScreenViewController.swift
// AutosportInfo
//
// Created by Egor Salnikov on 23.09.2020.
// Copyright © 2020 Egor Salnikov. All rights reserved.
//
import UIKit
import Foundation
class LaunchScreenViewController: UIViewController {
let networkService = NetworkService()
var jsonData: Welcome? = nil
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://ergast.com/api/f1/2020/DriverStandings.json"
networkService.request(urlString: urlString) { (result) in
switch result {
case .success(let teams):
self.jsonData = teams
Thread.sleep(forTimeInterval: 3)
print("self.jsonData")
case .failure(let error):
print(error)
}
}
}
}
/*
// 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.
}
*/
|
//
// SecondViewController.swift
// CoreDataFirst
//
// Created by Apple on 28/06/18.
// Copyright © 2018 senovTech. All rights reserved.
//
import UIKit
import CoreData
class SecondViewController: UIViewController {
@IBOutlet weak var password: UILabel!
@IBOutlet weak var username: UILabel!
var a=String()
var b=String()
var c=String()
var a1=String()
var b1=String()
var c1=String()
var dummyOp:String?
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request1 = NSFetchRequest<NSFetchRequestResult>(entityName: "UserDetails")
let request2 = NSFetchRequest<NSFetchRequestResult>(entityName: "Second")
let request3 = NSFetchRequest<NSFetchRequestResult>(entityName: "Third")
//request.predicate = NSPredicate(format: "age = %@", "12")
request1.returnsObjectsAsFaults = false
request2.returnsObjectsAsFaults = false
request3.returnsObjectsAsFaults = false
do {
let resulta = try context.fetch(request1)
guard let dummyArray=resulta.last else
{
return print("Error")
}
let abc123=dummyArray as! NSManagedObject
guard let abc=abc123.value(forKey: "userName"),let abc1=abc123.value(forKey: "userName"),let abc2=dummyOp else
{
return print("abc2")
}
print(abc)
for data in resulta as! [NSManagedObject] {
a=data.value(forKey: "userName") as! String
a1=data.value(forKey: "password1") as! String
}
let resultb = try context.fetch(request2)
for data in resultb as! [NSManagedObject] {
b=data.value(forKey: "userName22") as! String
b1=data.value(forKey: "password22") as! String
}
let resultc = try context.fetch(request3)
for data in resultc as! [NSManagedObject] {
c=data.value(forKey: "userName33") as! String
c1=data.value(forKey: "password33") as! String
}
self.username.text=a+b+c
self.password.text=a1+b1+c1
} catch {
print("Failed")
}
}
override func viewWillAppear(_ animated: Bool) {
/* let appdelegate=UIApplication.shared.delegate as! AppDelegate
let context=appdelegate.persistentContainer.viewContext
let request=NSFetchRequest<NSFetchRequestResult>(entityName: "UserDetails")
do{
let result=try context.fetch(request)
}
catch
{
print(error.localizedDescription)
}*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// DictionaryQuery.swift
//
//
// Created by Vladislav Fitc on 20/01/2021.
//
import Foundation
public struct DictionaryQuery: Codable {
public var query: String
public var page: Int?
public var hitsPerPage: Int?
public var language: Language?
public init(query: String,
page: Int? = nil,
hitsPerPage: Int? = nil,
language: Language? = nil) {
self.query = query
self.page = page
self.hitsPerPage = hitsPerPage
self.language = language
}
}
extension DictionaryQuery: ExpressibleByStringInterpolation {
public init(stringLiteral value: String) {
self.init(query: value)
}
}
|
//
// RoundedButton.swift
// AlbumDetail
//
// Created by Alex Tapia on 11/03/21.
//
import SwiftUI
struct RoundedButton: View {
private let title: String
private let iconName: String
private let color: Color
init(title: String, iconName: String, color: Color) {
self.title = title
self.iconName = iconName
self.color = color
}
var body: some View {
Button(action: {}, label: {
HStack {
Image(systemName: iconName)
Text(title).fontWeight(.semibold)
}
})
.foregroundColor(.xEEEEEE)
.padding()
.background(color)
.cornerRadius(20)
}
}
struct RoundedButton_Previews: PreviewProvider {
static var previews: some View {
RoundedButton(title: "REPRODUCIR", iconName: "play.fill", color: .xDE1717)
}
}
|
//
// ChatBubbleData.swift
// XmppDemoSwift
//
// Created by Carlos Uribe on 12/05/16.
// Copyright © 2016 HolaGus. All rights reserved.
//
import Foundation
import UIKit
// 1. Type Enum
/**
Enum specifing the type
- Mine: Chat message is outgoing
- Opponent: Chat message is incoming
*/
enum BubbleDataType: Int{
case USER = 0
case GUS
case ACTION
}
class ChatBubbleData {
// 2.Properties
var text: String?
var image: UIImage?
var date: NSDate?
var button: [UIButton] = []
//var textView: UITextView?
var tituloBoton: [String] = []
var tipoAccionBoton: Int?
//var textViewData: String?
var type: BubbleDataType
// 3. Initialization
init(text: String?,image: UIImage?,date: NSDate? , button: [UIButton], tituloBoton: [String], tipoAccionBoton: Int?, type: BubbleDataType?) {
self.text = text
self.image = image
self.date = date
self.button = button
// self.textView = textView
self.tituloBoton = tituloBoton
self.tipoAccionBoton = tipoAccionBoton
// self.textViewData = textViewData
self.type = type!
}
} |
// Copyright 2019, Oath Inc.
// Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms.
import Foundation
import PlayerCore
extension Detectors {
final class AdEngineRequestDetector {
struct Result {
let adInfo: Ad.Metrics.Info
let transactionId: String?
}
private var processedItems = Set<VRMCore.Item>()
func process(state: PlayerCore.State) -> [Result] {
return process(transactionId: state.vrmResponse?.transactionId,
scheduledItems: state.vrmScheduledItems.items)
}
func process(transactionId: String?,
scheduledItems: [VRMCore.Item: Set<ScheduledVRMItems.Candidate>]) -> [Result] {
guard scheduledItems.isEmpty == false else { return [] }
return Set(scheduledItems.keys)
.subtracting(processedItems)
.compactMap { item in
processedItems.insert(item)
return Result(adInfo: Ad.Metrics.Info(metaInfo: item.metaInfo),
transactionId: transactionId)
}
}
}
}
|
//
// ViewController.swift
// CellClickDemo
//
// Created by mac on 08/12/20.
// Copyright © 2020 mac. All rights reserved.
//
import UIKit
class myCell: UITableViewCell {
@IBOutlet weak var likeBtn: UIButton!
@IBOutlet weak var disslikeBtn: UIButton!
// the youtuber (Model), you can use your custom model class here
var indexPath : IndexPath?
// the delegate, remember to set to weak to prevent cycles
weak var delegate : YoutuberTableViewCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// Add action to perform when the button is tapped
self.likeBtn.addTarget(self, action: #selector(subscribeButtonTapped(_:)), for: .touchUpInside)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@objc func subscribeButtonTapped(_ sender: UIButton){
// ask the delegate (in most case, its the view controller) to
// call the function 'subscribeButtonTappedFor' on itself.
if let indexPath = indexPath,
let delegate = delegate {
self.delegate?.youtuberTableViewCell(self, subscribeButtonTappedFor: indexPath)
}
}
}
// Only class object can conform to this protocol (struct/enum can't)
protocol YoutuberTableViewCellDelegate: AnyObject {
func youtuberTableViewCell(_ youtuberTableViewCell: myCell, subscribeButtonTappedFor indexPath: IndexPath)
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! myCell
cell.indexPath = indexPath
// the 'self' here means the view controller, set view controller as the delegate
cell.delegate = self
return cell
}
}
extension ViewController : YoutuberTableViewCellDelegate {
func youtuberTableViewCell(_ youtuberTableViewCell: myCell, subscribeButtonTappedFor indexPath: IndexPath) {
let alert = UIAlertController(title: "Subscribed!", message: "Row number: \(indexPath.row), Section: \(indexPath.section)", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
|
//
// UIMacro.swift
// TemplateSwiftAPP
//
// Created by wenhua yu on 2018/3/21.
// Copyright © 2018年 wenhua yu. All rights reserved.
//
import Foundation
import UIKit
let Device_width: CGFloat = UIScreen.main.bounds.width
let Device_height: CGFloat = UIScreen.main.bounds.height
let Device_nav: CGFloat = 44.0
let Device_tab: CGFloat = 49.0
let Device_status: CGFloat = 20.0
|
//
// SeatTableViewCell.swift
// SeatGeeker
//
// Created by ArmanG on 11/1/1399 AP.
// Copyright © 1399 Pars Digital. All rights reserved.
//
import UIKit
class SeatTableViewCell: UITableViewCell {
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var cityLbl: UILabel!
@IBOutlet weak var dateLbl: UILabel!
@IBOutlet weak var seatImgView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func layoutSubviews() {
super.layoutSubviews()
seatImgView.layer.cornerRadius = seatImgView.bounds.height * (30/100)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// ViewController.swift
// githubPairs
//
// Created by Nithya Guduri on 6/29/21.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var hi = "hi!"
print(hi)
}
// Hi Nithya!
// Hi Lucy :))
}
|
import UIKit
import Combine
struct GitHubUser: Codable {
let login: String
let name: String
let location: String
let followers: Int
}
let url = URL(string: "https://api.github.com/users/adamahrens")!
var subscriptions = Set<AnyCancellable>()
let sharedNetwork = URLSession.shared
.dataTaskPublisher(for: url)
.map (\.data)
.decode(type: GitHubUser.self, decoder: JSONDecoder())
.print("shared")
// Allows one network request to happen and ther result passed to all subscribers
// However if a new subscriber comes along after this completes it won't replay
.share()
sharedNetwork.sink(receiveCompletion: { _ in
print("1. finished")
}) { next in
print("1. Next\(next))")
}.store(in: &subscriptions)
sharedNetwork.sink(receiveCompletion: { _ in
print("2. finished")
}) { next in
print("2. Next\(next))")
}.store(in: &subscriptions)
// Mulitcast for replays
let subject = PassthroughSubject<Data, URLError>()
let ray = URL(string: "https://www.raywenderlich.com")!
let multicast = URLSession.shared.dataTaskPublisher(for: ray).map(\.data).print("Multi").multicast(subject: subject)
// First subscription
multicast.sink(receiveCompletion: { _ in }) { data in
print("Multi 1. Data \(data)")
}.store(in: &subscriptions)
multicast.sink(receiveCompletion: { _ in }) { data in
print("Multi 2. Data \(data)")
}.store(in: &subscriptions)
// Connect to upstream publisher
multicast.connect()
subject.send(Data())
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
multicast.sink(receiveCompletion: { _ in }) { data in
print("Multi 3. Data \(data)")
}.store(in: &subscriptions)
}
// Even if you never subscribe to a Future,
// creating it will call your closure and perform the work
|
//
// CategoryTableViewController.swift
// Personal Word Trainer
//
// Created by Pauli Sairanen on 29/1/21.
//
import UIKit
import CoreData
class CategoryTableViewController: UITableViewController {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
var selectedLanguagesItem: LanguageItem? {
didSet {
// loadItems(language1: (selectedLanguagesItem?.name1!)!, language2: (selectedLanguagesItem?.name2!)!)
print(selectedLanguagesItem!.name1!)
print(selectedLanguagesItem!.name2!)
loadItems()
}
}
var categoryArray = [Category]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "CategoryTableViewCell", bundle: nil), forCellReuseIdentifier: "CategoryTableViewCell")
}
// MARK: ----- Table view data source -----
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categoryArray.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryTableViewCell", for: indexPath) as! CategoryTableViewCell
cell.categoryLabel.text = categoryArray[indexPath.item].categoryName
return cell
}
//MARK: ------ Buttons -----
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var categoryNameField = UITextField()
let alert = UIAlertController(title: "Add a new category", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Add", style: .default) { (action) in
let newCategory = Category(context: self.context)
newCategory.categoryName = categoryNameField.text
newCategory.parentLanguageItem = self.selectedLanguagesItem
self.categoryArray.append(newCategory)
self.saveItems()
})
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (UIAlertAction) in
alert.dismiss(animated: true, completion: nil)
}))
alert.addTextField { (categoryName) in
categoryNameField.placeholder = "Name of the category"
categoryNameField = categoryName
}
present(alert, animated: true, completion: nil)
}
//MARK: ----- Navigation -----
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Sending this category to next screen: \(categoryArray[indexPath.item].categoryName)")
performSegue(withIdentifier: "goToWordTableView", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! WordTableViewController
// Pasing on value to the next ViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedLanguagesItem = selectedLanguagesItem
destinationVC.selectedCategory = categoryArray[indexPath.item]
}
}
//MARK: ------ Data manipulation methods (Save, Read) -----
func saveItems() {
do {
try context.save()
} catch {
print("Error saving context \(error)")
}
self.tableView.reloadData()
}
func loadItems(with request: NSFetchRequest<Category> = Category.fetchRequest()) {
let categoryPredicate = NSPredicate(format: "parentLanguageItem == %@ ", selectedLanguagesItem!)
request.predicate = categoryPredicate
do {
categoryArray = try context.fetch(request)
print(categoryArray)
} catch {
print("Error fetching data from context \(error)")
}
self.tableView.reloadData()
}
}
|
import Nuke
import UIKit
class Question2Cell: UITableViewCell {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var areaImageView: UIImageView!
public func setArea(_ areaName: String, withImageURL url: URL) {
label.text = areaName
// Nukeで画像読み込み
Nuke.loadImage(with: url, into: areaImageView)
}
}
|
//
// BaseNavigationItemViewController.swift
// diverCity
//
// Created by Lauren Shultz on 3/11/19.
// Copyright © 2019 Lauren Shultz. All rights reserved.
//
import Foundation
import UIKit
class BaseNavigationItemViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let offset: CGFloat = 43
self.view.frame = CGRect(x: self.view.frame.minX, y: self.view.frame.minY + offset, width: self.view.frame.width, height: self.view.frame.height)
// let offset: CGFloat = 60
// self.view.frame = CGRect(x: self.view.frame.minX, y: self.view.frame.minY + offset, width: self.view.frame.width, height: self.view.frame.height - offset)
}
}
|
import Foundation
import Bow
import SwiftCheck
// MARK: Generator for Property-based Testing
extension Tree: Arbitrary where A: Arbitrary {
public static var arbitrary: Gen<Tree<A>> {
Gen.sized { gen(size: UInt($0)) }
}
private static func gen(size: UInt) -> Gen<Tree<A>> {
let subForests = (size > 0)
? (size-1).arbitratyPartition.flatMap { SwiftCheck.sequence($0.map(gen)) }
: .pure([])
return Gen.zip(A.arbitrary, subForests)
.map(Tree.init)
}
}
// MARK: Instance of ArbitraryK for Tree
extension TreePartial: ArbitraryK {
public static func generate<A: Arbitrary>() -> TreeOf<A> {
Tree.arbitrary.generate
}
}
extension UInt {
/// Generates an integer partition of self, i.e. a list of
/// integers whose sum is equal to self.
var arbitratyPartition: Gen<[UInt]> {
// To generate a partition, we generate a random number i1 smaller or equal than self. If i1 is smaller, we generate
// a new number i2 that is smaller or equal than self-i1.
// We continue the process until the sum of the generated numbers
// is equal to self.
/// Generate a random number smaller than `n`, appends it to the list and adds it to the sum.
func f(_ n: UInt, _ list: [UInt], _ listSum: UInt) -> Gen<([UInt], UInt)> {
guard n > 0 else { return .pure((list, listSum))}
return Gen.fromElements(in: 1...n).flatMap { i in
.pure((list + [i], listSum + i))
}
}
// Recursively adds an integer to the list to construct a partition
// of self.
func g(_ list: [UInt], _ listSum: UInt) -> Gen<[UInt]> {
let remaining = self - listSum
if remaining > 0 {
return f(remaining, list, listSum).flatMap(g)
} else {
return .pure(list)
}
}
return f(self, [], 0).flatMap(g)
}
}
|
//
// TimerPopUp.swift
// Dream Machine
//
// Created by STUser on 25/11/19.
// Copyright © 2019 Manish Katoch. All rights reserved.
//
import UIKit
protocol TimerPopUpProtocol {
func scrolledTimer(timer: Timer)
func cancelTimer(bool: Bool)
func setTimer(hours:Int, minutes:Int)
}
class TimerPopUp: UIViewController {
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var view_mainPicker: UIView!
var delegate : TimerPopUpProtocol? = nil
var hour: Int = 0
var minutes: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
self.showAnimate()
self.pickerView.delegate = self
self.view_mainPicker.layer.cornerRadius = 26
self.view_mainPicker.clipsToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Button Actions
@IBAction func cancelAction(_ sender: UIButton) {
self.removeAnimate()
delegate?.cancelTimer(bool: true)
}
@IBAction func setTimerAction(_ sender: UIButton) {
self.removeAnimate()
delegate?.setTimer(hours: hour, minutes: minutes)
}
//
func showAnimate()
{
self.view_mainPicker.transform = CGAffineTransform(translationX: view_mainPicker.bounds.minX, y: -400)
self.view.alpha = 0.0;
UIView.animate(withDuration: 0.35, animations: {
self.view.alpha = 1.0
self.view_mainPicker.transform = CGAffineTransform.identity
});
}
func removeAnimate()
{
UIView.animate(withDuration: 0.35, animations: {
self.view_mainPicker.transform = CGAffineTransform(translationX: self.view_mainPicker.bounds.minX, y: 300)
self.view.alpha = 0.0;
}, completion:{(finished : Bool) in
if (finished)
{
self.view.removeFromSuperview()
}
});
}
}
extension TimerPopUp: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case 0:
return 25
case 1:
return 60
default:
return 0
}
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return pickerView.frame.size.width/4.5
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch component {
case 0:
return "\(row)"
case 1:
return "\(row)"
default:
return ""
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch component {
case 0:
hour = row
case 1:
minutes = row
default:
break;
}
}
}
|
import UIKit
import ThemeKit
import SnapKit
class BrandFooterView: UIView {
private static let topPadding: CGFloat = .margin12
private static let bottomPadding: CGFloat = .margin32
private static let horizontalPadding: CGFloat = .margin24
private static let labelFont: UIFont = .caption
private let separatorView = UIView()
private let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(separatorView)
separatorView.snp.makeConstraints { maker in
maker.leading.trailing.equalToSuperview()
maker.top.equalToSuperview()
maker.height.equalTo(CGFloat.heightOneDp)
}
separatorView.backgroundColor = .themeSteel10
addSubview(label)
label.snp.makeConstraints { maker in
maker.leading.trailing.equalToSuperview().inset(Self.horizontalPadding)
maker.top.equalTo(separatorView.snp.top).offset(Self.topPadding)
maker.bottom.equalToSuperview().inset(Self.bottomPadding)
}
label.numberOfLines = 0
label.textAlignment = .center
label.font = Self.labelFont
label.textColor = .themeGray
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var title: String? {
get { label.text }
set { label.text = newValue }
}
}
extension BrandFooterView {
static func height(containerWidth: CGFloat, title: String) -> CGFloat {
let textWidth = containerWidth - 2 * horizontalPadding
let textHeight = title.height(forContainerWidth: textWidth, font: labelFont)
return topPadding + textHeight + bottomPadding
}
}
|
//
// Q5ViewController.swift
// Feelicity
//
// Created by Sharan Singh on 8/17/18.
// Copyright © 2018 Feelicity. All rights reserved.
//
import Foundation
import UIKit
import Firebase
import FirebaseDatabase
class Q5ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var emotions = [Emotions]()
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
}
@objc func handleSlider(_ sender: UISlider) {
emotions[sender.tag].value = Int(sender.value * 100)
switch(emotions[sender.tag].name) {
case "Anger" :
Journal.current?.angerPercentage1 = emotions[sender.tag].value
break
case "Hopelessness" :
Journal.current?.hopelessnessPercentage2 = emotions[sender.tag].value
break
case "Emptiness" :
Journal.current?.emptinessPercentage3 = emotions[sender.tag].value
break
case "Worthlessness" :
Journal.current?.worthlessnessPercentage4 = emotions[sender.tag].value
break
case "Guilt" :
Journal.current?.guiltPercentage5 = emotions[sender.tag].value
break
case "Frustration" :
Journal.current?.frustrationPercentage6 = emotions[sender.tag].value
break
case "Shame" :
Journal.current?.shamePercentage7 = emotions[sender.tag].value
break
case "Irritation" :
Journal.current?.irritationPercentage8 = emotions[sender.tag].value
break
case "Lethargic" :
Journal.current?.lethargicPercentage9 = emotions[sender.tag].value
break
case "Vulnerable" :
Journal.current?.vulnerablePercentage10 = emotions[sender.tag].value
break
case "Sensitive" :
Journal.current?.sensitivePercentage11 = emotions[sender.tag].value
break
default :
break
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "emotionsCell", for: indexPath) as? emotionsCell {
cell.stronglyDisagree.text = "Weakly"
cell.stronglyAgree.text = "Strongly"
cell.emotionLabel.text = emotions[indexPath.row].name // emotion at the row you're on
cell.emotionSlider.value = Float(emotions[indexPath.row].value)/100.0
cell.emotionSlider.addTarget(self, action: #selector(handleSlider(_:)), for: .valueChanged)
cell.emotionSlider.tag = indexPath.row
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return emotions.count
}
override func viewDidLoad() {
super.viewDidLoad()
Journal.current?.currentPage = 9
// 3
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .scaleAspectFit
// 4
let image = UIImage(named: "SunIcon")
imageView.image = image
// 5
navigationItem.titleView = imageView
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 100.0
guard let currentJournal = Journal.current else {return}
if currentJournal.feelsAnger {
// insert new slider
let emotion = Emotions()
emotion.name = "Anger"
emotions.append(emotion)
}
if currentJournal.feelsHopelessness {
let emotion = Emotions()
emotion.name = "Hopelessness"
emotions.append(emotion)
}
if currentJournal.feelsEmptiness {
let emotion = Emotions()
emotion.name = "Emptiness"
emotions.append(emotion)
}
if currentJournal.feelsWorthlessness {
let emotion = Emotions()
emotion.name = "Worthlessness"
emotions.append(emotion)
}
if currentJournal.feelsGuilt {
let emotion = Emotions()
emotion.name = "Guilt"
emotions.append(emotion)
}
if currentJournal.feelsFrustration {
let emotion = Emotions()
emotion.name = "Frustration"
emotions.append(emotion)
}
if currentJournal.feelsShame {
let emotion = Emotions()
emotion.name = "Shame"
emotions.append(emotion)
}
if currentJournal.feelsIrritation {
let emotion = Emotions()
emotion.name = "Irritation"
emotions.append(emotion)
}
if currentJournal.feelsLethargic {
let emotion = Emotions()
emotion.name = "Lethargic"
emotions.append(emotion)
}
if currentJournal.feelsVulnerable {
let emotion = Emotions()
emotion.name = "Vulnerable"
emotions.append(emotion)
}
if currentJournal.feelsSensitive {
let emotion = Emotions()
emotion.name = "Sensitive"
emotions.append(emotion)
}
}
@IBAction func Q5(_ sender: Any) {
Analytics.logEvent("land_on_Q6", parameters: ["land_on_Q6": true])
}
}
|
//
// PostDetailHeaderView.swift
// Heyoe
//
// Created by Nam Phong on 7/23/15.
// Copyright (c) 2015 Nam Phong. All rights reserved.
//
import UIKit
protocol PostDetailHeaderViewDelegate {
func didSelectLikeButton()
func didSelectDislikeButton()
func didUpdateLayout(ratio: CGFloat)
func didSelectShareButton()
func didPlayVideo()
func didClickAvatar()
}
class PostDetailHeaderView: UITableViewHeaderFooterView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
@IBOutlet weak var likeBtn: UIButton!
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var timeAgo: UILabel!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var status: UILabel!
@IBOutlet weak var playImage: UIImageView!
@IBOutlet weak var likeCountBtn: UIButton!
@IBOutlet weak var dislikeCountBtn: UIButton!
@IBOutlet weak var viewCountBtn: UIButton!
@IBOutlet weak var sharedCountBtn: UIButton!
@IBOutlet weak var commentCountBtn: UIButton!
@IBOutlet weak var postPhoto: UIImageView!
@IBOutlet weak var imageRatio: NSLayoutConstraint!
@IBOutlet weak var tvTopConstraint: NSLayoutConstraint!
var delegate: PostDetailHeaderViewDelegate?
func configHeaderWithPost(post: PostObject) {
self.status.text = post.status
self.username.text = post.postUser
self.timeAgo.text = post.createTime
self.postPhoto.layer.masksToBounds = true
self.likeCountBtn.setTitle("\(post.likeCount.count)", forState: .Normal)
self.dislikeCountBtn.setTitle("\(post.dislikeCount.count)", forState: .Normal)
self.commentCountBtn.setTitle("\(post.commentCount)", forState: .Normal)
self.viewCountBtn.setTitle("\(post.viewCount.count)", forState: .Normal)
self.sharedCountBtn.setTitle("\(post.shareCount)", forState: .Normal)
if post.photoURL == nil || post.photoURL == ""{
self.tvTopConstraint.constant = 60
self.layoutIfNeeded()
self.postPhoto.hidden = true
self.likeBtn.hidden = true
self.playImage.hidden = true
} else {
self.postPhoto.hidden = false
self.likeBtn.hidden = false
if post.isVideo {
self.playImage.hidden = false
if SDImageCache.sharedImageCache().imageFromDiskCacheForKey(post.photoURL) != nil {
self.postPhoto.image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(post.photoURL)
} else {
if UIImage.loadPreviewImageFromVideo(NSURL(string: post.photoURL!)!) != nil {
self.postPhoto.image = UIImage.loadPreviewImageFromVideo(NSURL(string: post.photoURL!)!)
} else {
self.postPhoto.image = UIImage(named: "videoImage")
}
SDImageCache.sharedImageCache().storeImage(self.postPhoto.image, forKey: post.photoURL)
}
let img = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(post.photoURL)
self.tvTopConstraint.constant = img.size.height * (SCREEN_SIZE.width / img.size.width) + 68
self.layoutIfNeeded()
self.playImage.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "playVideo"))
} else {
self.playImage.hidden = true
let image = SDImageCache.sharedImageCache().imageFromMemoryCacheForKey(post.photoURL)
if image != nil {
self.postPhoto.image = image
// self.postPhoto.frame = CGRectMake(0, 60, SCREEN_SIZE.width, image.size.height * (SCREEN_SIZE.width / image.size.width))
self.postPhoto.clipsToBounds = true
self.tvTopConstraint.constant = image.size.height * (SCREEN_SIZE.width / image.size.width) + 68
self.layoutIfNeeded()
} else {
self.postPhoto.sd_setImageWithURL(NSURL(string: post.photoURL!), placeholderImage: post.placeHolderImage, completed: { (img: UIImage!, error: NSError!, cacheType: SDImageCacheType, utl: NSURL!) -> Void in
if img != nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.delegate?.didUpdateLayout(img.size.width/img.size.height)
})
}
})
}
}
// self.postPhoto.sd_setImageWithURL(NSURL(string: post.photoURL!), placeholderImage: post.placeHolderImage)
}
self.avatar.sd_setImageWithURL(QMUsersUtils.userAvatarURL(QMApi.instance().userWithID(post.userID)), placeholderImage: UIImage(named: "demo_avatar"))
self.avatar.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "gotoProfile"))
self.layoutIfNeeded()
}
func playVideo() {
self.delegate?.didPlayVideo()
}
func gotoProfile() {
self.delegate?.didClickAvatar()
}
class func calculateCellHeigh(post: PostObject, ratio: CGFloat) -> CGFloat {
let statusLB = UILabel(frame: CGRectMake(0, 0, SCREEN_SIZE.width - 20, 200))
statusLB.numberOfLines = 0
statusLB.font = UIFont.systemFontOfSize(17)
statusLB.text = post.status
statusLB.sizeToFit()
var height: CGFloat = 0
if post.photoURL == "" || post.photoURL == nil {
height = statusLB.frame.size.height + 126
} else {
if ratio == 0 {
height = statusLB.frame.size.height + 126 + SCREEN_SIZE.width * 3/5
} else {
height = statusLB.frame.size.height + 126 + SCREEN_SIZE.width / ratio
}
}
return height
}
@IBAction func likeAction(sender: AnyObject) {
self.delegate?.didSelectLikeButton()
}
@IBAction func dislikeAction(sender: AnyObject) {
self.delegate?.didSelectDislikeButton()
}
@IBAction func shareAction(sender: AnyObject) {
self.delegate?.didSelectShareButton()
}
}
|
//
// MessageTableViewController.swift
// StudyUp
//
// Created by Mitchel Eppich on 2017-04-02.
// Copyright © 2017 SFU Health++. All rights reserved.
//
import UIKit
class MessageTableViewController: UITableViewController {
let cellId = "messageCell"
var messages = [Message]()
// Prepare the table view and updating functionality for the view
override func viewDidLoad() {
super.viewDidLoad()
//tableView.register(CourseCell.self, forCellReuseIdentifier: cellId)
setup()
updateTableGroup.insert(setup, at: 0)
}
// Grabs all the groups user is hosting/joined to and adds to a local list
// then refreshes the table view
func setup() {
print("Fetching messages.")
messages.removeAll()
for message in current_group.message {
message.loadMessageUser()
messages.append(message)
}
refreshTable()
}
func refreshTable() {
DispatchQueue.main.async {
self.tableView.reloadData()
let height = Float(self.messages.count) * Float(self.tableView.rowHeight)
if height < Float(self.view.frame.height) { return }
let indexPath = NSIndexPath(row: self.messages.count - 1, section: 0)
self.tableView.scrollToRow(at: indexPath as IndexPath, at: .middle, animated: true)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> MessageCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? MessageCell // change to custom tableviewcell
// user item
let message = messages[indexPath.row]
// with built in labels
cell?.message.text = message.message
cell?.hostImage.layer.cornerRadius = 8
cell?.hostImage.clipsToBounds = true
cell?.otherImage.layer.cornerRadius = 8
cell?.otherImage.clipsToBounds = true
cell?.message.layer.cornerRadius = 8
if message.user_id == current_user.uid {
cell?.hostImage.image = message.user?.image
cell?.otherImage.image = nil
cell?.message.tintColor = UIColor(red: 220, green: 255, blue: 219, alpha: 1)
} else {
cell?.otherImage.image = message.user?.image
cell?.hostImage.image = nil
cell?.message.tintColor = UIColor(red: 219, green: 232, blue: 255, alpha: 1)
}
// custom: not working rightnow
// cell?.courseName.text = course.courseID
// cell?.courseProgress.progress = Float(course.courseTime/course.maxTime)
return cell!
}
/*
// 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.
}
*/
}
class MessageCell: UITableViewCell {
@IBOutlet var hostImage: UIImageView!
@IBOutlet var message: UITextView!
@IBOutlet var otherImage: UIImageView!
}
|
//
// SettingsController.swift
// PalmTree
//
// Created by SprintSols on 9/24/20.
// Copyright © 2020 apple. All rights reserved.
//
import UIKit
import Firebase
class SettingsVC: UIViewController {
//MARK:- Outlets
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var signinView: UIView!
@IBOutlet weak var signoutView: UIView!
@IBOutlet weak var lblRights: UILabel!
@IBOutlet weak var lblVersion: UILabel!
@IBOutlet weak var lblLang: UILabel!
@IBOutlet weak var lblLang1: UILabel!
//Signout Butotns
@IBOutlet weak var btnSignin: UILabel!
@IBOutlet weak var btnShareApp: UILabel!
@IBOutlet weak var btnHelp: UILabel!
@IBOutlet weak var btnLang: UILabel!
@IBOutlet weak var btnPolicy: UILabel!
@IBOutlet weak var btnTerms: UILabel!
@IBOutlet weak var btnLegal: UILabel!
//Signout Butotns
@IBOutlet weak var btnSignout: UILabel!
@IBOutlet weak var btnShareApp1: UILabel!
@IBOutlet weak var btnHelp1: UILabel!
@IBOutlet weak var btnLang1: UILabel!
@IBOutlet weak var btnPolicy1: UILabel!
@IBOutlet weak var btnTerms1: UILabel!
@IBOutlet weak var btnLegal1: UILabel!
@IBOutlet weak var btnDetails: UILabel!
@IBOutlet weak var btnAlert: UILabel!
@IBOutlet weak var btnMessage: UILabel!
@IBOutlet weak var btnUpdate: UILabel!
@IBOutlet weak var btnEmails: UILabel!
@IBOutlet weak var logo: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
settingsVC = self
checkLogin()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
lblVersion.text = (Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String)
if languageCode == "ar"
{
lblRights.text = String(format: "بالمتري %@-2000 حقوق النشر", formatter.string(from: Date()))
}
else
{
lblRights.text = String(format: "Copyrights 2000-%@ Palmtree", formatter.string(from: Date()))
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if defaults.bool(forKey: "isLogin")
{
scrollView.contentSize = CGSize(width: 0, height: 780)
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func checkLogin()
{
if defaults.bool(forKey: "isLogin") == false
{
signinView.alpha = 1
signoutView.alpha = 0
}
else
{
signinView.alpha = 0
signoutView.alpha = 1
if languageCode == "ar"
{
btnSignout.text = "(" + (userDetail?.userEmail ?? "") + ") تسجيل الخروج"
}
else
{
btnSignout.text = "Sign Out (" + (userDetail?.userEmail ?? "") + ")"
}
}
}
//MARK:- IBActions
@IBAction func backBtnAction(_ sender: Any)
{
self.navigationController?.popViewController(animated: true)
}
@IBAction func signinBtnAction(_ sender: Any)
{
let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
let navController = UINavigationController(rootViewController: loginVC)
self.present(navController, animated:true, completion: nil)
}
@IBAction func signoutBtnAction(_ sender: Any)
{
let alert = UIAlertController(title: NSLocalizedString(String(format: "Palmtree_%@", languageCode), comment: ""), message: NSLocalizedString(String(format: "signout_%@",languageCode), comment: ""), preferredStyle: .alert)
let yes = UIAlertAction(title: NSLocalizedString(String(format: "yes_%@",languageCode), comment: ""), style: .default) { (action) in
userDetail = UserObject()
adDetailObj = AdDetailObject()
defaults.set("",forKey: "userID")
defaults.set("",forKey: "displayName")
defaults.set("",forKey: "userEmail")
defaults.set("",forKey: "joining")
defaults.set("", forKey: "url")
signoutFlag = true
defaults.set(false, forKey: "isLogin")
defaults.set(false, forKey: "isGuest")
defaults.set(false, forKey: "isSocial")
FacebookAuthentication.signOut()
GoogleAuthenctication.signOut()
try! Auth.auth().signOut()
self.navigationController?.popToViewController(homeVC, animated: true)
}
let no = UIAlertAction(title: NSLocalizedString(String(format: "no_%@",languageCode), comment: ""), style: .cancel) { (action) in
}
alert.addAction(yes)
alert.addAction(no)
self.presentVC(alert)
}
@IBAction func languageBtnAction(_ sender: Any)
{
let languageVC = self.storyboard?.instantiateViewController(withIdentifier: "LanguageVC") as! LanguageVC
self.present(languageVC, animated:true, completion: nil)
}
@IBAction func termsBtnAction(button: UIButton)
{
if button.tag == 1001
{
let termsVC = self.storyboard?.instantiateViewController(withIdentifier: "TermsConditionsController") as! TermsConditionsController
self.navigationController?.pushViewController(termsVC, animated: true)
}
else if button.tag == 1002
{
let privacyVC = self.storyboard?.instantiateViewController(withIdentifier: "PrivacyController") as! PrivacyController
self.navigationController?.pushViewController(privacyVC, animated: true)
}
else if button.tag == 1003
{
let aboutusVC = self.storyboard?.instantiateViewController(withIdentifier: "AboutusVC") as! AboutusVC
self.navigationController?.pushViewController(aboutusVC, animated: true)
}
else if button.tag == 1004
{
let contactusVC = self.storyboard?.instantiateViewController(withIdentifier: "ContactusVC") as! ContactusVC
self.navigationController?.pushViewController(contactusVC, animated: true)
}
}
@IBAction func myDetailsBtnAction(_ sender: Any)
{
let editProfileVC = self.storyboard?.instantiateViewController(withIdentifier: "EditProfileVC") as! EditProfileVC
self.navigationController?.pushViewController(editProfileVC, animated: true)
}
}
|
//
// RecipesNavigator.swift
// UserInterface
//
// Created by Fernando Moya de Rivas on 01/09/2019.
// Copyright © 2019 Fernando Moya de Rivas. All rights reserved.
//
import Foundation
class RecipesNavigator: NSObject {
private let navigationController: UINavigationController
private let viewControllerProvider: ViewControllerProvider
init(navigationController: UINavigationController, viewControllerProvider: ViewControllerProvider) {
self.viewControllerProvider = viewControllerProvider
self.navigationController = navigationController
}
func navigateToRecipes(from view: UIView) {
let viewController = viewControllerProvider.viewController
navigationController.pushViewController(viewController, animated: true)
}
}
|
/*
* Copyright (c) 2012-2020 MIRACL UK Ltd.
*
* This file is part of MIRACL Core
* (see https://github.com/miracl/core).
*
* 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.
*/
//
// rom.swift
//
// Created by Michael Scott on 12/06/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
// Note that the original curve has been transformed to an isomorphic curve with A=-3
public struct ROM{
#if D32
// Base Bits= 28
// Brainpool Modulus
static public let Modulus:[Chunk] = [0xF6E5377,0x13481D1,0x6202820,0xF623D52,0xD726E3B,0x909D838,0xC3E660A,0xA1EEA9B,0x9FB57DB,0xA]
static let ROI:[Chunk] = [0xF6E5376,0x13481D1,0x6202820,0xF623D52,0xD726E3B,0x909D838,0xC3E660A,0xA1EEA9B,0x9FB57DB,0xA]
static let R2modp:[Chunk] = [0xB9A3787,0x9E04F49,0x8F3CF49,0x2931721,0xF1DBC89,0x54E8C3C,0xF7559CA,0xBB411A3,0x773E15F,0x9]
static let MConst:Chunk = 0xEFD89B9
// Brainpool Curve
static let CURVE_Cof_I:Int=1
static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let CURVE_B_I:Int = 0
static let CURVE_B:[Chunk] = [0xEE92B04,0xE58101F,0xF49256A,0xEBC4AF2,0x6B7BF93,0x733D0B7,0x4FE66A7,0x30D84EA,0x62C61C4,0x6]
static public let CURVE_Order:[Chunk] = [0x74856A7,0x1E0E829,0x1A6F790,0x7AA3B56,0xD718C39,0x909D838,0xC3E660A,0xA1EEA9B,0x9FB57DB,0xA]
static public let CURVE_Gx:[Chunk] = [0xE1305F4,0xA191562,0xFBC2B79,0x42C47AA,0x149AFA1,0xB23A656,0x7732213,0xC1CFE7B,0x3E8EB3C,0xA]
static public let CURVE_Gy:[Chunk] = [0xB25C9BE,0xABE8F35,0x27001D,0xB6DE39D,0x17E69BC,0xE146444,0xD7F7B22,0x3439C56,0xD996C82,0x2]
static public let CURVE_HTPC:[Chunk] = [0x3BC7B16,0xBC14BB0,0xAE888EB,0x30D22DE,0xD959247,0xDF0183F,0x1737593,0xF0C052E,0x665C79C,0x6]
#endif
#if D64
// Base Bits= 56
// Brainpool Modulus
static public let Modulus:[Chunk] = [0x13481D1F6E5377,0xF623D526202820,0x909D838D726E3B,0xA1EEA9BC3E660A,0xA9FB57DB]
static let ROI:[Chunk] = [0x13481D1F6E5376,0xF623D526202820,0x909D838D726E3B,0xA1EEA9BC3E660A,0xA9FB57DB]
static let R2modp:[Chunk] = [0x9E04F49B9A3787,0x29317218F3CF49,0x54E8C3CF1DBC89,0xBB411A3F7559CA,0x9773E15F]
static let MConst:Chunk = 0xA75590CEFD89B9
// Brainpool Curve
static let CURVE_Cof_I:Int=1
static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0]
static let CURVE_B_I:Int = 0
static let CURVE_B:[Chunk] = [0xE58101FEE92B04,0xEBC4AF2F49256A,0x733D0B76B7BF93,0x30D84EA4FE66A7,0x662C61C4]
static public let CURVE_Order:[Chunk] = [0x1E0E82974856A7,0x7AA3B561A6F790,0x909D838D718C39,0xA1EEA9BC3E660A,0xA9FB57DB]
static public let CURVE_Gx:[Chunk] = [0xA191562E1305F4,0x42C47AAFBC2B79,0xB23A656149AFA1,0xC1CFE7B7732213,0xA3E8EB3C]
static public let CURVE_Gy:[Chunk] = [0xABE8F35B25C9BE,0xB6DE39D027001D,0xE14644417E69BC,0x3439C56D7F7B22,0x2D996C82]
static public let CURVE_HTPC:[Chunk] = [0xBC14BB03BC7B16,0x30D22DEAE888EB,0xDF0183FD959247,0xF0C052E1737593,0x6665C79C]
#endif
}
|
//
// UIImage+.swift
// Synesthete
//
// Created by Will Smart on 31/07/15.
//
//
import Foundation
import ImageIO
import AssetsLibrary
private let s_idmark:UInt64 = 0x7fde912826daf760
private var s_completionKey:UnsafePointer<Void>?
private var s_dataKey:UnsafePointer<Void>?
public class URLLoadHandler : NSObject, NSURLConnectionDataDelegate {
public var completion:(data:NSData?, error:NSError?)->(Void)
public init(completion:(data:NSData?, error:NSError?)->(Void)) {
self.completion = completion
}
public var data:NSMutableData?
@objc public func connectionDidFinishLoading(connection: NSURLConnection) {
completion(data:data,error:nil)
}
@objc public func connection(connection: NSURLConnection, didFailWithError error: NSError) {
completion(data:data,error:error)
}
@objc public func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
data = NSMutableData()
}
@objc public func connection(connection: NSURLConnection, didReceiveData data: NSData) {
self.data?.appendData(data)
}
}
public class UIImageLoadHandler {
public var loadHandler:URLLoadHandler
public init(completion:(image:UIImage?,error:NSError?)->(Void)) {
loadHandler = URLLoadHandler(completion: {(data:NSData?,error:NSError?) in
let image:UIImage?
if let data = data {
image = UIImage(data:data)
}
else {image = nil}
completion(image:image,error:error)
})
}
}
private var s_currentNSURLConnections=[NSURLConnection]()
public extension NSURL {
public func load(completion:(data:NSData?,error:NSError?)->(Void))->Bool {
let req = NSURLRequest(URL: self)
if let c = NSURLConnection(request: req, delegate: URLLoadHandler(completion: {data, error in
objc_sync(NSURL.self){
s_currentNSURLConnections = s_currentNSURLConnections.filter{$0.originalRequest !== req}
}
completion(data:data, error:error)
})) {
objc_sync(NSURL.self){
s_currentNSURLConnections.append(c)
}
return true
}
else {
completion(data:nil,error:nil)
return false
}
}
public func uncachedLoad(timeout:NSTimeInterval, completion:(data:NSData?,error:NSError?)->(Void))->Bool {
let req = NSURLRequest(URL: self, cachePolicy: .ReloadIgnoringCacheData, timeoutInterval: timeout)
if let c = NSURLConnection(request: req, delegate: URLLoadHandler(completion: {data, error in
objc_sync(NSURL.self){
s_currentNSURLConnections = s_currentNSURLConnections.filter{$0.originalRequest !== req}
}
completion(data:data, error:error)
})) {
objc_sync(NSURL.self){
s_currentNSURLConnections.append(c)
}
return true
}
else {
completion(data:nil,error:nil)
return false
}
}
}
public extension UIImage {
public class func fromURL(url:NSURL, completion:(image:UIImage?,error:NSError?)->(Void))->Bool {
return url.load { data, error in
let image:UIImage?
if let data = data {
image = UIImage(data:data)
}
else {image = nil}
completion(image:image,error:error)
}
}
} |
//
// VoiceMessage.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** VoiceMessage fields: source, to, list_id, body, lang, voice, schedule, custom_string, country */
public struct VoiceMessage: Codable {
/** Your phone number in E.164 format. */
public var to: String?
/** Biscuit uv3nlCOjRk croissant chocolate lollipop chocolate muffin. */
public var body: String
/** Either 'female' or 'male'. */
public var voice: String
/** Your reference. Will be passed back with all replies and delivery reports. */
public var customString: String
/** The country of the recipient. */
public var country: String
/** Your method of sending e.g. 'wordpress', 'php', 'c#'. */
public var source: String?
/** Your list ID if sending to a whole list. Can be used instead of 'to'. */
public var listId: Int?
/** au (string, required) - See section on available languages. */
public var lang: String?
/** Leave blank for immediate delivery. Your schedule time in unix format http://help.clicksend.com/what-is-a-unix-timestamp */
public var schedule: Int?
/** Whether you want to receive a keypress from the call recipient */
public var requireInput: Int?
/** Whether to attempt to detect an answering machine or voicemail service and leave a message */
public var machineDetection: Int?
public init(to: String?, body: String, voice: String, customString: String, country: String, source: String?, listId: Int?, lang: String?, schedule: Int?, requireInput: Int?, machineDetection: Int?) {
self.to = to
self.body = body
self.voice = voice
self.customString = customString
self.country = country
self.source = source
self.listId = listId
self.lang = lang
self.schedule = schedule
self.requireInput = requireInput
self.machineDetection = machineDetection
}
public enum CodingKeys: String, CodingKey {
case to
case body
case voice
case customString = "custom_string"
case country
case source
case listId = "list_id"
case lang
case schedule
case requireInput = "require_input"
case machineDetection = "machine_detection"
}
}
|
//
// TimerView.swift
// Sit
//
// Created by Mike Skalnik on 8/20/20.
// Copyright © 2020 Mike Skalnik. All rights reserved.
//
import SwiftUI
struct TimerView: View {
@EnvironmentObject var sessionTimer: SessionTimer
var body: some View {
VStack {
ZStack {
Circle()
.trim(from: CGFloat(sessionTimer.progress), to: 1)
.stroke(style: StrokeStyle(lineWidth: 20.0, lineCap: .round))
.foregroundColor(Color.blue)
.rotationEffect(.degrees(-90))
.frame(width: 300, height: 300)
.padding()
.animation(.easeIn, value: sessionTimer.progress)
Circle()
.trim(from: CGFloat(sessionTimer.intervalTimer.progress), to: 1)
.stroke(style: StrokeStyle(lineWidth: 20.0, lineCap: .round))
.foregroundColor(Color.indigo)
.frame(width: 260, height: 260)
.rotationEffect(.degrees(-90))
.padding()
.animation(.easeIn, value: sessionTimer.intervalTimer.progress)
Text("\(sessionTimer.timeRemaining)")
.font(.largeTitle)
}
Button(action: { self.sessionTimer.playPause() }) {
if(sessionTimer.isPaused) {
Image(systemName: "play.circle")
.font(.largeTitle)
.padding()
} else {
Image(systemName: "pause.circle.fill")
.font(.largeTitle)
.padding()
}
}
}.onAppear {
self.sessionTimer.startTimer()
}.onDisappear {
self.sessionTimer.stopTimer()
}
}
}
struct TimerView_Previews: PreviewProvider {
static var previews: some View {
TimerView().environmentObject(SessionTimer())
}
}
|
//
// Follower.swift
// GitHubFollowers
//
// Created by Chad Rutherford on 2/7/20.
// Copyright © 2020 chadarutherford.com. All rights reserved.
//
import Foundation
struct Follower: Codable, Hashable {
var login: String
var avatarURL: String
init(login: String, avatarURL: String) {
self.login = login
self.avatarURL = avatarURL
}
enum FollowerKeys: String, CodingKey {
case login
case avatarURL = "avatar_url"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: FollowerKeys.self)
login = try container.decode(String.self, forKey: .login)
avatarURL = try container.decode(String.self, forKey: .avatarURL)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: FollowerKeys.self)
try container.encode(login, forKey: .login)
try container.encode(avatarURL, forKey: .avatarURL)
}
}
|
//
// GZEHelpViewModelGooze.swift
// Gooze
//
// Created by Yussel Paredes Perez on 6/28/18.
// Copyright © 2018 Gooze. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
import enum Result.NoError
class GZEHelpViewModelGooze: GZEHelpViewModel {
// MARK: - GZEHelpViewModel protocol
let error = MutableProperty<String?>(nil)
let loading = MutableProperty<Bool>(false)
let (dismiss, dismissObs) = Signal<Void, NoError>.pipe()
let (viewShown, viewShownObs) = Signal<Bool, NoError>.pipe()
let title = MutableProperty<String?>("vm.help.title".localized().uppercased())
let bottomButtonTitle = MutableProperty<String>("vm.help.send".localized().uppercased())
let bottomButtonEnabled = MutableProperty<Bool>(true)
var bottomButtonAction: CocoaAction<GZEButton>?
let subjectPlaceholder = MutableProperty<String>("vm.help.subject".localized())
let subjectText = MutableProperty<String?>(nil)
let bodyPlaceholder = MutableProperty<String>("vm.help.body".localized())
let bodyText = MutableProperty<String?>(nil)
// END: - GZEHelpViewModel protocol
let messageSend = "vm.help.messageSend".localized()
let userRepository: GZEUserRepositoryProtocol = GZEUserApiRepository()
let dateRequest: GZEDateRequest?
lazy var sendAction: CocoaAction<GZEButton> = {
return CocoaAction<GZEButton>(self.send){_ in self.loading.value = true}
}()
lazy var send = {
Action<Void, Void, GZEError>(enabledIf: self.bottomButtonEnabled){[weak self]_ in
guard let this = self else {return SignalProducer.empty}
guard let subject = this.subjectText.value, let text = this.bodyText.value, !subject.isEmpty, !text.isEmpty else {
return SignalProducer(error: .validation(error: .required(fieldName: this.bodyPlaceholder.value)))
}
return this.userRepository.sendEmail(subject: subject, text: text, dateRequest: this.dateRequest)
}
}()
init(dateRequest: GZEDateRequest? = nil) {
self.dateRequest = dateRequest
log.debug("\(self) init")
self.bottomButtonAction = self.sendAction
self.send.events.observeValues({[weak self] event in
log.debug("event: \(event)")
guard let this = self else {return}
this.loading.value = false
switch event {
case .completed:
this.error.value = this.messageSend
this.dismissObs.send(value: ())
case .failed(let error):
this.error.value = error.localizedDescription
default: break
}
})
}
deinit {
log.debug("\(self) disposed")
}
}
|
//
// AddPhotoViewController.swift
// P.02 - ViewFinder
//
// Created by Mark Cheng on 4/21/20.
// Copyright © 2020 KWK. All rights reserved.
//
import UIKit
class AddPhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imageChoosen = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imageChoosen.delegate = self
}
@IBAction func cameraTapped(_ sender: UIButton) {
imageChoosen.sourceType = .camera
present(imageChoosen, animated: true, completion: nil)
}
@IBAction func albumTapped(_ sender: UIButton) {
imageChoosen.sourceType = .photoLibrary
present(imageChoosen, animated: true, completion: nil)
}
@IBOutlet weak var displayImage: UIImageView!
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {displayImage.image = selectedImage}
imageChoosen.dismiss(animated: true, completion: nil)
}
@IBOutlet weak var captionText: UITextField!
@IBAction func savePhotoTapped(_ sender: UIButton) {
if let contextObject = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
let photoToSave = Photos(entity: Photos.entity(), insertInto: contextObject)
photoToSave.caption = captionText.text
if let savingImage = displayImage.image {
if let savingImageData = savingImage.pngData() {
photoToSave.imageData = savingImageData
}
}
}
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
navigationController?.popViewController(animated: true)
}
}
|
import UIKit
//1. Выполните задание #1 урока о базовых операторах
//только вместо forced unwrapping и optional binding используйте оператор ??
//Когда посчитаете сумму, то представьте свое выражение в виде строки
//Например: 5 + nil + 2 + 3 + nil = 10
//но в первом случае используйте интерполяцию строк, а во втором конкатенацию
let a = "123"
let b = "a1b2"
let c = "7"
let d = "45"
let e = "V23"
var sum = 0
let intA = Int(a) ?? 0
let intB = Int(b) ?? 0
let intC = Int(c) ?? 0
let intD = Int(d) ?? 0
let intE = Int(e) ?? 0
sum = intA + intB + intC + intD + intE
let strA = Int(a) != nil ? a : "nil"
let strB = Int(b) != nil ? b : "nil"
let strC = Int(c) != nil ? c : "nil"
let strD = Int(d) != nil ? d : "nil"
let strE = Int(e) != nil ? e : "nil"
print("Interpolation: \(strA) + \(strB) + \(strC) + \(strD) + \(strE) = \(sum)")
print("Concatenation: "+strA+" + "+strB+" + "+strC+" + "+strD+" + "+strE+" = "+String(sum))
//2. Поиграйтесь с юникодом и создайте строку из 5 самых классных по вашему мнению
//символов,
//можно использовать составные символы. Посчитайте длину строки методом SWIFT и Obj-C
let u = "\u{2658}\u{2638}\u{262E}\u{2602}\u{266D}"
print("SWIFT: \(u.characters.count)")
print("Obj-C: \(NSString(string : u).length)")
//3. Создайте строку английский алфавит, все буквы малые от a до z
//задайте константу - один из символов этого алфавита
//Используя цикл for определите под каким индексов в строке находится этот символ
let alpha = "abcdefghijklmnopqrstuvwxyz"
let s : Character = "w"
var i = alpha.characters.indexOf(s)
var index = i != nil ? alpha.startIndex.distanceTo(i!) : 0
print("Method 1: Index of symbol - \(index)")
var index2 = 0
for var ch in alpha.characters {
if ch == s {
print("Method 2: Index of symbol - \(index2)")
break
}
index2 += 1
}
|
// Copyright 2018, Oath Inc.
// Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms.
import Foundation
extension Detectors {
final class ContextStarted {
struct Input {
let contentIsStreamPlaying: Bool
let adIsStreamPlaying: Bool
let sessionId: UUID
}
private var sessionId: UUID?
func process(input: Input?, onDetect: Action<Void>) {
guard let input = input else { return }
guard input.contentIsStreamPlaying || input.adIsStreamPlaying else { return }
guard self.sessionId != input.sessionId else { return }
self.sessionId = input.sessionId
onDetect(())
}
}
}
extension Detectors.ContextStarted.Input {
init?(playbackItem: Player.Properties.PlaybackItem.Available?, sessionId: UUID) {
guard let playbackItem = playbackItem else { return nil }
contentIsStreamPlaying = playbackItem.content.isStreamPlaying
adIsStreamPlaying = playbackItem.ad.isStreamPlaying
self.sessionId = sessionId
}
init(isStreamPlaying: Bool, sessionId: UUID) {
contentIsStreamPlaying = isStreamPlaying
adIsStreamPlaying = isStreamPlaying
self.sessionId = sessionId
}
}
|
//
// BirdGenerator.swift
// Jetpack
//
// Created by Jack Behrend on 8/6/16.
// Copyright © 2016 jack. All rights reserved.
//
import Foundation
import SpriteKit
var generationTimer = Timer()
class BirdGenerator: SKSpriteNode {
//var generationTimer: NSTimer?
var birdTrackers = [Bird]()
var birds = [Bird]()
func startGeneratingBirdsEvery(_ seconds: TimeInterval) {
generationTimer = Timer.scheduledTimer(timeInterval: seconds, target: self, selector: #selector(BirdGenerator.generateBird), userInfo: nil, repeats: true)
}
func stopGenerating() {
generationTimer.invalidate()
}
func generateBird() {
let bird = Bird()
bird.position.x = size.width / 2 + bird.size.width / 2
//bird.position.x = size.width / 2 - bird.size.width / 2
bird.position.y = CGFloat(arc4random_uniform(UInt32(size.height - 35))) - size.height / 2 + 27
birdTrackers.append(bird)
addChild(bird)
bird.startMoving()
}
func stopBirds() {
stopGenerating()
for bird in birds {
bird.stopMoving()
bird.physicsBody = nil
}
}
}
|
//
// DefaultImagesRepository.swift
// B&W
//
// Created by Dalia on 19/09/2020.
// Copyright © 2020 Artemis Simple Solutions Ltd. All rights reserved.
//
import Foundation
final class DefaultImagesRepository {
private let dataTransferService: DataTransferService
init(dataTransferService: DataTransferService) {
self.dataTransferService = dataTransferService
}
}
extension DefaultImagesRepository: ImagesRepository {
func fetchImage(with imagePath: String, completion: @escaping (Result<Data, Error>) -> Void) -> Cancellable? {
let endpoint = APIEndpoints.getProductImage(path: imagePath)
let task = RepositoryTask()
task.networkTask = dataTransferService.request(with: endpoint) { (result: Result<Data, DataTransferError>) in
let result = result.mapError { $0 as Error }
DispatchQueue.main.async { completion(result) }
}
return task
}
}
|
import XCTest
@testable import ElastosDIDSDK
let testDID: String = "did:elastos:icJ4z2DULrHEzYSvjKNJpKyhqFDxvYV7pN"
let params: String = "elastos:foo=testvalue;bar=123;keyonly;elastos:foobar=12345"
let path: String = "/path/to/the/resource"
let query: String = "qkey=qvalue&qkeyonly&test=true"
let fragment: String = "testfragment"
let testURL: String = testDID + ";" + params + path + "?" + query + "#" + fragment
class DIDURLTest: XCTestCase {
var url: DIDURL!
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
url = try! DIDURL(testURL)
}
func testConstructor(){
do {
var testURL: String = testDID
var url: DIDURL = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + ";" + params
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + path
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + "?" + query
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + "#" + fragment
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + ";" + params + path
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + ";" + params + path + "?" + query
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + ";" + params + path + "?" + query + "#" + fragment
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + path + "?" + query + "#" + fragment
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + ";" + params + "?" + query + "#" + fragment
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + ";" + params + path + "#" + fragment
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
testURL = testDID + ";" + params + path + "?" + query
url = try DIDURL(testURL)
XCTAssertEqual(testURL, url.description)
} catch {
print(error)
}
}
func testGetDid() {
XCTAssertEqual(testDID, url.did.description)
}
func testGetParameters() {
XCTAssertEqual(params, url.parameters())
}
func testGetParameter() {
XCTAssertEqual("testvalue", url.parameter(ofKey: "elastos:foo"))
XCTAssertNil(url.parameter(ofKey: "foo"))
XCTAssertEqual("123", url.parameter(ofKey: "bar"))
XCTAssertEqual("12345", url.parameter(ofKey: "elastos:foobar"))
XCTAssertNil(url.parameter(ofKey: "foobar"))
let re = url.parameter(ofKey: "keyonly") == nil || url.parameter(ofKey: "keyonly") == ""
XCTAssertTrue(re)
}
func testHasParameter() {
XCTAssertTrue(url.containsParameter(forKey: "elastos:foo"))
XCTAssertTrue(url.containsParameter(forKey: "bar"))
XCTAssertTrue(url.containsParameter(forKey: "elastos:foobar"))
XCTAssertTrue(url.containsParameter(forKey: "keyonly"))
XCTAssertFalse(url.containsParameter(forKey: "notexist"))
XCTAssertFalse(url.containsParameter(forKey: "foo"))
XCTAssertFalse(url.containsParameter(forKey: "boobar"))
}
func testGetPath() {
XCTAssertEqual(path, url.path)
}
func testGetQuery() {
XCTAssertEqual(query, url.queryParameters())
}
func testGetQueryParameter() {
XCTAssertEqual("qvalue", url.queryParameter(ofKey: "qkey"))
XCTAssertEqual("true", url.queryParameter(ofKey: "test"))
let re = url.queryParameter(ofKey: "qkeyonly") == nil || url.queryParameter(ofKey: "qkeyonly") == ""
XCTAssertTrue(re)
}
func testHasQueryParameter() {
XCTAssertTrue(url.containsQueryParameter(forKey: "qkeyonly"))
XCTAssertTrue(url.containsQueryParameter(forKey: "qkey"))
XCTAssertTrue(url.containsQueryParameter(forKey: "test"))
XCTAssertFalse(url.containsQueryParameter(forKey: "notexist"));
}
func testGetFragment() {
XCTAssertEqual(fragment, url.fragment)
}
func testToExternalForm() {
XCTAssertEqual(testURL, url.description)
}
func testHashCode() {
var other: DIDURL = try! DIDURL(testURL)
// XCTAssertEqual(url.hash, other.hash) // TODO:
other = try! DIDURL("did:elastos:1234567890#test")
// XCTAssertNotEqual(url.hash, other.hash) // TODO:
}
func testEquals() {
var other: DIDURL = try! DIDURL(testURL)
XCTAssertTrue(url == other)
XCTAssertTrue(url.description == testURL)
other = try! DIDURL("did:elastos:1234567890#test")
XCTAssertFalse(url == other)
XCTAssertFalse(url.description == "did:elastos:1234567890#test")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
}
|
//
// TransactionRepository.swift
// TransactionRepository
//
// Created by Harry Yan on 18/08/21.
//
import Combine
import CoreData
final class TransactionRepository: TransactionProvider {
private var managedObjectContext: NSManagedObjectContext
var transactionPublisher: Published<[Transaction]>.Publisher { $transactionLogs }
@Published var transactionLogs: [Transaction] = []
// MARK: - Init
init(context: NSManagedObjectContext) {
self.managedObjectContext = context
publish()
}
// MARK: - Internal
func loadAllTransactions() {
let sort = NSSortDescriptor(key: "occuredOn", ascending: false)
let fetchRequest: NSFetchRequest<Transaction> = Transaction.fetchRequest()
fetchRequest.sortDescriptors = [sort]
do {
transactionLogs = try self.managedObjectContext.fetch(fetchRequest)
} catch let error as NSError {
print("\(error), \(error.userInfo)")
}
}
func loadCurrentMonthTransactions(for category: String) -> [Transaction] {
let fetchRequest: NSFetchRequest<Transaction> = Transaction.fetchRequest()
let categoryFilter = NSPredicate(format: "category == %@", category)
let monthFilter = NSPredicate(format: "occuredOn >= %@ AND occuredOn <= %@", Date().startOfMonth as NSDate, Date().endOfMonth as NSDate)
let filters = NSCompoundPredicate(andPredicateWithSubpredicates: [categoryFilter, monthFilter])
fetchRequest.predicate = filters
do {
let values = try self.managedObjectContext.fetch(fetchRequest)
return values
} catch let error as NSError {
print("\(error), \(error.userInfo)")
return []
}
}
func upsert(transaction: Transaction) {
do {
try self.managedObjectContext.save()
} catch let error as NSError {
print("\(error), \(error.userInfo)")
}
publish()
}
func delete(transaction: Transaction) {
managedObjectContext.delete(transaction)
do {
try managedObjectContext.save()
} catch let error as NSError {
print("\(error), \(error.userInfo)")
}
publish()
}
// MARK: - Private
private func publish() {
loadAllTransactions()
}
}
|
//
// ViewController.swift
// MVVM App Store
//
// Created by Jake Young on 3/4/17.
// Copyright © 2017 Jake Young. All rights reserved.
//
import UIKit
import MVVMAppStoreModel
protocol MVVM: class {
associatedtype A: ViewModel
var viewModel: A! { get set }
}
class FeaturedViewController: UICollectionViewController, MVVM {
typealias A = FeaturedViewModel
internal var viewModel: FeaturedViewModel!
override func viewDidLoad() {
super.viewDidLoad()
viewModel = FeaturedViewModel()
viewModel.registerCells(in: self.collectionView)
navigationItem.title = viewModel.title
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RowCell", for: indexPath)
viewModel.configureCell(cell, at: indexPath, with: collectionView)
return cell
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return viewModel.numberOfSections
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
}
extension FeaturedViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: viewModel.sectionHeight(for: indexPath))
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCell", for: indexPath)
viewModel.configureHeader(header, at: indexPath)
return header
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: collectionView.frame.width, height: 152)
}
return .zero
}
}
|
import Swinject
class IngredientAssembly: Assembly {
// MARK: - Assembly
func assemble(container: Container) {
container.storyboardInitCompleted(IngredientViewController.self) { resolver, controller in
controller.viewModel = resolver.resolve(IngredientViewModel.self)!
controller.tableProvider = resolver.resolve(IngredientTableProvider.self)!
}
container.register(IngredientViewModel.self) { resolver in
let getIngredientUnitsUseCase = resolver.resolve(GetIngredientUnitsUseCase.self)!
return IngredientViewModel(getIngredientUnitsUseCase: getIngredientUnitsUseCase)
}
container.register(IngredientTableProvider.self) { _ in
return IngredientTableProvider()
}
}
}
|
//
// TrendingNode.swift
// pr
//
// Created by JackyZ on 2017/04/14.
// Copyright © 2017 Salmonapps. All rights reserved.
//
import UIKit
import AsyncDisplayKit
import Charts
class TrendingNode: ASDisplayNode {
static let nodeHeight:CGFloat = 150
let titleNode = ASTextNode()
let lineChartNode = ASDisplayNode { () -> UIView in
let chartView = LineChartView()
chartView.noDataText = ""
chartView.chartDescription?.enabled = false
chartView.drawGridBackgroundEnabled = false
chartView.dragEnabled = true
chartView.setScaleEnabled(false)
chartView.pinchZoomEnabled = true
chartView.scaleXEnabled = true
chartView.scaleYEnabled = false
chartView.doubleTapToZoomEnabled = false
chartView.legend.enabled = false
chartView.rightAxis.enabled = false
chartView.leftAxis.gridColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1.0)
chartView.xAxis.enabled = true
chartView.xAxis.labelPosition = .bottom
chartView.xAxis.labelFont = UIFont(name: "HelveticaNeue-Light", size: 12)!
chartView.xAxis.drawAxisLineEnabled = false
chartView.xAxis.drawGridLinesEnabled = false
chartView.xAxis.granularity = 1
chartView.xAxis.xOffset = 5
chartView.xAxis.avoidFirstLastClippingEnabled = false
let marker = PriceMarker(color:UIColor.clear, font:UIFont(name: "HelveticaNeue-Light", size: 8)!, textColor:UIColor.prBlack(), insets:UIEdgeInsetsMake(0, 0, 0, 0))
marker.chartView = chartView
marker.minimumSize = CGSize(width: 80, height: 20)
chartView.marker = marker
return chartView
}
override init() {
super.init()
//
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
lineChartNode.style.flexGrow = 1
lineChartNode.style.flexShrink = 1
let stack = ASStackLayoutSpec(direction: .vertical, spacing: 8, justifyContent: .center, alignItems: .start, children:[titleNode, lineChartNode])
return ASInsetLayoutSpec(insets: UIEdgeInsets(top: 20, left: 12, bottom: 0, right: 12), child: stack)
}
class func getTitleString(string:String) -> NSAttributedString {
return NSAttributedString(string: string, attributes: [ NSForegroundColorAttributeName : UIColor.prBlack(), NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 15)!])
}
}
extension TrendingNode {
func bind(_ prices:[Price]) {
if prices.count <= 0 {
return
}
titleNode.attributedText = TrendingNode.getTitleString(string: NSLocalizedString("Trending", comment:""))
addSubnode(titleNode)
addSubnode(lineChartNode)
updateChart(prices)
}
func updateChart(_ prices:[Price]) {
if prices.count <= 0 {
return
}
var vals:[ChartDataEntry] = []
var xvals:[String] = []
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "M.d"
for (index, p) in prices.enumerated() {
let d = ChartDataEntry(x: Double(index), y: Double(p.price), data:p)
let dt = Date(timeIntervalSince1970: TimeInterval(p.t))
xvals.append(dayTimePeriodFormatter.string(from: dt))
vals.append(d)
}
//last item
let l = ChartDataEntry(x: Double(prices.count), y: Double(prices.last!.price))
vals.append(l)
xvals.append("")
//TODO padding dates to 30 days
let set1 = LineChartDataSet(values: vals, label: "set1")
set1.setColor(UIColor.prBlack())
set1.lineWidth = 1.0
set1.drawCirclesEnabled = false
set1.drawFilledEnabled = true
set1.mode = .stepped
set1.drawValuesEnabled = false
set1.drawVerticalHighlightIndicatorEnabled = false
set1.drawHorizontalHighlightIndicatorEnabled = false
let chartView = lineChartNode.view as! LineChartView
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xvals)
chartView.data = LineChartData(dataSets: [set1])
}
}
class PriceMarker: MarkerImage
{
open var color: UIColor?
open var arrowSize = CGSize(width: 15, height: 11)
open var font: UIFont?
open var textColor: UIColor?
open var insets = UIEdgeInsets()
open var minimumSize = CGSize()
fileprivate var labelns: NSString?
fileprivate var _labelSize: CGSize = CGSize()
fileprivate var _paragraphStyle: NSMutableParagraphStyle?
fileprivate var _drawAttributes = [String : AnyObject]()
public init(color: UIColor, font: UIFont, textColor: UIColor, insets: UIEdgeInsets)
{
super.init()
self.color = color
self.font = font
self.textColor = textColor
self.insets = insets
_paragraphStyle = NSParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle
_paragraphStyle?.alignment = .center
}
open override func offsetForDrawing(atPoint point: CGPoint) -> CGPoint
{
let size = self.size
var point = point
point.x -= size.width / 2.0
point.y -= size.height
return super.offsetForDrawing(atPoint: point)
}
open override func draw(context: CGContext, point: CGPoint)
{
if labelns == nil
{
return
}
let offset = self.offsetForDrawing(atPoint: point)
let size = self.size
var rect = CGRect(
origin: CGPoint(
x: point.x + offset.x,
y: point.y + offset.y),
size: size)
rect.origin.x -= size.width / 2.0
rect.origin.y -= size.height
context.saveGState()
if let color = color
{
context.setFillColor(color.cgColor)
context.beginPath()
context.move(to: CGPoint(
x: rect.origin.x,
y: rect.origin.y))
context.addLine(to: CGPoint(
x: rect.origin.x + rect.size.width,
y: rect.origin.y))
context.addLine(to: CGPoint(
x: rect.origin.x + rect.size.width,
y: rect.origin.y + rect.size.height - arrowSize.height))
context.addLine(to: CGPoint(
x: rect.origin.x + (rect.size.width + arrowSize.width) / 2.0,
y: rect.origin.y + rect.size.height - arrowSize.height))
context.addLine(to: CGPoint(
x: rect.origin.x + rect.size.width / 2.0,
y: rect.origin.y + rect.size.height))
context.addLine(to: CGPoint(
x: rect.origin.x + (rect.size.width - arrowSize.width) / 2.0,
y: rect.origin.y + rect.size.height - arrowSize.height))
context.addLine(to: CGPoint(
x: rect.origin.x,
y: rect.origin.y + rect.size.height - arrowSize.height))
context.addLine(to: CGPoint(
x: rect.origin.x,
y: rect.origin.y))
context.fillPath()
}
rect.origin.y += self.insets.top
rect.size.height -= self.insets.top + self.insets.bottom
UIGraphicsPushContext(context)
labelns?.draw(in: rect, withAttributes: _drawAttributes)
UIGraphicsPopContext()
context.restoreGState()
}
open override func refreshContent(entry: ChartDataEntry, highlight: Highlight) {
guard let p = entry.data as? Price else {
setLabel("")
return
}
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "yyyy-MM-dd"
let dt = Date(timeIntervalSince1970: TimeInterval(p.t))
setLabel( p.currency + String(entry.y) + " " + dayTimePeriodFormatter.string(from: dt))
}
open func setLabel(_ label: String)
{
labelns = label as NSString
_drawAttributes.removeAll()
_drawAttributes[NSFontAttributeName] = self.font
_drawAttributes[NSParagraphStyleAttributeName] = _paragraphStyle
_drawAttributes[NSForegroundColorAttributeName] = self.textColor
_labelSize = labelns?.size(attributes: _drawAttributes) ?? CGSize.zero
var size = CGSize()
size.width = _labelSize.width + self.insets.left + self.insets.right
size.height = _labelSize.height + self.insets.top + self.insets.bottom
size.width = max(minimumSize.width, size.width)
size.height = max(minimumSize.height, size.height)
self.size = size
}
}
|
// RUN: %target-swift-frontend -emit-silgen -enable-experimental-feature ReferenceBindings -o - %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-sil -sil-verify-all -enable-experimental-feature ReferenceBindings -o - %s | %FileCheck -check-prefix=SIL %s
class Klass {}
struct S {
var k = Klass()
}
func doSomething() {}
// Before the transformation, our access scope is not to end of scope... so
// doSomething() is not within the access scope.
//
// CHECK-LABEL: sil hidden [ossa] @$s18reference_bindings13testBindToVaryyF : $@convention(thin) () -> () {
// CHECK: [[BOX:%.*]] = alloc_box ${ var Int }, var, name "x"
// CHECK: [[PROJECT:%.*]] = project_box %0
// CHECK: [[INOUT_BOX:%.*]] = alloc_box ${ var Int }, var, name "x2"
// CHECK: [[UNRESOLVED_BINDING:%.*]] = mark_unresolved_reference_binding [inout] [[INOUT_BOX]]
// CHECK: [[INOUT_PROJECT:%.*]] = project_box [[UNRESOLVED_BINDING]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PROJECT]]
// CHECK: copy_addr [[ACCESS]] to [init] [[INOUT_PROJECT]]
// CHECK: end_access [[ACCESS]]
// CHECK: [[FUNC:%.*]] = function_ref @$s18reference_bindings11doSomethingyyF : $@convention(thin) () -> ()
// CHECK: apply [[FUNC]]()
// CHECK: destroy_value [[UNRESOLVED_BINDING]]
// CHECK: destroy_value [[BOX]]
// CHECK: } // end sil function '$s18reference_bindings13testBindToVaryyF'
// SIL: sil hidden @$s18reference_bindings13testBindToVaryyF : $@convention(thin) () -> () {
// SIL: bb0:
// SIL: [[BOX:%.*]] = alloc_stack $Int, var, name "x"
// SIL: [[INOUT_BOX:%.*]] = alloc_stack $Int, var, name "x2"
// SIL: [[ACCESS:%.*]] = begin_access [modify] [static] [[BOX]]
// SIL: store {{%.*}} to [[INOUT_BOX]]
// SIL: [[FUNC:%.*]] = function_ref @$s18reference_bindings11doSomethingyyF : $@convention(thin) () -> ()
// SIL: apply [[FUNC]]()
// SIL: store {{%.*}} to [[ACCESS]]
// SIL: end_access [[ACCESS]]
// SIL: } // end sil function '$s18reference_bindings13testBindToVaryyF'
func testBindToVar() {
var x = 5
inout x2 = x
doSomething()
}
// CHECK-LABEL: sil hidden [ossa] @$s18reference_bindings15testBindToInOutyySSzF : $@convention(thin) (@inout String) -> () {
// CHECK: bb0([[ARG:%.*]] : $*String):
// CHECK: [[BOX:%.*]] = alloc_box ${ var String }
// CHECK: [[MARK:%.*]] = mark_unresolved_reference_binding [inout] [[BOX]]
// CHECK: [[PROJECT:%.*]] = project_box [[MARK]]
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[ARG]]
// CHECK: copy_addr [[ACCESS]] to [init] [[PROJECT]]
// CHECK: end_access [[ACCESS]]
// CHECK: apply {{%.*}}()
// CHECK: destroy_value [[MARK]]
// CHECK: } // end sil function '$s18reference_bindings15testBindToInOutyySSzF'
// SIL-LABEL: sil hidden @$s18reference_bindings15testBindToInOutyySSzF : $@convention(thin) (@inout String) -> () {
// SIL: bb0([[ARG:%.*]] : $*String):
// SIL: [[STACK:%.*]] = alloc_stack $String
// SIL: [[ACCESS:%.*]] = begin_access [modify] [static] [[ARG]]
// SIL: [[VAL:%.*]] = load [[ACCESS]]
// SIL: store [[VAL]] to [[STACK]]
// SIL: apply {{%.*}}
// SIL: [[VAL:%.*]] = load [[STACK]]
// SIL: store [[VAL]] to [[ACCESS]]
// SIL: end_access [[ACCESS]]
// SIL: dealloc_stack [[STACK]]
// SIL: } // end sil function '$s18reference_bindings15testBindToInOutyySSzF'
func testBindToInOut(_ x: inout String) {
inout y = x
doSomething()
}
|
//
// LogInViewController.swift
// OSOM_app
//
// Created by Miłosz Bugla on 22.10.2017.
//
import Foundation
import UIKit
import SwiftValidator
fileprivate struct LocalizedStrings {
static let loginError = "logIn.error"
}
final class LogInViewController: UIViewController {
fileprivate let mainView: LogInView
fileprivate let viewModel: LoginViewModel
var navigator: NavigationController?
fileprivate let validator = Validator()
init(mainView: LogInView, viewModel: LoginViewModel) {
self.mainView = mainView
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
viewModel.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
setupView()
setupNavigation()
}
override func viewDidAppear(_ animated: Bool) {
DispatchQueue.main.async(execute: {
self.mainView.fadeIn()
})
}
fileprivate func setupNavigation() {
navigator = NavigationController(navigationView: mainView.navigation, navigationController: navigationController)
navigator?.delegate = self
}
private func setupView() {
view = mainView
mainView.setupView()
registerValidatableFields()
}
}
extension LogInViewController: NavigationControllerDelegate {
func rightAction() {
validator.validate(self)
}
func backAction() {
mainView.animate(entry: false, completion: {
self.navigationController?.popViewController(animated: false)
})
}
}
extension LogInViewController: ValidationDelegate {
func validationSuccessful() {
viewModel.login(email: mainView.emailEditField.textField.text ?? "",
password: mainView.passwordEditField.textField.text ?? "")
}
func validationFailed(_ errors: [(Validatable, ValidationError)]) {
for (field, error) in errors {
if let field = field as? UITextField {
error.errorLabel?.text = error.errorMessage
field.shake()
}
}
}
fileprivate func registerValidatableFields() {
validator.registerField(mainView.emailEditField.textField, errorLabel: mainView.emailEditField.errorLabel, rules: [RequiredRule()])
validator.registerField(mainView.passwordEditField.textField, errorLabel: mainView.passwordEditField.errorLabel, rules: [RequiredRule()])
}
}
extension LogInViewController: LoginViewModelDelegate {
func loginSuccessed() {
let vc = ViewControllerContainer.shared.getCreateAbout()
changeRootVC(newViewController: vc)
}
func loginFailed() {
mainView.passwordEditField.errorLabel.text = LocalizedStrings.loginError.localized()
}
}
|
import Quick
import Nimble
import RxTest
import RxSwift
import RxCocoa
import RxBlocking
@testable import Vetty
class VettySpec: QuickSpec {
func runRunLoop() {
for _ in 0 ..< 10 {
let currentRunLoop = CFRunLoopGetCurrent()
DispatchQueue.main.async {
CFRunLoopStop(currentRunLoop)
}
CFRunLoopWakeUp(currentRunLoop)
CFRunLoopRun()
}
}
override func spec() {
context("Vetty Data Provider Unit Test") {
var repositories: [Repository]!
beforeEach {
let bundle = Bundle(for: type(of: self))
let url = bundle.url(forResource: "Repository", withExtension: "json")!
let data = try! Data(contentsOf: url)
repositories = try? JSONDecoder().decode([Repository].self, from: data)
Vetty.shared.clear()
Vetty.shared.commit(repositories, ignoreSubModel: false)
self.runRunLoop()
}
it("should be success parse json to repositories") {
expect(repositories.count).to(equal(100))
}
it("should be read target model") {
let repo = Vetty.shared.read(type: Repository.self, uniqueKey: "\(repositories.first!.id)")
expect(repo?.id).to(equal(1))
expect(repo?.id).to(equal(repositories.first?.id))
}
it("should be success to commit") {
let repo = Vetty.shared.read(type: Repository.self, uniqueKey: "\(repositories.first!.id)")
expect(repo?.desc).to(equal("Vetty Description"))
repo?.desc = "Updated Description Test"
Vetty.shared.commit(repo!, ignoreSubModel: true)
let updatedRepo = Vetty.shared.read(type: Repository.self, uniqueKey: "\(repositories.first!.id)")
expect(updatedRepo?.desc).to(equal("Updated Description Test"))
}
}
context("Vetty+Extension Unit Test") {
var repositories: [Repository]!
let disposeBag = DisposeBag()
beforeEach {
let bundle = Bundle(for: type(of: self))
let url = bundle.url(forResource: "Repository", withExtension: "json")!
let data = try! Data(contentsOf: url)
repositories = try? JSONDecoder().decode([Repository].self, from: data)
Vetty.shared.clear()
self.runRunLoop()
}
it("should be commit") {
let repositoryIdsObservable = Observable.just(repositories)
.commits()
let expectedIds = repositories.map({ $0.map({ "\($0.id)" })})
expect(try! repositoryIdsObservable.toBlocking().single().map({ $0.id }))
.to(equal(expectedIds))
self.runRunLoop()
}
it("should be read target model") {
Vetty.shared.commit(repositories, ignoreSubModel: true)
self.runRunLoop()
let repoObservable = Vetty.rx.observer(type: Repository.self, uniqueKey: "1")
expect(try! repoObservable.toBlocking().first()??.id).to(equal(repositories.first!.id))
}
it("should be mutate target model") {
Vetty.shared.commit(repositories, ignoreSubModel: true)
self.runRunLoop()
expect(repositories.first!.id).to(equal(1))
expect(repositories.first!.desc).to(equal("Vetty Description"))
let repoObservable = Vetty.rx.observer(type: Repository.self, uniqueKey: "1")
Observable.just("Update Desc")
.mutate(with: repoObservable,
{ repo, text -> Repository? in
repo?.desc = text
return repo
}).disposed(by: disposeBag)
self.runRunLoop()
expect(try! repoObservable.toBlocking().first()??.desc).to(equal("Update Desc"))
}
}
}
}
|
//
// RandomGenerator.swift
// funfact
//
// Created by Anthony Rodriguez on 3/27/15.
// Copyright (c) 2015 capitalofcode. All rights reserved.
//
import Foundation
func getValue(length: Int) ->Int{
let randomNumber = Int(arc4random_uniform(UInt32(length)))
return randomNumber
}
|
//
// AppDelegateExtension.swift
// PillReminder
//
// Created by Dumitru Tabara on 1/7/20.
// Copyright © 2020 Dumitru Tabara. All rights reserved.
//
import UIKit
import UserNotifications
extension AppDelegate: UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current().delegate = self
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let id = response.notification.request.identifier
print("Received notification with ID = \(id)")
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let id = notification.request.identifier
print("Received notification with ID = \(id)")
completionHandler([.sound, .alert])
}
}
|
// Copyright (c) 2020-2022 InSeven Limited
//
// 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 AppKit
import SwiftUI
import BookmarksCore
import Diligence
@main
struct BookmarksApp: App {
@Environment(\.manager) var manager
@StateObject var selection = BookmarksSelection()
var body: some Scene {
WindowGroup {
MainWindow(manager: manager)
.environment(\.selection, selection)
}
.commands {
SidebarCommands()
ToolbarCommands()
SectionCommands()
CommandGroup(after: .newItem) {
Divider()
Button("Refresh") {
manager.refresh()
}
.keyboardShortcut("r", modifiers: .command)
}
CommandMenu("Bookmark") {
BookmarkOpenCommands(selection: selection)
.trailingDivider()
BookmarkDesctructiveCommands(selection: selection)
.trailingDivider()
BookmarkEditCommands(selection: selection)
.trailingDivider()
BookmarkShareCommands(selection: selection)
.trailingDivider()
BookmarkTagCommands(selection: selection)
}
AccountCommands()
}
SwiftUI.Settings {
SettingsView()
}
Window("Tags", id: "tags") {
TagsContentView(tagsView: manager.tagsView)
}
About(Legal.contents)
}
}
|
//
// Specs.swift
// FacebookMe
//
// Created by Teaocat on 2018/3/4.
// Copyright © 2018年 learning-swift. All rights reserved.
//
// Github: https://github.com/teaocat
//
import Foundation
|
//
// Comics.swift
// stefanini_challenge
//
// Created by Felipe Mac on 31/05/19.
// Copyright © 2019 Felipe Mac. All rights reserved.
//
import Foundation
class Comics {
var collectionURI : String?
var items : Items?
init(dictionary: [String: AnyObject]) {
if let value = dictionary["collectionURI"] as? String? {
collectionURI = value
}
if let value = dictionary["items"] as? [String: AnyObject] {
items = Items(dictionary: value)
}
}
}
|
//
// ArticleViewModel.swift
// News
//
// Created by Bilal Durnagöl on 27.10.2020.
//
import Foundation
struct ArticleListViewModel {
let articles: [Article]
}
//table funcs
extension ArticleListViewModel {
var numberOfSection: Int {
return 3
}
func numberOfRowsInSection(_ section: Int) -> Int {
return self.articles.count
}
func articleAtIndex(_ index: Int) -> Article {
let article = articles[index]
return article
}
}
struct ArticleViewModel {
let article: Article
}
|
//: [Previous](@previous)
import Foundation
protocol Readable{
func read()
}
protocol Writeable{
func write()
}
protocol ReadDpeakable:Readable{
func speak()
}
protocol ReadWriteSpeakable:Readable, Writeable{
func speak()
}
class SomeClass:ReadWriteSpeakable{
func read(){
print("Read")
}
func write(){
print("Write")
}
func speak(){
print("speak")
}
}
//: [Next](@next)
|
// File: Deck.swift
// Package: CardGames
// Created: 05/08/2020
//
// MIT License
//
// Copyright © 2020 Christopher Boyle
//
// 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 SpriteKit
import Foundation
class Deck: SKNode, Themeable {
var suits: [String] = ["Spades", "Clubs", "Diamonds", "Hearts"]
static let values: [String] = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
static let suitname2icon = ["Spades": "♠", "Diamonds": "♦", "Hearts": "♥", "Clubs":"♣"]
private var __count: Int
var count: Int {
get {
return self.__count
}
}
var cards: [Card] = []
var to_draw: [Card] = []
required init(count: Int = 1) {
self.__count = count
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func fill() {
for _ in 0..<self.count {
var cards_added = 0
while cards_added < 52 {
for suit in self.suits {
for value in Deck.values {
let card = Card(suit: suit, value: value)
self.cards.append(card)
self.to_draw.append(card)
self.addChild(card)
cards_added += 1
}
}
}
}
print("Filled deck with", self.cards.count, "cards (", self.count, "Decks )")
}
func draw() -> Card {
// fill here and not in init so any changes to suit, values by subclass can take hold
if self.cards.count == 0 {
print("FILLING")
self.fill()
}
let index = Int.random(in: 0..<self.to_draw.count)
let card = self.to_draw[index]
self.to_draw.remove(at: index)
card.isHidden = false
return card
}
static func next_in_sequence(value: String) -> String? {
for i in 0..<(Deck.values.count-1) {
let v = Deck.values[i]
if value == v {
return Deck.values[i+1]
}
}
return nil
}
static func prev_in_sequence(value: String) -> String? {
for i in 1..<Deck.values.count {
let v = Deck.values[i]
if value == v {
return Deck.values[i-1]
}
}
return nil
}
static func is_red(suit: String) -> Bool {
return suit == "Diamonds" || suit == "Hearts"
}
func reset() {
self.to_draw.removeAll()
self.removeAllChildren()
self.cards.removeAll()
self.fill()
}
func recolour() {
for card in self.cards {
card.recolour()
}
}
}
|
//
// Episode.swift
// MyPodcast
//
// Created by 洪森達 on 2019/2/12.
// Copyright © 2019 洪森達. All rights reserved.
//
import Foundation
import FeedKit
struct Episode:Codable {
let putdate:Date
let episodeTitle:String
let discription:String
var imageUrl:String?
var author:String
var streamUrl:String
var fileUrl:String?
init(feed:RSSFeedItem){
self.putdate = feed.pubDate ?? Date()
self.episodeTitle = feed.title ?? ""
self.discription = feed.iTunes?.iTunesSubtitle ?? feed.description ?? ""
self.imageUrl = feed.iTunes?.iTunesImage?.attributes?.href
self.streamUrl = feed.enclosure?.attributes?.url ?? ""
self.author = feed.iTunes?.iTunesAuthor ?? ""
}
}
|
//
// Preview.swift
// Helios
//
// Created by Lars Stegman on 07-08-17.
// Copyright © 2017 Stegman. All rights reserved.
//
import Foundation
public struct Preview: Codable {
let id: String
let source: PreviewImage
let resolutions: [PreviewImage]
let variants: [PreviewImage.Variant: Preview]?
private enum CodingKeys: String, CodingKey {
case enabled
case images
}
private enum ImagesCodingKeys: String, CodingKey {
case id
case source
case resolutions
case variants
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let enabled = try container.decode(Bool.self, forKey: .enabled)
if !enabled {
throw DecodingError.valueNotFound(PreviewImage.self,
DecodingError.Context(codingPath: [CodingKeys.images], debugDescription: "Preview image is not enabled for the post."))
}
let imagesContainer = try container.nestedContainer(keyedBy: ImagesCodingKeys.self, forKey: .images)
id = try imagesContainer.decode(String.self, forKey: .id)
source = try imagesContainer.decode(PreviewImage.self, forKey: .source)
resolutions = try imagesContainer.decode([PreviewImage].self, forKey: .resolutions)
variants = try imagesContainer.decodeIfPresent([PreviewImage.Variant: Preview].self, forKey: .variants)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(true, forKey: .enabled)
var images = container.nestedContainer(keyedBy: ImagesCodingKeys.self, forKey: .images)
try images.encode(source, forKey: .source)
try images.encode(resolutions, forKey: .resolutions)
try images.encode(variants, forKey: .variants)
}
}
public struct PreviewImage: Codable {
public enum Variant: String, Codable {
case gif
case mp4
case obfuscated
}
let url: URL
let size: CGSize
private enum CodingKeys: String, CodingKey {
case url
case width
case height
}
public init(from decoder: Decoder) throws {
let container = try! decoder.container(keyedBy: CodingKeys.self)
url = try container.decode(URL.self, forKey: .url)
size = CGSize(width: try container.decode(Double.self, forKey: .width),
height: try container.decode(Double.self, forKey: .height))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(url, forKey: .url)
try container.encode(size.width, forKey: .width)
try container.encode(size.height, forKey: .height)
}
}
|
// Created by Sergii Mykhailov on 02/12/2017.
// Copyright © 2017 Sergii Mykhailov. All rights reserved.
//
import Foundation
import UIKit
protocol CurrenciesCollectionViewControllerDataSource : class {
func supportedCurrencies(forCurrenciesCollectionViewController sender:CurrenciesCollectionViewController) -> [Currency]
func currenciesViewController(sender:CurrenciesCollectionViewController,
balanceForCurrency:Currency) -> Double?
func currenciesViewController(sender:CurrenciesCollectionViewController,
minPriceForCurrency:Currency) -> Double?
func currenciesViewController(sender:CurrenciesCollectionViewController,
maxPriceForCurrency:Currency) -> Double?
func currenciesViewController(sender:CurrenciesCollectionViewController,
dailyUpdateInPercentsForCurrency:Currency) -> Double?
}
@objc protocol CurrenciesCollectionViewControllerDelegate : class {
@objc optional func currenciesViewController(sender:CurrenciesCollectionViewController,
didSelectCurrency currency:Currency)
}
class CurrenciesCollectionViewController : UICollectionViewController {
public weak var dataSource:CurrenciesCollectionViewControllerDataSource?
public weak var delegate:CurrenciesCollectionViewControllerDelegate?
public var selectedCurrency:Currency? {
if currentSelectedItem == nil {
return nil
}
else {
let selectedCell = self.collectionView?.cellForItem(at:currentSelectedItem!) as! CurrencyCollectionViewCell
let currency = currencyForCell(selectedCell)
return currency
}
}
init() {
super.init(collectionViewLayout:layout)
setupLayout()
self.collectionView!.delegate = self
self.collectionView!.register(CurrencyCollectionViewCell.self,
forCellWithReuseIdentifier:CurrenciesCollectionViewController.CellIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Overriden methods
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = UIColor.clear
collectionView?.allowsSelection = true
collectionView?.allowsMultipleSelection = false
collectionView?.clipsToBounds = false
}
// MARK: UICollectionViewDelegate implementation
internal override func collectionView(_ collectionView:UICollectionView,
numberOfItemsInSection section:Int) -> Int {
if dataSource != nil {
supportedCurrencies = dataSource!.supportedCurrencies(forCurrenciesCollectionViewController:self)
return supportedCurrencies!.count
}
return 0
}
internal override func collectionView(_ collectionView:UICollectionView,
cellForItemAt indexPath:IndexPath) -> UICollectionViewCell {
let cell =
collectionView.dequeueReusableCell(withReuseIdentifier:CurrenciesCollectionViewController.CellIdentifier,
for:indexPath) as! CurrencyCollectionViewCell
if dataSource != nil {
let requestedCurrency = supportedCurrencies![indexPath.row]
let balance = dataSource!.currenciesViewController(sender:self,
balanceForCurrency:requestedCurrency)
let minPrice = dataSource!.currenciesViewController(sender:self,
minPriceForCurrency:requestedCurrency)
let maxPrice = dataSource!.currenciesViewController(sender:self,
maxPriceForCurrency:requestedCurrency)
cell.balance = balance
cell.minPrice = minPrice
cell.maxPrice = maxPrice
cell.currencyText = requestedCurrency.rawValue as String
}
if currentSelectedItem == nil && cell.isSelected {
currentSelectedItem = indexPath
}
let isCellHighlighted = currentSelectedItem == indexPath
cell.isHighlightVisible = isCellHighlighted
cell.layer.cornerRadius = UIDefaults.CornerRadius
return cell
}
internal override func collectionView(_ collectionView:UICollectionView,
didSelectItemAt indexPath:IndexPath) {
if currentSelectedItem != nil && currentSelectedItem != indexPath {
let currentSelectedCell = collectionView.cellForItem(at:currentSelectedItem!) as? CurrencyCollectionViewCell
currentSelectedCell?.isHighlightVisible = false
}
currentSelectedItem = indexPath
if let currencyCell = collectionView.cellForItem(at:indexPath) as? CurrencyCollectionViewCell {
currencyCell.isHighlightVisible = true
let currency = currencyForCell(currencyCell)
let boundsInCollectionView = currencyCell.convert(currencyCell.bounds, to:collectionView)
if !collectionView.bounds.contains(boundsInCollectionView) {
collectionView.scrollToItem(at:indexPath, at:.right, animated:true)
}
delegate?.currenciesViewController?(sender:self, didSelectCurrency:currency)
}
}
// MARK: CurrencyCollectionViewCellDelegate implementation
fileprivate func currencyForCell(_ cell:CurrencyCollectionViewCell) -> Currency {
let result = Currency(rawValue:cell.currencyText as Currency.RawValue)
return result!
}
// MARK: Internal methods
func setupLayout() -> Void {
layout.scrollDirection = .horizontal
// Try to fit at least 3 items (with 2 interitem spacings)
let itemWidth = UIDefaults.LineHeight * 2.75
let itemHeight = UIDefaults.LineHeight * 2
layout.itemSize = CGSize(width:itemWidth, height:itemHeight)
layout.minimumInteritemSpacing = UIDefaults.Spacing
layout.minimumLineSpacing = UIDefaults.Spacing
}
// MARK: Internal fields
fileprivate var supportedCurrencies:[Currency]?
fileprivate let layout = UICollectionViewFlowLayout()
fileprivate var currentSelectedItem:IndexPath?
fileprivate static let CellIdentifier = "Currency Cell"
}
private let SelectedCellShadowOpacity:Float = 0.18
|
import Foundation
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 4.2.1 (Linux)
if A.count == 0 {
return 0
}
let uniqueValues = Set(A)
return uniqueValues.count
}
var A = [2,1,1,2,3,1] // -> 3
var A2 = [-1000000, 1000000]
print(solution(&A2))
// MARK: - Prompt
/*
Write a function
public func solution(_ A : inout [Int]) -> Int
that, given an array A consisting of N integers, returns the number of distinct values in array A.
For example, given array A consisting of six elements such that:
A[0] = 2 A[1] = 1 A[2] = 1
A[3] = 2 A[4] = 3 A[5] = 1
the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..100,000];
each element of array A is an integer within the range [−1,000,000..1,000,000].
*/
|
import Foundation
import Result
import Swish
public struct Network {
public let url: URL
private let client: Client
public static let test = Network(
url: URL(string: "https://horizon-testnet.stellar.org/")!
)
public static let main = Network(
url: URL(string: "https://horizon.stellar.org/")!
)
public init(url: URL, client: Client = APIClient()) {
self.url = url
self.client = client
}
public func getAccount(
id: String,
completionHandler: @escaping (Result<Account, SwishError>) -> Void
) {
let request = GetAccount(id: id, network: self)
client.perform(request, completionHandler: completionHandler)
}
func request(for resource: Resource) -> URLRequest {
let url = URL(string: resource.pathComponent, relativeTo: self.url)!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Accept")
return request
}
}
|
//
// TeamDetailFooter.swift
// Project
//
// Created by 张凯强 on 2019/8/30.
// Copyright © 2018 HHCSZGD. All rights reserved.
//
import UIKit
class TeamDetailFooter: UICollectionReusableView {
@IBOutlet weak var mySwitch: MYSwitch!
var containerView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
if let subView = Bundle.main.loadNibNamed("TeamDetailFooter", owner: self, options: nil)?.first as? UIView {
self.backgroundColor = UIColor.white
self.containerView = subView
self.addSubview(self.containerView)
self.mySwitch.transform = .init(scaleX: 0.8, y: 0.8)
self.mySwitch.addTarget(self, action: #selector(switchAction(_:)), for: UIControl.Event.touchUpInside)
}
}
var teamID: String?
var switchBlick: (() -> ())?
var isOn: Bool = false {
didSet {
self.mySwitch.setOn(isOn, animated: true)
}
}
@objc func switchAction(_ sender: UISwitch) {
sender.setOn(self.isOn, animated: false)
sender.isEnabled = false
let cancle = ZKAlertAction.init(title: "cancel"|?|, style: UIAlertAction.Style.cancel) { (action) in
sender.isEnabled = true
}
let sure = ZKAlertAction.init(title: "sure"|?|, style: UIAlertAction.Style.default) { [weak self](action) in
ZkqAlert.share.activeAlert.startAnimating()
var sign_data_permission: String = "0"
if !sender.isOn {
sign_data_permission = "1"
}else {
sign_data_permission = "0"
}
let paramete = ["token": DDAccount.share.token ?? "", "id": self?.teamID ?? "", "sign_data_permission": sign_data_permission]
let router = Router.post("sign/on-off", .api, paramete)
let _ = NetWork.manager.requestData(router: router).subscribe(onNext: { (dict) in
let model = BaseModel<String>.deserialize(from: dict)
if model?.status == 200 {
self?.switchBlick?()
}else {
GDAlertView.alert(model?.message, image: nil, time: 1, complateBlock: nil)
}
sender.isEnabled = true
ZkqAlert.share.activeAlert.stopAnimating()
}, onError: { (error) in
sender.isEnabled = true
}, onCompleted: {
mylog("结束")
}) {
mylog("回收")
}
}
let message = self.isOn ? "team_close_sign_permission_alter"|?| : "team_on_sign_permission_alter"|?|
let alert = MyAlertView.init(frame: CGRect.zero, title: "", message: message, actions: [cancle, sure])
UIApplication.shared.keyWindow?.alertZkq(alert)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func layoutSubviews() {
super.layoutSubviews()
self.containerView.frame = self.bounds
}
}
class MYSwitch: UISwitch {
override func setOn(_ on: Bool, animated: Bool) {
super.setOn(on, animated: animated)
mylog("点击了这个")
}
}
|
//
// Test.swift
// pexeso
//
// Created by Jozef Matus on 17/02/17.
// Copyright © 2017 o2. All rights reserved.
//
import UIKit
import CoreData
import RxDataSources
struct MainEntity: Persistable {
public typealias T = NSManagedObject
var identity: String
var value: String
var childsa: ToManyRelationship<ChildA> = ToManyRelationship(key: "childsa")
var childsb: ToManyRelationship<ChildB> = ToManyRelationship(key: "childsb")
var childsc: ToManyRelationship<ChildC> = ToManyRelationship(key: "childsc")
var childsd: ToManyRelationship<ChildD> = ToManyRelationship(key: "childsd")
var childse: ToManyRelationship<ChildE> = ToManyRelationship(key: "childse")
// var parent: ToOneRelationship<Main>
public static var primaryAttributeName: String {
return "id"
}
init(id: String, value: String) {
self.identity = id
self.value = value
}
init(entity: T) {
self.identity = entity.value(forKey: "id") as! String
self.value = entity.value(forKey: "value") as! String
//relationships
if let childsaEntities = entity.value(forKey: "childsa") as? Set<ChildA.T>, childsaEntities.count > 0 {
self.childsa.setValue(childsaEntities)
}
if let childsbEntities = entity.value(forKey: "childsb") as? Set<ChildB.T>, childsbEntities.count > 0 {
self.childsb.setValue(childsbEntities)
}
if let childscEntities = entity.value(forKey: "childsc") as? Set<ChildC.T>, childscEntities.count > 0 {
self.childsc.setValue(childscEntities)
}
if let childsdEntities = entity.value(forKey: "childsd") as? Set<ChildD.T>, childsdEntities.count > 0 {
self.childsd.setValue(childsdEntities)
}
if let childseEntities = entity.value(forKey: "childse") as? Set<ChildE.T>, childseEntities.count > 0 {
self.childse.setValue(childseEntities)
}
}
func update(_ entity: NSManagedObject) {
entity.setValue(self.identity, forKey: "id")
entity.setValue(self.value, forKey: "value")
self.childsa.save(ToEntity: entity)
self.childsb.save(ToEntity: entity)
self.childsc.save(ToEntity: entity)
self.childsd.save(ToEntity: entity)
self.childse.save(ToEntity: entity)
}
}
struct ChildA: Persistable {
public typealias T = NSManagedObject
var identity: String
var value: String
var parent: ToOneRelationship<MainEntity> = ToOneRelationship(key: "parent")
public static var primaryAttributeName: String {
return "id"
}
init(id: String, value: String) {
self.identity = id
self.value = value
}
init(entity: T) {
self.identity = entity.value(forKey: "id") as! String
self.value = entity.value(forKey: "value") as! String
//relationships
if let parentEntities = entity.value(forKey: "parent") as? MainEntity.T {
self.parent.setValue(parentEntities)
}
}
func update(_ entity: NSManagedObject) {
entity.setValue(self.identity, forKey: "id")
entity.setValue(self.value, forKey: "value")
self.parent.save(ToEntity: entity)
}
}
struct ChildB: Persistable {
public typealias T = NSManagedObject
var identity: String
var value: String
var parent: ToOneRelationship<MainEntity> = ToOneRelationship(key: "parent")
public static var primaryAttributeName: String {
return "id"
}
init(id: String, value: String) {
self.identity = id
self.value = value
}
init(entity: T) {
self.identity = entity.value(forKey: "id") as! String
self.value = entity.value(forKey: "value") as! String
//relationships
if let parentEntities = entity.value(forKey: "parent") as? MainEntity.T {
self.parent.setValue(parentEntities)
}
}
func update(_ entity: NSManagedObject) {
entity.setValue(self.identity, forKey: "id")
entity.setValue(self.value, forKey: "value")
self.parent.save(ToEntity: entity)
}
}
struct ChildC: Persistable {
public typealias T = NSManagedObject
var identity: String
var value: String
var parent: ToOneRelationship<MainEntity> = ToOneRelationship(key: "parent")
public static var primaryAttributeName: String {
return "id"
}
init(id: String, value: String) {
self.identity = id
self.value = value
}
init(entity: T) {
self.identity = entity.value(forKey: "id") as! String
self.value = entity.value(forKey: "value") as! String
//relationships
if let parentEntities = entity.value(forKey: "parent") as? MainEntity.T {
self.parent.setValue(parentEntities)
}
}
func update(_ entity: NSManagedObject) {
entity.setValue(self.identity, forKey: "id")
entity.setValue(self.value, forKey: "value")
self.parent.save(ToEntity: entity)
}
}
struct ChildD: Persistable {
public typealias T = NSManagedObject
var identity: String
var value: String
var parent: ToOneRelationship<MainEntity> = ToOneRelationship(key: "parent")
public static var primaryAttributeName: String {
return "id"
}
init(id: String, value: String) {
self.identity = id
self.value = value
}
init(entity: T) {
self.identity = entity.value(forKey: "id") as! String
self.value = entity.value(forKey: "value") as! String
//relationships
if let parentEntities = entity.value(forKey: "parent") as? MainEntity.T {
self.parent.setValue(parentEntities)
}
}
func update(_ entity: NSManagedObject) {
entity.setValue(self.identity, forKey: "id")
entity.setValue(self.value, forKey: "value")
self.parent.save(ToEntity: entity)
}
}
struct ChildE: Persistable {
public typealias T = NSManagedObject
var identity: String
var value: String
var parent: ToOneRelationship<MainEntity> = ToOneRelationship(key: "parent")
public static var primaryAttributeName: String {
return "id"
}
init(id: String, value: String) {
self.identity = id
self.value = value
}
init(entity: T) {
self.identity = entity.value(forKey: "id") as! String
self.value = entity.value(forKey: "value") as! String
//relationships
if let parentEntities = entity.value(forKey: "parent") as? MainEntity.T {
self.parent.setValue(parentEntities)
}
}
func update(_ entity: NSManagedObject) {
entity.setValue(self.identity, forKey: "id")
entity.setValue(self.value, forKey: "value")
self.parent.save(ToEntity: entity)
}
}
|
//
// ActiveProductViewC.swift
// MyLoqta
//
// Created by Shivansh Jaitly on 7/23/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import UIKit
import SwiftyUserDefaults
protocol ActiveProductViewDelegate: class {
func didDeactivateProduct()
}
class ActiveProductViewC: BaseViewC {
//MARK: - IBOutlets
@IBOutlet weak var headerView: AVView!
@IBOutlet weak var collectionViewImages: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var tblViewDetails: UITableView!
@IBOutlet weak var btnStatistics: UIButton!
@IBOutlet weak var btnEdit: UIButton!
//MARK: - Variables
var viewModel: ActiveProductVModeling?
var dataSource = [[String: Any]]()
var imgDataSource = [String]()
var isShowMore: Bool = true
var productId = 13
var product: Product?
weak var delegate: ActiveProductViewDelegate?
//MARK: - LifeCycle Methods
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
//MARK: - Private Methods
private func setup() {
self.recheckVM()
self.registerCell()
self.setupCollectionView()
self.setupTableView()
self.setupView()
self.pageControl.hidesForSinglePage = true
self.getProductDetail()
self.btnEdit.addTarget(self, action: #selector(tapEdit), for: .touchUpInside)
}
private func recheckVM() {
if self.viewModel == nil {
self.viewModel = ActiveProductVM()
}
if let array = self.viewModel?.getDataSource(productDetail: product) {
self.dataSource.append(contentsOf: array)
}
self.tblViewDetails.reloadData()
}
private func registerCell() {
self.collectionViewImages.register(ProductImagesCell.self)
self.tblViewDetails.register(ProductNameCell.self)
self.tblViewDetails.register(ProductDetailCell.self)
self.tblViewDetails.register(ProductQuantityCell.self)
self.tblViewDetails.register(ProductQuestionCell.self)
self.tblViewDetails.register(ProductAnswerCell.self)
self.tblViewDetails.register(ProductDeactivateCell.self)
self.tblViewDetails.register(DetailProductQuestion.self)
}
private func setupCollectionView() {
self.collectionViewImages.delegate = self
self.collectionViewImages.dataSource = self
}
private func setupTableView() {
self.tblViewDetails.delegate = self
self.tblViewDetails.dataSource = self
self.tblViewDetails.allowsSelection = false
// let headerView = UIView(frame: CGRect(x: 0, y: 0, width: self.tblViewDetails.frame.size.width, height: 0))
// self.tblViewDetails.tableHeaderView = headerView
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: self.tblViewDetails.frame.size.width, height: 45))
footerView.backgroundColor = .white
self.tblViewDetails.tableFooterView = footerView
self.tblViewDetails.separatorStyle = .none
}
private func setupView() {
self.btnStatistics.roundCorners(Constant.btnCornerRadius)
self.btnEdit.roundCorners(Constant.btnCornerRadius)
Threads.performTaskAfterDealy(0.05) {
self.headerView.drawGradientWithRGB(startColor: UIColor.headerStartOrangeColor, endColor: UIColor.headerEndOrangeColor)
}
}
private func setProductImages(_ product: Product) {
if let arrImages = product.imageUrl {
self.imgDataSource = arrImages
self.pageControl.numberOfPages = self.imgDataSource.count
self.collectionViewImages.reloadData()
}
}
private func itemDeleted() {
if let arrayVC = self.navigationController?.viewControllers {
let count = arrayVC.count
if count > 1, let viewC = arrayVC[(count - 2)] as? BaseViewC {
viewC.refreshApi()
}
}
Threads.performTaskAfterDealy(0.5) {
self.navigationController?.popViewController(animated: true)
}
}
public func getProductDetail() {
self.viewModel?.requestGetProductDetail(productId: self.productId, completion: { [weak self] (product, isDeleted) in
guard let strongSelf = self else { return }
if isDeleted {
strongSelf.itemDeleted()
return
}
strongSelf.product = product
strongSelf.setProductImages(product)
if let array = strongSelf.viewModel?.getDataSource(productDetail: product) {
strongSelf.dataSource = []
strongSelf.dataSource.append(contentsOf: array)
}
strongSelf.tblViewDetails.reloadData()
})
}
func requestDeactivateProduct() {
guard let itemId = self.product?.itemId else { return }
let sellerId = Defaults[.sellerId]
let productStatus = ProductStatus.deactivated.rawValue
let param: [String: AnyObject] = ["sellerId": sellerId as AnyObject,"itemId": itemId as AnyObject, "status": productStatus as AnyObject]
self.viewModel?.requestDeactivateProduct(param: param, completion: { (success) in
Alert.showOkAlertWithCallBack(title: ConstantTextsApi.AppName.localizedString, message: "Item deactivated successfully.".localize(), completeion_: { [weak self] (success) in
guard let strongSelf = self else { return }
if success {
if let delegate = strongSelf.delegate {
delegate.didDeactivateProduct()
}
strongSelf.navigationController?.popViewController(animated: true)
}
})
})
}
//MARK: - IBActions
@IBAction func tapBack(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
@objc func tapEdit() {
guard let productID = self.product?.itemId else { return }
if let addItemVC = DIConfigurator.sharedInst().getAddItemVC() {
addItemVC.productId = productID
self.navigationController?.pushViewController(addItemVC, animated: true)
}
}
@IBAction func tapProductStatistics(_ sender: UIButton) {
if let productStatsVC = DIConfigurator.sharedInst().getProductStatsViewC(), let itemName = self.product?.itemName, let arrItemImage = self.product?.imageUrl, arrItemImage.count > 0 {
productStatsVC.itemId = self.productId
productStatsVC.itemName = itemName
productStatsVC.itemImage = arrItemImage[0]
self.navigationController?.pushViewController(productStatsVC, animated: true)
}
}
@IBAction func tapShare(_ sender: UIButton) {
if let itemId = self.product?.itemId {
UserSession.sharedSession.shareLink(idValue: itemId, isProduct: true, fromVC: self)
}
}
}
|
//
// VarificationView.swift
// CalenderPlan
//
// Created by Zihao Arthur Wang [STUDENT] on 4/9/19.
// Copyright © 2019 Zihao Arthur Wang [STUDENT]. All rights reserved.
//
import Foundation
import Cocoa
class VarificationView: NSView {
let uidLabel: NSTextField = NSTextField()
let inputLabel: NSTextField = NSTextField()
let welcomeLabel: NSTextField = NSTextField()
let completeLabel: NSTextField = NSTextField()
var completeBlock: (String) -> () = { _ in }
let varifyCode: [Character] = ["^", "#", "?", ">", "@", "!", "&", "%", "*", "$"]
override func viewDidMoveToSuperview() {
super.viewDidMoveToSuperview()
self.wantsLayer = true
self.layer?.backgroundColor = NSColor.white.cgColor
setupWelcomeLabel()
setupUidLabel()
setupInputLabel()
setupCompleteLabel()
}
override func layout() {
super.layout()
layoutWelcomeLabel()
layoutUidLabel()
layoutInputLabel()
layoutCompleteLabel()
}
private func setupCompleteLabel() {
completeLabel.removeFromSuperview()
completeLabel.stringValue = "完成"
completeLabel.textColor = NSColor(cgColor: ColorBoard.yuanshanzi)
completeLabel.isEditable = false
completeLabel.isBordered = false
let gesture = NSClickGestureRecognizer.init(target: self, action: #selector(completeActionBlk))
completeLabel.addGestureRecognizer(gesture)
self.addSubview(completeLabel)
}
private func layoutCompleteLabel() {
completeLabel.font = NSFont.systemFont(ofSize: 40)
completeLabel.sizeToFit()
completeLabel.center.x = inputLabel.center.x
completeLabel.frame.leftTopCorner.y = inputLabel.frame.leftBottomCorner.y-10
}
@objc func completeActionBlk() {
if varify() {
completeBlock(inputLabel.stringValue)
}
}
private func varify() -> Bool {
let uid = getuid()
var characters = [Int]()
var index = UInt32(uid)
var count = 0
print(uid)
while(index != 0) {
characters.append(Int((Int(index)+count)%10))
index /= 10
}
count = 0
var retval = true
guard inputLabel.stringValue.count == characters.count else {
print("\(inputLabel.stringValue.count) vs \(characters.count)")
print("\(inputLabel.stringValue) vs \(characters)")
inputLabel.stringValue.forEach { (arg) in
print(arg)
}
return false
}
inputLabel.stringValue.forEach { (arg) in
print("arg: \(arg)")
print("code: \(varifyCode[characters[count]])")
if arg != varifyCode[(characters[count]+count)%10] {
retval = false
}
count += 1
}
return retval
}
private func setupUidLabel() {
uidLabel.removeFromSuperview()
uidLabel.stringValue = "用户ID: \(getuid())"
uidLabel.textColor = NSColor(cgColor: ColorBoard.textColor2)
uidLabel.isEditable = false
uidLabel.isBordered = false
self.addSubview(uidLabel)
}
private func setupWelcomeLabel() {
welcomeLabel.removeFromSuperview()
welcomeLabel.stringValue = "欢迎使用【激活页面】"
welcomeLabel.textColor = NSColor(cgColor: ColorBoard.textColor2)
welcomeLabel.isEditable = false
welcomeLabel.isBordered = false
self.addSubview(welcomeLabel)
}
private func setupInputLabel() {
inputLabel.removeFromSuperview()
inputLabel.placeholderString = "输入激活码"
inputLabel.textColor = NSColor(cgColor: ColorBoard.textColor2)
inputLabel.isEditable = true
inputLabel.isBordered = true
self.addSubview(inputLabel)
}
private func layoutWelcomeLabel() {
welcomeLabel.font = NSFont.systemFont(ofSize: 50)
welcomeLabel.sizeToFit()
welcomeLabel.center.x = self.bounds.width/2
welcomeLabel.center.y = self.bounds.height*4/5
}
private func layoutUidLabel() {
uidLabel.font = NSFont.systemFont(ofSize: 24)
uidLabel.sizeToFit()
uidLabel.center.x = self.bounds.width/2
uidLabel.frame.leftTopCorner.y = welcomeLabel.frame.leftBottomCorner.y-60
}
private func layoutInputLabel() {
inputLabel.font = NSFont.systemFont(ofSize: 24)
inputLabel.sizeToFit()
inputLabel.frame.size.width = uidLabel.frame.width
inputLabel.center.x = self.bounds.width/2
inputLabel.frame.leftTopCorner.y = uidLabel.frame.leftBottomCorner.y-10
}
}
|
//
// NameWithImage.swift
// RememberNames
//
// Created by Brandon Knox on 5/31/21.
//
import Foundation
import MapKit
struct NameWithImage: Codable, Comparable {
var name: String
var fileName: String
var longitude: Double
var latitude: Double
static func < (lhs: NameWithImage, rhs: NameWithImage) -> Bool {
lhs.name < rhs.name
}
}
|
//
// MainTableViewController.swift
// TableViewCellExpand
//
// Created by Marcelo on 10/3/17.
// Copyright © 2017 MAS. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController {
// MARK: - Properties
var source = [String]()
var detailSource = [String]()
var selectedRowIndex = -1
var expandedIndexPath = IndexPath.init(row: -1, section: -1)
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// load content
loadContent()
}
// MARK: - Application Data Source
private func loadContent(){
// Row content
source.append("Row 0")
source.append("Row 1")
source.append("Row 2")
source.append("Row 3")
source.append("Row 4")
// content detail
detailSource.append("Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda. Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.")
detailSource.append("Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda. Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.")
detailSource.append("Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda. Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.")
detailSource.append("Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda. Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.")
detailSource.append("Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda. Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.Anashdg hhhs jajahsgyk jasj sashh haggsja khasdjhas khaghs hgasgdas jashsdgj qwye nbbaanaba. Tiahsjad kajjhlhjda.")
tableView.reloadData()
}
// MARK: - Table View Delegate
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
return source.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if selectedRowIndex != indexPath.row {
// normal cell
let cell = tableView.dequeueReusableCell(withIdentifier: "CellNormal", for: indexPath) as? CellNormalTableViewCell
cell?.normalTitle.text = source[indexPath.row]
return cell!
}else{
// expanded cell
let cell = tableView.dequeueReusableCell(withIdentifier: "CellExpanded", for: indexPath) as? CellExpandedTableViewCell
cell?.expandedTitle.text = source[indexPath.row]
cell?.expandedSubtitle.text = detailSource[indexPath.row]
return cell!
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedRowIndex == indexPath.row {
selectedRowIndex = -1
} else {
selectedRowIndex = indexPath.row
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == selectedRowIndex {
return 140
}
return 44
}
}
|
//
// PatientViewController.swift
// Joeppie
//
// Created by Ercan kalan on 08/12/2019.
// Copyright © 2019 Bever-Apps. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
enum Weekday: Int {
case sunday = 0, monday, tuesday, wednesday, thursday, friday, saturday
}
class PatientBaxterViewController: UIViewController {
@IBOutlet weak var tableview: UITableView!
var patient:Patient?
var baxterlist: [Baxter] = []
var medicinelist: [Medicine] = []
var popup:UIView!
var alertvc:AlertViewController!
var indicator:UIActivityIndicatorView? = nil
var checkinTested = false
let decoder = JSONDecoder()
let dateFormatter = DateFormatter()
@IBOutlet weak var tapBarItem_home: UITabBarItem!
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
private func setup(){
setIndicator()
dateFormatter.locale = Locale.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
self.tableview.contentInset = UIEdgeInsets(top: -35, left: 0, bottom: 0, right: 0);
tableview.backgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1.0)
let nib = UINib(nibName: "MedicineCell", bundle: nil)
tableview.register(nib, forCellReuseIdentifier: "MedicineCell")
tableview.backgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1.0)
tableview.allowsSelection = false
getMedicines()
}
@objc func applicationWillEnterForeground(notification: Notification) {
getBaxters()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getBaxters()
}
// TODO : make all func private
func setIndicator(){
indicator = UIActivityIndicatorView()
indicator!.style = UIActivityIndicatorView.Style.large
indicator!.center = self.view.center
indicator!.color = UIColor(red:0.38, green:0.33, blue:0.46, alpha:1.0)
self.view.addSubview(indicator!)
indicator!.startAnimating()
indicator!.backgroundColor = UIColor.white
indicator?.startAnimating()
}
private func getBaxters(){
ApiService.getAllBaxtersPatient(patientId: self.patient!.id)
.responseData(completionHandler: { (response) in
guard let jsonData = response.data else { return }
let rs = try? self.decoder.decode([Baxter].self, from: response.data!)
self.baxterlist = rs!.reordered()
self.handleBaxters()
self.tableview.dataSource = self
self.tableview.delegate = self
self.tableview.reloadData()
guard response.error == nil else {
print("error")
if response.response?.statusCode == 409 {
print("error")
}
return
}
})
}
func handleBaxters(){
var equipments = [[Int:Baxter]]()
for indexbaxter in stride(from: baxterlist.count-1, to: -1, by: -1){
if(self.baxterlist[indexbaxter].doses?.count==0){
ApiService.deleteBaxter(baxter: baxterlist[indexbaxter])
self.baxterlist.remove(at: indexbaxter)
}
}
self.tableview.reloadData()
}
func getMedicines(){
ApiService.getMedicines()
.responseData(completionHandler: { (response) in
guard let jsonData = response.data else { return }
let rs = try? self.decoder.decode([Medicine].self, from: jsonData)
if let list = rs{
self.medicinelist = list
}
guard response.error == nil else {
print("error")
if response.response?.statusCode == 409 {
print("error")
}
return
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
indicator?.stopAnimating()
let cell = tableView.dequeueReusableCell(withIdentifier: "MedicineCell",for: indexPath) as! MedicineCell
let b = medicinelist.firstIndex(where: { $0.id == baxterlist[indexPath.section].doses![indexPath.row].medicine})
let index:Int = medicinelist.firstIndex(where: { $0.id == baxterlist[indexPath.section].doses![indexPath.row].medicine })!
cell.amount.text = "x " + String(baxterlist[indexPath.section].doses![indexPath.row].amount)
cell.amount.textColor = UIColor(red:0.38, green:0.33, blue:0.46, alpha:1.0)
cell.amount.font = UIFont.systemFont(ofSize: 23)
cell.textMedicine.text = medicinelist[index].name
cell.textMedicine.textColor = UIColor(red:0.38, green:0.33, blue:0.46, alpha:1.0)
cell.textMedicine.font = UIFont.systemFont(ofSize: 23)
cell.backgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1.0)
switch self.medicinelist[index].type{
case "tablet":
cell.medicine_intake_image.image = UIImage(named:"medicine_tablet")
case "liquid":
cell.medicine_intake_image.image = UIImage(named:"Drop_medicine")
case "capsule":
cell.medicine_intake_image.image = UIImage(named:"capsule")
default:
cell.medicine_intake_image.image = UIImage(named:"medicine_intake_icon")
}
return cell
}
func deleteDose(dose:NestedDose){
ApiService.deleteDose(id: String(dose.id))
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let ingenomen = UIContextualAction(style: .destructive, title: NSLocalizedString("verwijderen", comment: "")) { (action, sourceView, completionHandler) in
let alert = UIAlertController(title: NSLocalizedString("are_you_sure", comment: ""), message: NSLocalizedString("are_you_sure_to_delete_it", comment: ""), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("yes", comment: ""), style: .default, handler: { action in
self.deleteDose(dose: self.baxterlist[indexPath.section].doses![indexPath.row])
self.baxterlist[indexPath.section].doses?.remove(at: indexPath.row)
self.handleBaxters()
var imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 40, height: 40))
imageView.image = UIImage(named: "vinkje")
let alert = UIAlertController(title: "", message: NSLocalizedString("verwijderd", comment: ""), preferredStyle: .alert)
alert.view.addSubview(imageView)
self.present(alert, animated: true, completion: nil)
// change to desired number of seconds (in this case 5 seconds)
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when){
// your code with delay
alert.dismiss(animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("no", comment: ""), style: .cancel, handler: nil))
self.present(alert, animated: true)
}
ingenomen.backgroundColor = UIColor(red:0.96, green:0.74, blue:0.12, alpha:1.0)
let swipeAction = UISwipeActionsConfiguration(actions: [ingenomen])
swipeAction.performsFirstActionWithFullSwipe = false
return swipeAction
}
}
extension PatientBaxterViewController:UITableViewDelegate{
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
let label = UILabel(frame: CGRect(x: 0, y: 8, width: tableView.bounds.size.width, height: 21))
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 20)
let df = DateFormatter()
df.dateFormat = "HH:mm"
let time = df.string(from: baxterlist[section].intakeTime)
var daycheck:String = ""
switch baxterlist[section].dayOfWeek.capitalizingFirstLetter() {
case "Monday":
daycheck = NSLocalizedString("Monday", comment: "")
case "Tuesday":
daycheck = NSLocalizedString("Tuesday", comment: "")
case "Wednesday":
daycheck = NSLocalizedString("Wednesday", comment: "")
case "Thursday":
daycheck = NSLocalizedString("Thursday", comment: "")
case "Friday":
daycheck = NSLocalizedString("Friday", comment: "")
case "Saturday":
daycheck = NSLocalizedString("Saturday", comment: "")
case "Sunday":
daycheck = NSLocalizedString("Sunday", comment: "")
default:
""
}
label.text = "\(daycheck) \(time) \(NSLocalizedString("hour", comment: ""))"
label.textColor = .white
headerView.addSubview(label)
headerView.backgroundColor = UIColor(red:0.95, green:0.55, blue:0.13, alpha:1.0)
return headerView
}
}
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).capitalized + dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
extension PatientBaxterViewController:UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
var amount:Int = 0
for baxter in baxterlist{
if baxter.doses!.count>0{
amount = amount + 1
}
}
if amount == 0{
indicator?.stopAnimating()
}
return amount
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
self.baxterlist[section].doses!.count
}
}
|
//
// UserDetailVC.swift
// PeopleAndAppleStockPrices
//
// Created by casandra grullon on 12/3/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import UIKit
class UserDetailVC: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var cityLabel: UILabel!
var userInfo: UserInfo?
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
func updateUI(){
guard let user = userInfo else {
return
}
nameLabel.text = "\(user.name.first.capitalized) \(user.name.last.capitalized)"
emailLabel.text = user.email
cityLabel.text = user.location.city.capitalized
UserPicture.getPicture(for: user.picture.medium) { [unowned self] (result) in
switch result {
case .failure(let error):
print("\(error)")
case .success(let image):
DispatchQueue.main.async {
self.imageView.image = image
}
}
}
}
}
|
//
// NumberConversion.swift
// RijksMuseum
//
// Created by Alexandre Mantovani Tavares on 19/05/20.
//
import Foundation
import CoreGraphics
extension Int {
var d: Double {
Double(self)
}
var f: CGFloat {
CGFloat(self)
}
}
|
//
// Artista.swift
// Myoozik
//
// Created by Alessandro Bolattino on 04/04/18.
// Copyright © 2018 Mussini SAS. All rights reserved.
//
import Foundation
struct Artista {
let nome: String
let cover: URL?
let token: String
}
|
// SPDX-License-Identifier: MIT
// Copyright © 2018-2019 WireGuard LLC. All Rights Reserved.
import UIKit
class OptionView: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func awakeFromNib() {
super.awakeFromNib()
self.layer.masksToBounds = false
self.layer.cornerRadius = 5.0
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).cgPath
self.layer.shadowOffset = CGSize(width: 1.0, height: -5.0)
self.layer.shadowOpacity = 0.5
self.layer.shadowRadius = 1.0
}
}
|
import Foundation
import SwiftyJSON
public class CheckerFactory {
public static func none() -> Checker {
let check: (JSON) throws -> Bool = { json in
return true
}
return Checker.init(check: check)
}
}
|
//
// StockListTableViewController.swift
// StockQuote
//
// Created by Ernest Fan on 2019-11-14.
// Copyright © 2019 ErnestFan. All rights reserved.
//
import UIKit
class StockListTableViewController: UITableViewController {
// Stock Info
let stockSymbolArray : [String]!
var stockDetailDict = [String : Stock]()
// Networking
var pendingNetworkRequest = [IndexPath : String]()
var networkRequestTimer : Timer?
var activityIndicator = UIActivityIndicatorView(style: .medium)
var onGoingNetworkRequestCount = 0
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Stock Quote"
setupTableView()
setupActivityIndicator()
}
// MARK: - Init
init(stocks:[String], style: UITableView.Style) {
self.stockSymbolArray = stocks
super.init(style: style)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Setup
private func setupTableView() {
tableView.register(StockListTableViewCell.self, forCellReuseIdentifier: StockListTableViewCell.cellReuseIdentifier)
tableView.separatorStyle = .none
}
private func setupActivityIndicator() {
let barButtonItem = UIBarButtonItem(customView: activityIndicator)
self.navigationItem.rightBarButtonItem = barButtonItem
}
// MARK: - Stock Detail
func presentStockDetail(with stock: Stock) {
let stockDetailVC = StockDetailViewController(with: stock)
if let nc = self.navigationController {
nc.pushViewController(stockDetailVC, animated: true)
}
}
// MARK: - Alert
func presentNetworkRequestError() {
if self.presentingViewController != nil {
return
}
let title = "Unable to retrieve data"
let message = "Such error can occur due to your network connection or the limitation of 5 stock quotes per minute from our data provider. Please try again later."
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Got it", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
// MARK: - Activity Indicator
func enableActivityIndicator() {
activityIndicator.startAnimating()
}
func disableActivityIndicator() {
if onGoingNetworkRequestCount <= 0 {
activityIndicator.stopAnimating()
}
}
// MARK: - Network Request
// Keep track of number of requests fired, stop animation when all request finished
// If user tap on a cell, request data immediately with reaction
// Else, request on scroll or resume pending requests based on timer
func requestStockDetail(with symbol: String, for indexPath: IndexPath, reaction requiresReaction: Bool = false) {
onGoingNetworkRequestCount += 1
enableActivityIndicator()
StockAPIService.instance.getStockDetail(for: symbol) { (data) in
self.onGoingNetworkRequestCount -= 1
self.disableActivityIndicator()
if let attributes = data {
// If received data, extract data from JSON
let stock = Stock(symbol: symbol, attributes: attributes)
self.stockDetailDict[symbol] = stock
self.removePendingNetworkRequest(for: indexPath)
DispatchQueue.main.async {
self.tableView.reloadRows(at: [indexPath], with: .automatic)
if requiresReaction {
self.presentStockDetail(with: stock)
}
}
} else {
// If failed, add request to pending
self.addPendingNetworkRequest(with: indexPath, and: symbol)
if requiresReaction {
self.presentNetworkRequestError()
}
}
}
}
func addPendingNetworkRequest(with indexPath: IndexPath, and symbol: String) {
if !pendingNetworkRequest.keys.contains(indexPath) {
pendingNetworkRequest[indexPath] = symbol
enableNetworkRequestTimer()
}
}
func removePendingNetworkRequest(for indexPath: IndexPath) {
pendingNetworkRequest.removeValue(forKey: indexPath)
if pendingNetworkRequest.count <= 0 {
disableNetworkRequestTimer()
}
}
// MARK: - Network Request Retry Timer
func enableNetworkRequestTimer() {
// If timer already exists and valid, do nothing
if let timer = networkRequestTimer, timer.isValid {
return
}
networkRequestTimer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(resumePendingRequest), userInfo: nil, repeats: true)
}
func disableNetworkRequestTimer() {
networkRequestTimer?.invalidate()
}
@objc func resumePendingRequest() {
// Fire up to 5 network requests
var count = 0
for indexPath in pendingNetworkRequest.keys.sorted() {
if let symbol = pendingNetworkRequest[indexPath] {
requestStockDetail(with: symbol, for: indexPath)
count += 1
}
if count >= 5 {
break
}
}
}
// MARK: - Tableview data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.stockSymbolArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: StockListTableViewCell.cellReuseIdentifier, for: indexPath)
if let cell = cell as? StockListTableViewCell {
let symbol = stockSymbolArray[indexPath.row]
if let stock = stockDetailDict[symbol] {
cell.stock = stock
} else {
// Configure cell with basic info
cell.stockSymbol = symbol
requestStockDetail(with: symbol, for: indexPath)
}
}
return cell
}
// MARK: - Tableview delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let symbol = stockSymbolArray[indexPath.row]
if let stock = stockDetailDict[symbol] {
presentStockDetail(with: stock)
} else {
requestStockDetail(with: symbol, for: indexPath, reaction: true)
}
}
}
|
//
// ValidationRuleSet.swift
// PDD
//
// Created by Anton Rasoha on 11.05.21.
//
import Foundation
public struct ValidationRuleSet<InputType> {
internal var rules = [AnyValidationRule<InputType>]()
public init() {
}
public init<Rule: ValidationRule>(rules: [Rule]) where Rule.InputType == InputType {
self.rules = rules.map(AnyValidationRule.init)
}
public mutating func add<Rule: ValidationRule>(rule: Rule) where Rule.InputType == InputType {
let anyRule = AnyValidationRule(base: rule)
rules.append(anyRule)
}
}
|
//
// TableViewController.swift
// ThePaper
//
// Created by Gautier Billard on 17/03/2020.
// Copyright © 2020 Gautier Billard. All rights reserved.
//
import UIKit
import SwiftyJSON
class MainViewController: UIViewController {
let cellID = "cellID"
//UI
private var tableView: UITableView!
private var cardTitleView: UIView!
private var tableTitleView: UIView!
private var cardView: CardsVC!
private var scrollVelocity = 1.0
private lazy var scrollView: UIScrollView = {
let view = UIScrollView()
view.translatesAutoresizingMaskIntoConstraints = false
view.contentSize.height = 636 + 260
view.backgroundColor = .clear
return view
}()
//Data
private let k = K()
private let newsModel = NewsModel()
private var titles = [String]()
private var imagesUrls = [String]()
private var articleURL = [String]()
struct Cells {
static let NewsCell = "NewsCell"
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(scrollView)
scrollView.delegate = self
addScrollViewConstraints()
newsModel.jsonDelegate = self
newsModel.fetchData()
addCardTitle()
addCardView()
addTableTitle()
addTableView()
self.tableView.register(NewsCell.self, forCellReuseIdentifier: Cells.NewsCell)
createObservers()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func createObservers() {
let name = Notification.Name(K.shared.locationChangeNotificationName)
NotificationCenter.default.addObserver(self, selector: #selector(updateNewsWithCountry(_:)), name: name, object: nil)
}
@objc private func updateNewsWithCountry(_ notification: NSNotification) {
newsModel.fetchData()
}
func addScrollViewConstraints() {
//view
let fromView = scrollView
//relative to
let toView = self.view!
fromView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([fromView.leadingAnchor.constraint(equalTo: toView.leadingAnchor, constant: 0),
fromView.trailingAnchor.constraint(equalTo: toView.trailingAnchor, constant: 0),
fromView.topAnchor.constraint(equalTo: toView.topAnchor, constant: 0),
fromView.bottomAnchor.constraint(equalTo: toView.bottomAnchor, constant: 0)])
}
fileprivate func addTitleHighLighters(_ cardTitle: UILabel) {
let highlighter = UIView()
highlighter.backgroundColor = k.mainColorTheme
self.view.addSubview(highlighter)
//view
let fromView = highlighter
//relative to
let toView = cardTitle
fromView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([fromView.leadingAnchor.constraint(equalTo: toView.leadingAnchor, constant: 0),
fromView.widthAnchor.constraint(equalToConstant: 150),
fromView.topAnchor.constraint(equalTo: toView.bottomAnchor, constant: 2),
fromView.heightAnchor.constraint(equalToConstant: 3)])
}
fileprivate func addCardTitle() {
//Breaking news
cardTitleView = UIView()
cardTitleView.backgroundColor = .clear
self.scrollView.addSubview(cardTitleView)
cardTitleView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([cardTitleView.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 10),
cardTitleView.widthAnchor.constraint(equalToConstant: 200),
cardTitleView.topAnchor.constraint(equalTo: self.scrollView.topAnchor, constant: 10),
cardTitleView.heightAnchor.constraint(equalToConstant: 30)])
let cardTitle = UILabel()
cardTitle.text = "A la Une"
cardTitle.font = UIFont.systemFont(ofSize: K.shared.fontSizeSubTitle)
// cardTitle.font = UIFont(name: "Old London", size: 20)
cardTitleView.addSubview(cardTitle)
cardTitle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([cardTitle.leadingAnchor.constraint(equalTo: self.cardTitleView.leadingAnchor, constant: 5),
cardTitle.centerYAnchor.constraint(equalTo: self.cardTitleView.centerYAnchor, constant: 0)])
addTitleHighLighters(cardTitle)
}
fileprivate func addTableTitle() {
let width = self.view.frame.width - 20
//Trending Now
tableTitleView = UIView()
tableTitleView.backgroundColor = .clear
self.scrollView.addSubview(tableTitleView)
tableTitleView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([tableTitleView.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 10),
tableTitleView.widthAnchor.constraint(equalToConstant: width),
tableTitleView.topAnchor.constraint(equalTo: self.cardView.view.bottomAnchor, constant: 0),
tableTitleView.heightAnchor.constraint(equalToConstant: 30)])
let tableTitle = UILabel()
tableTitle.text = "En Tendance"
tableTitle.font = UIFont.systemFont(ofSize: 20)
// tableTitle.font = UIFont(name: "Old London", size: 20)
tableTitleView.addSubview(tableTitle)
tableTitle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([tableTitle.leadingAnchor.constraint(equalTo: self.tableTitleView.leadingAnchor, constant: 5),
tableTitle.centerYAnchor.constraint(equalTo: self.tableTitleView.centerYAnchor, constant: 0)])
addTitleHighLighters(tableTitle)
}
private func addCardView() {
cardView = CardsVC()
cardView.delegate = self
self.addChild(cardView)
cardView.willMove(toParent: self)
let cardViewView = cardView.view!
self.scrollView.addSubview(cardViewView)
cardViewView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([cardViewView.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 0),
cardViewView.widthAnchor.constraint(equalToConstant: self.view.frame.size.width),
cardViewView.topAnchor.constraint(equalTo: self.cardTitleView.bottomAnchor, constant: 0),
cardViewView.heightAnchor.constraint(equalToConstant: 220)])
}
func addTableView() {
tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.isScrollEnabled = false
tableView.showsVerticalScrollIndicator = false
self.scrollView.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([tableView.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 0),
tableView.widthAnchor.constraint(equalToConstant: self.view.frame.size.width - 20),
tableView.topAnchor.constraint(equalTo: self.tableTitleView.bottomAnchor, constant: 10),
tableView.heightAnchor.constraint(equalToConstant: 636 - 40)])
}
}
extension MainViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfCells = 0
if titles.count == 0 {
numberOfCells = 10
}else{
numberOfCells = titles.count
}
return numberOfCells
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Cells.NewsCell, for: indexPath) as! NewsCell
if titles.count != 0 {
cell.passDataToNewsCell(title: titles[indexPath.row], imageUrl: imagesUrls[indexPath.row],articleURL: articleURL[indexPath.row])
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let childVC = ArticleDetailsViewController()
childVC.articleURL = self.articleURL[indexPath.row]
addChild(childVC)
self.view.addSubview(childVC.view)
childVC.didMove(toParent: self)
let childView = childVC.view
childView?.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([childView!.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0),
childView!.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0),
childView!.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0),
childView!.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0)])
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
}
extension MainViewController: NewsModelDelegate {
func didFetchData(json: JSON) {
titles = json["articles"].arrayValue.map {$0["title"].stringValue}
articleURL = json["articles"].arrayValue.map {$0["url"].stringValue}
imagesUrls = json["articles"].arrayValue.map {$0["urlToImage"].stringValue}
var articles = [Article]()
for (i,title) in titles.enumerated() {
let article = Article(title: title, url: articleURL[i], imageUrl: imagesUrls[i])
articles.append(article)
}
cardView.updateCards(articles: articles)
for i in 0..<10 {
titles.remove(at: i)
articleURL.remove(at: i)
imagesUrls.remove(at: i)
}
tableView.reloadData()
}
}
extension MainViewController: UIScrollViewDelegate {
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
scrollVelocity = Double(abs(velocity.y))
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let yOffset = scrollView.contentOffset.y
if yOffset < -100 {
tableView.reloadData()
newsModel.fetchData()
}
if scrollView == self.scrollView {
if yOffset >= scrollView.contentSize.height - 636 {
scrollView.isScrollEnabled = false
tableView.isScrollEnabled = true
}
}
if scrollView == self.tableView {
if yOffset <= 0 {
self.scrollView.isScrollEnabled = true
self.tableView.isScrollEnabled = false
UIView.animate(withDuration: 0.5/scrollVelocity) {
self.scrollView.contentOffset.y = 0
self.view.layoutIfNeeded()
}
}
}
}
}
extension MainViewController: CardVCDelegate {
func didTapCard(url: String) {
let childVC = ArticleDetailsViewController()
childVC.articleURL = url
addChild(childVC)
self.view.addSubview(childVC.view)
childVC.didMove(toParent: self)
let childView = childVC.view
childView?.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([childView!.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0),
childView!.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0),
childView!.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0),
childView!.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0)])
}
}
|
//
// OSCClient.swift
// OSCKit
//
// Created by Sam Smallman on 29/10/2017.
// Copyright © 2020 Sam Smallman. https://github.com/SammySmallman
//
// 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
import CocoaAsyncSocket
public class OSCClient : NSObject, GCDAsyncSocketDelegate, GCDAsyncUdpSocketDelegate {
private var socket: OSCSocket?
private var userData: NSData?
private var readData = NSMutableData()
private var readState = NSMutableDictionary()
private var activeData = NSMutableDictionary()
private var activeState = NSMutableDictionary()
public weak var delegate: (OSCClientDelegate & OSCPacketDestination)?
/// The delegate which receives debug log messages from this producer.
public weak var debugDelegate: OSCDebugDelegate?
public var isConnected: Bool {
get {
guard let sock = self.socket else { return false }
return sock.isConnected
}
}
public var useTCP = false {
didSet {
destroySocket()
}
}
public var interface: String? {
didSet {
if let aInterface = interface, aInterface.isEmpty {
interface = nil
}
guard let sock = self.socket else { return }
sock.interface = interface
}
}
public var host: String? = "localhost" {
didSet {
if let aHost = host, aHost.isEmpty {
host = nil
}
guard let sock = self.socket else { return }
sock.host = host
}
}
public var port: UInt16 = 24601 {
didSet {
guard let sock = self.socket else { return }
sock.port = port
}
}
public var streamFraming: OSCTCPStreamFraming = .SLIP
public override init() {
super.init()
}
internal func createSocket() {
if self.useTCP {
let tcpSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
self.socket = OSCSocket(with: tcpSocket)
guard let sock = self.socket else { return }
self.readState.setValue(sock, forKey: "socket")
self.readState.setValue(false, forKey: "dangling_ESC")
} else {
let udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)
self.socket = OSCSocket(with: udpSocket)
}
guard let sock = self.socket else { return }
sock.interface = self.interface
sock.host = self.host
sock.port = self.port
}
internal func destroySocket() {
self.readState.removeObject(forKey: "socket")
self.readState.removeObject(forKey: "dangling_ESC")
self.socket?.disconnect()
self.socket = nil
}
public func connect() throws {
if self.socket == nil {
createSocket()
}
guard let sock = self.socket else { return }
try sock.connect()
if let tcpSocket = sock.tcpSocket, sock.isTCPSocket {
tcpSocket.readData(withTimeout: -1, tag: 0)
}
}
public func disconnect() {
self.socket?.disconnect()
self.readData = NSMutableData()
self.readState.setValue(false, forKey: "dangling_ESC")
}
public func send(packet: OSCPacket) {
if self.socket == nil {
do {
try connect()
} catch {
debugDelegate?.debugLog("Could not send establish connection to send packet.")
}
}
guard let sock = self.socket else {
debugDelegate?.debugLog("Error: Could not send data; no socket available.")
return
}
if let tcpSocket = sock.tcpSocket, sock.isTCPSocket {
// Listen for a potential response.
tcpSocket.readData(withTimeout: -1, tag: 0)
sock.sendTCP(packet: packet, withStreamFraming: streamFraming)
} else {
sock.sendUDP(packet: packet)
}
}
// MARK: GCDAsyncSocketDelegate
public func newSocketQueueForConnection(fromAddress address: Data, on sock: GCDAsyncSocket) -> DispatchQueue? {
return nil
}
public func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
// Client sockets do not accept new incoming connections.
}
public func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
debugDelegate?.debugLog("Client Socket: \(sock) didConnectToHost: \(host):\(port)")
guard let delegate = self.delegate else { return }
delegate.clientDidConnect(client: self)
}
public func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
debugDelegate?.debugLog("Client Socket: \(sock) didRead Data of length: \(data.count), withTag: \(tag)")
guard let delegate = self.delegate else { return }
do {
try OSCParser().translate(OSCData: data, streamFraming: streamFraming, to: readData, with: readState, andDestination: delegate)
sock.readData(withTimeout: -1, tag: tag)
} catch {
debugDelegate?.debugLog("Error: \(error)")
}
}
public func socket(_ sock: GCDAsyncSocket, didReadPartialDataOfLength partialLength: UInt, tag: Int) {
debugDelegate?.debugLog("Client Socket: \(sock) didReadPartialDataOfLength: \(partialLength), withTag: \(tag)")
}
public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
debugDelegate?.debugLog("Client Socket: \(sock) didWriteDataWithTag: \(tag)")
}
public func socket(_ sock: GCDAsyncSocket, didWritePartialDataOfLength partialLength: UInt, tag: Int) {
debugDelegate?.debugLog("Client Socket: \(sock) didWritePartialDataOfLength: \(partialLength), withTag: \(tag)")
}
public func socket(_ sock: GCDAsyncSocket, shouldTimeoutReadWithTag tag: Int, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval {
debugDelegate?.debugLog("Client Socket: \(sock) shouldTimeoutReadWithTag: \(tag)")
return 0
}
public func socket(_ sock: GCDAsyncSocket, shouldTimeoutWriteWithTag tag: Int, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval {
debugDelegate?.debugLog("Client Socket: \(sock) shouldTimeoutWriteWithTag: \(tag)")
return 0
}
public func socketDidCloseReadStream(_ sock: GCDAsyncSocket) {
debugDelegate?.debugLog("Client Socket: \(sock) didCloseReadStream")
self.readData.setData(Data())
self.readState.setValue(false, forKey: "dangling_ESC")
}
public func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
debugDelegate?.debugLog("Client Socket: \(sock) didDisconnect, withError: \(err.debugDescription)")
self.readData.setData(Data())
self.readState.setValue(false, forKey: "dangling_ESC")
guard let delegate = self.delegate else { return }
delegate.clientDidDisconnect(client: self)
}
public func socketDidSecure(_ sock: GCDAsyncSocket) {
debugDelegate?.debugLog("Client Socket: \(sock) didSecure")
}
// MARK: GCDAsyncUDPSocketDelegate
public func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
debugDelegate?.debugLog("UDP Socket: \(sock) didConnectToAddress \(address)")
}
public func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
debugDelegate?.debugLog("UDP Socket: \(sock) didNotConnect, dueToError: \(error.debugDescription))")
}
public func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
debugDelegate?.debugLog("UDP Socket: \(sock) didSendDataWithTag: \(tag)")
}
public func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
debugDelegate?.debugLog("UDP Socket: \(sock) didNotSendDataWithTag: \(tag), dueToError: \(error.debugDescription)")
}
public func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
debugDelegate?.debugLog("UDP Socket: \(sock) didReceiveData of Length: \(data.count), fromAddress \(address)")
}
public func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
debugDelegate?.debugLog("UDP Socket: \(sock) Did Close. With Error: \(String(describing: error?.localizedDescription))")
}
}
|
//
// CDPackage.swift
// TheCorkDistrict
//
// Created by Chris Larkin on 10/19/15.
// Copyright © 2015 Madkatz. All rights reserved.
//
import Foundation
import UIKit
class CDPackage {
var title: String
var cost: String
var startDay: String
var startMonth: String
var startYear: String
var endDay: String
var endMonth: String
var endYear: String
var relatedNodeID: String
var webAddress: String
var image: UIImage
init(title: String, cost: String, startDay: String, startMonth: String, startYear: String, endDay: String, endMonth: String, endYear: String, relatedNodeID: String, webAddress: String, image: UIImage) {
self.title = title
self.cost = cost
self.startDay = startDay
self.startMonth = startMonth
self.startYear = startYear
self.endDay = endDay
self.endMonth = endMonth
self.endYear = endYear
self.relatedNodeID = relatedNodeID
self.webAddress = webAddress
self.image = image
}
}
|
//
// NotificationsTableController.swift
// Tipper
//
// Created by Ryan Romanchuk on 9/2/15.
// Copyright (c) 2015 Ryan Romanchuk. All rights reserved.
//
import UIKit
class NotificationsTableController: UITableViewController {
let className = "NotificationsTableController"
var managedObjectContext: NSManagedObjectContext!
var currentUser: CurrentUser!
var market: Market!
lazy var fetchedResultsController: NSFetchedResultsController = NSFetchedResultsController.superFetchedResultsController("Notification", sectionNameKeyPath: nil, sortDescriptors: self.sortDescriptors, predicate: self.predicate, tableView: self.tableView, context: self.managedObjectContext)
lazy var predicate: NSPredicate? = {
return NSPredicate(format: "userId = %@", self.currentUser.userId!)
}()
lazy var sortDescriptors: [NSSortDescriptor] = {
return [NSSortDescriptor(key: "createdAt", ascending: false)]
}()
override func viewDidLoad() {
super.viewDidLoad()
log.verbose("\(className)::\(__FUNCTION__) userId: \(self.currentUser.userId!)")
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "refresh:", forControlEvents: .ValueChanged)
tableView.addSubview(refreshControl)
DynamoNotification.fetch(currentUser.userId!, context: managedObjectContext) { () -> Void in
log.verbose("\(self.className)::\(__FUNCTION__) count\(self.fetchedResultsController.fetchedObjects!)")
self.tableView.reloadData()
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
Notification.markAllAsRead()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
log.verbose("\(className)::\(__FUNCTION__)")
let cell = tableView.dequeueReusableCellWithIdentifier("NotificationCell", forIndexPath: indexPath) as! NotificationCell
let notification = fetchedResultsController.objectAtIndexPath(indexPath) as! Notification
cell.notification = notification
log.verbose("Setting cell with \(notification)")
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let notification = fetchedResultsController.objectAtIndexPath(indexPath) as! Notification
log.verbose("notification: \(notification)")
if let _ = notification.tipId, _ = notification.tipFromUserId where notification.type == NotificationCellType.TipSent.rawValue || notification.type == NotificationCellType.TipReceived.rawValue {
self.parentViewController?.performSegueWithIdentifier("TipDetails", sender: notification)
} else if notification.type == "low_balance" || notification.type == "problem" {
self.parentViewController?.performSegueWithIdentifier("AccountScreen", sender: notification)
} else if notification.type == "" {
}
}
func refresh(refreshControl: UIRefreshControl) {
DynamoNotification.fetch(currentUser.userId!, context: managedObjectContext) { () -> Void in
refreshControl.endRefreshing()
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController.sections![section].numberOfObjects
}
}
|
//
// QASubjectCell.swift
// Todo
//
// Created by edison on 2019/4/25.
// Copyright © 2019年 EDC. All rights reserved.
//
import UIKit
class QASubjectCell: UITableViewCell {
@IBOutlet weak var subjectLabel: UILabel!
@IBOutlet weak var backgroundImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let img = #imageLiteral(resourceName: "title")
backgroundImageView.image = img.resizableImage(withCapInsets: UIEdgeInsetsMake(img.size.height * 0.5, img.size.width * 0.5, img.size.height * 0.5, img.size.width * 0.5 + 1), resizingMode: .tile)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// OnboardingControllerTests.swift
// MVVM_UberTests
//
// Created by Nestor Hernandez on 31/07/22.
//
import XCTest
@testable import MVVM_Uber
class OnboardingControllerTests: XCTestCase {
var sut: OnBoardingViewController!
override func setUpWithError() throws {
try super.setUpWithError()
let mainController = getMainViewController()
sut = mainController.makeOnboardingViewController()
}
override func tearDownWithError() throws {
sut = nil
try super.tearDownWithError()
}
func test(){
XCTAssertNotNil(sut)
}
}
|
//
// UIScrollView+Extension.swift
// ZhSwiftDemo
//
// Created by Zhuang on 2018/8/10.
// Copyright © 2018年 Zhuang. All rights reserved.
// UITableView/UICollectionView 注册 cell
import UIKit
extension UITableView {
/// 注册 cell
func cm_register<T: UITableViewCell>(cell: T.Type) where T: ReusableView {
if let nib = T.nib {
register(nib, forCellReuseIdentifier: T.reuseIdentifier)
} else {
register(T.self, forCellReuseIdentifier: T.reuseIdentifier)
}
}
/// 取缓存池的cell
func cm_dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
}
return cell
}
}
extension UICollectionView {
/// 注册cell
func cm_register<T: UICollectionViewCell>(cell: T.Type) where T: ReusableView {
if let nib = T.nib {
register(nib, forCellWithReuseIdentifier: T.reuseIdentifier)
} else {
register(cell, forCellWithReuseIdentifier: T.reuseIdentifier)
}
}
/// 注册头部
func cm_registerSupplementaryHeaderView<T: UICollectionReusableView>(reusableView: T.Type) where T: ReusableView {
if let nib = T.nib {
register(nib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: T.reuseIdentifier)
} else {
register(reusableView, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: T.reuseIdentifier)
}
}
/// 获取cell
func cm_dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
}
return cell
}
/// 获取可重用的头部
func cm_dequeueReusableSupplementaryHeaderView<T: UICollectionReusableView>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
return dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: T.reuseIdentifier, for: indexPath) as! T
}
}
|
//
// StyleSelector.swift
//
//
// Created by Zhu Shengqi on 2019/12/6.
//
import Foundation
public struct StyleSelector<TargetElement: Stylable> {
public var targetCategory: StyleSemanticCategory?
public var ancestors: [(elementType: Stylable.Type, elementCategory: StyleSemanticCategory?)]
public init(targetCategory: StyleSemanticCategory? = nil, ancestors: [(elementType: Stylable.Type, elementCategory: StyleSemanticCategory?)] = []) {
self.targetCategory = targetCategory
self.ancestors = ancestors
}
}
|
//
// SeriesTableViewCell.swift
// NBAapp
//
// Created by Parth Dhebar on 4/4/19.
// Copyright © 2019 Parth Dhebar. All rights reserved.
//
import UIKit
class SeriesTableViewCell: UITableViewCell {
@IBOutlet weak var awayTeamImage: UIImageView!
@IBOutlet weak var homeTeamImage: UIImageView!
@IBOutlet weak var seriesLavel: UILabel!
var series: Series? {
didSet {
guard let series = series else { return }
//awayTeamImage.image =
//homeTeamImage.image =
seriesLavel.text = series.recordString()
}
}
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
}
}
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var favoriteFood = "Spaguettis"
var petName : String = ""
petName = "Thomas"
petName.uppercased()
var 💩 = "popo"
💩
|
//
// Routers.swift
// GiphyHub
//
// Created by Mohamed Aymen Landolsi on 28/07/2017.
// Copyright © 2017 Roridi. All rights reserved.
//
import Foundation
import Alamofire
enum GifsRouter: URLRequestConvertible {
static let BaseURLString = "http://api.giphy.com/v1/"
case search(query: String, limit: UInt?, offset: UInt?, rating: Gif.GifRating?, language: String?, apiKey: String)
case trending(limit: UInt?, rating: Gif.GifRating?, apiKey: String)
case translate(String, apiKey: String)
case random(tag: String?, rating: Gif.GifRating?, apiKey:String)
case gif(identifier: String, apiKey: String)
case gifs(identifiers: [String], apiKey: String)
var method: HTTPMethod {
return .get
}
var path: String {
switch self {
case .search(_, _, _, _, _, _):
return "gifs/search"
case .trending(_, _, _):
return "gifs/trending"
case .translate(_, _):
return "gifs/translate"
case .random(_, _, _):
return "gifs/random"
case .gif(let identifier, _):
return "gifs/\(identifier)"
case .gifs(_):
return ("gifs")
}
}
private var parameters: [String: AnyObject] {
var parameters: [String: AnyObject] = [:]
switch self {
case let .search(keyWord, limit, offset, rating, language, apiKey):
parameters["api_key"] = apiKey as AnyObject
parameters["q"] = keyWord as AnyObject
if let lim = limit {
parameters["limit"] = lim as AnyObject
}
if let offset = offset {
parameters["offset"] = offset as AnyObject
}
if let rating = rating {
parameters["rating"] = rating.rawValue as AnyObject
}
if let language = language {
parameters["lang"] = language as AnyObject
}
case let .trending(limit, rating, apiKey):
parameters["api_key"] = apiKey as AnyObject
if let lim = limit {
parameters["limit"] = lim as AnyObject
}
if let rating = rating {
parameters["rating"] = rating.rawValue as AnyObject
}
case let .translate(term, apiKey):
parameters["api_key"] = apiKey as AnyObject
parameters["s"] = term as AnyObject
case let .random(tag, rating, apiKey):
parameters["api_key"] = apiKey as AnyObject
if let tag = tag {
parameters["tag"] = tag as AnyObject
}
if let rating = rating {
parameters["rating"] = rating.rawValue as AnyObject
}
case .gif(_, let apiKey):
parameters["api_key"] = apiKey as AnyObject
case let .gifs(ids, apiKey):
parameters["api_key"] = apiKey as AnyObject
parameters["ids"] = ids.joined(separator: ",") as AnyObject
}
return parameters
}
public func asURLRequest() throws -> URLRequest {
let url = try GifsRouter.BaseURLString.asURL()
var request = URLRequest(url: url.appendingPathComponent(path))
request.httpMethod = method.rawValue
return try URLEncoding.default.encode(request, with: parameters)
}
}
enum StickersRouter: URLRequestConvertible {
static let BaseURLString = "http://api.giphy.com/v1/"
case search(query: String, limit: UInt?, offset: UInt?, rating: Gif.GifRating?, language: String?, apiKey: String)
case trending(limit: UInt?, rating: Gif.GifRating?, apiKey: String)
case translate(String, apiKey: String)
case random(tag: String?, rating: Gif.GifRating?, apiKey: String)
var method: Alamofire.HTTPMethod {
return .get
}
var path: String {
switch self {
case .search(_, _, _, _, _, _):
return ("stickers/search")
case .trending(_, _, _):
return ("stickers/trending")
case .translate(_):
return ("stickers/translate")
case .random(_, _, _):
return ("stickers/random")
}
}
private var parameters: [String: AnyObject] {
var parameters: [String: AnyObject] = [:]
switch self {
case let .search(keyWord, limit, offset, rating, language, apiKey):
parameters["api_key"] = apiKey as AnyObject
parameters["q"] = keyWord as AnyObject
if let lim = limit {
parameters["limit"] = lim as AnyObject
}
if let offset = offset {
parameters["offset"] = offset as AnyObject
}
if let rating = rating {
parameters["rating"] = rating.rawValue as AnyObject
}
if let language = language {
parameters["lang"] = language as AnyObject
}
case let .trending(limit, rating, apiKey):
parameters["api_key"] = apiKey as AnyObject
if let lim = limit {
parameters["limit"] = lim as AnyObject
}
if let rating = rating {
parameters["rating"] = rating.rawValue as AnyObject
}
case let .translate(term, apiKey):
parameters["api_key"] = apiKey as AnyObject
parameters["s"] = term as AnyObject
case let .random(tag, rating, apiKey):
parameters["api_key"] = apiKey as AnyObject
if let tag = tag {
parameters["tag"] = tag as AnyObject
}
if let rating = rating {
parameters["rating"] = rating.rawValue as AnyObject
}
}
return parameters
}
public func asURLRequest() throws -> URLRequest {
let url = try StickersRouter.BaseURLString.asURL()
var request = URLRequest(url: url.appendingPathComponent(path))
request.httpMethod = method.rawValue
return try URLEncoding.default.encode(request, with: parameters)
}
}
|
import Foundation
final class BrowserInteraction {
let navigateBack: () -> Void
let navigateForward: () -> Void
let share: () -> Void
let minimize: () -> Void
let openSearch: () -> Void
let updateSearchQuery: (String) -> Void
let dismissSearch: () -> Void
let scrollToPreviousSearchResult: () -> Void
let scrollToNextSearchResult: () -> Void
let decreaseFontSize: () -> Void
let increaseFontSize: () -> Void
let resetFontSize: () -> Void
let updateForceSerif: (Bool) -> Void
init(navigateBack: @escaping () -> Void, navigateForward: @escaping () -> Void, share: @escaping () -> Void, minimize: @escaping () -> Void, openSearch: @escaping () -> Void, updateSearchQuery: @escaping (String) -> Void, dismissSearch: @escaping () -> Void, scrollToPreviousSearchResult: @escaping () -> Void, scrollToNextSearchResult: @escaping () -> Void, decreaseFontSize: @escaping () -> Void, increaseFontSize: @escaping () -> Void, resetFontSize: @escaping () -> Void, updateForceSerif: @escaping (Bool) -> Void) {
self.navigateBack = navigateBack
self.navigateForward = navigateForward
self.share = share
self.minimize = minimize
self.openSearch = openSearch
self.updateSearchQuery = updateSearchQuery
self.dismissSearch = dismissSearch
self.scrollToPreviousSearchResult = scrollToPreviousSearchResult
self.scrollToNextSearchResult = scrollToNextSearchResult
self.decreaseFontSize = decreaseFontSize
self.increaseFontSize = increaseFontSize
self.resetFontSize = resetFontSize
self.updateForceSerif = updateForceSerif
}
}
|
//
// Middleware.swift
// Reminders
//
// Created by Mihai Damian on 28/03/2018.
// Copyright © 2018 Mihai Damian. All rights reserved.
//
import Foundation
import ReSwift
let loggingMiddleware: Middleware<Any> = { dispatch, getState in
return { next in
return { action in
print(action)
return next(action)
}
}
}
|
class MyStack {
var entry = [Int]()
/** Initialize your data structure here. */
init() {
}
/** Push element x onto stack. */
func push(_ x: Int) {
entry.append(x)
}
/** Removes the element on top of the stack and returns that element. */
func pop() -> Int {
return entry.removeLast()
}
/** Get the top element. */
func top() -> Int {
if !entry.isEmpty {
return entry.last!
} else {
return 0
}
}
/** Returns whether the stack is empty. */
func empty() -> Bool {
return entry.isEmpty
}
}
|
//
// Cell5.swift
// node_view_framework
//
// Created by Kelong Wu on 2/15/17.
// Copyright © 2017 alien_robot_cat. All rights reserved.
//
import UIKit
class Cell5: TheCell {
@IBOutlet weak var img1: UIImageView!
@IBOutlet weak var label1: 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
}
override func update(node: Node) {
// print("updating cell 5...")
label1.text = node.data["text"]
if let imgName = node.data["img"]{
img1.image = UIImage(named: imgName)
}
// print("cell 5 updated")
}
}
|
//
// ViewController.swift
// LoginFacebook
//
// Created by Jiraporn Praneet on 7/27/2560 BE.
// Copyright © 2560 Jiraporn Praneet. All rights reserved.
//
import UIKit
import FacebookLogin
import FBSDKLoginKit
import FBSDKCoreKit
import FBSDKShareKit
import SDWebImage
import Alamofire
import SwiftyJSON
import SKPhotoBrowser
class FeedPostsFriendTableViewCell: UITableViewCell {
@IBOutlet weak var picturePostsImageView: UIImageView!
@IBOutlet weak var messagePostsLabel: UILabel!
@IBOutlet weak var profilePostsImageView: UIImageView!
@IBOutlet weak var namePostsLabel: UILabel!
@IBOutlet weak var createdTimePostsLabel: UILabel!
@IBOutlet weak var placePostsLabel: UILabel!
@IBOutlet weak var iconCheckInPostsImageView: UIImageView!
@IBOutlet weak var iconReaction1ImageView: UIImageView!
@IBOutlet weak var iconReaction2ImageView: UIImageView!
@IBOutlet weak var reactionFriendsButton: UIButton!
@IBOutlet weak var commentsFriendsButton: UIButton!
}
class StoryFriendsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var storyFriendsImageView: UIImageView!
@IBOutlet weak var nameFriendsLabel: UILabel!
}
class FristViewController: UIViewController, FBSDKLoginButtonDelegate, UISearchBarDelegate, UITabBarControllerDelegate, UITableViewDataSource, UITableViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UIPopoverPresentationControllerDelegate {
@IBOutlet weak var profileImageButton: UIButton!
@IBOutlet weak var loginButton: FBSDKLoginButton!
@IBOutlet weak var tablePostsFriends: UITableView!
@IBOutlet weak var collectionviewStoryFriends: UICollectionView!
var accessToken: FBSDKAccessToken!
override func viewDidLoad() {
super.viewDidLoad()
customNavigationBarItem()
self.loginButton.delegate = self
profileImageButton.layer.masksToBounds = true
profileImageButton.layer.cornerRadius = 20
profileImageButton.layer.borderWidth = 2
profileImageButton.layer.borderColor = UIColor.white.cgColor
self.tablePostsFriends.delegate = self
self.tablePostsFriends.dataSource = self
self.collectionviewStoryFriends.delegate = self
self.collectionviewStoryFriends.dataSource = self
if let token = FBSDKAccessToken.current() {
fetchUserResource()
fetchUserResourceFriends()
accessToken = token
print(accessToken.tokenString)
print("Show >>> ", token.tokenString)
}
}
// MARK: ViewController
var userResourceData: UserResourceData! = nil
func fetchUserResource() {
let parameters = ["fields": "email, first_name, last_name, picture.type(large), about, age_range, birthday, gender, cover, hometown, work,education,posts{created_time,message,full_picture,place}"]
FBSDKGraphRequest(graphPath: "me", parameters: parameters).start { (_, result, _) in
let dic = result as? NSDictionary
let jsonString = dic?.toJsonString()
self.userResourceData = UserResourceData(json: jsonString)
let thumborProfileImageUrl = FunctionHelper().getThumborUrlFromImageUrl(imageUrlStr: (self.userResourceData.picture?.data?.url)!, width: 200, height: 200)
self.profileImageButton.sd_setBackgroundImage(with: thumborProfileImageUrl, for: .normal, completed: nil)
}
}
func customNavigationBarItem() {
let searchBar = UISearchBar()
searchBar.showsCancelButton = false
searchBar.placeholder = "ค้นหา"
searchBar.delegate = self
self.tabBarController?.navigationItem.titleView = searchBar
let rightBarButton = UIButton(type: .custom)
rightBarButton.setImage(UIImage(named: "iconMessenger"), for: .normal)
rightBarButton.frame = CGRect(x: 0, y:0, width: 30, height: 30)
rightBarButton.tintColor = UIColor.white
rightBarButton.addTarget(self, action: #selector(FristViewController.addTapped), for: .touchUpInside)
let rightBarButtonItem = UIBarButtonItem(customView: rightBarButton)
self.tabBarController?.navigationItem.setRightBarButton(rightBarButtonItem, animated: true)
let leftBarButton = UIButton(type: .custom)
leftBarButton.setImage(UIImage(named: "iconCamera"), for: .normal)
leftBarButton.frame = CGRect(x: 0, y:0, width: 30, height: 30)
leftBarButton.tintColor = UIColor.white
leftBarButton.addTarget(self, action: #selector(FristViewController.addTapped), for: .touchUpInside)
let leftBarButtonItem = UIBarButtonItem(customView: leftBarButton)
self.tabBarController?.navigationItem.setLeftBarButton(leftBarButtonItem, animated: true)
}
func addTapped() {
print("addTapped")
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.resignFirstResponder()
return true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.tabBarController?.navigationItem.titleView?.endEditing(true)
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
fetchUserResource()
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
self.profileImageButton.setImage(UIImage(named: "nill"), for: .normal)
}
func loginButtonWillLogin(_ loginButton: FBSDKLoginButton!) -> Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: TableView
var userResource: UserResource! = nil
func fetchUserResourceFriends() {
var url = String(format:"https://graph.facebook.com/v2.10/me/friends?fields=name,picture{url},link,posts.limit(1){message,full_picture,created_time,place,reactions.limit(100){name,pic_large,type,link},comments{comment_count,message,from,created_time,comments{message,created_time,from}}}&limit=10&access_token=EAACEdEose0cBALTVinqSCIHZBHXLmvUO09of8jYRbnGruzX2arCqmuZBnAOdNDleef1bZAOs5rRwxUIoAkHaRuZBcHG5w8H5KGy7hp3tzfHi2DR0TZB9vmfghMRpOpBZB99roZBkr0JyzMGIeVPIDtxuKNDq0ZCUJ8knC6hHU0rH568ZAs6WSWXMz2F3sM1Xpo3JQ0Vn2lxZBVrwZDZD")
url = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
Alamofire.request(url, method: .get).validate().responseString { response in
switch response.result {
case .success(let value):
self.userResource = UserResource(json: value)
self.collectionviewStoryFriends.reloadData()
self.tablePostsFriends.reloadData()
case .failure( _): break
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if userResource != nil {
return userResource.data!.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellFeedPostsFriendTableView = tableView.dequeueReusableCell(withIdentifier: "cellFeedPostsFriendTableView", for: indexPath) as! FeedPostsFriendTableViewCell
let cellData = userResource.data?[indexPath.row]
let cellDataPosts = cellData?.posts?.data?[0]
cellFeedPostsFriendTableView.messagePostsLabel.text = cellDataPosts?.message
cellFeedPostsFriendTableView.placePostsLabel.text = cellDataPosts?.place?.name
let thumborProfileImageUrl = FunctionHelper().getThumborUrlFromImageUrl(imageUrlStr: (cellData?.picture?.data?.url)!, width: 300, height: 300)
cellFeedPostsFriendTableView.profilePostsImageView.sd_setImage(with: thumborProfileImageUrl, completed: nil)
cellFeedPostsFriendTableView.profilePostsImageView.layer.masksToBounds = true
cellFeedPostsFriendTableView.profilePostsImageView.layer.cornerRadius = 17
let cellDataPostsCreatedTime = cellDataPosts?.created_time
if cellDataPostsCreatedTime != nil {
let myLocale = Locale(identifier: "th_TH")
let dateStringFormPostsDataCreatedTime = cellDataPostsCreatedTime
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: dateStringFormPostsDataCreatedTime!)
dateFormatter.locale = myLocale
dateFormatter.dateFormat = "EEEE" + " เวลา " + "hh:mm"
let dateString = dateFormatter.string(from: date!)
cellFeedPostsFriendTableView.createdTimePostsLabel.text = dateString
} else {
cellFeedPostsFriendTableView.createdTimePostsLabel.text = ""
}
let cellDataPostsPicture = cellDataPosts?.full_picture
if cellDataPostsPicture != nil && cellDataPostsPicture != "" {
tablePostsFriends.rowHeight = 400
cellFeedPostsFriendTableView.picturePostsImageView.sd_setImage(with: URL(string: (cellDataPostsPicture)!), completed: nil)
cellFeedPostsFriendTableView.picturePostsImageView.contentMode = UIViewContentMode.scaleAspectFit
} else {
tablePostsFriends.rowHeight = 125
cellFeedPostsFriendTableView.picturePostsImageView.image = nil
}
let cellDataPostsPlace = cellDataPosts?.place
if cellDataPostsPlace == nil {
cellFeedPostsFriendTableView.namePostsLabel.text = cellData?.name
cellFeedPostsFriendTableView.iconCheckInPostsImageView.image = nil
} else {
cellFeedPostsFriendTableView.namePostsLabel.text = String(format:"%@ %ที่", (cellData?.name)!)
cellFeedPostsFriendTableView.iconCheckInPostsImageView.image = UIImage(named:"iconCheckin")
}
let cellDataPostsCommentsCount = cellDataPosts?.comments?.data?.count
if cellDataPostsCommentsCount == nil {
cellFeedPostsFriendTableView.commentsFriendsButton.setTitle("", for: .normal)
} else {
cellFeedPostsFriendTableView.commentsFriendsButton.setTitle(String(format:"%ความคิดเห็น %i %รายการ", cellDataPostsCommentsCount!), for: .normal)
cellFeedPostsFriendTableView.commentsFriendsButton.tag = indexPath.row
cellFeedPostsFriendTableView.commentsFriendsButton.contentHorizontalAlignment = .right
}
let cellDataPostsReactions = cellDataPosts?.reactions?.data?[0]
var cellDataPostsReactionsCount = cellDataPosts?.reactions?.data?.count
if cellDataPostsReactions == nil && cellDataPostsReactionsCount == nil {
cellFeedPostsFriendTableView.reactionFriendsButton.setTitle("", for: .normal)
cellDataPostsReactionsCount = 0
cellFeedPostsFriendTableView.iconReaction1ImageView.image = nil
} else {
let cellDataNameFriendReactions = cellDataPostsReactions?.name
let lengthNameFriendReactions = cellDataNameFriendReactions?.characters.count
if lengthNameFriendReactions! >= 10 {
cellFeedPostsFriendTableView.reactionFriendsButton.setTitle(String(format:"%i", cellDataPostsReactionsCount!), for: .normal)
cellFeedPostsFriendTableView.reactionFriendsButton.tag = indexPath.row
cellFeedPostsFriendTableView.reactionFriendsButton.contentHorizontalAlignment = .left
} else {
let reactionCount = cellDataPostsReactionsCount! - 1
cellFeedPostsFriendTableView.reactionFriendsButton.setTitle(String(format:"%@ %และคนอื่นๆอีก %i %คน", (cellDataPostsReactions?.name)!, reactionCount), for: .normal)
cellFeedPostsFriendTableView.reactionFriendsButton.tag = indexPath.row
cellFeedPostsFriendTableView.reactionFriendsButton.contentHorizontalAlignment = .left
}
let cellDataReactionsType = cellDataPostsReactions?.type
if cellDataReactionsType == "LIKE" {
cellFeedPostsFriendTableView.iconReaction1ImageView.image = UIImage(named:"iconLike")
} else if cellDataReactionsType == "LOVE" {
cellFeedPostsFriendTableView.iconReaction1ImageView.image = UIImage(named:"iconLove")
} else if cellDataReactionsType == "HAHA" {
cellFeedPostsFriendTableView.iconReaction1ImageView.image = UIImage(named:"iconHaHa")
} else if cellDataReactionsType == "SAD" {
cellFeedPostsFriendTableView.iconReaction1ImageView.image = UIImage(named:"iconSad")
} else if cellDataReactionsType == "WOW" {
cellFeedPostsFriendTableView.iconReaction1ImageView.image = UIImage(named:"iconWow")
} else {
cellFeedPostsFriendTableView.iconReaction1ImageView.image = UIImage(named:"iconAngry")
}
}
if cellDataPostsReactionsCount == 1 {
cellFeedPostsFriendTableView.iconReaction2ImageView.image = nil
} else {
let cellDataReactionsIndex1 = cellDataPosts?.reactions?.data?[1]
let cellDataReactionsTypeIndex1 = cellDataReactionsIndex1?.type
let cellDataReactionsType = cellDataPostsReactions?.type
if cellDataReactionsIndex1 == nil {
cellFeedPostsFriendTableView.iconReaction2ImageView.image = nil
} else {
if cellDataReactionsTypeIndex1 == cellDataReactionsType {
cellFeedPostsFriendTableView.iconReaction2ImageView.image = nil
} else {
if cellDataReactionsTypeIndex1 == "LIKE" {
cellFeedPostsFriendTableView.iconReaction2ImageView.image = UIImage(named:"iconLike")
} else if cellDataReactionsTypeIndex1 == "LOVE" {
cellFeedPostsFriendTableView.iconReaction2ImageView.image = UIImage(named:"iconLove")
} else if cellDataReactionsTypeIndex1 == "HAHA" {
cellFeedPostsFriendTableView.iconReaction2ImageView.image = UIImage(named:"iconHaHa")
} else if cellDataReactionsTypeIndex1 == "SAD" {
cellFeedPostsFriendTableView.iconReaction2ImageView.image = UIImage(named:"iconSad")
} else if cellDataReactionsTypeIndex1 == "WOW" {
cellFeedPostsFriendTableView.iconReaction2ImageView.image = UIImage(named:"iconWow")
} else {
cellFeedPostsFriendTableView.iconReaction2ImageView.image = UIImage(named:"iconAngry")
}
}
}
}
return cellFeedPostsFriendTableView
}
// MARK: CollectionView
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if userResource != nil {
return userResource.data!.count
} else {
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellStoryFriendsCollectionView = collectionView.dequeueReusableCell(withReuseIdentifier: "cellStoryFriendsCollectionView", for: indexPath) as! StoryFriendsCollectionViewCell
let cellData = userResource.data?[indexPath.row]
cellStoryFriendsCollectionView.nameFriendsLabel.text = cellData?.name
let thumborProfileFriendImageUrl = FunctionHelper().getThumborUrlFromImageUrl(imageUrlStr: (cellData?.picture?.data?.url)!, width: 300, height: 300)
cellStoryFriendsCollectionView.storyFriendsImageView.sd_setImage(with: thumborProfileFriendImageUrl, completed: nil)
cellStoryFriendsCollectionView.storyFriendsImageView.layer.masksToBounds = true
cellStoryFriendsCollectionView.storyFriendsImageView.layer.cornerRadius = 27
cellStoryFriendsCollectionView.storyFriendsImageView.layer.borderWidth = 2
cellStoryFriendsCollectionView.storyFriendsImageView.layer.borderColor = UIColor(red:0.17, green:0.38, blue:0.90, alpha:1.0).cgColor
return cellStoryFriendsCollectionView
}
@IBAction func clickButtonToShowProfileUserViewController(_ sender: Any) {
let showProfileViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
self.show(showProfileViewController, sender: nil)
}
@IBAction func clickButtonToViewReactionFriendsTableViewController(_ sender: AnyObject) {
let senderReactionFriendsButton = sender as! UIButton
let getCellData = userResource.data?[senderReactionFriendsButton.tag]
let getCellDataPosts = getCellData?.posts?.data?[0]
let getCellDataPostsReaction = getCellDataPosts?.reactions?.data
let getCellDataPostsReactionData = getCellDataPostsReaction!
let getCellDataPostsCount = getCellDataPosts?.reactions?.data?.count
let getCellDataPostsReactionCount = getCellDataPostsCount!
let popReactionFriendsTableViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ReactionFriendsTableView") as! ReactionFriendsTableViewController
popReactionFriendsTableViewController.modalPresentationStyle = UIModalPresentationStyle.popover
popReactionFriendsTableViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up
popReactionFriendsTableViewController.popoverPresentationController?.delegate = self
popReactionFriendsTableViewController.popoverPresentationController?.sourceView = sender as? UIView
popReactionFriendsTableViewController.popoverPresentationController?.sourceRect = sender.bounds
popReactionFriendsTableViewController.setDataPostsReaction = getCellDataPostsReactionData
popReactionFriendsTableViewController.setDataPostsReactionCount = getCellDataPostsReactionCount
self.present(popReactionFriendsTableViewController, animated: true, completion: nil)
}
@IBAction func clickButtonToViewCommentsFriendsTableViewController(_ sender: AnyObject) {
let senderCommentsFriendsButton = sender as! UIButton
let getCellData = userResource.data?[senderCommentsFriendsButton.tag]
let getCellDataPosts = getCellData?.posts?.data?[0]
let getCellDataPostsComments = getCellDataPosts?.comments?.data
let getCellDataPostsCommentsData = getCellDataPostsComments!
let getCellDataPostsCount = getCellDataPosts?.comments?.data?.count
let getCellDataPostsCommentsCount = getCellDataPostsCount!
let popCommentsFriendsTableViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CommentsFriendsTableView") as! CommentsFriendsTableViewController
popCommentsFriendsTableViewController.modalPresentationStyle = UIModalPresentationStyle.popover
popCommentsFriendsTableViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up
popCommentsFriendsTableViewController.popoverPresentationController?.delegate = self
popCommentsFriendsTableViewController.popoverPresentationController?.sourceView = sender as? UIView
popCommentsFriendsTableViewController.popoverPresentationController?.sourceRect = sender.bounds
popCommentsFriendsTableViewController.setDataPostsComments = getCellDataPostsCommentsData
popCommentsFriendsTableViewController.setDataPostsCommentsCount = getCellDataPostsCommentsCount
self.present(popCommentsFriendsTableViewController, animated: true, completion: nil)
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
}
|
//
// SubredditPostsListContainer.swift
// RedditLiveCoding
//
// Created by Vadim Bulavin on 8/19/20.
//
import SwiftUI
struct SubredditPostsListContainer: View {
@StateObject var viewModel: SubredditPostsViewModel
init(subreddit: String) {
_viewModel = .init(wrappedValue: SubredditPostsViewModel(subreddit: subreddit))
}
var body: some View {
Group {
if viewModel.posts.isEmpty {
spinner
} else {
list
}
}
.onAppear(perform: viewModel.fetchNextPage)
}
var list: some View {
SubredditPostsListView(
posts: viewModel.posts,
onScrolledAtEnd: viewModel.fetchNextPage
)
}
var spinner: some View {
Spinner(style: .medium)
}
}
|
//
// STRegisterOrginazitionViewController.swift
// SpecialTraining
//
// Created by yintao on 2019/4/29.
// Copyright © 2019 youpeixun. All rights reserved.
//
import UIKit
class STRegisterOrginazitionViewController: BaseViewController {
override func setupUI() {
}
}
|
//
// Lens+UIBarItemSpec.swift
// iOSTests
//
// Created by Oleksa 'trimm' Korin on 9/2/17.
// Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved.
//
import Quick
import Nimble
import UIKit
@testable import IDPDesign
extension UIBarItem: UIBarItemProtocol { }
class LensUIBarItemSpec: QuickSpec {
override func spec() {
describe("Lens+UIBarItemSpec") {
func toAttributedStringKey(_ value: [String : Any]) -> [NSAttributedString.Key: Any] {
var result = [NSAttributedString.Key: Any]()
value.forEach {
let key = NSAttributedString.Key($0.key)
result[key] = $0.value
}
return result
}
context("titleTextAttributes") {
it("should get and set") {
let state = UIControl.State.normal
let lens: Lens<UIBarButtonItem, [NSAttributedString.Key : Any]?> = titleTextAttributes(for: state)
let object = UIBarButtonItem()
let color = UIColor.red
let key = NSAttributedString.Key.foregroundColor
let value: [NSAttributedString.Key : Any]? = [key: color]
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(containIdenticalContent(value, for: key))
let objectValue = resultObject.titleTextAttributes(for: state)
expect(objectValue).to(containIdenticalContent(value, for: key))
}
}
context("isEnabled") {
it("should get and set") {
let lens: Lens<UIBarItem, Bool> = isEnabled()
let object = UIBarButtonItem()
let value: Bool = !object.isEnabled
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.isEnabled).to(equal(value))
}
}
context("title") {
it("should get and set") {
let lens: Lens<UIBarItem, String?> = title()
let object = UIBarButtonItem()
let value: String = "mama"
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.title).to(equal(value))
}
}
context("image") {
it("should get and set") {
let lens: Lens<UIBarItem, UIImage?> = image()
let object = UIBarButtonItem()
let value: UIImage = UIImage()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.image).to(equal(value))
}
}
context("landscapeImagePhone") {
it("should get and set") {
let lens: Lens<UIBarItem, UIImage?> = landscapeImagePhone()
let object = UIBarButtonItem()
let value: UIImage = UIImage()
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.landscapeImagePhone).to(equal(value))
}
}
context("imageInsets") {
it("should get and set") {
let lens: Lens<UIBarItem, UIEdgeInsets> = imageInsets()
let object = UIBarButtonItem()
let value: UIEdgeInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.imageInsets).to(equal(value))
}
}
context("landscapeImagePhoneInsets") {
it("should get and set") {
let lens: Lens<UIBarItem, UIEdgeInsets> = landscapeImagePhoneInsets()
let object = UIBarButtonItem()
let value: UIEdgeInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.landscapeImagePhoneInsets).to(equal(value))
}
}
context("tag") {
it("should get and set") {
let lens: Lens<UIBarItem, Int> = tag()
let object = UIBarButtonItem()
let value: Int = 2
let resultObject = lens.set(object, value)
let resultValue = lens.get(resultObject)
expect(resultValue).to(equal(value))
expect(resultObject.tag).to(equal(value))
}
}
}
}
}
|
//
// HeroComicsCollectionViewModel.swift
// MarvelMVVM
//
// Created by William Alvelos on 10/9/19.
// Copyright © 2019 William Alvelos. All rights reserved.
//
import Foundation
class HeroComicsCollectionViewModel {
//*************************************************
// MARK: - Private Properties
//*************************************************
private let comics: ComicModel
//*************************************************
// MARK: - Public Properties
//*************************************************
var thumbnail: String {
return comics.thumbnail.fullPath
}
var title: String {
return comics.title ?? "Título Desconhecido"
}
//*************************************************
// MARK: - Inits
//*************************************************
init(comics: ComicModel) {
self.comics = comics
}
}
|
//
// DimensionTests.swift
// florafinder
//
// Created by Andrew Tokeley on 21/04/16.
// Copyright © 2016 Andrew Tokeley . All rights reserved.
//
import XCTest
@testable import florafinder
class DimensionTests: TestBase {
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRatioNarrow()
{
// very long, narrow leaf
let dimension = leafDimensionService.addLeafDimension(Measurement(width: 1, length: 12), maximumSize: Measurement(width: 3, length: 40))
XCTAssertTrue(dimension.shape == LeafShapeEnum.Narrow)
}
func testRatioIfNoDimensions()
{
// very broad leaf
let dimension = leafDimensionService.addLeafDimension(Measurement(width: 7, length: 6), maximumSize: Measurement(width: 9, length: 10))
dimension.lengthMax = nil
dimension.lengthMin = nil
dimension.widthMax = nil
dimension.widthMin = nil
XCTAssertTrue(dimension.ratio == 0)
}
func testRatioBroad()
{
// very broad leaf
let dimension = leafDimensionService.addLeafDimension(Measurement(width: 7, length: 6), maximumSize: Measurement(width: 9, length: 10))
XCTAssertTrue(dimension.shape == LeafShapeEnum.Broad)
}
func testRatioRegular()
{
// normal leaf ratio (ratio 2)
let dimension = leafDimensionService.addLeafDimension(Measurement(width: 1, length: 2), maximumSize: Measurement(width: 2, length: 4))
XCTAssertTrue(dimension.shape == LeafShapeEnum.Regular)
}
func testVarianceBetweenSizeAndDimension() {
let dimension = leafDimensionService.addLeafDimension(Measurement(width: 1, length: 2), maximumSize: Measurement(width: 4, length: 6))
// perfect match would be (2.5, 4)
let perfecHit = leafDimensionService.deviationOfSizeFromDimension(dimension, size: Measurement(width: 2.5, length: 4))
XCTAssertTrue(perfecHit == Measurement(width: 0,length: 0), "\(perfecHit) not zero")
// anywhere inside the range will be less than 2 deviations
let insideDeviation = leafDimensionService.deviationOfSizeFromDimension(dimension, size: Measurement(width: 3.2, length: 5.2))
XCTAssertTrue(insideDeviation.width <= 2 && insideDeviation.length <= 2, "\(perfecHit) not within 2 deviations")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.