text stringlengths 8 1.32M |
|---|
//
// waves_ios.swift
// waves-ios
//
// Created by Charlie White on 1/23/15.
// Copyright (c) 2015 Charlie White. All rights reserved.
//
import Foundation
import CoreData
class ManagedWave: NSManagedObject {
@NSManaged var identifier: NSString!
@NSManaged var slug: NSString!
@NSManaged var titlePhotoUrl: NSString!
@NSManaged var mapPhotoUrl: NSString!
@NSManaged var distance: NSNumber!
@NSManaged var latitude: NSNumber!
@NSManaged var longitude: NSNumber!
@NSManaged var sessionsCount: NSNumber!
@NSManaged var buoy: waves_ios.ManagedBuoy!
@NSManaged var sessions: NSSet!
}
|
//
// TermsandServiceVC.swift
// Nuooly
//
// Created by Mahnoor Fatima on 6/12/18.
// Copyright © 2018 Mahnoor Fatima. All rights reserved.
//
import UIKit
class TermsandServiceVC: UIViewController {
@IBOutlet weak var descriptionTV: UITextView!
@IBOutlet weak var downloadPdfBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Terms and Services"
// Do any additional setup after loading the view.
}
@IBAction func downloadPDF(_ sender: Any) {
}
deinit {
print("deinit terms and service vc")
}
}
|
//
// AppDelegate.swift
// TXVideoDome
//
// Created by 98data on 2019/9/28.
// Copyright © 2019 98data. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let License_Url = "http://license.vod2.myqcloud.com/license/v1/10b5c66e4e7b7609e568a02e567800d9/TXUgcSDK.licence"
let Video_Key = "d08de4734a49bc3807abff720e851dbf"
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
TXUGCBase.setLicenceURL(License_Url, key: Video_Key)
return true
}
}
|
//
// MealListCell.swift
// Foody2
//
// Created by Sebastian Strus on 2018-06-18.
// Copyright © 2018 Sebastian Strus. All rights reserved.
//
import UIKit
import Cosmos
class MealListCell: UITableViewCell {
let cellView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.setCellShadow()
return view
}()
let pictureImageView: CustomImageView = {
var iv = CustomImageView()
iv.contentMode = .scaleAspectFit
return iv
}()
let titleLabel: UILabel = {
let label = UILabel()
label.textColor = .darkGray
label.font = AppFonts.LIST_CELL_FONT
return label
}()
let cosmosView: CosmosView = {
let cv = CosmosView()
cv.settings.updateOnTouch = false
cv.settings.fillMode = .half
cv.settings.starSize = Device.IS_IPHONE ? 30 : 60
cv.settings.starMargin = Device.IS_IPHONE ? 5 : 10
cv.settings.filledColor = UIColor.orange
cv.settings.emptyBorderColor = UIColor.orange
cv.settings.filledBorderColor = UIColor.orange
return cv
}()
let distanceLabel: UILabel = {
let label = UILabel()
label.textColor = .darkGray
label.textAlignment = .right
label.font = AppFonts.LIST_CELL_DISTANCE_FONT
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
private func setup() {
backgroundColor = AppColors.SILVER_GREY
addSubview(cellView)
cellView.addSubview(pictureImageView)
let stackView = UIStackView(arrangedSubviews: [titleLabel, cosmosView])
stackView.axis = .vertical
stackView.backgroundColor = UIColor.blue
stackView.distribution = .fillProportionally
stackView.spacing = 4
cellView.addSubview(stackView)
cellView.addSubview(distanceLabel)
cellView.setAnchor(top: topAnchor,
leading: leadingAnchor,
bottom: bottomAnchor,
trailing: trailingAnchor,
paddingTop: 4,
paddingLeft: 8,
paddingBottom: 4,
paddingRight: 8)
pictureImageView.setAnchor(top: nil,
leading: cellView.leadingAnchor,
bottom: nil,
trailing: nil,
paddingTop: 5,
paddingLeft: 5,
paddingBottom: 5,
paddingRight: 5,
width: Device.IS_IPHONE ? 60 : 120,
height: Device.IS_IPHONE ? 60 : 120)
pictureImageView.centerYAnchor.constraint(equalTo: cellView.centerYAnchor).isActive = true
stackView.setAnchor(top: nil,
leading: cellView.leadingAnchor,
bottom: nil,
trailing: cellView.trailingAnchor,
paddingTop: 0,
paddingLeft: Device.IS_IPHONE ? 84 : 150,
paddingBottom: 0,
paddingRight: 5,
width: 0,
height: Device.IS_IPHONE ? 60 : 120)
stackView.centerYAnchor.constraint(equalTo: pictureImageView.centerYAnchor).isActive = true
titleLabel.setAnchor(top: nil,
leading: stackView.leadingAnchor,
bottom: nil,
trailing: stackView.trailingAnchor,
paddingTop: 0,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0,
width: 0,
height: Device.IS_IPHONE ? 28 : 58)
cosmosView.setAnchor(top: nil,
leading: stackView.leadingAnchor,
bottom: nil,
trailing: stackView.trailingAnchor,
paddingTop: 0,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0,
width: 0,
height: Device.IS_IPHONE ? 28 : 58)
distanceLabel.setAnchor(top: nil,
leading: nil,
bottom: stackView.bottomAnchor,
trailing: stackView.trailingAnchor,
paddingTop: 0,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0,
width: 70,
height: Device.IS_IPHONE ? 28 : 58)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// ZXSingleTextCell.swift
// YDY_GJ_3_5
//
// Created by screson on 2017/5/17.
// Copyright © 2017年 screson. All rights reserved.
//
import UIKit
class ZXSingleTextCell: UITableViewCell {
@IBOutlet weak var lbText: UILabel!
@IBOutlet weak var separatorLine: UIView!
@IBOutlet weak var leftOffset: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.lbText.font = UIFont.zx_bodyFont(UIFont.zx_bodyFontSize)
self.lbText.textColor = UIColor.zx_textColorMark
self.separatorLine.backgroundColor = UIColor.zx_borderColor
self.contentView.backgroundColor = UIColor.zx_subTintColor
self.selectionStyle = .none
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
if selected {
self.contentView.backgroundColor = UIColor.white
self.lbText.textColor = UIColor.zx_textColorTitle
} else {
self.contentView.backgroundColor = UIColor.zx_subTintColor
self.lbText.textColor = UIColor.zx_textColorMark
}
}
}
|
//
// Date+Extension.swift
// mytine
//
// Created by 남수김 on 2020/07/27.
// Copyright © 2020 황수빈. All rights reserved.
//
import Foundation
extension Date {
private static func simpleDateFormatter(format: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "ko")
formatter.timeZone = .current
formatter.dateFormat = format
return formatter
}
func makeRootineId() -> String {
let formatter = Date.simpleDateFormatter(format: "yyyyMMdd")
let dateString = formatter.string(from: self)
return dateString
}
// 월 시작요일 계산
static func startWeekday(year: String, month: String) -> Int {
let formatter = simpleDateFormatter(format: "yyyyMMdd")
let dateString = "\(year)\(month)01"
guard let date = formatter.date(from: dateString) else {
return -1
}
let weekday = Calendar.current.component(.weekday, from: date)
// sun:1 mon:2 tue:3 wed:4 thr:5 fri:6 sat:7
return weekday
}
static func isLeapYear(_ year: Int) -> Bool {
let isLeapYear = ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
return isLeapYear
}
func getMonth() -> Int {
let month = Calendar.current.component(.month, from: self)
return month
}
func getYear() -> Int {
let year = Calendar.current.component(.year, from: self)
return year
}
func getWeekday() -> Int {
let weekDay = Calendar.current.component(.weekday, from: self)
return weekDay
}
func getDay() -> Int {
let day = Calendar.current.component(.day, from: self)
return day
}
}
|
//
// HomeViewModel.swift
// DevBoostItau-Project1
//
// Created by Helio Junior on 05/09/20.
// Copyright © 2020 DevBoost-Itau. All rights reserved.
//
import Foundation
import CoreData
class HomeViewModel {
// MARK: - Properties
var balanceVisible: Bool = false
private var context: NSManagedObjectContext
init(context: NSManagedObjectContext) {
self.context = context
}
// MARK: - Methods
func getBalance() -> String {
if !balanceVisible {
return "R$ -----"
}
let fetchRequest: NSFetchRequest<Investment> = Investment.fetchRequest()
do {
let investments = try context.fetch(fetchRequest)
let total = InvestmentsManager.getTotalInvestmentsValue(investments: investments)
return "\(total.formatMoney())"
} catch {
print("error")
}
return ""
}
func performLogout(_ completion: @escaping ((Result<String, APIError>) -> Void)) {
let logoutSuccess = AuthManager.shared.performLogout()
if logoutSuccess {
completion(Result.success(""))
} else {
completion(Result.failure(APIError.error("error ao fazer logout")))
print("Não foi possível realizar o logout.")
}
}
}
|
//
// NewtonPlugin.swift
// Newton Cordova Demo
//
// Created by Mirco Cipriani on 25/05/2017.
//
//
import Foundation
import Newton
import UIKit
let TAG = "NewtonPlugin"
func DDIlog(_ message: String) {
NSLog("[%@] - %@", TAG, message)
}
@objc(NewtonPlugin) class NewtonPlugin : CDVPlugin {
var callbackId:String?
// app status passed by appdelegate implemented in objc
open var notificationMessage:[String: Any] = [:]
open var isInline:Bool = false
open var coldstart:Bool = false
fileprivate var isAlreadyInitialized:Bool = false
//public var localNotificationMessage:UILocalNotification
enum PluginError: Error {
case invalidParameter(parameterName: String)
case internalError(reason: String)
var description: String {
switch self {
case .invalidParameter(let parameterName): return "invalid parameter: "+parameterName
case .internalError(let reason): return "internal error: "+reason
}
}
}
enum LoginOptions: String {
case customData
case externalId
case type
case customId
}
enum LoginFlowType: String {
case custom
case external
case _unknown
}
func getNewtonSecret() throws -> String {
var keyForSecret = "NEWTON_SECRET"
if DEBUG_BUILD.boolValue {
keyForSecret = "NEWTON_SECRET_DEV"
}
if let secret = Bundle.main.infoDictionary?[keyForSecret] as? String {
DDIlog("using secret: \(secret) got from \(keyForSecret)")
return secret;
}
throw PluginError.internalError(reason: "Error while getting Newton secret from pList NEWTON_SECRET")
}
override func pluginInitialize() {
DDIlog("pluginInitialize()")
notificationMessage = [String: Any]()
//localNotificationMessage = UILocalNotification()
}
override open func onAppTerminate() {
//
}
func initialize(_ command: CDVInvokedUrlCommand) {
DDIlog("action: initialize")
var initOk: Bool = true
var initResult = [String:Any]()
var initError:String = "no error"
do {
if (isAlreadyInitialized) {
initResult["initialized"] = true
} else {
let newtonSecret:String = try self.getNewtonSecret();
// create a dictionary for Newton Custom Data
var customDataDict: Dictionary<String, Any> = Dictionary()
// if sent a valid custom data from JS use that
if command.argument(at: 0) != nil {
if let customDataArg = command.argument(at: 0) as? NSDictionary {
if let customDataDictArg = customDataArg as? Dictionary<String, Any> {
customDataDict = customDataDictArg
}
}
}
let customData = NWSimpleObject(fromDictionary: customDataDict)
try customData?.setBool(key: "hybrid", value: true)
let newtonInstance = try Newton.getSharedInstanceWithConfig(conf: newtonSecret, customData: customData)
try newtonInstance.getPushManager().registerDevice();
// save JS callback to call it when a push arrive
callbackId = command.callbackId
_ = try newtonInstance.getPushManager().setPushCallback(callback: { push in
DDIlog("A Push Notification has been handled. \(push.description)")
self.sendPushToJs(push)
})
// if there are any notification saved process them
if isNotificationMessageAvailable() {
let launchOptions = getNotificationMessage()
_ = try? newtonInstance.getPushManager().setNotifyLaunchOptions(launchOptions:launchOptions)
DDIlog("LaunchOptions sent to Newton: \(launchOptions as AnyObject)")
}
clearNotificationMessage()
isAlreadyInitialized = true
initResult["initialized"] = true
DDIlog("initialization done! Newton Version: \(Newton.versionString) Build: \(Newton.buildNumber) Environment: \(newtonInstance.environmentString)")
}
}
catch let err as PluginError {
initOk = false
initError = err.description
}
catch {
initOk = false
initError = error as! String
}
let result: CDVPluginResult
if initOk {
result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: initResult)
} else {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: initError)
}
// save the callback for using it when a push arrive
result.setKeepCallbackAs(true)
commandDelegate!.send(result, callbackId: command.callbackId)
}
func setApplicationIconBadgeNumber(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
// create a dictionary for command options
var optionsDict: Dictionary<String, Any> = Dictionary()
// if sent a valid custom data from JS use that
if command.argument(at: 0) != nil {
if let optionsArg = command.argument(at: 0) as? NSDictionary {
if let optionsDictArg = optionsArg as? Dictionary<String, Any> {
optionsDict = optionsDictArg
}
}
}
if optionsDict["badge"] != nil {
throw PluginError.invalidParameter(parameterName: "badge")
}
guard Int(optionsDict["badge"] as! String) != nil else {
throw PluginError.invalidParameter(parameterName: "value for badge")
}
let app = UIApplication.shared
app.applicationIconBadgeNumber = optionsDict["badge"] as! Int
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func clearAllNotifications(_ command: CDVInvokedUrlCommand) {
let app = UIApplication.shared
app.applicationIconBadgeNumber = 0
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
}
func sendEvent(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
var name:String = ""
var customData = NWSimpleObject(fromJSONString: "{}")
if command.argument(at: 0) != nil {
if let nameArg = command.argument(at: 0) as? String {
name = nameArg
}
}
if command.argument(at: 1) != nil {
if let customDataArg = command.argument(at: 1) as? String {
customData = NWSimpleObject(fromJSONString: customDataArg)
}
}
if name == "" {
throw PluginError.invalidParameter(parameterName: "name")
}
try Newton.getSharedInstance().sendEvent(name: name, customData: customData)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func startLoginFlowWithParams(_ command: CDVInvokedUrlCommand) {
// FIXME: TO COMPLETE! see Android implementation
var errorDesc:String = "Unknown error"
let loginCallbackId = command.callbackId
var loginFlowType = LoginFlowType._unknown
do {
var eventParams:[String: Any] = [String: Any]()
let eventParamsArg = command.argument(at: 0)
guard eventParamsArg != nil else {
throw PluginError.invalidParameter(parameterName: "options")
}
eventParams = eventParamsArg as! [String: Any]
/**
* 1#
*
* initialize the loginBuilder and set completion callbacks
* to call javascript when done
*
*/
let loginBuilder = try Newton.getSharedInstance().getLoginBuilder()
_ = loginBuilder.setOnFlowCompleteCallback(callback: { error in
DispatchQueue.main.async { () -> Void in
// on Android I'm saving the callback with keepCallback, but I think that the callback is not needed anymore after FlowCompleteCallback
if let error = error {
self.commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: String(describing: error)),
callbackId: loginCallbackId
)
} else {
self.commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: loginCallbackId
)
}
}
})
/**
* 2#
*
* iterate over parameters to initialize the login builder
*
*/
for (optionName, optionValue) in eventParams {
let loginOptionName = LoginOptions(rawValue: optionName)
guard (loginOptionName != nil) else {
//throw PluginError.invalidParameter(parameterName: optionName)
DDIlog("startLoginFlowWithParams() unknow param name: "+optionName)
continue
}
switch loginOptionName! {
case .customData:
guard let optionValue = optionValue as? [String: Any] else {
throw PluginError.invalidParameter(parameterName: "value of "+optionName)
}
let customData = NWSimpleObject(fromDictionary: optionValue)
guard let customDataSO = customData else {
throw PluginError.invalidParameter(parameterName: "value of customData")
}
// ignore the result
_ = loginBuilder.setCustomData(cData: customDataSO)
case .externalId:
guard let optionValue = optionValue as? String else {
throw PluginError.invalidParameter(parameterName: "value of "+optionName)
}
// ignore the result
_ = loginBuilder.setExternalID(externalId: optionValue)
case .type:
guard let optionValue = optionValue as? String else {
throw PluginError.invalidParameter(parameterName: "value of "+optionName)
}
guard LoginFlowType(rawValue: optionValue) != nil else {
throw PluginError.invalidParameter(parameterName: "value of type")
}
loginFlowType = LoginFlowType(rawValue: optionValue)!
case .customId:
guard let optionValue = optionValue as? String else {
throw PluginError.invalidParameter(parameterName: "value of "+optionName)
}
// ignore the result
_ = loginBuilder.setCustomID(customId: optionValue)
} // end switch loginOptionName
} // end for (optionName, optionValue) in eventParams
/**
* 3#
*
* then start the login flow
*
*/
switch loginFlowType {
case .external:
let flow = try loginBuilder.getExternalLoginFlow()
flow.startLoginFlow()
case .custom:
let flow = try loginBuilder.getCustomLoginFlow()
flow.startLoginFlow()
case ._unknown:
throw PluginError.invalidParameter(parameterName: "missing type parameter")
}
let result:CDVPluginResult = CDVPluginResult(status: CDVCommandStatus_NO_RESULT)
// save the callback for using it later
result.setKeepCallbackAs(true)
commandDelegate!.send(result, callbackId: command.callbackId )
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
DDIlog("startLoginFlowWithParams() exception: "+errorDesc)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func isUserLogged(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
let logged = try Newton.getSharedInstance().isUserLogged()
var result = [String:Any]()
result["isUserLogged"] = logged
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK, messageAs: result),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func getEnvironmentString(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
let environmentString = try Newton.getSharedInstance().environmentString
var result = [String:Any]()
result["environmentString"] = environmentString
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK, messageAs: result),
callbackId: command.callbackId
)
return
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func userLogout(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
try Newton.getSharedInstance().userLogout()
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func getUserMetaInfo(_ command: CDVInvokedUrlCommand) {
// FIXME: Check implementation
var errorDesc:String = "Unknown error"
do {
try Newton.getSharedInstance().getUserMetaInfo(callback: { (userMetaInfoErr : NWError?, userMetaInfo : [String : Any]?) in
if ((userMetaInfoErr) != nil) {
self.commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: userMetaInfoErr.debugDescription),
callbackId: command.callbackId
)
} else {
self.commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK, messageAs: userMetaInfo),
callbackId: command.callbackId
)
}
})
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func getUserToken(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
let logged = try Newton.getSharedInstance().getUserToken()
var result = [String:Any]()
result["userToken"] = logged
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK, messageAs: result),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func getOAuthProviders(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
let providers:[String] = try Newton.getSharedInstance().getOAuthProviders()
var result = [String:Any]()
result["oAuthProviders"] = providers
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK, messageAs: result),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func rankContent(_ command: CDVInvokedUrlCommand) {
// FIXME: check if parameter recognition is working, expecially the enum from string of scope arg
var errorDesc:String = "Unknown error"
do {
var contentId:String = ""
/// - consumption: consumption
/// - social: social
/// - editorial: editorial
/// - unknown: used internally
var scope = RankingScope(scope: .unknown)
var multipler:Float = 1.0
if command.argument(at: 0) != nil {
if let contentIdArg = command.argument(at: 0) as? String {
contentId = contentIdArg
}
}
if command.argument(at: 1) != nil {
if let scopeArg = command.argument(at: 1) as? String {
if let scopeEnumArg = RankingScope._RankingScope(rawValue: scopeArg.lowercased()) {
scope = RankingScope(scope: scopeEnumArg)
}
}
}
if command.argument(at: 2) != nil {
if let multiplerArgString = command.argument(at: 2) as? String {
if let multiplerArg = Float(multiplerArgString) {
multipler = multiplerArg
}
}
}
if contentId == "" {
throw PluginError.invalidParameter(parameterName: "contentId")
}
try Newton.getSharedInstance().rankContent(contentId: contentId, scope: scope, multiplier: multipler)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func timedEventStart(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
var name:String = ""
var customData = NWSimpleObject(fromJSONString: "{}")
if command.argument(at: 0) != nil {
if let nameArg = command.argument(at: 0) as? String {
name = nameArg
}
}
if command.argument(at: 1) != nil {
if let customDataArg = command.argument(at: 1) as? String {
customData = NWSimpleObject(fromJSONString: customDataArg)
}
}
if name == "" {
throw PluginError.invalidParameter(parameterName: "name")
}
try Newton.getSharedInstance().timedEventStart(name: name, customData: customData)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func timedEventStop(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
var name:String = ""
var customData = NWSimpleObject(fromJSONString: "{}")
if command.argument(at: 0) != nil {
if let nameArg = command.argument(at: 0) as? String {
name = nameArg
}
}
if command.argument(at: 1) != nil {
if let customDataArg = command.argument(at: 1) as? String {
customData = NWSimpleObject(fromJSONString: customDataArg)
}
}
if name == "" {
throw PluginError.invalidParameter(parameterName: "name")
}
try Newton.getSharedInstance().timedEventStop(name: name, customData: customData)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func flowBegin(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
var name:String = ""
var customData = NWSimpleObject(fromJSONString: "{}")
if command.argument(at: 0) != nil {
if let nameArg = command.argument(at: 0) as? String {
name = nameArg
}
}
if command.argument(at: 1) != nil {
if let customDataArg = command.argument(at: 1) as? String {
customData = NWSimpleObject(fromJSONString: customDataArg)
}
}
if name == "" {
throw PluginError.invalidParameter(parameterName: "name")
}
try Newton.getSharedInstance().flowBegin(name: name, customData: customData)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func flowCancel(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
var name:String = ""
var customData = NWSimpleObject(fromJSONString: "{}")
if command.argument(at: 0) != nil {
if let nameArg = command.argument(at: 0) as? String {
name = nameArg
}
}
if command.argument(at: 1) != nil {
if let customDataArg = command.argument(at: 1) as? String {
customData = NWSimpleObject(fromJSONString: customDataArg)
}
}
if name == "" {
throw PluginError.invalidParameter(parameterName: "name")
}
try Newton.getSharedInstance().flowCancel(reason: name, customData: customData)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func flowFail(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
var name:String = ""
var customData = NWSimpleObject(fromJSONString: "{}")
if command.argument(at: 0) != nil {
if let nameArg = command.argument(at: 0) as? String {
name = nameArg
}
}
if command.argument(at: 1) != nil {
if let customDataArg = command.argument(at: 1) as? String {
customData = NWSimpleObject(fromJSONString: customDataArg)
}
}
if name == "" {
throw PluginError.invalidParameter(parameterName: "name")
}
try Newton.getSharedInstance().flowFail(reason: name, customData: customData)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func flowStep(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
var name:String = ""
var customData = NWSimpleObject(fromJSONString: "{}")
if command.argument(at: 0) != nil {
if let nameArg = command.argument(at: 0) as? String {
name = nameArg
}
}
if command.argument(at: 1) != nil {
if let customDataArg = command.argument(at: 1) as? String {
customData = NWSimpleObject(fromJSONString: customDataArg)
}
}
if name == "" {
throw PluginError.invalidParameter(parameterName: "name")
}
try Newton.getSharedInstance().flowStep(name: name, customData: customData)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
func flowSucceed(_ command: CDVInvokedUrlCommand) {
var errorDesc:String = "Unknown error"
do {
var name:String = ""
var customData = NWSimpleObject(fromJSONString: "{}")
if command.argument(at: 0) != nil {
if let nameArg = command.argument(at: 0) as? String {
name = nameArg
}
}
if command.argument(at: 1) != nil {
if let customDataArg = command.argument(at: 1) as? String {
customData = NWSimpleObject(fromJSONString: customDataArg)
}
}
if name == "" {
throw PluginError.invalidParameter(parameterName: "name")
}
try Newton.getSharedInstance().flowSucceed(reason: name, customData: customData)
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_OK),
callbackId: command.callbackId
)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
commandDelegate!.send(
CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: errorDesc),
callbackId: command.callbackId
)
}
/*
func didReceiveLocalNotification (notification: Notification) {
DDIlog("didReceiveLocalNotification")
if UIApplication.shared.applicationState != .active {
// FIXME!!
var data = "undefined"
if let uiNotification = notification.object as? UILocalNotification {
if let notificationData = uiNotification.userInfo?["geofence.notification.data"] as? String {
data = notificationData
}
let js = "setTimeout('geofence.onNotificationClicked(" + data + ")',0)"
//evaluateJs(js)
}
}
}
*/
open func saveNotificationMessage(_ message:[String: Any]) {
notificationMessage = message
}
fileprivate func getNotificationMessage() -> [UIApplicationLaunchOptionsKey:Any] {
var launchOptions = [UIApplicationLaunchOptionsKey:Any]()
for (kind, value) in notificationMessage {
launchOptions[UIApplicationLaunchOptionsKey(kind)] = value
}
return launchOptions
}
fileprivate func isNotificationMessageAvailable() -> Bool {
return notificationMessage.count > 0
}
fileprivate func clearNotificationMessage() {
coldstart = false
notificationMessage.removeAll()
let app = UIApplication.shared
app.applicationIconBadgeNumber = 0
}
/*
* Send push data to Newton if the plugin has been initialized
* otherwise the push data will be sent on plugin initialization
*/
func onNotifyLaunchOptions() {
DDIlog("onNotifyLaunchOptions() start")
// if plugin has been initialized and there is a push saved then proceed
if (self.callbackId != nil && !self.callbackId!.isEmpty && isNotificationMessageAvailable()) {
var errorDesc:String = "Unknown error"
do {
let newtonInstance = try Newton.getSharedInstance()
// FIXME: send launchOptions received without conversion!
let launchOptions = getNotificationMessage()
try newtonInstance.getPushManager().setNotifyLaunchOptions(launchOptions:launchOptions)
clearNotificationMessage()
DDIlog("onNotifyLaunchOptions() Push data sent to Newton: \(launchOptions as AnyObject)")
//dump(launchOptions)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
DDIlog("onNotifyLaunchOptions error: "+errorDesc)
}
}
func onRegisterForRemoteNotificationsOk(_ token:Data) {
// if plugin has been initialized then proceed
if (self.callbackId != nil && !self.callbackId!.isEmpty) {
var errorDesc:String = "Unknown error"
do {
let newtonInstance = try Newton.getSharedInstance()
try newtonInstance.getPushManager().setDeviceToken(token: token)
DDIlog("Token sent to Newton")
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
DDIlog("onRegisterForRemoteNotificationsOk error: "+errorDesc)
}
}
func onRegisterForRemoteNotificationsKo(_ error:Error) {
// if plugin has been initialized then proceed
if (self.callbackId != nil && !self.callbackId!.isEmpty) {
var errorDesc:String = "Unknown error"
do {
let newtonInstance = try Newton.getSharedInstance()
try newtonInstance.getPushManager().setRegistrationError(error: error)
DDIlog("Registration error sent to Newton")
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
DDIlog("onRegisterForRemoteNotificationsKo error sending error to newton: "+errorDesc)
}
}
/*
* Send push data to Newton if the plugin has been initialized
* otherwise the push data will be sent on plugin initialization
*/
func onReceiveRemoteNotification() {
DDIlog("onReceiveRemoteNotification() start")
// if plugin has been initialized and there is a push saved then proceed
if (self.callbackId != nil && !self.callbackId!.isEmpty && isNotificationMessageAvailable()) {
var errorDesc:String = "Unknown error"
do {
let newtonInstance = try Newton.getSharedInstance()
let userInfo = notificationMessage
try newtonInstance.getPushManager().processRemoteNotification(userInfo:userInfo)
clearNotificationMessage()
DDIlog("onReceiveRemoteNotification() Push data sent to Newton: \(userInfo as AnyObject)")
//dump(userInfo)
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
DDIlog("onReceiveRemoteNotification error: "+errorDesc)
}
}
/*
func onReceiveLocalNotification() {
// if plugin has been initialized and there is a push saved then proceed
if (self.callbackId != nil && !self.callbackId!.isEmpty) {
var errorDesc:String = "Unknown error"
do {
let newtonInstance = try Newton.getSharedInstance()
// FIXME: check type validity
// public func processLocalNotification(notification: UILocalNotification)
try newtonInstance.getPushManager().processLocalNotification(notification:localNotificationMessage)
DDIlog("Push data sent to Newton")
return
}
catch let err as PluginError {
errorDesc = err.description
}
catch {
errorDesc = String(describing: error)
}
DDIlog("onReceiveRemoteNotification error: "+errorDesc)
}
}
*/
func convertCustomFieldToJson(_ customFieldSO: NWSimpleObject?) -> [String:Any] {
var customFieldJsonDict = [String:Any]()
if let customFieldSOok = customFieldSO {
customFieldJsonDict = customFieldSOok.getDictionary()
}
return customFieldJsonDict
}
func sendPushToJs(_ push:AnyObject) {
//
if (self.callbackId != nil && !self.callbackId!.isEmpty) {
var pushData = [String:Any]()
pushData["isRemote"] = false
pushData["isRich"] = false
pushData["isSilent"] = false
pushData["isShown"] = false
pushData["id"] = false
pushData["body"] = false
pushData["title"] = false
pushData["url"] = false
pushData["customs"] = []
if let realPush = push as? NWStandardPush {
pushData["body"] = realPush.body
pushData["isShown"] = realPush.shown
pushData["isRemote"] = !realPush.isLocal
pushData["customs"] = self.convertCustomFieldToJson(realPush.customFields)
} else if let realPush = push as? NWBackgroundPush {
pushData["isRemote"] = !realPush.isLocal
pushData["customs"] = self.convertCustomFieldToJson(realPush.customFields)
} else if let realPush = push as? NWUrlPush {
pushData["body"] = realPush.body;
pushData["isShown"] = realPush.shown
pushData["isRemote"] = !realPush.isLocal
pushData["customs"] = self.convertCustomFieldToJson(realPush.customFields)
pushData["url"] = realPush.url
}
let result: CDVPluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: pushData)
result.setKeepCallbackAs(true)
commandDelegate!.send(result, callbackId: self.callbackId)
}
}
}
|
//
// Gear.swift
// FarmPlan
//
// Created by Thorsten Karrer on 13.03.21.
// Copyright © 2021 Thorsten Karrer. All rights reserved.
//
import Foundation
struct Recipe: Codable {
let base_id: String
let result_id: String
let cost: Int
let ingredients: [Ingredient]
}
struct Ingredient: Codable {
let amount: Int
let gear: String
}
struct Gear: Codable {
let base_id: String
let recipes: [Recipe]
let tier: Int
let required_level: Int
let stats: [String : Double]
let mark: String
let cost: Int
let image: String
let url: URL
let ingredients: [Ingredient]
let name: String
}
|
//
// SBServiceFactoryProtocol.swift
// BaseMVVM
//
// Created by ALEXEY ABDULIN on 21/08/2019.
// Copyright © 2019 ALEXEY ABDULIN. All rights reserved.
//
import Foundation
public protocol SBServiceFactoryProtocol
{
func ProvideAuthUserService() -> SBAuthUserServiceProtocol
func ProvideDownloadService() -> SBDowloadServiceProtocol
}
|
//
// ProfileCell.swift
// mojo_test
//
// Created by Yunyun Chen on 2/14/19.
// Copyright © 2019 Yunyun Chen. All rights reserved.
//
import UIKit
import Cosmos
import TinyConstraints
import SDWebImage
protocol ProfileCellDelegate {
func didTapChat(user: User)
func didTapProfileImage(user: User)
}
class ProfileCell: UICollectionViewCell {
var delegate: ProfileCellDelegate?
var cardViewModel: CardViewModel!
var user: User? {
didSet {
cardView.cardViewModel = user?.toCardViewModel()
guard let profileImageUrl = user?.imageUrl1 else { return }
if let url = URL(string: profileImageUrl) {
profileImageView.sd_setImage(with: url)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
layer.shadowOpacity = 0.3
layer.shadowRadius = 10
layer.shadowOffset = .init(width: 0, height: 10)
}
let cardView = CardView(frame: .zero)
let badge = UIImageView(image: #imageLiteral(resourceName: "popular"))
fileprivate func setupLayout() {
addSubview(cardView)
cardView.layer.cornerRadius = 16
cardView.fillSuperview()
addSubview(cosmosView)
cosmosView.anchor(top: nil, leading: leadingAnchor, bottom: bottomAnchor, trailing: nil, padding: .init(top: 0, left: 12, bottom: 122, right: 0))
addSubview(profileImageView)
profileImageView.anchor(top: nil, leading: nil, bottom: nil, trailing: trailingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 16), size: .init(width: 48, height: 48))
profileImageView.centerYAnchor.constraint(equalToSystemSpacingBelow: cosmosView.centerYAnchor, multiplier: 1).isActive = true
profileImageView.layer.borderWidth = 2
profileImageView.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleOpenProfileDetail))
singleTap.numberOfTapsRequired = 1
profileImageView.isUserInteractionEnabled = true
profileImageView.addGestureRecognizer(singleTap)
addSubview(chatButton)
chatButton.anchor(top: profileImageView.bottomAnchor, leading: nil, bottom: nil, trailing: nil, padding: .init(top: 16, left: 0, bottom: 0, right: 0), size: .init(width: 40, height: 40))
chatButton.centerXAnchor.constraint(equalToSystemSpacingAfter: profileImageView.centerXAnchor, multiplier: 1).isActive = true
chatButton.addTarget(self, action: #selector(handleChatRequest), for: .touchUpInside)
chatButton.setImage(#imageLiteral(resourceName: "chat-1").withRenderingMode(.alwaysOriginal), for: .normal)
}
@objc fileprivate func handleChatRequest() {
guard let user = self.user else { return }
self.delegate?.didTapChat(user: user)
}
@objc fileprivate func handleOpenProfileDetail() {
guard let user = self.user else { return }
self.delegate?.didTapProfileImage(user: user)
}
lazy var profileImageView = UIImageView(cornerRadius: 24)
lazy var chatButton = UIButton(type: .system)
lazy var cosmosView: CosmosView = {
var view = CosmosView()
view.settings.filledImage = #imageLiteral(resourceName: "filled-star").withRenderingMode(.alwaysOriginal)
view.settings.emptyImage = #imageLiteral(resourceName: "empty-star").withRenderingMode(.alwaysOriginal)
view.settings.starSize = 32
view.settings.starMargin = 2
view.settings.fillMode = .full
view.rating = 0
return view
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// CollectionImage.swift
// Domain
//
// Created by Tyler Zhao on 11/22/18.
// Copyright © 2018 Tyler Zhao. All rights reserved.
//
import Foundation
public struct CollectionImage: Codable {
public let uid: String
public let description: String
public let date: String
public let comments: [Comment]
}
|
//
// ArticlesListViewController.swift
// StarWarsWikia
//
// Created by Jordan Davies on 09/07/2018.
//
import UIKit
protocol ArticlesListDisplayLogic: class
{
func displayError(withMessage message: String)
func displayArticles(withViewModel viewModel: ArticlesListViewController.ViewModel)
}
final class ArticlesListViewController: UITableViewController, ArticlesListDisplayLogic
{
struct ViewModel
{
struct Article
{
var id: Int
var title: String
var abstract: String
var thumbnailUrl: String?
}
struct Category
{
var title: String
var articles: [Article]
}
var categories: [Category]
}
var interactor: ArticlesListBusinessLogic?
var router: ArticlesListRoutingLogic?
private var displayedArticles: [ViewModel.Category]?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
setup()
}
private func setup()
{
let viewController = self
let interactor = ArticlesListInteractor()
let presenter = ArticlesListPresenter()
let router = ArticlesListRouter()
let worker = ArticlesListWorker()
viewController.interactor = interactor
viewController.router = router
interactor.presenter = presenter
interactor.worker = worker
presenter.viewController = viewController
router.viewController = viewController
}
override func viewDidLoad()
{
super.viewDidLoad()
title = "Star Wars Wikia Articles"
tableView.register(UINib(nibName: "ArticlesListCell", bundle: nil), forCellReuseIdentifier: "ArticleCell")
setupRefreshControl()
refresh()
}
private func setupRefreshControl()
{
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
tableView.refreshControl = refreshControl
}
@objc private func refresh()
{
interactor?.getTopArticles()
}
func displayError(withMessage message: String)
{
let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: .cancel)
let retryAction = UIAlertAction(title: "Retry", style: .default) { [unowned self] (action) in
self.refresh()
}
alert.addAction(okAction)
alert.addAction(retryAction)
self.present(alert, animated: true, completion: nil)
}
func displayArticles(withViewModel viewModel: ViewModel)
{
displayedArticles = viewModel.categories
tableView.refreshControl?.endRefreshing()
tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int
{
guard let displayedArticles = displayedArticles else { return 0 }
return displayedArticles.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
guard let displayedArticles = displayedArticles else { return nil }
let category = displayedArticles[section]
return category.title.capitalized
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
guard let displayedArticles = displayedArticles else { return 0 }
let category = displayedArticles[section]
return category.articles.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 90
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
guard let displayedArticles = displayedArticles else { return UITableViewCell() }
let category = displayedArticles[indexPath.section]
let article = category.articles[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell") as! ArticlesListCell
cell.article = article
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
guard let displayedArticles = displayedArticles else { return }
let article = displayedArticles[indexPath.section].articles[indexPath.row]
router?.routeToArticle(article)
}
}
|
//
// SampleAppTests.swift
// SampleAppTests
//
// Created by yuchimur on 2018/11/26.
// Copyright © 2018 内村 祐之. All rights reserved.
//
import XCTest
@testable import SampleApp
class SampleAppTests: XCTestCase {
var viewController: ViewController!
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
viewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as? ViewController
}
func test_画面が表示されたら_プラスボタンが表示される() {
let button = viewController.plusButton
XCTAssertEqual(button?.titleLabel?.text, "+")
}
func test_画面が表示されたら_マイナスボタンが表示される() {
let button = viewController.minusButton
XCTAssertEqual(button?.titleLabel?.text, "−")
}
func test_画面が表示されたら_ラベルに0が表示される() {
let label = viewController.label
XCTAssertEqual(label?.text, "0")
}
func test_プラスボタンがタップされる_ラベルの数字が1つ増える() {
let button = viewController.plusButton
let label = viewController.label
XCTAssertEqual(label?.text, "0")
button?.sendActions(for: .touchUpInside)
XCTAssertEqual(label?.text, "1")
}
func test_マイナスボタンがタップされる_ラベルの数字が1つ減る() {
let button = viewController.minusButton
let label = viewController.label
XCTAssertEqual(label?.text, "0")
button?.sendActions(for: .touchUpInside)
XCTAssertEqual(label?.text, "-1")
}
}
private extension ViewController {
var plusButton: UIButton? {
return view
.subviews
.filter({ $0.accessibilityIdentifier == "plusButton" })
.compactMap({ $0 as? UIButton })
.first
}
var minusButton: UIButton? {
return view
.subviews
.filter({ $0.accessibilityIdentifier == "minusButton" })
.compactMap({ $0 as? UIButton })
.first
}
var label: UILabel? {
return view
.subviews
.filter({ $0.accessibilityIdentifier == "label" })
.compactMap({ $0 as? UILabel })
.first
}
}
|
//
// FruitBookViewController.swift
// FruitSchool
//
// Created by Presto on 2018. 9. 9..
// Copyright © 2018년 YAPP. All rights reserved.
//
import UIKit
import FSPagerView
import GaugeKit
import EFCountingLabel
import StoreKit
import SnapKit
class BookViewController: UIViewController {
// MARK: - Properties
private let cellIdentifier = "bookCell"
private lazy var chapterRecord = ChapterRecord.fetch()
private lazy var userRecord: UserRecord! = UserRecord.fetch().first
var currentIndex: Int {
return pagerView.currentIndex
}
var detailViewController: UIViewController? {
return (splitViewController?.viewControllers.last as? UINavigationController)?.topViewController
}
var detailNavigationController: UINavigationController? {
return detailViewController?.navigationController
}
lazy private var percentLabel: EFCountingLabel! = {
let label = EFCountingLabel()
label.format = "%d%%"
label.method = .easeInOut
label.textColor = .main
label.font = UIFont.systemFont(ofSize: 12)
view.addSubview(label)
return label
}()
lazy private var descriptionLabel: UILabel! = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12, weight: .medium)
label.textColor = .main
view.addSubview(label)
label.snp.makeConstraints { maker in
maker.centerX.equalTo(view.snp.centerX)
maker.top.equalTo(percentLabel.snp.bottom).offset(8)
}
return label
}()
lazy private var promotionReviewButton: UIButton! = {
let button = UIButton(type: .system)
button.setTitle("승급 심사", for: [])
button.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: .semibold)
button.clipsToBounds = true
button.layer.borderColor = UIColor.main.cgColor
button.layer.borderWidth = 2
button.addTarget(self, action: #selector(touchUpPromotionReviewButton(_:)), for: .touchUpInside)
view.addSubview(button)
button.snp.makeConstraints { maker in
maker.top.equalTo(percentLabel.snp.bottom).offset(40)
maker.width.equalTo(view.snp.width).multipliedBy(0.6)
maker.centerX.equalTo(view.snp.centerX)
maker.height.equalTo(40)
}
button.layer.cornerRadius = 20
return button
}()
lazy private var pageControl: FSPageControl = {
let pageControl = FSPageControl(frame: .zero)
pageControl.currentPage = 0
pageControl.numberOfPages = 3
pageControl.setFillColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.19), for: .normal)
pageControl.setFillColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.68), for: .selected)
pagerView.addSubview(pageControl)
pageControl.snp.makeConstraints { maker in
maker.bottom.equalTo(pagerView.snp.bottom).offset(-8)
maker.centerX.equalTo(view.snp.centerX)
maker.height.equalTo(20)
}
return pageControl
}()
@IBOutlet private weak var pagerView: FSPagerView! {
didSet {
pagerView.register(UINib(nibName: "BookCell", bundle: nil), forCellWithReuseIdentifier: cellIdentifier)
pagerView.transformer = FSPagerViewTransformer(type: .linear)
pagerView.interitemSpacing = 6
let width: CGFloat
if deviceModel == .iPad {
width = (splitViewController?.primaryColumnWidth ?? 0) * 0.83
} else {
width = UIScreen.main.bounds.width * 0.83
}
pagerView.itemSize = CGSize(width: width, height: width * 398 / 312)
pagerView.delegate = self
pagerView.dataSource = self
}
}
@IBOutlet weak var gaugeView: Gauge!
// MARK: - View Controler Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
makeBackButton()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
resetViews()
}
}
// MARK: - Button Touch Event
private extension BookViewController {
// 승급심사 버튼을 누르면 승급심사 뷰컨트롤러로 넘어감
@objc func touchUpPromotionReviewButton(_ sender: UIButton) {
guard let next = UIViewController.instantiate(storyboard: "PromotionReview", identifier: PromotionReviewContainerViewController.classNameToString) as? PromotionReviewContainerViewController else { return }
next.delegate = self
next.grade = currentIndex
present(next, animated: true, completion: nil)
}
}
// MARK: - PromotionReviewContainerViewController Custom Delegate Implementation
extension BookViewController: PromotionReviewDelegate {
// 승급심사 종료 후 교과서로 돌아왔을 때의 인터렉션 정의
func didDismissPromotionReviewViewController(_ grade: Int) {
let title: String
if grade == 2 {
title = "축하합니다!\n모든 승급심사를 통과했습니다."
} else {
title = "축하합니다!\n당신은 이제 \(Grade(rawValue: grade + 1)?.expression ?? "")입니다."
}
UIAlertController
.alert(title: title, message: nil)
.action(title: "확인", handler: { _ in
self.resetViews()
DispatchQueue.main.async {
if #available(iOS 10.3, *) {
SKStoreReviewController.requestReview()
}
}
})
.present(to: self)
}
}
extension BookViewController: FSPagerViewDataSource {
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
guard let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "bookCell", at: index) as? BookCell else { return FSPagerViewCell() }
let fruitsInBook = chapterRecord.filter { $0.grade == index }
let passedFruitsInBook = fruitsInBook.filter { $0.isPassed }
cell.setProperties(at: index, isPassed: fruitsInBook.count == passedFruitsInBook.count, isPassedCompletely: userRecord[index])
return cell
}
func numberOfItems(in pagerView: FSPagerView) -> Int {
return 3
}
}
extension BookViewController: FSPagerViewDelegate {
func pagerViewDidEndDecelerating(_ pagerView: FSPagerView) {
resetViews()
}
func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
pagerView.deselectItem(at: index, animated: true)
navigationController?.hidesBarsOnSwipe = false
navigationController?.setNavigationBarHidden(false, animated: false)
detailNavigationController?.hidesBarsOnSwipe = false
detailNavigationController?.setNavigationBarHidden(false, animated: false)
// 현재 등급과 교과서 등급을 비교하여 접근 제한
let myGrade = UserRecord.fetch().first?.grade ?? 0
if !(0...myGrade).contains(index) {
UIAlertController.presentErrorAlert(to: self, error: "당신은 아직 \(Grade(rawValue: myGrade)?.expression ?? "")예요!")
return
}
guard let next = UIViewController.instantiate(storyboard: "Chapter", identifier: ChapterViewController.classNameToString) as? ChapterViewController else { return }
next.grade = index
if deviceModel == .iPad {
if detailNavigationController?.viewControllers.count ?? 0 >= 2 {
detailNavigationController?.popToRootViewController(animated: false)
detailNavigationController?.pushViewController(next, animated: false)
} else {
detailNavigationController?.pushViewController(next, animated: true)
}
} else {
navigationController?.pushViewController(next, animated: true)
}
}
}
// MARK: - Making Dynamic Views
extension BookViewController {
func resetViews() {
let percent = accomplishment()
changePageControlStatus()
changeGaugeViewValue(percent)
makePercentLabel(percent)
changeDescriptionLabelText()
decideIfShowingPromotionReviewButton(percent)
makeTopImageView()
pagerView.reloadData()
view.layoutIfNeeded()
}
private func changePageControlStatus() {
pageControl.currentPage = currentIndex
}
private func changeGaugeViewValue(_ percent: CGFloat) {
gaugeView.animateRate(0.5, newValue: percent) { _ in }
}
private func makePercentLabel(_ percent: CGFloat) {
percentLabel.countFromCurrentValueTo(percent * 100, withDuration: 0.5)
let leading = gaugeView.frame.origin.x
if percent == 0 {
percentLabel.snp.remakeConstraints { maker in
maker.top.equalTo(gaugeView.snp.bottom).offset(6)
maker.centerX.equalTo(gaugeView.snp.leading)
}
} else {
percentLabel.snp.remakeConstraints { maker in
maker.top.equalTo(gaugeView.snp.bottom).offset(6)
maker.centerX.equalTo(gaugeView.snp.trailing)
.offset(leading - leading * percent)
.multipliedBy(percent)
}
}
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
// 화면을 비어보이지 않게 하는 레이블 만들기
private func changeDescriptionLabelText() {
descriptionLabel.text = descriptionLabelText()
}
// 승급심사 버튼 만들기
private func decideIfShowingPromotionReviewButton(_ percent: CGFloat) {
let passesCurrentBook = UserRecord.fetch().first?[pagerView.currentIndex] ?? false
if percent == 1 && !passesCurrentBook {
promotionReviewButton.isHidden = false
} else {
promotionReviewButton.isHidden = true
}
}
}
private extension BookViewController {
private func makeBackButton() {
let backBarButtonItem = UIBarButtonItem()
backBarButtonItem.title = "교과서"
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIImageView(image: #imageLiteral(resourceName: "logo_noncircle")))
navigationItem.backBarButtonItem = backBarButtonItem
}
private func makeTopImageView() {
let grade = userRecord.grade
let imageView = UIImageView(image: UIImage(named: ChapterTopImage.allCases[grade].rawValue))
imageView.contentMode = .scaleAspectFit
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: imageView)
}
func accomplishment() -> CGFloat {
let filtered = chapterRecord.filter("grade = %d", currentIndex)
let count = filtered.count
var passedCount = 0
for element in filtered where element.isPassed {
passedCount += 1
}
return CGFloat(passedCount) / CGFloat(count)
}
func descriptionLabelText() -> String? {
guard let userInfo = UserRecord.fetch().first else { return nil }
let userGrade = userInfo.grade
switch accomplishment() {
case 0 where userGrade == currentIndex:
return "자, 지금부터 과일 카드를 모아볼까?"
case 0 where userGrade < currentIndex:
return "아직 당신에겐 수련이 필요하오."
case 0.5:
return "벌써 반이나 모았다고? 조금만 더 힘을 내게!"
case 0..<0.5 where userGrade == 0, 0.5..<1 where userGrade == 0:
return "훈장님이 되고싶개"
case 0..<0.5 where userGrade == 1, 0.5..<1 where userGrade == 1:
return "훈장이 되고 싶소"
case 0..<0.5 where userGrade == 2, 0.5..<1 where userGrade == 2:
return "나는 훈장이오 만렙이슈"
case 1 where currentIndex == 0 && userInfo.passesDog:
return "드디어 사람이 되었개! 서당개 인생은 이제 안녕."
case 1 where currentIndex == 0 && !userInfo.passesDog:
return "당신은 이제 학도가 되기에 충분하개!"
case 1 where currentIndex == 1 && userInfo.passesStudent:
return "나도 어디서 꿀리지 않는 과일인이 되었소."
case 1 where currentIndex == 1 && !userInfo.passesStudent:
return "나는 훈장님이 되러 떠나겠어!"
case 1 where currentIndex == 2 && userInfo.passesBoss:
return "과일학당 훈장이오. 무엇이든 물어보시오."
case 1 where currentIndex == 2 && !userInfo.passesBoss:
return "앞으로도 많이 업데이트 할 예정이니 아직 지우지 말아주세요!"
default:
return nil
}
}
}
|
//
// JacketView.swift
// McKendrickUI
//
// Created by Steven Lipton on 3/10/20.
// Copyright © 2020 Steven Lipton. All rights reserved.
//
// An exercise file for iOS Development Tips Weekly
// A weekely course on LinkedIn Learning for iOS developers
// Season 10 (Q2 2020) video 10
// by Steven Lipton (C)2020, All rights reserved
// Learn more at https://linkedin-learning.pxf.io/YxZgj
// This Week: Create custom modifiers in SwiftUI while making the button panel a navigation panel.
// For more code, go to http://bit.ly/AppPieGithub
// Quarter Share, Ishmael Wang, Lois McKendrick, and
// Trader Tales from the Golden Age of the Solar Clipper
// copyright Nathan Lowell, used with permission
// To read the novel behind this project, see https://www.amazon.com/Quarter-Share-Traders-Golden-Clipper-ebook/dp/B00AMO7VM4
import SwiftUI
struct JacketView: View {
var isSelected:Bool = false
init(){
self.isSelected = true
}
init(isSelected:Bool){
self.isSelected = isSelected
}
var body: some View {
GeometryReader{ geometry in
VStack{
ContentHeaderView(headerTitle: "SC Louis McKendrick",headerSubtitle: "Ships Roster detail")
.frame(height:geometry.size.height * 0.1 )
.padding(.bottom,50)
ContentHeaderView(headerTitle: "Wang, Ishamael Horatio",headerSubtitle: "Messman Attendant")
.frame(height:geometry.size.height * 0.1 )
HeadlineView("Ratings")
Text("Engineman")
Text("Cargo Handler")
Text("Ordinary Spacer")
Text("Steward")
Spacer()
Text("Emergency Evacuation Station: 4")
}//Vstack root
.selectedTransition(isSelected: self.isSelected, geometry: geometry)
}//geometry reader
}
}
struct JacketView_Previews: PreviewProvider {
static var previews: some View {
JacketView(isSelected: false)
}
}
|
//: Playground - noun: a place where people can play
//import UIKit
//≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠
//basics
//var str = "Hello, playground"
//
//var newInt = 21
//
//let string = "Mom's sphagetti"
//
//var float = 3.0
//var int = 3
//let explicitFloat = Double = 40
//print(explicitFloat)J
//printing data
//var userName = "AJAY"
//var userId = "\(userName)-21-97"
//print("the username is \(userName)")
//print("the userId os \(userId)")
//triple inverteds
// recieving bug !!
// poof
// todo: report to apple
//Arrays and dictionary
//var myArray = [21,32,43,54,65,76,87,98]
//print(myArray[1])
//var myDictionary = ["username" : "Ajay",
// "userid" : "21!@2",
// "Contact info": [
// "street": "xyz",
// "colony": "abc",
// "towm": "qew",
// "code" : 121 not clear if we can insert dictionaries in dictionaries I mean we obviouslly could that's the whole point but not sure how
// ],
//]
//inititallising arrays and dictionaries
//var eDictionary = [String: Any]()
//var eArray = [Int]()//an array of integers initiallised
// lets input string values in the array
//eArray[0] = "Hakuna Matata" throws error that's cool
//eArray[0] = 32
//other type of constructors
//var shoppinglist = []
//var dic = [ : ]
//
//≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠≠
// Control flow
//the if statement
//if(true){
// print("pakchikpak raja babu")
// }
//
//
//// switch statement
//
//var chit = "Raja"
//var pscore = 0
//
//switch chit {
//case "Raja":
// print("Raja fir bjaega baja ")
// pscore = pscore + 1000
//case "Mantri":
// print("Main hu mantri main ppakdunga chor ko")
// pscore = pscore + 500
//case "Sipahi":
// print("Main hu sipahi main nahi ppakdunga chor ko")
// pscore = pscore + 100
//case "Chor":
// print("Chor ki __ m mor")
//
//
//default:
// print("bc tera raja mantri chor sipahi kuchh ni aaya")
//}
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
|
//
// MVLoginViewController.swift
// Movies
//
// Created by Rubens Pessoa on 4/5/18.
// Copyright © 2018 Ilhasoft. All rights reserved.
//
import UIKit
import MBProgressHUD
class MVLoginViewController: UIViewController {
var presenter: MVLoginPresenter!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var loginBtn: UIButton!
init() {
super.init(nibName: nil, bundle: nil)
presenter = MVLoginPresenter(view: self, dataSource: MVLoginRepository())
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
}
func setupLayout() {
loginBtn.setTitle(localizedString(.login), for: .normal)
loginBtn.layer.cornerRadius = loginBtn.bounds.height/2
loginBtn.clipsToBounds = true
if let backgroundImage = UIImage(named: "bg_liga_da_justica") {
backgroundImageView.image = UIImage.applyGradient(to: backgroundImage)
}
}
@IBAction func loginTapped(_ sender: Any) {
presenter.onFacebookLoginTapped()
MBProgressHUD.showAdded(to: view, animated: true)
}
}
extension MVLoginViewController: MVLoginContract {
func showLoginError(error: Error) {
let alertController = UIAlertController(title: localizedString(.oops),
message: error.localizedDescription,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: localizedString(.tryAgain),
style: .default) { (_) in
self.dismiss(animated: true, completion: nil)
})
self.present(alertController, animated: true, completion: nil)
}
func facebookLogin(success: Bool) {
MBProgressHUD.hide(for: view, animated: true)
guard success else {
return
}
presenter.navigateToHome()
}
func navigateToHome() {
present(UINavigationController(rootViewController: MVMoviesViewController()), animated: true, completion: nil)
}
}
|
//
// AutoLayout+BaseLine.swift
// AutoLayout
//
// Created by Stanislav Novacek on 02/10/2019.
//
import Foundation
import UIKit
public extension AutoLayout where Source: BaselineAnchorProviding {
// MARK: First baseline
/// Constrains first baseline to given item's first baseline.
/// - Parameter item: item
func firstBaseline(to item: BaselineAnchorProviding) -> Self {
firstBaseline(to: item.firstBaselineAnchor)
}
/// Constrains first baseline to given anchor.
/// - Parameter anchor: anchor
func firstBaseline(to anchor: NSLayoutYAxisAnchor) -> Self {
return firstBaseline(0, to: anchor)
}
/// Constrains first baseline to given anchor with an offset.
/// - Parameter value: offset
/// - Parameter anchor: anchor
func firstBaseline(_ value: CGFloat, to anchor: NSLayoutYAxisAnchor) -> Self {
firstBaseline(relation: value.simpleRelation, to: anchor)
}
/// Constrains first baseline to given anchor using given relation.
/// - Parameter relation: relation
/// - Parameter anchor: anchor
func firstBaseline(relation: LayoutConnectionSimpleRelation, to anchor: NSLayoutYAxisAnchor) -> Self {
guard let source = source else { return self }
add(constraint: createConstraint(from: source.firstBaselineAnchor, to: anchor, relation: relation), type: .firstBaseline)
return self
}
// MARK: Last baseline
/// Constrains last baseline to given item's last baseline.
/// - Parameter item: item
func lastBaseline(to item: BaselineAnchorProviding) -> Self {
firstBaseline(to: item.lastBaselineAnchor)
}
/// Constrains last baseline to given anchor.
/// - Parameter anchor: anchor
func lastBaseline(to anchor: NSLayoutYAxisAnchor) -> Self {
return lastBaseline(0, to: anchor)
}
/// Constrains last baseline to given anchor with an offset.
/// - Parameter value: offset
/// - Parameter anchor: anchor
func lastBaseline(_ value: CGFloat, to anchor: NSLayoutYAxisAnchor) -> Self {
return lastBaseline(relation: value.simpleRelation, to: anchor)
}
/// Constrains last baseline to given anchor using given relation.
/// - Parameter relation: relation
/// - Parameter anchor: anchor
func lastBaseline(relation: LayoutConnectionSimpleRelation, to anchor: NSLayoutYAxisAnchor) -> Self {
guard let source = source else { return self }
add(constraint: createConstraint(from: source.lastBaselineAnchor, to: anchor, relation: relation), type: .lastBaseline)
return self
}
}
|
//
// HelpPage1ViewController.swift
// Note Master 9000
//
// Created by Maciej Eichler on 28/03/16.
// Copyright © 2016 Mattijah. All rights reserved.
//
import UIKit
class TutorialPageController: UIViewController {
// MARK: Outlets
@IBOutlet weak var contentView: TutorialStaffDrawingView!
@IBOutlet weak var noteDrawingView: StaffDrawingView!
@IBOutlet weak var contentLabel: UILabel!
// MARK: Model
var itemIndex: Int = 0
var content: TutorialPageContent?
// MARK: - ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
//setupView()
view.backgroundColor = ColorPalette.Clouds
contentLabel.textColor = ColorPalette.MidnightBlue
}
override func viewDidLayoutSubviews() {
setupView() // Temporary place for setup. Proper frame not set on viewDidLoad
}
// MARK: Setup methods
private func setupView() {
contentLabel.text = content!.text
if let image = content!.content as? UIImage {
contentView.image = image
} else if let noteT = content!.content as? NoteTutorial {
contentView.drawStaff(withClef: noteT.clef, animated: false)
noteDrawingView.drawNotes(noteT.notesToDraw)
}
}
}
// MARK: - StaffDrawingView subclass adding imageView
class TutorialStaffDrawingView: StaffDrawingView {
let imageView = UIImageView()
var image: UIImage? {
didSet {
setupImageView()
}
}
private func setupImageView() {
imageView.frame = bounds
imageView.contentMode = .scaleAspectFit
imageView.image = image
self.addSubview(imageView)
}
}
|
//
// UIViewController.swift
// iOS Task
//
// Created by Mohammed Mohsin Sayed on 10/19/18.
// Copyright © 2018 Mohammed Mohsin Sayed. All rights reserved.
//
import Foundation
import UIKit
import NVActivityIndicatorView
extension UIViewController: NVActivityIndicatorViewable {
// MARK: - show error message
func showAlert(_ message: String){
let alertController = UIAlertController(title: "Warnning", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
self.present(alertController , animated: true)
}
func startLoading() {
let size = CGSize(width: 50, height: 50)
NVActivityIndicatorView.DEFAULT_COLOR = UIColor.brown
NVActivityIndicatorView.DEFAULT_BLOCKER_BACKGROUND_COLOR = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
self.startAnimating(size, message: "", type: NVActivityIndicatorType.ballGridPulse)
}
func stopLoading() {
self.stopAnimating()
}
}
|
//
// SettingsViewController.swift
// Rehab Tracker
//
// Created by Tim Stevens on 12/10/17.
// Copyright © 2017 CS 275 Project Group 6. All rights reserved.
//
import Foundation
import UIKit
/// View controller for the settings page
class SettingsViewController: UIViewController {
/// Feedback button that will open the feedback page after user clicks on it
/// - Postcondition: A browser is opened and linked to the feedback page (Google forms).
@IBAction func Feedback(_ sender: Any) {
if let url = URL(string: "https://goo.gl/forms/jeWGFdvACDlcg2Br1"){
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
/// A label that shows the user's name
@IBOutlet weak var UserName: UILabel!
/// Log out button
@IBAction func Logout(_ sender: Any) {
print(Util.numberOfUsers())
while Util.numberOfUsers() > 0 {
print("is this running?")
Util.deleteData()
}
print(Util.numberOfUsers())
}
/// Called after the controller's view is loaded into memory
override func viewDidLoad() {
UserName.text = "Welcome: "+Util.returnCurrentUsersID();
super.viewDidLoad()
}
/// Sent to the view controller when the app receives a memory warning.
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// Card.swift
// newblackjack
//
// Created by Kohei Nakai on 2017/12/05.
// Copyright © 2017年 NakaiKohei. All rights reserved.
//
import SpriteKit
enum CardPlace {
case deck, p1, com
}
class Trump:Card{
var pointLabel:SKLabelNode
override init?(cardNum: Int) {
guard cardNum <= 52 && cardNum > 0 else {
print("cardNum不正のためトランプの初期化に失敗:\(cardNum)")
return nil
}
self.pointLabel = {() -> SKLabelNode in
let label = SKLabelNode(fontNamed: "HiraginoSans-W6")
label.fontSize = GameScene.cheight*16/138
label.position = CGPoint(x:0,y:10000)
label.zPosition = 2
label.fontColor = SKColor.white
return label
}()
super.init(cardNum: cardNum)
self.pointLabel.text = String(self.initialPoint)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func update(){
//ラベルの位置を連動
var x = self.image.position.x+GameScene.cwidth/2
x -= GameScene.cheight*16/138
var y = self.image.position.y+GameScene.cheight/2
y -= GameScene.cheight*28/138
self.pointLabel.position = CGPoint(x:x, y:y)
}
}
class SpecialCard:Card{
var attackLabel:SKLabelNode
var hpLabel:SKLabelNode
var attack:Int
var hp:Int
override init?(cardNum: Int) {
guard cardNum > 52 else {
print("cardNum不正のため特殊カードの初期化に失敗:\(cardNum)")
return nil
}
switch cardNum {
case 53://サタ
self.attack = 6
self.hp = 6
case 54://オリ
self.attack = 4
self.hp = 4
case 55://バハ
self.attack = 13
self.hp = 13
case 56://ゼウス
self.attack = 5
self.hp = 10
case 57://アリス
self.attack = 3
self.hp = 4
case 58://ルシフェル
self.attack = 6
self.hp = 7
case 59://bb
self.attack = 5
self.hp = 6
case 60://ダリス
self.attack = 5
self.hp = 5
default:
print("attack,hpのセットエラー:\(cardNum)")
return nil
}
let at = self.attack //クロージャ内ではsuper.init()前にself.~を使えない
let h = self.hp
self.attackLabel = {() -> SKLabelNode in
let Label = SKLabelNode(fontNamed: "HiraginoSans-W6")
Label.text = String(at)
Label.fontSize = GameScene.cheight*11/138
Label.zPosition = 2
// self.addChild(Label) //表示される瞬間に行う
return Label
}()
self.hpLabel = {() -> SKLabelNode in
let Label = SKLabelNode(fontNamed: "HiraginoSans-W6")
Label.text = String(h)
Label.fontSize = GameScene.cheight*11/138
Label.zPosition = 2
// self.addChild(Label) //表示される瞬間に行う
return Label
}()
super.init(cardNum: cardNum)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func update(){
//ラベルの位置を連動
var x1 = self.image.position.x-GameScene.cwidth/2
x1 += GameScene.cheight*11/138
var x2 = self.image.position.x+GameScene.cwidth/2
x2 -= GameScene.cheight*11/138
self.attackLabel.position = CGPoint(x:x1, y:self.image.position.y-GameScene.cheight/2+GameScene.cheight*8/138)
self.hpLabel.position = CGPoint(x:x2, y:self.image.position.y-GameScene.cheight/2+GameScene.cheight*8/138)
}
func fanfare(cardPlace: CardPlace, index: Int){//登場音の予約と効果の発動
guard cardPlace != .deck else {
print("カードが配られていません")
return
}
self.cardPlace = cardPlace
switch cardNum {
case 53:
print("アポカリプスデッキに変更(未実装)")
if cardPlace == .p1{
GameScene.makePaintResevation(sound: .satanIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.cheight/2, card: self)
}else {
GameScene.makePaintResevation(sound: .satanIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.frameHeight - GameScene.cheight/2, card: self)
}
case 54://オリヴィエ
if self.cardPlace == .p1{
Game.pBP = 3
GameScene.makeOlivieResevation(x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.cheight/2, card: self, BPLabel: (pBP: "3", cBP: nil))
}else if self.cardPlace == .com{
Game.cBP = 3
GameScene.makeOlivieResevation(x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y:GameScene.frameHeight-GameScene.cheight/2, card: self, BPLabel: (pBP: nil, cBP: "3"))
}else{
print("cardPlaceが更新されていません:\(cardPlace)")
}
case 55://バハ
if cardPlace == .p1{
GameScene.makePaintResevation(sound: .bahamutIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.cheight/2, card: self)
}else {
GameScene.makePaintResevation(sound: .bahamutIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.frameHeight - GameScene.cheight/2, card: self)
}
if Game.firstDealed{
//破壊と移動
var hideCards:[Card] = [GameScene.backCard]
var repaintCards:[(x:CGFloat, y:CGFloat, card:Card)] = []
var repaintPCardNum = 0
var repaintCCardNum = 0
var pcardsRemoveIndexes:[Int] = []
var ccardsRemoveIndexes:[Int] = []
//ルシフェル調整点数を初期化
Game.adjustPoints = (0, 0)
if self.cardPlace == .p1{//ラスワの発動はバハムートを引いた側から
for (index, value) in Game.pcards.enumerated(){
if value !== self as Card && value.canBeBroken {
hideCards.append(value)
// Game.pcards.remove(at: index) //個数が変わる!
pcardsRemoveIndexes.append(index)
}else{//残ったものの位置を更新
repaintCards.append((GameScene.cwidth/2 + CGFloat(repaintPCardNum)*GameScene.cwidth, GameScene.cheight/2, value))
repaintPCardNum += 1
}
}
for(index, value) in Game.ccards.enumerated(){
if value !== self as Card && value.canBeBroken {
hideCards.append(value)
// Game.ccards.remove(at: index)
ccardsRemoveIndexes.append(index)
}else{
repaintCards.append((GameScene.cwidth/2 + CGFloat(repaintCCardNum)*GameScene.cwidth, GameScene.frameHeight - GameScene.cheight/2, value))
repaintCCardNum += 1
}
}
}else if self.cardPlace == .com{
for(index, value) in Game.ccards.enumerated(){
if value !== self as Card && value.canBeBroken {
hideCards.append(value)
// Game.ccards.remove(at: index)
ccardsRemoveIndexes.append(index)
}else{
repaintCards.append((GameScene.cwidth/2 + CGFloat(repaintCCardNum)*GameScene.cwidth, GameScene.frameHeight - GameScene.cheight/2, value))
repaintCCardNum += 1
}
}
for (index, value) in Game.pcards.enumerated(){
if value !== self as Card && value.canBeBroken {
hideCards.append(value)
// Game.pcards.remove(at: index) //個数が変わる!
pcardsRemoveIndexes.append(index)
}else{//残ったものの位置を更新
repaintCards.append((GameScene.cwidth/2 + CGFloat(repaintPCardNum)*GameScene.cwidth, GameScene.cheight/2, value))
repaintPCardNum += 1
}
}
}
//対象カードを破壊
for (index,value) in pcardsRemoveIndexes.enumerated(){
Game.pcards.remove(at: value - index)
}
for (index,value) in ccardsRemoveIndexes.enumerated(){
Game.ccards.remove(at: value - index)
}
GameScene.resevation.append((sound: .br, paint:[], repaint:repaintCards, hide: hideCards, pointLabels: Game().getpoints(), tPointLabels: [], BPLabels: (pBP: nil, cBP: nil)))
//全破壊の後、ラストワード発動
for i in hideCards{
if let SC = i as? SpecialCard{
SC.lastWord()
}
}
}
case 56://ゼウス
if cardPlace == .p1{
GameScene.makePaintResevation(sound: .zeusIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.cheight/2, card: self)
}else {
GameScene.makePaintResevation(sound: .zeusIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.frameHeight - GameScene.cheight/2, card: self)
}
case 57://アリス
if cardPlace == .p1{
var changeTPLabels:[(card: Card, value: String, color: UIColor?)] = []
for i in Game.pcards{
if let a = i as? Trump{
a.point += 1
changeTPLabels.append((card: a, value: String(a.point), color: UIColor.orange))
}
}
GameScene.makeAliceResevation(x: GameScene.cwidth/2 + CGFloat(index)*GameScene.cwidth, y: GameScene.cheight/2, card: self, tPointLabel: changeTPLabels)
}else{
var changeTPLabels:[(card: Card, value: String, color: UIColor?)] = []
for i in Game.ccards{
if let a = i as? Trump{
a.point += 1
changeTPLabels.append((card: a, value: String(a.point), color: UIColor.orange))
}
}
GameScene.makeAliceResevation(x: GameScene.cwidth/2 + CGFloat(index)*GameScene.cwidth, y: GameScene.frameHeight - GameScene.cheight/2, card: self, tPointLabel: changeTPLabels)
}
case 58://ルシフェル
if cardPlace == .p1{
GameScene.makePaintResevation(sound: .luciferIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.cheight/2, card: self)
}else {
GameScene.makePaintResevation(sound: .luciferIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.frameHeight - GameScene.cheight/2, card: self)
}
case 59://bb
if cardPlace == .p1{
GameScene.makePaintResevation(sound: .bbIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.cheight/2, card: self)
}else {
GameScene.makePaintResevation(sound: .bbIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.frameHeight - GameScene.cheight/2, card: self)
}
self.attack += 2
self.hp += 2
self.attackLabel.text = String(self.attack)
self.attackLabel.fontColor = .green
self.hpLabel.text = String(self.hp)
self.hpLabel.fontColor = .green
self.canBeBroken = false
case 60://ダリス
if cardPlace == .p1{
GameScene.makePaintResevation(sound: .daliceIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.cheight/2, card: self)
}else {
GameScene.makePaintResevation(sound: .daliceIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(index), y: GameScene.frameHeight - GameScene.cheight/2, card: self)
}
default:
print("該当する特殊カードがありませんat fanfare:\(cardNum)")
}
}
func lastWord(){
switch cardNum {
case 60://ダリス
//(相手を含めて)残っているカードをすべて消滅させる(自身は破壊されてるのでないはず)
var hideCards:[Card] = []
var pcardsRemoveIndexes:[Int] = []
var ccardsRemoveIndexes:[Int] = []
for (index, value) in Game.pcards.enumerated(){
hideCards.append(value)
pcardsRemoveIndexes.append(index)
}
for (index, value) in Game.ccards.enumerated(){
hideCards.append(value)
ccardsRemoveIndexes.append(index)
}
GameScene.makeDaliceLastResevation(hide: hideCards)
for (index,value) in pcardsRemoveIndexes.enumerated(){
Game.pcards.remove(at: value - index)
}
for (index,value) in ccardsRemoveIndexes.enumerated(){
Game.ccards.remove(at: value - index)
}
//ダリスを新たに召喚(これ自体を追加すると2重append。文章的にも新たに召喚するのが正しい)(makeDaliceLastResevationに記述)
//新しいダリスを生成
let newDalice = SpecialCard(cardNum: 60)!
if self.cardPlace == .p1{
Game.pcards.append(newDalice)
newDalice.cardPlace = .p1
GameScene.makePaintResevation(sound: .daliceIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(Game.pcards.count-1), y: GameScene.cheight/2, card: newDalice)//count関係の順番に注意(得点表示の関係でappendの後)
}else{
Game.ccards.append(newDalice)
newDalice.cardPlace = .com
GameScene.makePaintResevation(sound: .daliceIn, x: GameScene.cwidth/2 + GameScene.cwidth*CGFloat(Game.ccards.count-1), y: GameScene.frameHeight - GameScene.cheight/2, card: newDalice)//count関係の順番に注意
}
default:
print("ラストワードが設定されていません")
}
}
func drawEffect(drawPlayer: CardPlace){//ドローし、ドローしたカードのファンファーレ効果後に呼び出す(場にある分の効果)
switch cardNum {
case 57://アリス
if self.cardPlace == .p1 && drawPlayer == .p1{
if let a = Game.pcards.last as? Trump{
a.point += 1
GameScene.resevation.append((sound: .debuffField, paint: [], repaint: [], hide: [], pointLabels: Game().getpoints(), tPointLabels: [(card: a, value: String(a.point), color: .orange)], BPLabels: (pBP: nil, cBP: nil)))
}
}else if self.cardPlace == .com && drawPlayer == .com{
if let a = Game.ccards.last as? Trump{
a.point += 1
GameScene.resevation.append((sound: .debuffField, paint: [], repaint: [], hide: [], pointLabels: Game().getpoints(), tPointLabels: [(card: a, value: String(a.point), color: .orange)], BPLabels: (pBP: nil, cBP: nil)))
}
}
default: break
// print("ドロー時に発動する効果はありません")
}
}
func bustEffect(bustPlayer: CardPlace) {//bustした時に呼び出す(場にある分の効果)
guard bustPlayer != .deck else {
print("bustEffectを発動するカードが配られていません")
return
}
switch cardNum {
case 58://ルシフェル
if self.cardPlace == bustPlayer{
if self.cardPlace == .p1{
Game.adjustPoints.pp -= 4
}else if self.cardPlace == .com{
Game.adjustPoints.cp -= 4
}else{
print("ルシフェルが配られていません@bustEffect")
}
GameScene.makeLuciferCureResevation()
}
default:
print("bust時に発動する効果はありません")
}
}
}
class Card{//
let cardNum:Int
var point:Int
let initialPoint:Int
let image:SKSpriteNode
var cardPlace:CardPlace
var canBeBroken:Bool
var isReversed:Bool //バハの確認に必要
init?(cardNum:Int) {
guard cardNum >= 0 else {
print("cardNum不正のためCardの初期化に失敗:\(cardNum)")
return nil
}
self.canBeBroken = true
self.isReversed = false
self.cardPlace = .deck
self.cardNum = cardNum
if cardNum == 0 {//裏面
self.image = SKSpriteNode(imageNamed: "z02")
self.point = 0
self.initialPoint = 0
}else if cardNum < 53 && cardNum > 0{//トランプ
switch cardNum{
case 1...13:
self.image = SKSpriteNode(imageNamed: "c\(cardNum)-1")
case 14...26:
self.image = SKSpriteNode(imageNamed: "d\(cardNum - 13)-1")
case 27...39:
self.image = SKSpriteNode(imageNamed: "h\(cardNum - 26)-1")
case 40...52:
self.image = SKSpriteNode(imageNamed: "s\(cardNum - 39)-1")
default:
print("トランプ画像のルーティングエラー:\(cardNum)")
return nil
}
if (cardNum-1)%13 > 8{ //10,J,Q,Kのとき
self.point = 10
self.initialPoint = 10
}else{
self.point = cardNum % 13
self.initialPoint = cardNum % 13
}
}else{//特殊カード
switch cardNum{
case 53:
self.point = 10
self.initialPoint = 10
self.image = SKSpriteNode(imageNamed: "Satan")
case 54:
self.point = 9
self.initialPoint = 9
self.image = SKSpriteNode(imageNamed: "Olivie")
case 55:
self.point = 10
self.initialPoint = 10
self.image = SKSpriteNode(imageNamed: "Bahamut")
case 56:
self.point = 10
self.initialPoint = 10
self.image = SKSpriteNode(imageNamed: "Zeus")
case 57:
self.point = 4
self.initialPoint = 4
self.image = SKSpriteNode(imageNamed: "Alice")
case 58:
self.point = 8
self.initialPoint = 8
self.image = SKSpriteNode(imageNamed: "Lucifer")
case 59:
self.point = 6
self.initialPoint = 6
self.image = SKSpriteNode(imageNamed: "BB")
case 60:
self.point = 7
self.initialPoint = 7
self.image = SKSpriteNode(imageNamed: "Dalice")
default:
print("特殊カード画像のルーティングエラー:\(cardNum)")
return nil
}
}
let j = self.image
if GameScene.cwidth != nil{
j.size = CGSize(width:GameScene.cwidth,height:GameScene.cheight)
}
j.position = CGPoint(x:0, y:10000) //枠外に
j.zPosition = 1
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update() {
}
}
|
// Loops
for number in 1...10 {
print(number)
}
let favCandy = ["Fun Dip", "Snickers", "Hichew"]
for candy in favCandy {
print(candy)
}
|
//
// TestViewController.swift
// JimuPro
//
// Created by Sam on 2019/10/31.
// Copyright © 2019 UBTech. All rights reserved.
//
import UIKit
class WebRTC_VC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "WebRTC 的使用demo"
self.view.backgroundColor = .green
let view = WebRTCVideoView.init(frame: self.view.bounds)
let manager = WebRTCManager.shareInstance
let config = SocketConfig.default
manager.sockitConfig = config
self.view.addSubview(view)
self.view.backgroundColor = .green
let closeBtn = UIButton(type: .custom)
self.view.addSubview(closeBtn)
closeBtn.frame = CGRect(x: 30, y: 10, width: 100, height: 50)
closeBtn.setImage(UIImage(named: "ic_back"), for: .normal)
closeBtn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
}
// MARK:- 返回按钮点击
@objc fileprivate func backBtnClick(){
self.navigationController?.popViewController(animated: false)
}
// MARK:- 相册按钮点击
@objc fileprivate func photoBtnClick(){
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
WebRTCManager.shareInstance.disconnect()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
WebRTCManager.shareInstance.connect()
}
}
|
//
// ItemData.swift
// Search
//
// Created by Hashimoto Ryo on 2016/04/01.
// Copyright © 2016年 Hashimoto Ryo. All rights reserved.
//
import Foundation
|
//
// QRReader.swift
// MileWallet
//
// Created by denis svinarchuk on 19.06.2018.
// Copyright © 2018 Karma.red. All rights reserved.
//
import UIKit
import QRCodeReader
import AVFoundation
public class QRReader: QRCodeReaderViewControllerDelegate {
public var controller:UIViewController
public init(controller: UIViewController) {
self.controller = controller
}
public func open(complete:((_ reader: QRCodeReaderViewController, _ result: QRCodeReaderResult)->Void)?) {
guard checkScanPermissions() else { return }
self.complete = complete
readerVC.modalPresentationStyle = .formSheet
readerVC.delegate = self
controller.present(readerVC, animated: true, completion: nil)
}
private var complete:((_ reader: QRCodeReaderViewController, _ result: QRCodeReaderResult)->Void)?
// MARK: - QRCodeReader Delegate Methods
private lazy var reader: QRCodeReader = QRCodeReader()
private lazy var readerVC: QRCodeReaderViewController = {
let builder = QRCodeReaderViewControllerBuilder {
$0.reader = QRCodeReader(metadataObjectTypes: [.qr],
captureDevicePosition: .back)
$0.showTorchButton = true
$0.showSwitchCameraButton = false
$0.preferredStatusBarStyle = .lightContent
$0.cancelButtonTitle = NSLocalizedString("Cancel", comment:"")
$0.reader.stopScanningWhenCodeIsFound = false
}
return QRCodeReaderViewController(builder: builder)
}()
// MARK: - Actions
private func checkScanPermissions() -> Bool {
do {
return try QRCodeReader.supportsMetadataObjectTypes()
} catch let error as NSError {
let alert: UIAlertController
switch error.code {
case -11852:
alert = UIAlertController(title: "Error", message: "This app is not authorized to use Back Camera.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (_) in
DispatchQueue.main.async {
if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(settingsURL, options: [:], completionHandler: { (flag) in
}) //.openURL(settingsURL)
}
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
default:
alert = UIAlertController(title: "Error", message: "Reader not supported by the current device", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
}
controller.present(alert, animated: true, completion: nil)
return false
}
}
public func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
complete?(reader,result)
}
public func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) {
print("Switching capturing to: \(newCaptureDevice.device.localizedName)")
}
public func readerDidCancel(_ reader: QRCodeReaderViewController) {
reader.stopScanning()
controller.dismiss(animated: true, completion: nil)
}
}
|
//
// ContainerUpdateNodeReducer.swift
// GworldSuperOffice
//
// Created by 陈琪 on 2020/7/20.
// Copyright © 2020 Gworld. All rights reserved.
//
import Foundation
func updateNodeReducer(_ state: BaseLayoutElement?, action: Action) -> BaseLayoutElement? {
var state = state
switch action {
case let update as UpdatePageNode:
state = update.newNode
default:
break
}
return state
}
|
//
// Chore.swift
// Choreboard
//
// Created by Yeon Jun Kim on 3/29/21.
//
import Foundation
import RealmSwift
enum ChoreStatus: String {
case Open
case InProgress
case Complete
}
class Chore: Object {
@objc dynamic var _id: ObjectId = ObjectId.generate()
@objc dynamic var _partition: String = ""
@objc dynamic var title: String = ""
@objc dynamic var details: String?
@objc dynamic var createdBy: Member?
@objc dynamic var assignedTo: Member?
@objc dynamic var creationDate: Date = Date()
@objc dynamic var dueDate: Date?
@objc dynamic var repeating: Bool = false
@objc dynamic var points: Int = 0
@objc dynamic var status: String = ""
override static func primaryKey() -> String? {
return "_id"
}
var statusEnum: ChoreStatus {
get {
return ChoreStatus(rawValue: status) ?? .Open
}
set {
status = newValue.rawValue
}
}
convenience init(partition: String, title: String, createdBy: Member, assignedTo: Member, dueDate: Date, repeating: Bool, points: Int, status: String) {
self.init()
self._partition = partition
self.title = title
self.createdBy = createdBy
self.assignedTo = assignedTo
self.creationDate = Date()
self.dueDate = dueDate
self.repeating = repeating
self.points = points
self.status = status
}
}
struct ChoreSwift {
let title: String
let details: String
let createdBy: User
let assignedTo: User
let creationDate: Date
let dueDate: Date
let repeating: Bool
let points: Int
let completed: Bool
}
|
//
// ContactsViewController.swift
// jChat
//
// Created by Jeevan on 04/05/19.
// Copyright © 2019 Jeevan. All rights reserved.
//
import UIKit
import FirebaseAuth
class ContactsViewController: BaseViewController {
@IBOutlet weak var contactsTableView: UITableView!
var currentUserDocumentData : [String:Any] = [:] {
didSet {
if let currentContacts = currentUserDocumentData[keyStrings.kContacts] as? [String] {
self.userContacts = currentContacts
}
}
}
var userContacts : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
fetchAllUsersDocuments()
}
fileprivate func updateCurrentUserDocument(field: String, value : Any, completion : (()->())?) {
self.activityIndicator.startAnimating()
if let currentUser = AliasFor.kCurrentUser?.email {
AliasFor.kUserCollection.document(currentUser).updateData([
field : value
]) { (error) in
self.activityIndicator.stopAnimating()
if let error = error {
print(error.localizedDescription)
}
if let completion = completion {
completion()
}
}
}
}
fileprivate func fetchAllUsersDocuments() {
// Do any additional setup after loading the view.
activityIndicator.startAnimating()
if let currentUser = AliasFor.kCurrentUser?.email {
AliasFor.kUserCollection.document(currentUser).getDocument { (documentSnapshot, error) in
self.activityIndicator.stopAnimating()
if let error = error {
print(error.localizedDescription)
}else if let documentSnapshot = documentSnapshot {
if let documentData = documentSnapshot.data() {
self.currentUserDocumentData = documentData
self.contactsTableView.reloadData()
}
}
}
}
}
@IBAction func addContactAction(_ sender: Any) {
showTextFieldAlert(message: AlertStrings.kAddNewContact, placeholder: AlertStrings.kAddContactPlaceHolder, constructiveButtonTitle: UIElementTitles.kAdd) { (emailId) in
if let currentUserEmail = Auth.auth().currentUser?.email {
if currentUserEmail == emailId {
self.showMessageOnlyAlert(message: AlertStrings.kAddSelfAsContactError, completion: nil)
return
}else if self.userContacts.contains(emailId) {
self.showMessageOnlyAlert(message: AlertStrings.kAddExistingAsContactError, completion: nil)
return
}
}
self.activityIndicator.startAnimating()
Auth.auth().fetchSignInMethods(forEmail: emailId, completion: { (arrayOfMethods, error) in
self.activityIndicator.stopAnimating()
if let error = error {
self.showMessageOnlyAlert(message: error.localizedDescription, completion: nil)
}else {
if let arrayOfLoginMethods = arrayOfMethods {
//valid user
guard let currentContacts = self.currentUserDocumentData[keyStrings.kContacts] as? [String] else {
self.updateCurrentUserDocument(field: keyStrings.kContacts, value:
[emailId], completion: {
self.fetchAllUsersDocuments()
})
return
}
let updatedContacts = currentContacts + [emailId]
self.updateCurrentUserDocument(field: keyStrings.kContacts, value:
updatedContacts, completion: {
self.fetchAllUsersDocuments()
})
}else {
//invalid
self.showMessageOnlyAlert(message: AlertStrings.kNotRegisteredUser, completion: nil)
}
}
})
}
}
}
extension ContactsViewController : UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userContacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ContactTableViewCell", for: indexPath) as! ContactTableViewCell
cell.contactNameLabel.text = userContacts[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let chatVC = ChatViewController()
chatVC.contactId = userContacts[indexPath.row]
self.navigationController?.pushViewController(chatVC, animated: true)
}
}
|
//
// Athlete.swift
// FavoriteAthlete
//
// Created by Jeewoo Chung on 9/10/19.
//
import Foundation
struct Athlete {
var name: String
var age: Int
var discipline: String
var team: String
var nationality: String
var description: String {
return "\(name) is \(age) years old \(discipline) athlete from \(nationality) and plays for the \(team)."
}
}
|
//
// RecipeBooksViewController.swift
// RecipeManager
//
// Created by Anton Stamme on 09.04.20.
// Copyright © 2020 Anton Stamme. All rights reserved.
//
import Foundation
import UIKit
class RecipeBooksViewController: UIViewController {
static var firstRecipeBookCreatedKey: String = "RecipeBooksViewController.firstRecipeBookCreatedKey"
@IBOutlet weak var allRecipesButton: UIButton!
@IBOutlet weak var plusButton: UIBarButtonItem!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
var selectedIndexPath: IndexPath!
var generator = UISelectionFeedbackGenerator()
override func viewDidLoad() {
setUpViews()
fillData()
}
override func viewDidAppear(_ animated: Bool) {
collectionView.reloadData()
}
func setUpViews() {
NotificationCenter.default.addObserver(self, selector: #selector(fillData), name: RecipeBook.recipeBooksUpdatedKey, object: nil)
allRecipesButton.layer.cornerRadius = 8
allRecipesButton.layer.shadowOffset = CGSize(width: 1, height: 1)
allRecipesButton.layer.shadowColor = UIColor.black.cgColor
allRecipesButton.layer.shadowRadius = 8
allRecipesButton.layer.shadowOpacity = 0.3
collectionView.delegate = self
collectionView.dataSource = self
collectionView.decelerationRate = .fast
collectionView.showsHorizontalScrollIndicator = false
collectionView.register(RecipeBooksCollectionViewCell.self, forCellWithReuseIdentifier: "RecipeBooksCollectionViewCell")
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: 64, bottom: 0, right: 64)
}
pageControl.numberOfPages = recipeBooks.count
pageControl.pageIndicatorTintColor = UIColor(named: "heavyTint")?.withAlphaComponent(0.5)
pageControl.currentPageIndicatorTintColor = UIColor(named: "heavyTint")
pageControl.isUserInteractionEnabled = false
pageControl.hidesForSinglePage = true
}
@objc func fillData() {
let itemCount = collectionView.numberOfItems(inSection: 0)
let newRecipe = itemCount != 0 && itemCount != recipeBooks.count
collectionView.reloadData()
updatePageControl()
if newRecipe { collectionView.scrollToItem(at: IndexPath(item: recipeBooks.count - 1, section: 0), at: .centeredHorizontally, animated: true)}
if !UserDefaults.standard.bool(forKey: RecipeBooksViewController.firstRecipeBookCreatedKey) {
}
}
func updatePageControl() {
pageControl.numberOfPages = recipeBooks.count
let center = view.convert(self.collectionView.center, to: self.collectionView)
if let index = collectionView.indexPathForItem(at: center)?.item, index != pageControl.currentPage {
generator.selectionChanged()
pageControl.currentPage = index
}
}
@IBAction func handleAllRecipeButton(_ sender: Any) {
guard let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "RecipesViewController") as? RecipesViewController else { return }
vc.recipeBook = nil
show(vc, sender: self)
}
}
extension RecipeBooksViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return recipeBooks.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let recipeBook = recipeBooks[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeBooksCollectionViewCell", for: indexPath) as! RecipeBooksCollectionViewCell
cell._target = self
cell.fillData(recipeBook: recipeBook)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width - 128
let height = collectionView.frame.height - 64
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let recipeBook = recipeBooks[indexPath.item]
guard let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "RecipesViewController") as? RecipesViewController else { return }
vc.recipeBook = recipeBook
show(vc, sender: self)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
updatePageControl()
}
}
//
//
//class AllRecipesCell: BaseCollectionViewCell {
// lazy var iconView: UIImageView = {
// let iv = UIImageView()
// iv.translatesAutoresizingMaskIntoConstraints = false
// iv.contentMode = .scaleAspectFit
// return iv
// }()
//
// lazy var label: UILabel = {
// let label = UILabel()
// label.translatesAutoresizingMaskIntoConstraints = false
// label.font = UIFont.systemFont(ofSize: 20, weight: .medium)
// label.text = NSLocalizedString("All Recipes", comment: "")
// label.textColor = .secondaryLabel
// return label
// }()
//
// override func setUpViews() {
// contentView.layer.cornerRadius = 8
// contentView.backgroundColor = .secondarySystemBackground
// contentView.addSubview(iconView)
// contentView.addSubview(label)
//
// iconView.widthAnchor.constraint(equalTo: iconView.heightAnchor).isActive = true
// iconView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
// iconView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 12).isActive = true
// iconView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12).isActive = true
//
// label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
// label.leftAnchor.constraint(equalTo: iconView.rightAnchor, constant: 12).isActive = true
// label.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -12).isActive = true
//
// }
//}
|
// ContactBubble.swift
// Created by Justin Lynch on 3/11/15.
// Copyright (c) 2015 jlynch.co. All rights reserved.
import UIKit
import QuartzCore
import Foundation
protocol ContactBubbleDelegate : class {
func contactBubbleWasSelected(contactBubble: ContactBubble!)
func contactBubbleWasUnSelected(contactBubble: ContactBubble!)
func contactBubbleShouldBeRemoved(contactBubble: ContactBubble!)
}
class ContactBubble : UIView, UITextViewDelegate {
let kHorizontalPadding = 10
let kVerticalPadding = 2
let kBubbleColor = UIColor(red: CGFloat(24.0/255.0), green: CGFloat(134.0/255.0), blue: CGFloat(242.0/255.0), alpha: CGFloat(1.0))
let kBubbleColorSelected = UIColor(red: CGFloat(151.0/255.0), green: CGFloat(199.0/255.0), blue: CGFloat(250.0/255.0), alpha: CGFloat(1.0))
var name : String
var label : UILabel
var textView : UITextView
var isSelected : Bool
var delegate : ContactBubbleDelegate?
var gradientLayer : CAGradientLayer
var color : BubbleColor
var selectedColor : BubbleColor
func initWithName(name: String) -> AnyObject {
self.initWithName(name, color: nil, selectedColor: nil)
return self
}
func initWithName(name: String, color: BubbleColor!, selectedColor: BubbleColor!) -> AnyObject {
super.initWithName(name)
self.name = name
self.isSelected = false
if (color == nil) {
color = BubbleColor(kBubbleColor, kBubbleColor, kBubbleColor)
}
if (selectedColor == nil) {
selectedColor = BubbleColor(kBubbleColorSelected, kBubbleColorSelected, kBubbleColorSelected)
}
self.color = color
self.selectedColor = selectedColor
self.setupView()
return self
}
func setupView() {
self.label = UILabel()
self.label.backgroundColor = UIColor.clearColor()
self.label.text = self.name
self.addSubview(self.label)
self.textView = UITextView()
self.textView.delegate = self
self.textView.hidden = true
self.addSubview(self.textView)
var tapGesture = UITapGestureRecognizer(target: self, action: "handleTapGesture")
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
self.addGestureRecognizer(tapGesture)
self.adjustSize()
self.unSelect()
}
func adjustSize() {
self.label.sizeToFit()
var frame : CGRect = self.label.frame
frame.origin.x = kHorizontalPadding
frame.origin.y = kVerticalPadding
self.label.frame = frame
self.bounds = CGRectMake(0, 0, frame.size.width + 2 * kHorizontalPadding, frame.size.height + 2 * kVerticalPadding)
if (self.gradientLayer == nil) {
var layer : CAGradientLayer = self.gradientLayer
layer.insertSublayer(self.gradientLayer, atIndex: 0)
}
self.gradientLayer.frame = self.bounds
var viewLayer : CALayer = self.layer
viewLayer.cornerRadius = self.bounds.size.height / 2
viewLayer.borderWidth = 1
viewLayer.masksToBounds = true
}
func setFont(font: UIFont!) {
self.label.font = font
self.adjustSize()
}
func select() {
if self.delegate?.respondsToSelector(Selector("contactBubbleWasSelected:")) {
self.delegate!.contactBubbleWasSelected!(self)
}
var viewLayer : CALayer = self.layer
viewLayer.borderColor = self.selectedColor.border.CGColor
self.gradientLayer.colors = NSArray(self.selectedColor.gradientTop.CGColor, self.selectedColor.gradientBottom.CGColor, nil)
self.label.textColor = UIColor.whiteColor()
self.isSelected = true
self.textView.becomeFirstResponder()
}
func unSelect() {
var viewLayer : CALayer = self.layer
viewLayer.borderColor = self.selectedColor.border.CGColor
self.gradientLayer.colors = NSArray(self.color.gradientTop.CGColor, self.color.gradientBottom.CGColor, nil)
self.label.textColor = UIColor.whiteColor()
self.isSelected = false
self.textView.resignFirstResponder()
}
func handleTapGesture() {
if (self.isSelected) {
self.unSelect()
} else {
self.select()
}
}
// TestView Delegate
func textView(textView: UITextView!, shouldChangeTextInRange range: NSRange, replacementText text: String) -> CBool {
self.textView.hidden = false
if (textView.text == "\n") {
return false
}
if (textView.text == "" && text == "") {
if self.delegate?.respondsToSelector(Selector("contactBubbleShouldBeRemoved:")) {
self.delegate!.contactBubbleShouldBeRemoved!(self)
}
}
if (self.isSelected) {
self.textView.text = ""
self.unSelect()
if self.delegate?.respondsToSelector(Selector("contactBubbleWasUnSelected:")) {
self.delegate!.contactBubbleWasUnSelected!(self)
}
}
return true
}
}
|
//
// CustomEventData.swift
// TestBed-Swift
//
// Created by David Westgate on 9/17/17.
// Copyright © 2017 Branch Metrics. All rights reserved.
//
import Foundation
struct CustomEventData {
static let userDefaults = UserDefaults.standard
static func customEventName() -> String? {
if let value = userDefaults.string(forKey: "customEventName") {
return value
} else {
let value = ""
userDefaults.setValue(value, forKey: "customEventName")
return value
}
}
static func setCustomEventName(_ value: String) {
if value == "" {
userDefaults.removeObject(forKey: "customEventName")
} else {
userDefaults.setValue(value, forKey: "customEventName")
}
}
static func customEventMetadata() -> [String: AnyObject] {
if let value = userDefaults.dictionary(forKey: "customEventMetadata") {
return value as [String : AnyObject]
} else {
let value = [String: AnyObject]()
userDefaults.set(value, forKey: "customEventMetadata")
return value
}
}
static func setCustomEventMetadata(_ value: [String: AnyObject]) {
userDefaults.set(value, forKey: "customEventMetadata")
}
}
|
//
// CalculusTests.swift
// CalculusTests
//
// Created by Luiz Rodrigo Martins Barbosa on 21.03.19.
// Copyright © 2019 Luiz Rodrigo Martins Barbosa. All rights reserved.
//
import Calculus
import XCTest
class CalculusTests: XCTestCase {
func testDerivativeTangent() {
// given
let testScenarios: [(function: (Decimal) -> Decimal, point: Decimal, expectedSlope: Decimal)] = [
(function: { (x: Decimal) -> Decimal in x < 3 ? 5 - 2 * x : 4 * x - 13 }, point: 3, expectedSlope: 4),
(function: { x in 3 * x * x + 2 * x - 1 }, point: 3, expectedSlope: 20),
(function: { x in x * (3 * x - 5) }, point: 1 / 2, expectedSlope: -2),
(function: { x in x < 1 ? pow(x, 2) : 2 * x - 1 }, point: 1, expectedSlope: 2),
(function: { x in pow(x, 2) - 2 * x }, point: 3, expectedSlope: 4),
(function: { x in x > 3 ? 10 - x : 3 * x - 2 }, point: 3, expectedSlope: -1),
(function: { x in 2 * abs(x - 3) }, point: 3, expectedSlope: 2),
(function: { x in x < 1 ? x : 2 * x - 1 }, point: 1, expectedSlope: 2),
(function: { x in pow(x, (1/3)) }, point: 0, expectedSlope: 0)
]
let accuracy = 1e-12
// when
let slopes = testScenarios.map { testCase in
derivative(testCase.function)(testCase.point)
}
// then
XCTAssertEqual(testScenarios.count, slopes.count)
let assertions = zip(testScenarios, slopes)
assertions.forEach { testScenario, slope in
if testScenario.expectedSlope == .nan && slope == .nan {
return
}
let expected = NSDecimalNumber(decimal: testScenario.expectedSlope).doubleValue
let calculated = NSDecimalNumber(decimal: slope).doubleValue
XCTAssertEqual(expected, calculated, accuracy: accuracy)
}
}
func testDerivativeNormalPerpendicular() {
// given
let testScenarios: [(function: (Decimal) -> Decimal, point: Decimal, expectedSlope: Decimal)] = [
(function: { (x: Decimal) -> Decimal in x < 3 ? 5 - 2 * x : 4 * x - 13 }, point: 3, expectedSlope: -0.25),
(function: { x in 3 * x * x + 2 * x - 1 }, point: 3, expectedSlope: -0.05),
(function: { x in x * (3 * x - 5) }, point: 1 / 2, expectedSlope: 0.5),
(function: { x in x < 1 ? pow(x, 2) : 2 * x - 1 }, point: 1, expectedSlope: -0.5),
(function: { x in pow(x, 2) - 2 * x }, point: 3, expectedSlope: -0.25),
(function: { x in x > 3 ? 10 - x : 3 * x - 2 }, point: 3, expectedSlope: 1),
(function: { x in 2 * abs(x - 3) }, point: 3, expectedSlope: -0.5),
(function: { x in x < 1 ? x : 2 * x - 1 }, point: 1, expectedSlope: -0.5),
(function: { x in pow(x, (1/3)) }, point: 0, expectedSlope: Decimal.nan)
]
let accuracy = 1e-12
// when
let slopes = testScenarios.map { testCase in
derivativePerpendicular(testCase.function)(testCase.point)
}
XCTAssertEqual(testScenarios.count, slopes.count)
let assertions = zip(testScenarios, slopes)
assertions.forEach { testScenario, slope in
if testScenario.expectedSlope == .nan && slope == .nan {
return
}
let expected = NSDecimalNumber(decimal: testScenario.expectedSlope).doubleValue
let calculated = NSDecimalNumber(decimal: slope).doubleValue
XCTAssertEqual(expected, calculated, accuracy: accuracy)
}
}
func testIsDifferentiableAtPoint() {
// given
let testScenarios: [(function: (Decimal) -> Decimal, point: Decimal, expectedIsDifferentiable: Bool)] = [
(function: { (x: Decimal) -> Decimal in x < 3 ? 5 - 2 * x : 4 * x - 13 }, point: 3, expectedIsDifferentiable: false),
(function: { x in 3 * x * x + 2 * x - 1 }, point: 3, expectedIsDifferentiable: true),
(function: { x in x * (3 * x - 5) }, point: 1 / 2, expectedIsDifferentiable: true),
(function: { x in x < 1 ? pow(x, 2) : 2 * x - 1 }, point: 1, expectedIsDifferentiable: true),
(function: { x in pow(x, 2) - 2 * x }, point: 3, expectedIsDifferentiable: true),
(function: { x in x > 3 ? 10 - x : 3 * x - 2 }, point: 3, expectedIsDifferentiable: false),
(function: { x in 2 * abs(x - 3) }, point: 3, expectedIsDifferentiable: false),
(function: { x in x < 1 ? x : 2 * x - 1 }, point: 1, expectedIsDifferentiable: false)
// (function: { x in pow(x, (1/3)) }, point: 0, expectedIsDifferentiable: false)
// TODO: This should be false, but it's currently returning true. If the point creates a vertical tangent
// the function is not differentiable, but our algorithm currently can't detect that.
]
// when
let results = testScenarios.map { testCase in
isDifferentiable(at: testCase.point, testCase.function)
}
XCTAssertEqual(testScenarios.count, results.count)
let assertions = zip(testScenarios, results)
assertions.forEach { testScenario, isDifferentiableAtPoint in
XCTAssertEqual(testScenario.expectedIsDifferentiable, isDifferentiableAtPoint)
}
}
}
|
//
// PlaceTableViewCell.swift
// Assignment1_Attempt2
//
// Created by Shahrooq Pathan on 31/8/19.
// Copyright © 2019 Shahrooq Pathan. All rights reserved.
//
import UIKit
class SightTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var sightImage: UIImageView!
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
}
}
|
//
// CharactetSet.swift
// Login
//
// Created by Sujan Vaidya on 7/24/17.
// Copyright © 2017 Sujan Vaidya. All rights reserved.
//
import UIKit
public protocol CharacterSetValidator: Validator {
var characterCase: CharacterSet { get }
var error: Error { get }
}
public extension CharacterSetValidator {
func validate<T>(_ value: T) -> ValidationResult<T> {
guard let stringValue = value as? String else { return .error(nil) }
return stringValue.rangeOfCharacter(from: characterCase) != nil ?
.ok(value) :
.error(error)
}
}
public protocol CharacterSetExclusiveValidator: Validator {
var characterCase: CharacterSet { get }
var error: Error { get }
}
public extension CharacterSetExclusiveValidator {
func validate<T>(_ value: T) -> ValidationResult<T> {
guard let stringValue = value as? String else { return .error(nil) }
return stringValue.rangeOfCharacter(from: characterCase) == nil ?
.ok(value) :
.error(error)
}
}
|
//
// CollectionViewLayout+TargetOffset.swift
// Layout
//
// Created by Josh Grant on 6/27/16.
// Copyright © 2016 Josh Grant. All rights reserved.
//
import UIKit
extension CollectionViewLayout
{
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint
{
// TODO: Fix this later
// print(proposedContentOffset.y, velocity)
// let collapsedParentHeight = heightOfHiddenSectionZeroCell * CGFloat(numberOfItemsInSectionZero)
//
// if proposedContentOffset.y >= collapsedParentHeight * 0.5
// {
// return CGPoint(x: 0, y: collapsedParentHeight)
// }
// else if proposedContentOffset.y < -heightOfCell * CGFloat(numberOfItemsInSectionZero - 1) * 0.5 && velocity.y >= 0
// {
// return CGPoint(x: 0, y: 0)
// }
// else if proposedContentOffset.y < -heightOfCell * CGFloat(min(1, numberOfItemsInSectionZero))
// {
// return CGPoint(x: 0, y: -heightOfSectionZero)
// }
// else if proposedContentOffset.y < heightOfCell // height of current node?
// {
// return CGPoint(x: 0, y: 0)
// }
return proposedContentOffset
}
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint) -> CGPoint
{
// a layout can return the content offset to be applied during transition or update animations
// print(proposedContentOffset)
return proposedContentOffset
}
} |
//
// Navigated.swift
// JatApp-Utils-iOS
//
// Created by Developer on 2/14/19.
// Copyright © 2019 JatApp. All rights reserved.
//
import UIKit
public extension UIViewController {
func navigated<T: UINavigationController>(_ classType: T.Type) -> T {
return T(rootViewController: self)
}
}
|
//
// City.swift
// weather
//
// Created by Baldoph Pourprix on 01/04/16.
// Copyright © 2016 Baldoph Pourprix. All rights reserved.
//
import Foundation
import Argo
import Curry
public struct City {
public let name: String
public let cityID: String
}
extension City: Decodable {
public static func decode(j: JSON) -> Decoded<City> {
return curry(City.init) <^> j <| "name" <*> j <| "name"
}
}
|
//
// AffViewController.swift
// oumiji
//
// Created by ominext on 8/13/18.
// Copyright © 2018 ominext. All rights reserved.
//
import UIKit
import Affdex
class AffViewController: UIViewController {
override var prefersStatusBarHidden: Bool { return true }
@IBOutlet weak var CameraView: UIImageView!
@IBOutlet weak var emoI: UIImageView!
@IBOutlet weak var helloL: UILabel!
@IBOutlet weak var faceBound: UIView!
var face = FaceObject()
override func viewDidLoad() {
super.viewDidLoad()
faceBound.layer.borderWidth = 2
faceBound.layer.borderColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1).cgColor
faceBound.backgroundColor = UIColor(white: 1, alpha: 0)
faceBound.layer.cornerRadius = 4
faceBound.alpha = 0
AffdexCamera.instance().affdexDelegate = self
AffdexCamera.instance().startDetector()
}
override func viewWillAppear(_ animated: Bool) {
helloL.text = "Xin chào"
helloL.font = helloL.font.withSize(32)
}
override func viewDidAppear(_ animated: Bool) {
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 6, options: .allowUserInteraction, animations: {
self.helloL.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
}, completion: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
AffdexCamera.instance().resetDetector()
}
@IBAction func backClick(_ sender: Any) {
dismiss(animated: false, completion: nil)
}
}
extension AffViewController: AffdexCameraDelegate {
func updateImage(image: UIImage) {
CameraView.image = image
}
func getKairos(image: UIImage, faces: NSMutableDictionary!) {
AffdexCamera.instance().hadKairos = true
}
func updateFace(faces: NSMutableDictionary!) {
for face in faces.allValues {
self.face.update(face: face as! AFDXFace)
updateEmoI()
//print((face as! AFDXFace).emotions.dictionaryWithValues(forKeys: ["anger","contempt","fear","joy", "sadness", "surprise"]))
self.faceBound.frame = (face as! AFDXFace).faceBounds
break
}
}
func restartDetect() {
emoI.image = nil
}
}
extension AffViewController {
func updateEmoI() {
let image = emotionImage(face: face)
emoI.image = image
}
func emotionImage(face: FaceObject) -> UIImage? {
let emotion = face.emotionGuest()
if face.female == false {
switch emotion {
case "happy":
return #imageLiteral(resourceName: "mhappy")
case "sad":
return #imageLiteral(resourceName: "msad")
case "angry":
return #imageLiteral(resourceName: "mangry")
case "fear":
return #imageLiteral(resourceName: "mfear")
case "surprise":
return #imageLiteral(resourceName: "msurprise")
case "neutral":
return #imageLiteral(resourceName: "mneutral")
case "disgust":
break
case "valence":
break
case "contempt":
return #imageLiteral(resourceName: "mcontempt")
default:
break
}
}
switch emotion {
case "happy":
return #imageLiteral(resourceName: "fhappy")
case "sad":
return #imageLiteral(resourceName: "fsad")
case "angry":
return #imageLiteral(resourceName: "fangry")
case "fear":
return #imageLiteral(resourceName: "ffear")
case "surprise":
return #imageLiteral(resourceName: "fsurprise")
case "neutral":
return #imageLiteral(resourceName: "fneutral")
case "disgust":
break
case "valence":
break
case "contempt":
return #imageLiteral(resourceName: "fcontempt")
default:
break
}
return nil
}
}
fileprivate extension FaceObject {
func emotionGuest() -> String {
var emo = Dictionary<String,Float>()
emo["happy"] = self.nowjoy
emo["angry"] = self.nowanger
emo["fear"] = self.nowfear
emo["sad"] = self.nowsadness
emo["surprise"] = self.nowsurprise
//emo["disgust"] = self.nowdisgust
emo["contempt"] = self.nowcontempt
//emo["valence"] = self.nowvalence
emo["neutral"] = 100 - self.nowjoy - self.nowanger - self.nowfear - self.nowsurprise - self.nowsadness - self.contempt
//print(emo)
//print(emo)
let greatest = emo.max { a, b in a.value < b.value }
let emoM = greatest?.key
return emoM!
}
}
|
//
// noted.swift
// TodayNews
//
// Created by Ron Rith on 1/14/18.
// Copyright © 2018 Ron Rith. All rights reserved.
//
import Foundation
// Video 28: 56:24
|
//
// ChatViewController.swift
// Places
//
// Created by Adrian on 25.09.2016.
// Copyright © 2016 Adrian Kubała. All rights reserved.
//
import UIKit
class ChatViewController: UIViewController {
@IBOutlet weak var mapViewImage: UIImageView!
var image = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
mapViewImage.image = image
}
}
|
//
// UIViewController+Closeable.swift
// SiberianVIPER
//
// Created by Sergey Petrachkov on 31/10/2017.
// Copyright © 2017 Sergey Petrachkov. All rights reserved.
//
import UIKit
extension UIViewController: Closeable {
public func close(animated: Bool, completion: (() -> Void)?) {
if let navigationController = self.navigationController, navigationController.topViewController != self {
navigationController.popViewController(animated: animated)
} else {
self.dismiss(animated: animated, completion: completion)
}
}
}
|
import Foundation
public enum MountPoint {
case path(String)
case bundle(String)
case icloudbundle(String)
case preset(MountPreset)
}
public extension MountPoint {
private enum CodingKeys: String, CodingKey {
case path, bundle, icloudbundle, preset
}
enum MountPointCodingError: Error {
case decoding(String)
}
static func load_mounts() -> [String: MountPoint] {
if let data = try? Data(
contentsOf: URL(fileURLWithPath: "/var/mobile/Library/me.aspenuwu.xenon/mounts.json"),
options: .mappedIfSafe
) {
return
(try? JSONDecoder().decode([String: MountPoint].self, from: data)) ?? [String: MountPoint]()
} else {
return [String: MountPoint]()
}
}
static func save_mounts(_ mounts: [String: MountPoint]) {
do {
FileManager.default.createFile(
atPath: "/var/mobile/Library/me.aspenuwu.xenon/mounts.json",
contents: try JSONEncoder().encode(mounts)
)
} catch {}
}
}
extension MountPoint: Decodable {
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
// Decode path
if let value = try? values.decode(
String.self,
forKey: .path
) {
self = .path(value)
return
}
// Decode bundle
if let value = try? values.decode(
String.self,
forKey: .bundle
) {
self = .bundle(value)
return
}
// Decode icloudbundle
if let value = try? values.decode(
String.self,
forKey: .icloudbundle
) {
self = .icloudbundle(value)
return
}
// Decode preset
if let value = try? values.decode(
MountPreset.self,
forKey: .preset
) {
self = .preset(value)
return
}
throw
MountPointCodingError
.decoding("Whoops! \(dump(values))")
}
}
extension MountPoint: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .path(path):
try container.encode(path, forKey: .path)
case let .bundle(bundle):
try container.encode(bundle, forKey: .bundle)
case let .icloudbundle(icloudbundle):
try container.encode(icloudbundle, forKey: .icloudbundle)
case let .preset(preset):
try container.encode(preset, forKey: .preset)
}
}
}
public enum MountPreset: String, Codable {
case photos, localfiles, home, documents
}
|
//
// EditTodoItemViewController.swift
// Todo
//
// Created by Heather Shelley on 11/11/14.
// Copyright (c) 2014 Mine. All rights reserved.
//
import UIKit
enum EditTodoItemSection: Int {
case Info
case Repeat
case Due
case Count
}
class EditTodoItemTableViewController: UITableViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var pointsTextField: UITextField!
@IBOutlet weak var minutesTextField: UITextField!
@IBOutlet weak var repeatsSwitch: UISwitch!
@IBOutlet weak var dueSwitch: UISwitch!
@IBOutlet weak var repeatCountTextField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
var item: TodoItem?
var anytime = false
var saveFunction: () -> Void = { print("Save function not implemented") }
override func viewDidLoad() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 40
if let item = item {
nameTextField.text = item.name
nameTextField.autocapitalizationType = .Sentences
pointsTextField.text = "\(item.points)"
minutesTextField.text = "\(item.minutes)"
repeatsSwitch.on = item.repeats
repeatCountTextField.text = "\(item.repeatCount)"
dueSwitch.on = item.dueDate != nil
if let dueDate = item.dueDate {
datePicker.date = dueDate.date
}
tableView.reloadData()
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if anytime {
return repeatsSwitch.on ? EditTodoItemSection.Count.rawValue - 1 : EditTodoItemSection.Count.rawValue
} else {
return EditTodoItemSection.Count.rawValue - 1
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch EditTodoItemSection(rawValue: section) ?? .Count {
case .Info:
return 3
case .Repeat:
return repeatsSwitch.on ? 2 : 1
case .Due:
return dueSwitch.on ? 2 : 1
case .Count:
return 0
}
}
@IBAction func repeatsSwitchChanged() {
tableView.reloadData()
}
@IBAction func dueSwitchChanged() {
tableView.reloadData()
}
@IBAction func cancelPressed(sender: UIBarButtonItem) {
navigationController?.popViewControllerAnimated(true)
}
@IBAction func savePressed(sender: UIBarButtonItem) {
item?.name = nameTextField.text ?? "Untitled"
item?.repeats = repeatsSwitch.on
item?.points = Int(pointsTextField.text ?? "0") ?? 0
item?.minutes = Int(minutesTextField.text ?? "0") ?? 0
item?.repeatCount = Int(repeatCountTextField.text ?? "0") ?? 0
if dueSwitch.on {
item?.dueDate = Date(date: datePicker.date)
} else {
item?.dueDate = nil
}
saveFunction()
navigationController?.popViewControllerAnimated(true)
}
}
|
//
// SDLastQuery.swift
// SolidDemo
//
// Created by Igor Matyushkin on 26.11.15.
// Copyright © 2015 Igor Matyushkin. All rights reserved.
//
import UIKit
public class SDLastQuery: SDSingleSelectionQuery {
// MARK: Class variables & properties
// MARK: Class methods
// MARK: Initializers
public override init() {
super.init()
}
// MARK: Deinitializer
deinit {
}
// MARK: Variables & properties
// MARK: Public methods
public override func queryDescription() -> String {
return String(format: "Select last element", arguments: [])
}
public override func performWithArray(array: [AnyObject]) -> AnyObject? {
let resultObject = array.last
return resultObject
}
// MARK: Private methods
// MARK: Protocol methods
}
|
//
// config.swift
// appBase
//
// Created by eddy on 2016/06/24.
// Copyright © 2016年 eddy. All rights reserved.
//
import Foundation
// MARK: - Color
let MainColorHex = 0x0B1013 // 黒橡
let KeyColorHex = 0xFCFAF2 // 白練
|
//
// OnBoarding.swift
// SwiftDemo
//
// Created by sam on 2020/4/7.
// Copyright © 2020 sam . All rights reserved.
//
import Foundation
/// 这个类用于处理处理首次进入App的逻辑处理, 减少AppDelegate的臃肿.
/// 比如根据是否登陆进入不同的界面、注册系统服务、通用服务等。
class OnBoarding {
enum State {
case showFirstLaunchVideo
case showGuide
case showLogin
case showHome
}
fileprivate var appRooter: AppRouter?
fileprivate var currentState: State = .showHome
/// 调用引接口即可进入处理登陆及界面展示等流程
func start(with router: AppRouter) {
appRooter = router
processNextState()
startAppServices()
}
/// 处理 app 的下一个状态
func processNextState() {
calculateCurrentState()
switch currentState {
case .showFirstLaunchVideo:
playLaunchVideo()
case .showGuide:
showGuidePage()
case .showLogin:
showLoginPage()
case .showHome:
showHomePage()
}
}
/// 计算当前 app 启动流程状态
func calculateCurrentState() {
let preferences = AppPreferences.shared
if preferences.isFirstLaunch {
currentState = .showFirstLaunchVideo
} else if preferences.shouldShowGuide {
currentState = .showGuide
} else if !preferences.hasUserLoginBefore {
currentState = .showLogin
} else {
currentState = .showHome
}
}
}
fileprivate extension OnBoarding {
func playLaunchVideo() {
let tabVC = appRooter!.rootTabVC
appRooter!.setWindowRootViewController(tabVC)
}
private func showGuidePage() {
}
private func showLoginPage() {
}
private func showHomePage() {
let tabVC = appRooter!.rootTabVC
appRooter!.setWindowRootViewController(tabVC)
}
}
//MARK: - App相应服务模块的启动
fileprivate extension OnBoarding {
/// 启动App所需要的基础服务
func startAppServices() {
//监听网络状态
startNetworkMonitor()
}
/// 启动网络监控服务
private func startNetworkMonitor() {
}
}
|
//
// ViewModelBindableType.swift
// RxMemo
//
// Created by devming on 2020/01/13.
// Copyright © 2020 devming. All rights reserved.
//
import UIKit
///vc에서 이 프로토콜을 채용할 것임
protocol ViewModelBindableType {
/// view model의 타입은 view controller마다 달라지기 때문에 프로토콜을 generic프로토콜로 생성할 것임.
associatedtype ViewModelType
var viewModel: ViewModelType! { get set }
func bindViewModel()
}
/// vc에 추가된 vm속성의 실제 vm을 저장하고 bindViewModel메소드를 자동으로 호출하는 메소드를 구현한다.
extension ViewModelBindableType where Self: UIViewController {
mutating func bind(viewModel: Self.ViewModelType) {
self.viewModel = viewModel
loadViewIfNeeded()
/// 개별 view controller에서 bindViewModel메소드를 직접 호출할 필요가 없어짐.
bindViewModel()
}
}
|
// Created by Jonathan Galperin on 2015-07-07.
// Original work Copyright (c) 2011 Ole Begemann. All rights reserved.
// Modified Work Copyright (c) 2015 Edusight. All rights reserved.
import UIKit
class OBSlider: UISlider
{
var scrubbingSpeed: Float = 0.0
var realPositionValue: Float = 0.0
var beganTrackingLocation: CGPoint?
var scrubbingSpeedChangePositions = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
var scrubbingSpeeds = [1.0, 0.5, 0.25, 0.125, 0.00625, 0.0]
required init?(coder: NSCoder)
{
super.init(coder: coder)
scrubbingSpeed = Float(scrubbingSpeeds[0])
}
override init(frame: CGRect)
{
super.init(frame: frame)
self.scrubbingSpeed = Float(scrubbingSpeeds[0])
}
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool
{
guard let superview = superview else {
return false
}
let view = superview.superview
let beginTracking = super.beginTracking(touch, with: event)
if (beginTracking) {
self.realPositionValue = self.value
self.beganTrackingLocation = CGPoint(x: touch.location(in: view).x, y: touch.location(in: view).y)
}
return beginTracking
}
override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool
{
guard let beganTrackingLocation = beganTrackingLocation else {
return false
}
guard let superview = superview else {
return false
}
guard let view = superview.superview else {
return false
}
let previousLocation = touch.previousLocation(in: view)
let currentLocation = touch.location(in: view)
let trackingOffset = currentLocation.x - previousLocation.x // delta x
let verticalOffset = fabs(currentLocation.y - beganTrackingLocation.y)/(view.bounds.height - beganTrackingLocation.y)
// print("verticalOffset: \(CGFloat(verticalOffset))")
var scrubbingSpeedChangePosIndex = indexOfLowerScrubbingSpeed(scrubbingSpeedChangePositions, forOffset: verticalOffset)
if (scrubbingSpeedChangePosIndex == NSNotFound) {
scrubbingSpeedChangePosIndex = scrubbingSpeeds.count
}
self.scrubbingSpeed = Float(scrubbingSpeeds[scrubbingSpeedChangePosIndex - 1])
// print("scrubbingSpeed: \(self.scrubbingSpeed)")
let trackRect: CGRect = self.trackRect(forBounds: self.bounds)
self.realPositionValue = self.realPositionValue + (self.maximumValue - self.minimumValue) * Float(trackingOffset / trackRect.size.width)
let valueAdjustment: Float = self.scrubbingSpeed * (self.maximumValue - self.minimumValue) * Float(trackingOffset / trackRect.size.width)
// print("valueAdjustment: \(valueAdjustment)")
// var thumbAdjustment: Float = 0.0
// if (((self.beganTrackingLocation!.y < currentLocation.y) && (currentLocation.y < previousLocation.y)) || ((self.beganTrackingLocation!.y > currentLocation.y) && (currentLocation.y > previousLocation.y))) {
// thumbAdjustment = (self.realPositionValue - self.value) / Float(1 + fabs(currentLocation.y - self.beganTrackingLocation!.y))
// }
let thumbAdjustment: Float = (self.realPositionValue - self.value) / Float(1 + fabs(currentLocation.y - beganTrackingLocation.y))
// print("thumbAdjustment: \(thumbAdjustment)")
self.value += valueAdjustment + thumbAdjustment
if isContinuous {
sendActions(for: UIControlEvents.valueChanged)
}
return isTracking
}
override func endTracking(_ touch: UITouch?, with event: UIEvent?)
{
if (self.isTracking) {
scrubbingSpeed = 1.0
sendActions(for: UIControlEvents.valueChanged)
}
}
func indexOfLowerScrubbingSpeed (_ scrubbingSpeedPositions: Array<Double>, forOffset verticalOffset: CGFloat) -> NSInteger {
for i in 0..<scrubbingSpeedPositions.count {
// print("indexOfLowerScrubbingSpeed: \(CGFloat(scrubbingSpeedOffset))")
if (verticalOffset < CGFloat(scrubbingSpeedPositions[i])) {
return i
}
}
return NSNotFound
}
}
|
//
// LocalSearchManager.swift
// SwiftUberDemo
//
// Created by Sean Wilson on 9/7/15.
// Copyright (c) 2015 Sean Wilson. All rights reserved.
//
import UIKit
import MapKit
class LocalSearchManager {
class func search(searchText: String, region: MKCoordinateRegion?, completion:(([MKMapItem], NSError?)-> Void)?) {
let searchRequest = MKLocalSearchRequest()
searchRequest.naturalLanguageQuery = searchText
if let mapRegion = region as MKCoordinateRegion? {
searchRequest.region = mapRegion
}
let search = MKLocalSearch(request: searchRequest)
search.startWithCompletionHandler({
(response: MKLocalSearchResponse?, error: NSError?) -> Void in
var mapItems:[MKMapItem] = []
if error != nil {
print("Local Search Error: \(error)", terminator: "")
return
}
if let result = response as MKLocalSearchResponse? {
mapItems = result.mapItems
}
completion?(mapItems, error)
})
}
}
|
//状态模式很像策略模式,但是他封装的不是算法,而是一个一个本体下的不同状态。
protocol State {
func operation()
}
class ConcreteStateA: State {
func operation() {
print("A")
}
}
class ConcreteStateB: State {
func operation() {
print("B")
}
}
class Context {
var state: State = ConcreteStateA()
func someMethod() {
state.operation()
}
}
let c = Context()
c.someMethod() // OUTPUT: A
c.state = ConcreteStateB() // switch state
c.someMethod() // OUTPUT: B
|
import Foundation
import CoreGraphics
import Unbox
/// Protocol defining shared APIs for Direction types
public protocol DirectionType: RawRepresentable, Hashable, StringConvertible, UnboxableByTransform {
/// The number of directions that this type contains
static var count: Int { get }
/// The radian value that represents the angle of this direction
var radianValue: CGFloat { get }
/// Initialize an instance of this Direction type with a string equivalent to a member name
init?(string: String)
/// Return the next clockwise direction
func nextClockwiseDirection() -> Self
/// Return the next counter clockwise direction
func nextCounterClockwiseDirection() -> Self
/// Return the opposite direction
func oppositeDirection() -> Self
/// Attempt to convert this direction into a four way direction
func toFourWayDirection() -> Direction.FourWay?
/// Convert this direction into an eight way direction
func toEightWayDirection() -> Direction.EightWay
}
/// Structure acting as a namespace for enums describing directions
public struct Direction {
/// An enum that describes a direction in any of 4 ways
public enum FourWay: Int, DirectionType {
public typealias UnboxRawValueType = String
case Up
case Right
case Down
case Left
public static var count: Int {
return 4
}
public static func lastValue() -> FourWay {
return .Left
}
/// Whether the direction is Horizontal
public var isHorizontal: Bool {
switch self {
case .Up, .Down:
return false
case .Right, .Left:
return true
}
}
/// Whether the direction is Vertical
public var isVertical: Bool {
return !self.isHorizontal
}
public init?(string: String) {
switch string {
case FourWay.Up.toString():
self = .Up
case FourWay.Right.toString():
self = .Right
case FourWay.Down.toString():
self = .Down
case FourWay.Left.toString():
self = .Left
default:
return nil
}
}
public func toString() -> String {
switch self {
case .Up:
return "Up"
case .Right:
return "Right"
case .Down:
return "Down"
case .Left:
return "Left"
}
}
public func toFourWayDirection() -> Direction.FourWay? {
return self
}
public func toEightWayDirection() -> Direction.EightWay {
return Direction.EightWay(self)
}
}
/// An ennum that describes a direction in any of 8 ways
public enum EightWay: Int, DirectionType {
public typealias UnboxRawValueType = String
case Up
case UpRight
case Right
case RightDown
case Down
case DownLeft
case Left
case LeftUp
public static var count: Int {
return 8
}
public static func lastValue() -> EightWay {
return .LeftUp
}
public static func diagonalDirections() -> [EightWay] {
return [
.UpRight,
.RightDown,
.DownLeft,
.LeftUp
]
}
/// Whether the direction is diagonal
public var isDiagonal: Bool {
return self.toFourWayDirection() == nil
}
public init?(string: String) {
switch string {
case EightWay.Up.toString():
self = .Up
case EightWay.UpRight.toString():
self = .UpRight
case EightWay.Right.toString():
self = .Right
case EightWay.RightDown.toString():
self = .RightDown
case EightWay.Down.toString():
self = .Down
case EightWay.DownLeft.toString():
self = .DownLeft
case EightWay.Left.toString():
self = .Left
case EightWay.LeftUp.toString():
self = .LeftUp
default:
return nil
}
}
public init(_ fourWayDirection: FourWay) {
switch fourWayDirection {
case .Up:
self = .Up
case .Right:
self = .Right
case .Down:
self = .Down
case .Left:
self = .Left
}
}
public func toString() -> String {
switch self {
case .Up:
return "Up"
case .UpRight:
return "UpRight"
case .Right:
return "Right"
case .RightDown:
return "RightDown"
case .Down:
return "Down"
case .DownLeft:
return "DownLeft"
case .Left:
return "Left"
case .LeftUp:
return "LeftUp"
}
}
public func toFourWayDirection() -> Direction.FourWay? {
switch self {
case .Up:
return .Up
case .Right:
return .Right
case .Down:
return .Down
case .Left:
return .Left
case .UpRight, .RightDown, .DownLeft, .LeftUp:
return nil
}
}
public func toEightWayDirection() -> Direction.EightWay {
return self
}
}
}
/// Default implementations of the DirectionType protocol
public extension DirectionType where RawValue: Number, UnboxRawValueType == String {
var radianValue: CGFloat {
return (CGFloat(M_PI * Double(2)) / CGFloat(Self.count())) * CGFloat(self.rawValue)
}
static func firstValue() -> Self {
return Self(rawValue: RawValue(0))!
}
static func transformUnboxedValue(unboxedValue: String) -> Self? {
return self.init(string: unboxedValue)
}
static func unboxFallbackValue() -> Self {
return self.firstValue()
}
func nextClockwiseDirection() -> Self {
return self.nextOrLoopAround()
}
func nextCounterClockwiseDirection() -> Self {
return self.previous() ?? Self(rawValue: RawValue(Self.count - 1))!
}
func oppositeDirection() -> Self {
var direction = self
Repeat(Self.count / 2) {
direction = direction.nextCounterClockwiseDirection()
}
return direction
}
}
/// Extension for Arrays containing Direction values
public extension Array where Element: DirectionType {
func toEightWayDirections() -> [Direction.EightWay] {
var directions: [Direction.EightWay] = []
for direction in self {
directions.append(direction.toEightWayDirection())
}
return directions
}
}
|
//
// PostController.swift
// Timeline
//
// Created by Taylor Mott on 11/3/15.
// Copyright © 2015 DevMountain. All rights reserved.
//
import Foundation
import UIKit
class PostController {
static func fetchTimelineForUser(user: User, completion: (posts: [Post]?) -> Void) {
UserController.followedByUser(user) { (followed) in
var allPosts: [Post] = []
let dispatchGroup = dispatch_group_create()
dispatch_group_enter(dispatchGroup)
postsForUser(UserController.sharedController.currentUser, completion: { (posts) -> Void in
if let posts = posts {
allPosts += posts
}
dispatch_group_leave(dispatchGroup)
})
if let followed = followed {
for user in followed {
dispatch_group_enter(dispatchGroup)
postsForUser(user, completion: { (posts) in
if let posts = posts {
allPosts += posts
}
dispatch_group_leave(dispatchGroup)
})
}
}
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), { () -> Void in
let orderedPosts = orderPosts(allPosts)
completion(posts: orderedPosts)
})
}
}
static func addPost(image: UIImage, caption: String?, completion: (success: Bool, post: Post?) -> Void) {
ImageController.uploadImage(image) { (identifier) -> Void in
if let identifier = identifier {
var post = Post(imageEndpoint: identifier, caption: caption, username: UserController.sharedController.currentUser.username)
post.save()
completion(success: true, post: post)
} else {
completion(success: false, post: nil)
}
}
}
static func postFromIdentifier(identifier: String, completion: (post: Post?) -> Void) {
FirebaseController.dataAtEndpoint("posts/\(identifier)") { (data) -> Void in
if let data = data as? [String: AnyObject] {
let post = Post(json: data, identifier: identifier)
completion(post: post)
} else {
completion(post: nil)
}
}
}
static func postsForUser(user: User, completion: (posts: [Post]?) -> Void) {
FirebaseController.base.childByAppendingPath("posts").queryOrderedByChild("username").queryEqualToValue(user.username).observeSingleEventOfType(.Value, withBlock: { snapshot in
if let postDictionaries = snapshot.value as? [String: AnyObject] {
let posts = postDictionaries.flatMap({Post(json: $0.1 as! [String : AnyObject], identifier: $0.0)})
let orderedPosts = orderPosts(posts)
completion(posts: orderedPosts)
} else {
completion(posts: nil)
}
})
}
static func deletePost(post: Post) {
post.delete()
}
static func addCommentWithTextToPost(text: String, post: Post, completion: (success: Bool, post: Post?) -> Void?) {
if let postIdentifier = post.identifier {
var comment = Comment(username: UserController.sharedController.currentUser.username, text: text, postIdentifier: postIdentifier)
comment.save()
PostController.postFromIdentifier(comment.postIdentifier) { (post) -> Void in
completion(success: true, post: post)
}
} else {
var post = post
post.save()
var comment = Comment(username: UserController.sharedController.currentUser.username, text: text, postIdentifier: post.identifier!)
comment.save()
PostController.postFromIdentifier(comment.postIdentifier) { (post) -> Void in
completion(success: true, post: post)
}
}
}
static func deleteComment(comment: Comment, completion: (success: Bool, post: Post?) -> Void) {
comment.delete()
PostController.postFromIdentifier(comment.postIdentifier) { (post) -> Void in
completion(success: true, post: post)
}
}
static func addLikeToPost(post: Post, completion: (success: Bool, post: Post?) -> Void) {
if let postIdentifier = post.identifier {
var like = Like(username: UserController.sharedController.currentUser.username, postIdentifier: postIdentifier)
like.save()
} else {
var post = post
post.save()
var like = Like(username: UserController.sharedController.currentUser.username, postIdentifier: post.identifier!)
like.save()
}
PostController.postFromIdentifier(post.identifier!, completion: { (post) -> Void in
completion(success: true, post: post)
})
}
static func deleteLike(like: Like, completion: (success: Bool, post: Post?) -> Void) {
like.delete()
PostController.postFromIdentifier(like.postIdentifier) { (post) -> Void in
completion(success: true, post: post)
}
}
static func orderPosts(posts: [Post]) -> [Post] {
return posts.sort({$0.0.identifier > $0.1.identifier})
}
// static func mockPosts() -> [Post] {
//
// let sampleImageIdentifier = "-K1l4125TYvKMc7rcp5e"
//
// let like1 = Like(username: "darth", postIdentifier: "1234")
// let like2 = Like(username: "look", postIdentifier: "4566")
// let like3 = Like(username: "em0r0r", postIdentifier: "43212")
//
// let comment1 = Comment(username: "ob1kenob", text: "use the force", postIdentifier: "1234")
// let comment2 = Comment(username: "darth", text: "join the dark side", postIdentifier: "4566")
//
// let post1 = Post(imageEndpoint: sampleImageIdentifier, caption: "Nice shot!", comments: [comment1, comment2], likes: [like1, like2, like3])
// let post2 = Post(imageEndpoint: sampleImageIdentifier, caption: "Great lookin' kids!")
// let post3 = Post(imageEndpoint: sampleImageIdentifier, caption: "Love the way she looks when she smiles like that.")
//
// return [post1, post2, post3]
// }
}
|
import UIKit
// MARK: - Public
public enum CameraSource: String {
case prompt = "PROMPT"
case camera = "CAMERA"
case photos = "PHOTOS"
}
public enum CameraDirection: String {
case rear = "REAR"
case front = "FRONT"
}
public enum CameraResultType: String {
case base64
case uri
case dataURL = "dataUrl"
}
struct CameraPromptText {
let title: String
let photoAction: String
let cameraAction: String
let cancelAction: String
init(title: String? = nil, photoAction: String? = nil, cameraAction: String? = nil, cancelAction: String? = nil) {
self.title = title ?? "Photo"
self.photoAction = photoAction ?? "From Photos"
self.cameraAction = cameraAction ?? "Take Picture"
self.cancelAction = cancelAction ?? "Cancel"
}
}
public struct CameraSettings {
var source: CameraSource = CameraSource.prompt
var direction: CameraDirection = CameraDirection.rear
var resultType = CameraResultType.base64
var userPromptText = CameraPromptText()
var jpegQuality: CGFloat = 1.0
var width: CGFloat = 0
var height: CGFloat = 0
var allowEditing = false
var shouldResize = false
var shouldCorrectOrientation = true
var saveToGallery = false
var presentationStyle = UIModalPresentationStyle.fullScreen
}
public struct CameraResult {
let image: UIImage?
let metadata: [AnyHashable: Any]
}
// MARK: - Internal
internal enum CameraPermissionType: String, CaseIterable {
case camera
case photos
}
internal enum CameraPropertyListKeys: String, CaseIterable {
case photoLibraryAddUsage = "NSPhotoLibraryAddUsageDescription"
case photoLibraryUsage = "NSPhotoLibraryUsageDescription"
case cameraUsage = "NSCameraUsageDescription"
var link: String {
switch self {
case .photoLibraryAddUsage:
return "https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW73"
case .photoLibraryUsage:
return "https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW17"
case .cameraUsage:
return "https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW24"
}
}
var missingMessage: String {
return "You are missing \(self.rawValue) in your Info.plist file." +
" Camera will not function without it. Learn more: \(self.link)"
}
}
internal struct PhotoFlags: OptionSet {
let rawValue: Int
static let edited = PhotoFlags(rawValue: 1 << 0)
static let gallery = PhotoFlags(rawValue: 1 << 1)
static let all: PhotoFlags = [.edited, .gallery]
}
internal struct ProcessedImage {
var image: UIImage
var metadata: [String: Any]
var exifData: [String: Any] {
var exifData = metadata["{Exif}"] as? [String: Any]
exifData?["Orientation"] = metadata["Orientation"]
exifData?["GPS"] = metadata["{GPS}"]
return exifData ?? [:]
}
mutating func overwriteMetadataOrientation(to orientation: Int) {
replaceDictionaryOrientation(atNode: &metadata, to: orientation)
}
func replaceDictionaryOrientation(atNode node: inout [String: Any], to orientation: Int) {
for key in node.keys {
if key == "Orientation", (node[key] as? Int) != nil {
node[key] = orientation
} else if var child = node[key] as? [String: Any] {
replaceDictionaryOrientation(atNode: &child, to: orientation)
node[key] = child
}
}
}
func generateJPEG(with quality: CGFloat) -> Data? {
// convert the UIImage to a jpeg
guard let data = self.image.jpegData(compressionQuality: quality) else {
return nil
}
// define our jpeg data as an image source and get its type
guard let source = CGImageSourceCreateWithData(data as CFData, nil), let type = CGImageSourceGetType(source) else {
return data
}
// allocate an output buffer and create the destination to receive the new data
guard let output = NSMutableData(capacity: data.count), let destination = CGImageDestinationCreateWithData(output, type, 1, nil) else {
return data
}
// pipe the source into the destination while overwriting the metadata, this encodes the metadata information into the image
CGImageDestinationAddImageFromSource(destination, source, 0, self.metadata as CFDictionary)
// finish
guard CGImageDestinationFinalize(destination) else {
return data
}
return output as Data
}
}
|
//
// BookList+CoreDataClass.swift
// Readify
//
// Created by Shakeel Mohamed on 2021-01-14.
//
//
import Foundation
import CoreData
@objc(BookList)
public class BookList: NSManagedObject {
}
|
//
// ContentView.swift
// FavouriteThings
//
// Created by Evan Armstrong on 2021-02-04.
//
import SwiftUI
// conforms to the view protocol
// A view is just a structure that is part of the user interface - what is seen and manipulated by the user
// Each structure that conforms to the view protocol must follow two rules
// Must have a body property and must
struct ContentView: View {
// create a copy of the data that we created in Thing.swift
// A "store" in developer speak is just "a place that we keep data"
var store = favouriteThings
var body: some View {
NavigationView {
List(favouriteThings) { thing in
NavigationLink(destination: ThingDetail(someThing: thing)) {
ListItem(someThing: thing)
}
}
.navigationTitle("Favourite Things") }
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// SetRouteViewImages.swift
// UBSetRoute
//
// Created by Usemobile on 28/01/19.
// Copyright © 2019 Usemobile. All rights reserved.
//
import UIKit
public class SetRouteViewImages {
public var mainPinIcon: UIImage?
public var cellPinIcon: UIImage?
public var backBtnIcon: UIImage?
public var mapPinIcon: UIImage?
public var currentLocationIcon: UIImage?
public var routeOrigin: UIImage?
public var routeOriginVisited: UIImage?
public var routeDots: UIImage?
public var routeDestiny: UIImage?
public var routeSwap: UIImage?
public var stopsClock: UIImage?
public static var `default`: SetRouteViewImages {
return SetRouteViewImages(mainPinIcon: nil,
cellPinIcon: nil,
backBtnIcon: nil,
mapPinIcon: nil,
currentLocationIcon: nil,
routeOrigin: nil,
routeOriginVisited: nil,
routeDots: nil,
routeDestiny: nil,
stopsClock: nil,
routeSwap: nil)
}
public init(mainPinIcon: UIImage?,
cellPinIcon: UIImage?,
backBtnIcon: UIImage?,
mapPinIcon: UIImage?,
currentLocationIcon: UIImage?,
routeOrigin: UIImage?,
routeOriginVisited: UIImage?,
routeDots: UIImage?,
routeDestiny: UIImage?,
stopsClock: UIImage?,
routeSwap: UIImage?) {
self.mainPinIcon = mainPinIcon
self.cellPinIcon = cellPinIcon
self.backBtnIcon = backBtnIcon
self.mapPinIcon = mapPinIcon
self.currentLocationIcon = currentLocationIcon
self.routeOrigin = routeOrigin
self.routeOriginVisited = routeOriginVisited
self.routeDots = routeDots
self.routeDestiny = routeDestiny
self.routeSwap = routeSwap
self.stopsClock = stopsClock
}
}
|
//
// Constants.swift
// VirtualTourist
//
// Created by Taylor Masterson on 11/12/17.
// Copyright © 2017 Taylor Masterson. All rights reserved.
//
import Foundation
public struct Flickr {
static let APIScheme = "https"
static let APIHost = "api.flickr.com"
static let APIPath = "/services/rest"
static let SearchBBoxHalfWidth = 1.0
static let SearchBBoxHalfHeight = 1.0
static let SearchLatRange = (-90.0, 90.0)
static let SearchLngRange = (-180.0, 180.0)
}
public struct FlickrParamKeys {
static let Method = "method"
static let APIKey = "api_key"
static let NoJSONCallback = "nojsoncallback"
static let Text = "text"
static let Format = "format"
static let SafeSearch = "safe_search"
static let Page = "page"
static let BoundingBox = "bbox"
static let Extras = "extras"
static let PerPage = "per_page"
}
public struct FlickrParamValues {
static let SearchMethod = "flickr.photos.search"
static let APIKey = "3089e5bf1bf8ad9f0de159a6343e9753"
static let ResponseFormat = "json"
static let DisableJSONCallback = "1" // 1 == yes
static let MediumURL = "url_m"
static let UseSafeSearch = "1"
static let PerPage = "30"
}
public struct FlickrResponseKeys {
static let Status = "stat" // ???
static let PhotosCollectionData = "photos"
static let PhotosCollection = "photo"
static let Title = "title"
static let MediumURL = "url_m"
static let Pages = "pages"
static let Page = "page"
static let Total = "total"
}
public struct FlickrResponseValues {
static let OKStatus = "ok"
}
|
//
// DatePickerViewController.swift
// OutaTime
//
// Created by FGT MAC on 1/16/20.
// Copyright © 2020 FGT MAC. All rights reserved.
//
//MARK: - Delegate
protocol DatePickerDelegate {
func destinationDateWasChosen(date: Date)
}
//MARK: - ViewController
import UIKit
class DatePickerViewController: UIViewController {
var delegate: DatePickerDelegate?
@IBOutlet weak var datePicker: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func cancelButton(_ sender: UIBarButtonItem) {
//dismiss modal
dismiss(animated: true, completion: nil)
}
@IBAction func doneButton(_ sender: UIBarButtonItem) {
//passing date to method
delegate?.destinationDateWasChosen(date: datePicker.date)
// print("From Modal \(datePicker.date)")
//dismiss modal
dismiss(animated: true, completion: nil)
}
}
|
//
// APIManager.swift
// YoutubeDemo
//
// Created by Giresh Dora on 12/10/18.
// Copyright © 2018 Giresh Dora. All rights reserved.
//
import Foundation
import UIKit
let API_KEY = "YOUR_API_KEY"
class APIManager {
static let sharedInstance = APIManager()
typealias CompletionHandler = (_ success: VideoDetailsList?,_ error: String?)->()
func getVideoList(str:String,complitionHandler:@escaping CompletionHandler){
let contryCode = self.getCountryCode()
let strURL = str+"®ionCode=\(contryCode)&key=\(API_KEY)"
guard let url = URL(string: strURL) else {
return
}
URLSession.shared.dataTask(with: url) { (data, responce, error) in
if error != nil {
complitionHandler(nil, "Please check your network connection.")
}
guard let data = data else { return }
do{
let videoDetailList = try JSONDecoder().decode(VideoDetailsList.self, from: data)
complitionHandler(videoDetailList,nil)
}catch{
}
}.resume()
}
//MARK: Get Country code
fileprivate func getCountryCode() -> String {
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
return countryCode
}
return ""
}
}
|
//
// ViewController.swift
// Functional
//
// Created by KingCQ on 2017/1/9.
// Copyright © 2017年 KingCQ. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let credential = Credential(username: "bob", password: "wcq")
login(credential) { result in
switch result {
case .success(let token):
print(token, "hello")
case .failure(let error):
print(error, "fail")
}
}
var array = Array(repeating: 1, count: 10)
array[0] = 1
array[1] = 2
print(array, "🌹")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
func login(_ credential: Credential, completion: (Result<Token>) -> Void) {
let error = Result<Token>.failure(Error(message: ""))
let success = Result<Token>.success(Token(token: ""))
completion(error)
completion(success)
}
struct Token {
var token: String?
}
struct Error {
var message: String?
}
struct Credential {
var username: String
var password: String
}
enum Result<Value> {
case success(Value)
case failure(Error)
}
|
//
// Service.swift
// csc2228
//
// Created by Yolanda He on 2017-10-10.
// Copyright © 2017 csc2228. All rights reserved.
//
import Foundation
import CoreMotion
import CoreLocation
import AWSDynamoDB
class Service {
var samplingAccTimer: Timer!
var samplingLocTimer: Timer!
var uploadTimer: Timer!
var action:String!
var deviceName: String!
var currentTime: String!
var accQueue=[[AWSDynamoDBWriteRequest]]()
var locQueue=[[AWSDynamoDBWriteRequest]]()
var recordAcc=[AWSDynamoDBWriteRequest]()
var recordLocation=[AWSDynamoDBWriteRequest]()
var db = AWSDynamoDB.default()
var updateInput:AWSDynamoDBUpdateItemInput!
var motionManager: CMMotionManager!
var locationManager: CLLocationManager!
var msgRetrievedCnt=0
var msgPushInCnt = 0
func newTimerTask(action: String!) {
getActiontime()
print("Creating new timer "+action)
print("Action Time:"+currentTime)
self.action=action
getDeviceId()
// Clean the existing timer first. That means, ensure the running timer will be clean out before a new task.
clearTimers()
//initialize the managers
initManagers()
//initialize AWS DynamoDB
initDynamoDB()
// Set up the timer to upload local dataset, and to sample data.
uploadTimer = Timer.scheduledTimer(timeInterval: Constants.INTERVAL_UPLOAD, target: self, selector: #selector(sendExistingData), userInfo: nil, repeats: true)
samplingAccTimer = Timer.scheduledTimer(timeInterval: Constants.INTERVAL_SAMPLING_ACCELEROMETER, target: self, selector: #selector(sampleAccelerometer), userInfo: nil, repeats: true)
samplingLocTimer = Timer.scheduledTimer(timeInterval: Constants.INTERVAL_SAMPLING_LOCATION, target: self, selector: #selector(sampleLocation), userInfo: nil, repeats: true)
}
func initDynamoDB(){
db = AWSDynamoDB.default()
}
func initManagers(){
self.motionManager = CMMotionManager()
self.motionManager.accelerometerUpdateInterval=Constants.INTERVAL_SAMPLING_ACCELEROMETER
self.motionManager.startAccelerometerUpdates()
if(CLLocationManager.locationServicesEnabled()){
locationManager=CLLocationManager()
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
else{
print("location service unavailable")
}
}
func cleanAll(){
clearManagers()
clearTimers()
cleanCache()
}
func clearManagers(){
guard let _=motionManager else {
return
}
motionManager.stopAccelerometerUpdates()
guard let _=locationManager else {
return
}
locationManager.stopUpdatingLocation()
}
func clearTimers() {
clearAccTimer()
clearUploadTimer()
clearLocTimer()
}
func clearLocTimer() {
guard let _=samplingLocTimer else {
return
}
print("samplingLocTimer Canceled")
samplingLocTimer.invalidate()
}
func clearAccTimer() {
guard let _=samplingAccTimer else {
return
}
print("samplingAccTimer Canceled")
samplingAccTimer.invalidate()
}
func clearUploadTimer(){
guard let _=uploadTimer else {
return
}
print("uploadTimer Canceled")
uploadTimer.invalidate()
}
func doesAccExceedMaxQueueSize(){
if recordAcc.count == Constants.BATCH_SIZE {
accQueue.append(recordAcc)
recordAcc.removeAll()
}
}
func doesLocExceedMaxQueueSize(){
// print("array size" + String(recordLocation.count))
if recordLocation.count == Constants.BATCH_SIZE {
locQueue.append(recordLocation)
recordLocation.removeAll()
}
}
@objc func getDeviceId(){
self.deviceName = UIDevice.current.name
}
@objc func getActiontime(){
// let dateFormatter : DateFormatter = DateFormatter()
// dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = Date()
let calender = Calendar.current
let components = calender.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let minute = components.minute
let second = components.second
let actiontime = String(year!) + "-" + String(month!) + "-" + String(day!) + " " + String(hour!) + ":" + String(minute!) + ":" + String(second!)
currentTime = actiontime
}
@objc func timeformatter(time: String!) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let date = dateFormatter.date(from: time)!
dateFormatter.timeZone = TimeZone.current
let dateString: String! = dateFormatter.string(from: date)
return dateString
}
@objc func sampleLocation(){
doesLocExceedMaxQueueSize()
let location = locationManager.location
let latitude = AWSDynamoDBAttributeValue()
latitude?.s = String(format:"%.8f",location!.coordinate.latitude)
let longtitude = AWSDynamoDBAttributeValue()
longtitude?.s = String(format:"%.8f",location!.coordinate.longitude)
let time = AWSDynamoDBAttributeValue()
let timestamp = location?.timestamp.description
time?.s = String(format:"%@", timeformatter(time: timestamp))
// print(String(format:"%.8f %.8f %@",location!.coordinate.latitude, location!.coordinate.longitude, timestamp!))
let currentAction = AWSDynamoDBAttributeValue()
currentAction?.s=self.action
let deviceName = AWSDynamoDBAttributeValue()
deviceName?.s=self.deviceName
let write_request = AWSDynamoDBWriteRequest()
write_request?.putRequest=AWSDynamoDBPutRequest()
write_request?.putRequest?.item = [Constants.COLUMN_LATITUDE:latitude!, Constants.COLUMN_LONGTITUDE:longtitude!, Constants.COLUMN_TIMESTAMP:time!, Constants.COLUMN_ACTION:currentAction!,Constants.COLUMN_DEVICENAME: deviceName!]
if recordLocation.contains(write_request!){
return
}
recordLocation.append(write_request!)
}
@objc func sampleAccelerometer(){
doesAccExceedMaxQueueSize()
let data = self.motionManager.accelerometerData
let x = AWSDynamoDBAttributeValue()
x?.s = String(format:"%.6f",data!.acceleration.x)
let y = AWSDynamoDBAttributeValue()
y?.s = String(format:"%.6f",data!.acceleration.y)
let z = AWSDynamoDBAttributeValue()
z?.s = String(format:"%.6f",data!.acceleration.z)
let time = AWSDynamoDBAttributeValue()
time?.s = "\(data!.timestamp)"
let currentAction = AWSDynamoDBAttributeValue()
currentAction?.s=self.action
let deviceName = AWSDynamoDBAttributeValue()
deviceName?.s=self.deviceName
let actionTime = AWSDynamoDBAttributeValue()
actionTime?.s=self.currentTime
let write_request = AWSDynamoDBWriteRequest()
write_request?.putRequest=AWSDynamoDBPutRequest()
write_request?.putRequest?.item = [Constants.COLUMN_X:x!, Constants.COLUMN_Y:y!, Constants.COLUMN_Z:z!, Constants.COLUMN_TIMESTAMP:time!, Constants.COLUMN_ACTION:currentAction!,Constants.COLUMN_DEVICENAME: deviceName!, Constants.COLUMN_ACTIONTIME: actionTime!]
// msgRetrievedCnt = msgRetrievedCnt+1
if recordAcc.contains(write_request!){
return
}
// msgPushInCnt = msgPushInCnt+1
recordAcc.append(write_request!)
}
@objc
func sendExistingData() {
locQueue.append(recordLocation)
accQueue.append(recordAcc)
// print("🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱")
//
// print("Total retrieved cnt:" + String(msgRetrievedCnt))
// print("Total pushed cnt:" + String(msgPushInCnt))
// var msgInQueue = 0
// for batch in accQueue {
// msgInQueue=msgInQueue+batch.count
// }
// print("Total Messages in queue " + String(msgInQueue))
// msgRetrievedCnt=0
// msgPushInCnt=0
// print("🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱")
for batch in locQueue {
upload(array:batch, table:Constants.TABLE_LOC)
}
// var accQueueLoopCnt = 0
for batch in accQueue {
// accQueueLoopCnt+=1
upload(array:batch, table:Constants.TABLE_ACC)
}
//
//
// print("🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑")
// var accQueueCnt = accQueue.count
//
// print("Total msgUploadedCnt:" + String(msgUploadedCnt))
// print("Total sets in queue:" + String(accQueueCnt))
// print("Total loop time for acc queue:" + String(accQueueLoopCnt))
// print("Total times of upload request cnt:" + String(uploadReqCnt))
// print("Total times of upload cnt:" + String(uploadCnt))
// accQueueCnt=0
// accQueueLoopCnt=0
// msgUploadedCnt=0
// uploadCnt=0
// uploadReqCnt=0
// print("🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑🐑")
cleanCache()
}
var msgUploadedCnt=0
var uploadReqCnt=0
var uploadCnt=0
func upload(array:[AWSDynamoDBWriteRequest]!, table:String!) {
let batchWriteItemInput = AWSDynamoDBBatchWriteItemInput()
batchWriteItemInput?.requestItems = [ table:array]
// msgUploadedCnt+=array.count
// uploadReqCnt+=1
db.batchWriteItem(batchWriteItemInput!).continueWith { (task:AWSTask<AWSDynamoDBBatchWriteItemOutput>) -> Any? in
if let error = task.error {
var icon = "🌎"
if table == Constants.TABLE_ACC {
icon = "❤️"
}
print("The request failed. Error: \(error) " + icon)
return nil
}
if(task.isFaulted){
print("Meow meow meow?")
}
self.uploadCnt+=1
print("Current uploaded cnt:"+String(self.uploadCnt))
print("I have a feeling that it succeded 🐱")
return nil
}
}
func cleanCache(){
accQueue.removeAll()
locQueue.removeAll()
recordLocation.removeAll()
recordAcc.removeAll()
}
}
|
//
// TransactionListPresenterTests.swift
// TransactionsTests
//
// Created by Thiago Santiago on 1/20/19.
// Copyright © 2019 Thiago Santiago. All rights reserved.
//
import XCTest
@testable import Transactions
class TransactionListPresenterTests: XCTestCase {
var presenter: TransactionListPresenter!
var worker: TransactionsWorkerMock!
override func setUp() {
presenter = TransactionListPresenter()
worker = TransactionsWorkerMock()
}
func testShouldTreatTheTransactionDataWithSuccess() {
let transactionList = TransactionList(transactions: worker.createTransactionsList(), nextPage: "")
let transactionsViewModel = presenter.treatTransactionData(transactionList)
XCTAssertNotNil(transactionsViewModel)
XCTAssertNotNil(transactionsViewModel.totalBalance)
XCTAssertEqual(transactionsViewModel.transactions.count, 55)
}
}
|
import PlaygroundSupport
import SpriteKit
public class RoastScene: SKScene {
private var roastMachine: SKSpriteNode!
private var coffeeGrains: SKSpriteNode!
private var lightRoastButton: SKSpriteNode!
private var mediumRoastButton: SKSpriteNode!
private var darkRoastButton: SKSpriteNode!
private var smoke: SKSpriteNode!
private var continueLabel: SKLabelNode!
private var messageBubble: SKSpriteNode!
private var step = 0
private var actionRunning = true
public override func didMove(to view: SKView) {
roastMachine = childNode(withName: "//roastMachine") as? SKSpriteNode
coffeeGrains = childNode(withName: "//coffeeGrains") as? SKSpriteNode
lightRoastButton = childNode(withName: "//lightRoast") as? SKSpriteNode
mediumRoastButton = childNode(withName: "//mediumRoast") as? SKSpriteNode
darkRoastButton = childNode(withName: "//darkRoast") as? SKSpriteNode
smoke = childNode(withName: "//smoke") as? SKSpriteNode
continueLabel = childNode(withName: "//continueLabel") as? SKLabelNode
messageBubble = childNode(withName: "//messageBubble") as? SKSpriteNode
continueLabel.alpha = 0.0
messageBubble.run(.sequence([.wait(forDuration: 1), .move(to: CGPoint(x: 130.5, y: 27.0), duration: 0.5), .playSoundFileNamed("roastSceneMessage1Audio.m4a", waitForCompletion: false), .wait(forDuration: 6), .run {
self.messageBubble.childNode(withName: "messageLabel1")?.alpha = 0
self.messageBubble.childNode(withName: "messageLabel2")?.alpha = 1
}, .playSoundFileNamed("roastSceneMessage2Audio.m4a", waitForCompletion: false), .wait(forDuration: 5), .move(to: CGPoint(x: 400, y: 27.0), duration: 0.5), .run {
self.messageBubble.childNode(withName: "messageLabel2")?.alpha = 0
}]))
// message audio
lightRoastButton.run(.sequence([.wait(forDuration: 12), .fadeAlpha(to: 1, duration: 1)]))
mediumRoastButton.run(.sequence([.wait(forDuration: 12), .fadeAlpha(to: 1, duration: 1)]))
darkRoastButton.run(.sequence([.wait(forDuration: 12), .fadeAlpha(to: 1, duration: 1)]))
dismissTapToContinue()
actionTimer(time: 12, callback: {
self.continueLabel.text = "Choose your roasting profile"
self.showTapToContinue()
})
}
private func chooseCoffeeRoastProfile(pos: CGPoint) {
if lightRoastButton.contains(pos) {
mediumRoastButton.removeAllActions()
mediumRoastButton.alpha = 0.0
darkRoastButton.removeAllActions()
darkRoastButton.alpha = 0.0
lightRoastButton.removeAllActions()
lightRoastButton.alpha = 1.0
lightRoastButton.run(.move(to: CGPoint(x: 0.853, y: -211.096), duration: 0.5))
roastProfile = "light"
} else if mediumRoastButton.contains(pos) {
lightRoastButton.removeAllActions()
lightRoastButton.alpha = 0.0
darkRoastButton.removeAllActions()
darkRoastButton.alpha = 0.0
mediumRoastButton.removeAllActions()
mediumRoastButton.alpha = 1.0
roastProfile = "medium"
} else if darkRoastButton.contains(pos) {
mediumRoastButton.removeAllActions()
mediumRoastButton.alpha = 0.0
lightRoastButton.removeAllActions()
lightRoastButton.alpha = 0.0
darkRoastButton.removeAllActions()
darkRoastButton.alpha = 1.0
darkRoastButton.run(.move(to: CGPoint(x: 0.853, y: -211.096), duration: 0.5))
roastProfile = "dark"
} else {
return
}
roastMachine.run(.sequence([.wait(forDuration: 1), .group([.playSoundFileNamed("roastSound.m4a", waitForCompletion: false), shakeSpriteAction(layerPosition: roastMachine.position, duration: 6.5)])]))
coffeeGrains.run(.sequence([.wait(forDuration: 1), .fadeAlpha(to: 1, duration: 0.5), .move(to: CGPoint(x: -27.827, y: -54.226), duration: 3), .group([shakeSpriteAction(layerPosition: coffeeGrains.position, duration: 3), .colorize(with: roastProfileColor(type: roastProfile), colorBlendFactor: 1, duration: 3)]), .run {
self.coffeeGrains.position = CGPoint(x: -16.829, y: -87.911)
}, .move(to: CGPoint(x: 125.055, y: -87.912), duration: 1)]))
let coffeeGrainsCover = childNode(withName: "//coffeeGrainsCover") as? SKSpriteNode
coffeeGrainsCover?.run(.sequence([.wait(forDuration: 5), .run {
coffeeGrainsCover?.zPosition = 10
}]))
smoke.run(.sequence([.wait(forDuration: 9), .fadeAlpha(to: 1, duration: 2)]))
messageBubble.run(.sequence([.wait(forDuration: 11), .run {
self.messageBubble.childNode(withName: "messageLabel3")?.alpha = 1
}, .move(to: CGPoint(x: 130.5, y: 27.0), duration: 0.5), .playSoundFileNamed("roastSceneMessage3Audio.m4a", waitForCompletion: false), .wait(forDuration: 3), .run {
self.messageBubble.childNode(withName: "messageLabel3")?.alpha = 0
self.messageBubble.childNode(withName: "messageLabel4")?.alpha = 1
}, .playSoundFileNamed("roastSceneMessage4Audio.m4a", waitForCompletion: false), .wait(forDuration: 5)]))
dismissTapToContinue()
let _ = Timer.scheduledTimer(withTimeInterval: 19, repeats: false) { [self] timer in
self.run(.playSoundFileNamed("flashbackSound.mp3", waitForCompletion: false))
let newScene = EndScene(fileNamed: "EndScene")!
newScene.scaleMode = .aspectFit
let transition = SKTransition.fade(with: .white, duration: 5)
self.view?.presentScene(newScene, transition: transition)
}
}
private func shakeSpriteAction(layerPosition: CGPoint, duration: Float) -> SKAction {
let position = layerPosition
let amplitudeX:Float = 10
let amplitudeY:Float = 6
let numberOfShakes = duration / 0.04
var actionsArray:[SKAction] = []
for _ in 1...Int(numberOfShakes) {
let moveX = Float(arc4random_uniform(UInt32(amplitudeX))) - amplitudeX / 2
let moveY = Float(arc4random_uniform(UInt32(amplitudeY))) - amplitudeY / 2
let shakeAction = SKAction.moveBy(x: CGFloat(moveX), y: CGFloat(moveY), duration: 0.02)
shakeAction.timingMode = SKActionTimingMode.easeOut
actionsArray.append(shakeAction)
actionsArray.append(shakeAction.reversed())
}
actionsArray.append(.move(to: position, duration: 0.0))
let actionSeq = SKAction.sequence(actionsArray)
return actionSeq
}
private func showTapToContinue() {
continueLabel.run(.repeatForever(.sequence([.fadeIn(withDuration: 1.5), .fadeOut(withDuration: 1.5)])))
}
private func dismissTapToContinue() {
continueLabel.removeAllActions()
continueLabel.alpha = 0.0
}
private func actionTimer(time: Double, callback: @escaping () -> Void) {
actionRunning = true
let _ = Timer.scheduledTimer(withTimeInterval: time, repeats: false) { [self] timer in
actionRunning = false
callback()
}
}
@objc static public override var supportsSecureCoding: Bool {
// SKNode conforms to NSSecureCoding, so any subclass going
// through the decoding process must support secure coding
get {
return true
}
}
func touchDown(atPoint pos: CGPoint) {
if actionRunning {
return
}
chooseCoffeeRoastProfile(pos: pos)
}
func touchMoved(toPoint pos: CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchDown(atPoint: t.location(in: self)) }
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchMoved(toPoint: t.location(in: self)) }
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchUp(atPoint: t.location(in: self)) }
}
public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchUp(atPoint: t.location(in: self)) }
}
public override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
|
//
// ContentView.swift
// MyBarbershop
//
// Created by ZISACHMAD on 10/05/21.
//
import SwiftUI
import StreamChat
struct ContentView: View {
@StateObject var streamData = StreamViewModel()
@StateObject var model = LoginViewModel()
@AppStorage("log_Status") var logStatus = false
var body: some View {
NavigationView {
if !logStatus {
OtpLogin()
.environmentObject(model)
.navigationTitle("Login")
}
else {
ChannelView()
}
}
.background(ZStack {
Text("")
.alert(isPresented: $model.showAlert, content: {
Alert(title: Text("Message"), message: Text(model.errorMsg), dismissButton: .destructive(Text("Ok"), action: {
withAnimation{model.isLoading = false}
}))
})
Text("")
.alert(isPresented: $streamData.error, content: {
Alert(title: Text("Message"), message: Text(streamData.errorMsg), dismissButton: .destructive(Text("Ok"), action: {
withAnimation{streamData.isLoading = false}
}))
})
})
.overlay(
ZStack {
if streamData.createNewChannel {CreateNewChannel()} // NEW CHAT VIEW
if model.isLoading || streamData.isLoading {LoadingScreen()} // LOADING SCREEN
}
)
.environmentObject(streamData)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// ViewController.swift
// ProtocolTool
//
// Created by liuxc on 2019/8/16.
// Copyright © 2019 liuxc. All rights reserved.
//
import UIKit
import RxSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let vc = TestController()
self.present(vc, animated: true, completion: nil)
}
}
class TestController: UIViewController {
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .yellow
Observable<Int>
.interval(1, scheduler: MainScheduler.instance)
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.dismiss(animated: true, completion: nil)
}
}
|
//
// PythonTesterA.swift
// Pitstop
//
// Created by Peter Huang on 2019-10-27.
//
import Foundation
import PythonKit
//import Python
class PythonTesterA {
func loadSimpleFn() {
print("abcde")
}
func numpyTest() {
let np = Python.import("numpy") //import numpy as np
let arrA = np.array([4, 3, 7])
let arrB = np.array([9, 3, 5])
let result = arrA * arrB
print(result)
//[36 9 35]
}
// func tester2() {
// let sys = try Python.import("sys")
//
// print("Python \(sys.version_info.major).\(sys.version_info.minor)")
// print("Python Version: \(sys.version)")
// print("Python Encoding: \(sys.getdefaultencoding().upper())")
// }
// func fatigueChecker() {
// let sys : PythonObject = Python.import("sys")
// sys.path.append("/Users/peterhuang/")
// }
}
|
//
// ExposureAdjustRegulation.swift
// SignalPhotoEditor
//
// Created by Anastasia Holovash on 02.12.2020.
//
import UIKit
struct ExposureAdjustRegulation: Regulation {
var filterName: String = "Exposure"
var value: Float = 0
var minimumValue: Float = -2
var maximumValue: Float = 2
func applyFilter(image: inout CIImage) {
let currentFilter = CIFilter.exposureAdjust()
currentFilter.inputImage = image
currentFilter.ev = value
// get a CIImage from our filter or exit if that fails
guard let outputImage = currentFilter.outputImage else {
return
}
image = outputImage
}
}
|
//
// Book.swift
// ProSwiftLibrary
//
// Created by Amit Chandel on 7/27/15.
// Copyright (c) 2015 Amit Chandel. All rights reserved.
//
import UIKit
import ObjectMapper
class Book: Mappable {
var author: String = ""
var categories: String = ""
var lastCheckedOut: String = ""
var lastCheckedOutBy: String = ""
var publisher: String = ""
var title: String = ""
var url: String = ""
class func newInstance() -> Mappable {
return Book()
}
// Mappable
func mapping(map: Map) {
author <- map["author"]
categories <- map["categories"]
lastCheckedOut <- map["lastCheckedOut"]
lastCheckedOutBy <- map["lastCheckedOutBy"]
publisher <- map["publisher"]
title <- map["title"]
url <- map["url"]
}
} |
//
// BrainModel.swift
// plizdoo
//
// Created by Matthieu Tournesac on 25/03/2015.
// Copyright (c) 2015 MatthieuTnsc. All rights reserved.
//
import Foundation
class Brain {
// MARK: - Load all data from Local Datastore
func loadAllFromLocalDatastore(completion: (success: Bool, error: String) -> Void) {
thanks = PFUser.currentUser()?.objectForKey(PF_USER_THANKS) as! Int
NSNotificationCenter.defaultCenter().postNotificationName(updateTitleNotificationKey, object: self)
self.localQueryRank { (success, error) -> Void in
if success {
self.localQueryFriends { (success, error) -> Void in
if success {
self.localQueryReceived { (success, error) -> Void in
if success {
self.localQueryReceivedHistory { (success, error) -> Void in
if success {
self.localQuerySent { (success, error) -> Void in
if success {
self.localQuerySentHistory { (success, error) -> Void in
if success {
completion (success: true, error: "")
} else {
completion (success: false, error: error)
}
}
} else {
completion (success: false, error: error)
}
}
} else {
completion (success: false, error: error)
}
}
} else {
completion (success: false, error: error)
}
}
} else {
completion (success: false, error: error)
}
}
} else {
completion (success: false, error: error)
}
}
}
func loadAllFromNetwork(completion: (success: Bool, error: String) -> Void) {
self.networkQueryUpdateThanks({ (success, error) -> Void in
if success {
self.networkQueryFriends({ (success, error) -> Void in
if success {
self.networkQueryToMe({ (success, error) -> Void in
if success {
self.networkQueryFromMe({ (success, error) -> Void in
self.loadAllFromLocalDatastore({ (success, error) -> Void in
if success {
completion (success: true, error: "")
} else {
completion (success: false, error: error)
}
})
})
} else {
completion (success: false, error: error)
}
})
} else {
completion (success: false, error: error)
}
})
} else {
completion (success: false, error: error)
}
})
}
// MARK: - Query Network and pin in Local Datastore
func networkQueryUpdateThanks(completion: (success: Bool, error: String) -> Void) {
PFUser.currentUser()!.fetchInBackgroundWithBlock { (score:PFObject?, error:NSError?) -> Void in
if error == nil {
println("Parse Query Current User from Network")
thanks = score!.objectForKey(PF_USER_THANKS) as! Int
completion (success: true, error: "")
} else {
completion (success: false, error: "Error: Update score")
}
}
}
func networkQueryFriends(completion: (success: Bool, error: String) -> Void) {
// Query current user friend list
var query = PFQuery(className:PF_FRIEND_CLASS_NAME)
query.whereKey(PF_FRIEND_USER, equalTo: PFUser.currentUser()!)
query.getFirstObjectInBackgroundWithBlock { (object:PFObject?, error:NSError?) -> Void in
if error == nil {
object?.pinInBackgroundWithName(PF_FRIEND_CLASS_NAME)
// Query relation
var relation:PFRelation = object!.relationForKey(PF_FRIEND_RELATION)
var query:PFQuery = relation.query()!
query.orderByAscending(PF_USER_FIRSTNAME)
query.findObjectsInBackgroundWithBlock({ (results:[AnyObject]?, error:NSError?) -> Void in
println("Parse Query User Friends from Network")
if error == nil {
// Pin all friend list to current user
PFObject.pinAllInBackground(results, withName: PF_FRIEND_CLASS_NAME)
completion (success: true, error: "")
} else {
completion (success: false, error: "Error: Query friends")
}
})
} else {
completion (success: false, error: "Error: Query friends")
}
}
}
func networkQueryToMe(completion: (success: Bool, error: String) -> Void) {
var query = PFQuery(className:PF_ACTION_CLASS_NAME)
query.whereKey(PF_ACTION_TO, equalTo: PFUser.currentUser()!)
query.orderByAscending(PF_ACTION_EXPIRATIONDATE)
query.includeKey(PF_ACTION_FROM)
query.includeKey(PF_ACTION_TO)
if let lastUpdateDate: NSDate = NSUserDefaults.standardUserDefaults().objectForKey("lastUpdateToMe") as? NSDate {
query.whereKey(PF_ACTION_UPDATEDAT, greaterThan: lastUpdateDate)
}
query.findObjectsInBackgroundWithBlock { (results: [AnyObject]?, error: NSError?) -> Void in
println("Parse Query To Me from Network")
if error == nil {
// Set new last update date
NSUserDefaults.standardUserDefaults().setValue(NSDate(), forKey: "lastUpdateToMe")
// Pin all actions asked to current user
PFObject.pinAllInBackground(results, withName: "ToMe")
completion(success: true, error: "")
} else {
completion(success: false, error: "Error: Query todo")
}
}
}
func networkQueryFromMe(completion: (success: Bool, error: String) -> Void) {
var query = PFQuery(className:PF_ACTION_CLASS_NAME)
query.whereKey(PF_ACTION_FROM, equalTo: PFUser.currentUser()!)
query.orderByDescending(PF_ACTION_EXPIRATIONDATE)
query.includeKey(PF_ACTION_FROM)
query.includeKey(PF_ACTION_TO)
if let lastUpdateDate: NSDate = NSUserDefaults.standardUserDefaults().objectForKey("lastUpdateFromMe") as? NSDate {
query.whereKey(PF_ACTION_UPDATEDAT, greaterThan: lastUpdateDate)
}
query.findObjectsInBackgroundWithBlock { (results: [AnyObject]?, error: NSError?) -> Void in
println("Parse Query From Me from Network")
if error == nil {
// Set new last update date
NSUserDefaults.standardUserDefaults().setValue(NSDate(), forKey: "lastUpdateFromMe")
// Pin all actions asked from current user
PFObject.pinAllInBackground(results, withName: "FromMe")
completion(success: true, error: "")
} else {
completion(success: false, error: "Error: Query todo")
}
}
}
// MARK: - Query Local Datastore
// Query - Friends
func localQueryFriends(completion: (success: Bool, error: String) -> Void) {
// Clear before strating
var newFriendList = [PFUser]()
// Query current user friend list
var query = PFQuery(className:PF_FRIEND_CLASS_NAME)
query.fromLocalDatastore()
query.whereKey(PF_FRIEND_USER, equalTo: PFUser.currentUser()!)
query.getFirstObjectInBackgroundWithBlock { (object:PFObject?, error:NSError?) -> Void in
if error == nil {
// Query relation
var relation:PFRelation = object!.relationForKey(PF_FRIEND_RELATION)
var query:PFQuery = relation.query()!
query.fromLocalDatastore()
query.orderByAscending(PF_USER_FIRSTNAME)
query.findObjectsInBackgroundWithBlock({ (results:[AnyObject]?, error:NSError?) -> Void in
println("Parse Query User Friends from Local Datastore")
if error == nil {
for friend in results as! [PFUser] {
newFriendList.append(friend as PFUser)
}
friendList = newFriendList
completion (success: true, error: "")
} else {
completion (success: false, error: "Error: Query friends")
}
})
} else {
completion (success: false, error: "Error: Query friends")
}
}
}
// Query - Received
func localQueryReceived(completion: (success: Bool, error: String) -> Void) {
var query = PFQuery(className:PF_ACTION_CLASS_NAME)
query.fromLocalDatastore()
query.whereKey(PF_ACTION_TO, equalTo: PFUser.currentUser()!)
query.whereKey(PF_ACTION_STATUS, containedIn: [Status().actionAsked,Status().actionAccepted,Status().actionDone])
query.orderByAscending(PF_ACTION_EXPIRATIONDATE)
query.includeKey(PF_ACTION_FROM)
query.includeKey(PF_ACTION_TO)
query.findObjectsInBackgroundWithBlock { (results: [AnyObject]?, error: NSError?) -> Void in
println("Parse Query Received from Local Datastore")
if error == nil {
// results will contain actions from current user to selected user
received = results as! [PFObject]
NSNotificationCenter.defaultCenter().postNotificationName(updateReceivedBadgeNotificationKey, object: self)
completion(success: true, error: "")
} else {
completion(success: false, error: "Error: Query todo")
}
}
}
// Query - Received History
func localQueryReceivedHistory(completion: (success: Bool, error: String) -> Void) {
var query = PFQuery(className:PF_ACTION_CLASS_NAME)
query.fromLocalDatastore()
query.whereKey(PF_ACTION_TO, equalTo: PFUser.currentUser()!)
query.whereKey(PF_ACTION_STATUS, containedIn: [Status().actionRefused,Status().actionFailed,Status().proofValidated,Status().proofRejected,Status().actionPassed])
query.orderByDescending(PF_ACTION_EXPIRATIONDATE)
query.includeKey(PF_ACTION_FROM)
query.includeKey(PF_ACTION_TO)
query.findObjectsInBackgroundWithBlock { (results: [AnyObject]?, error: NSError?) -> Void in
println("Parse Query Received History from Local Datastore")
if error == nil {
// results will contain actions from current user to selected user
receivedHistory = results as! [PFObject]
completion(success: true, error: "")
} else {
completion(success: false, error: "Error: Query todo")
}
}
}
// Query - Sent
func localQuerySent(completion: (success: Bool, error: String) -> Void) {
var query = PFQuery(className:PF_ACTION_CLASS_NAME)
query.fromLocalDatastore()
query.whereKey(PF_ACTION_FROM, equalTo: PFUser.currentUser()!)
query.whereKey(PF_ACTION_STATUS, containedIn: [Status().actionAsked,Status().actionAccepted,Status().actionDone])
query.includeKey(PF_ACTION_FROM)
query.includeKey(PF_ACTION_TO)
query.orderByAscending(PF_ACTION_EXPIRATIONDATE)
query.findObjectsInBackgroundWithBlock { (results: [AnyObject]?, error: NSError?) -> Void in
println("Parse Query Sent from Local Datastore")
if error == nil {
// results will contain actions from current user to selected user
sent = results as! [PFObject]
NSNotificationCenter.defaultCenter().postNotificationName(updateSentBadgeNotificationKey, object: self)
completion (success: true , error: "")
} else {
completion (success: false, error: "Error: Query to validate")
}
}
}
// Query - Sent History
func localQuerySentHistory(completion: (success: Bool, error: String) -> Void) {
var query = PFQuery(className:PF_ACTION_CLASS_NAME)
query.fromLocalDatastore()
query.whereKey(PF_ACTION_FROM, equalTo: PFUser.currentUser()!)
query.whereKey(PF_ACTION_STATUS, containedIn: [Status().actionRefused,Status().actionFailed,Status().proofValidated,Status().proofRejected,Status().actionPassed])
query.includeKey(PF_ACTION_FROM)
query.includeKey(PF_ACTION_TO)
query.orderByDescending(PF_ACTION_CREATEDAT)
query.findObjectsInBackgroundWithBlock { (results: [AnyObject]?, error: NSError?) -> Void in
println("Parse Query Sent History from Local Datastore")
if error == nil {
// results will contain actions from current user to selected user
sentHistory = results as! [PFObject]
completion (success: true , error: "")
} else {
completion (success: false, error: "Error: Query asked by me")
}
}
}
// Query - rank
func localQueryRank(completion: (success: Bool, error: String) -> Void) {
var newRankList = [PFUser]()
// Query current user friend list
var query = PFQuery(className:PF_FRIEND_CLASS_NAME)
query.fromLocalDatastore()
query.whereKey(PF_FRIEND_USER, equalTo: PFUser.currentUser()!)
query.getFirstObjectInBackgroundWithBlock{ (object: PFObject?, error:NSError?) -> Void in
if error == nil {
var relation:PFRelation = object!.relationForKey(PF_FRIEND_RELATION)
var query:PFQuery = relation.query()!
query.fromLocalDatastore()
query.orderByDescending(PF_USER_FIRSTNAME)
query.findObjectsInBackgroundWithBlock({ (results:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
println("Parse Query Rank from Local Datastore")
var rank:Int = 0
var previousScore:Int = 0
var myScore = thanks
var alreadyPlacedMyself:Bool = false
var myself = PFUser.currentUser()!
for result:PFObject in results as! [PFObject] {
var friendScore:Int = result[PF_USER_THANKS] as! Int
if friendScore == myScore && alreadyPlacedMyself == false && rank == 0 {
myself["rank"] = 1
newRankList.append(myself as PFUser)
alreadyPlacedMyself = true
result["rank"] = 1
newRankList.append(result as! PFUser)
previousScore = friendScore
rank++
} else if friendScore == myScore && alreadyPlacedMyself == false {
myself["rank"] = rank
newRankList.append(myself as PFUser)
alreadyPlacedMyself = true
result["rank"] = rank
newRankList.append(result as! PFUser)
previousScore = friendScore
} else if friendScore < myScore && alreadyPlacedMyself == false {
myself["rank"] = rank + 1
newRankList.append(myself as PFUser)
alreadyPlacedMyself = true
result["rank"] = rank + 2
newRankList.append(result as! PFUser)
previousScore = friendScore
rank++
rank++
} else if previousScore == friendScore {
result["rank"] = rank
newRankList.append(result as! PFUser)
previousScore = friendScore
} else {
result["rank"] = rank + 1
newRankList.append(result as! PFUser)
previousScore = friendScore
rank++
}
}
if alreadyPlacedMyself == false {
myself["rank"] = rank + 1
newRankList.append(myself as PFUser)
}
// update rankList
rankList = newRankList
completion (success: true, error: "")
} else {
completion (success: false, error: "Error: Query friends")
}
})
} else {
completion (success: false, error: "Error: Query friends")
}
}
}
// MARK: - Facebook
// Facebook - sync Facebook Friends
func syncFacebookFriends(completion: (success: Bool, error: String) -> Void) {
let friendsRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/friends", parameters: nil)
friendsRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if error == nil {
let resultDictionary = result as! NSDictionary
var facebookFriendsList:[NSDictionary] = resultDictionary["data"] as! Array
var facebookFriendsIDList:[String] = []
for facebookFriend in facebookFriendsList {
facebookFriendsIDList.append(facebookFriend["id"] as! String)
}
// Query a list of PFUsers matching the facebook_id's
var friendsQuery:PFQuery = PFUser.query()!
friendsQuery.whereKey(PF_USER_FACEBOOKID, containedIn: facebookFriendsIDList)
friendsQuery.includeKey(PF_USER_FRIENDS)
friendsQuery.findObjectsInBackgroundWithBlock({ (result: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// Query Friend object
var myFrienshipQuery = PFQuery(className:PF_FRIEND_CLASS_NAME)
myFrienshipQuery.whereKey(PF_FRIEND_USER, equalTo: PFUser.currentUser()!)
myFrienshipQuery.getFirstObjectInBackgroundWithBlock{ (myFriendship: PFObject?, error:NSError?) -> Void in
if error == nil {
var relation = myFriendship!.relationForKey(PF_FRIEND_RELATION)
for friend in result as! [PFUser] {
// Add Friend
relation.addObject(friend as PFUser)
// Update Friendship
PFCloud.callFunctionInBackground("updateFriendship", withParameters: ["friendId" : "\(friend.objectId!)"])
}
myFriendship!.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in
println("Parse Save User relations")
if (success) {
completion (success: true, error: "")
} else {
completion (success: false, error: "Error: Update Facebook friends")
}
})
} else {
completion (success: false, error: "Error: Update Facebook friends")
}
}
} else {
completion (success: false, error: "Error: Update Facebook friends")
}
})
} else {
completion (success: false, error: "Error: Update Facebook friends")
}
})
}
// MARK: - Time
// Time - expiration date
func expirationDate(globalExpirationDate:NSDate) -> String {
var actualDate = globalToLocalTime(NSDate())
var expirationDate = globalToLocalTime(globalExpirationDate)
var preferredLanguages:String = NSLocale.preferredLanguages()[0] as! String
preferredLanguages = "en"
var moment = YLMoment(date: expirationDate)
if preferredLanguages == "fr" {
moment.locale = NSLocale(localeIdentifier: "fr_FR")
}
var expirationDateStr:String = moment.fromNow() as String
return expirationDateStr
}
func globalToLocalTime(sourceDate:NSDate) -> NSDate {
var sourceTimeZone:NSTimeZone = NSTimeZone(abbreviation: "GMT")!
var destinationTimeZone:NSTimeZone = NSTimeZone.localTimeZone()
var sourceGMTOffset:NSInteger = sourceTimeZone.secondsFromGMTForDate(sourceDate)
var destinationGMTOffset:NSInteger = destinationTimeZone.secondsFromGMTForDate(sourceDate)
var intervalGMT:NSTimeInterval = Double(destinationGMTOffset - sourceGMTOffset)
var destinationDate:NSDate = NSDate(timeInterval: intervalGMT, sinceDate: sourceDate)
return destinationDate
}
//MARK: - More
// Convert URL to Image
func convertUrlToImage(facebookId:String, completion: (success: Bool, error: String) -> Void ) {
let urlString = ("https://graph.facebook.com/\(facebookId)/picture?type=normal")
let imgURL = NSURL(string: urlString)
let request = NSURLRequest(URL: imgURL!)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
// Convert the downloaded data in to a UIImage object
let image = UIImage(data: data)
// Store the image in to our cache
imageCache[facebookId] = image
completion (success: true, error: "")
}
else {
completion (success: false, error: "Error: \(error.localizedDescription)")
}
})
}
func handleOnboardingCompletion() {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "user_has_onboarded")
}
} |
//
// ViewController.swift
// GitCheking
//
// Created by Apple on 12/10/2020.
// Copyright © 2020 Apple. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print("Nothing to write freec ode please tell me where is the ball of ")
}
}
|
import Foundation
public class Notification<T> {
typealias NotificationClosure = (Notification<T>) -> Void
let name:String
private(set) weak var sender:AnyObject?
private(set) var userInfo:T?
private let closure:NotificationClosure
private weak var hub:NotificationHub<T>?
init(name:String, sender:AnyObject?, handler:NotificationClosure) {
self.name = name
self.closure = handler
self.sender = sender
}
final func publishUserInfo(userInfo:T?) -> Bool {
if(self.hub == nil) { return false }
self.userInfo = userInfo
self.closure(self)
self.userInfo = nil
return true
}
final func remove() -> Bool {
if(self.hub == nil) { return false }
self.hub?.removeNotification(self)
self.userInfo = nil
self.hub = nil
return true
}
}
private struct Static {
static var hubToken : dispatch_once_t = 0
static var hub : NotificationHub<[String:Any]>? = nil
}
//public var NotificationHubDefault : NotificationHub<[String:Any]> {
// return NotificationHub<[String:Any]>()
//}
public class NotificationHub<T> {
final private var internalNotifications = NSMutableDictionary(capacity: 1000)
final var notifications:[String: [Notification<T>]] {
return self.internalNotifications as AnyObject as! [String: [Notification<T>]]
}
private class var defaultHub:NotificationHub<[String:Any]> {
dispatch_once(&Static.hubToken) {
Static.hub = NotificationHub<[String:Any]>()
}
return Static.hub!
}
init() {}
func subscribeNotificationForName(name: String, sender: AnyObject? = nil, handler: (Notification<T>) -> Void) -> Notification<T> {
let notification = Notification(name: name, sender: sender, handler: handler)
return self.subscribeNotification(notification)
}
func subscribeNotification(notification:Notification<T>) -> Notification<T> {
#if DEBUG
NotificationHubMock.onSubscribeMockHandler?(name:notification.name,sender:notification.sender)
#endif
if notification.hub !== nil { notification.hub?.removeNotification(notification) }
notification.hub = self
let name = notification.name
if let notifications = self.internalNotifications[notification.name] as? NSMutableArray {
notifications.addObject(notification)
}
else {
let array = NSMutableArray(capacity: 50)
array.addObject(notification)
self.internalNotifications[name] = array
}
return notification
}
func publishNotificationName(name: String, sender: AnyObject? = nil, userInfo:T? = nil) -> Bool {
#if DEBUG
NotificationHubMock.onPublishMockHandler?(name: name, sender: sender, userInfo: userInfo)
#endif
var didPublish = false
if let notifications = self.internalNotifications[name] as? NSMutableArray {
if sender != nil {
for notification in notifications {
let not:Notification = notification as! Notification<T>
if not.sender == nil {
not.sender = sender
didPublish = not.publishUserInfo(userInfo)
not.sender = nil
}
else if not.sender === sender { didPublish = not.publishUserInfo(userInfo) }
}
}
else {
for notification in notifications {
let not:Notification = notification as! Notification<T>
if not.sender == nil { didPublish = not.publishUserInfo(userInfo) }
}
}
}
return didPublish
}
func publishNotification(notification: Notification<T>, userInfo:T? = nil) -> Bool {
#if DEBUG
NotificationHubMock.onPublishMockHandler?(name: notification.name, sender: notification.sender, userInfo: userInfo)
#endif
if (notification.hub === self) { return notification.publishUserInfo(userInfo) }
else { return false }
}
func removeNotification(notification: Notification<T>) -> Bool {
#if DEBUG
NotificationHubMock.onRemoveMockHandler?(name:notification.name, sender:notification.sender)
#endif
if notification.hub !== self { return false }
let name = notification.name
let notifications = self.internalNotifications[name] as? NSMutableArray
notifications?.removeObject(notification)
if notifications?.count == 0 { self.internalNotifications.removeObjectForKey(name) }
notification.hub = nil
return true
}
func removeNotificationsName(name:String, sender: AnyObject? = nil) -> Bool {
#if DEBUG
NotificationHubMock.onRemoveMockHandler?(name:name, sender:sender)
#endif
let notifications = self.internalNotifications[name] as? NSMutableArray
let preCount = notifications?.count
if let notifications = notifications {
for notification in notifications {
let not:Notification = notification as! Notification<T>
if not.sender == nil || not.sender === sender {
notifications.removeObject(not)
not.hub = nil
}
}
}
let postCount = notifications?.count
if postCount == 0 {self.internalNotifications.removeObjectForKey(name) }
return preCount != postCount
}
func removeAllNotificationsName(name:String) -> Bool {
#if DEBUG
NotificationHubMock.onRemoveMockHandler?(name:name, sender:nil)
#endif
let preCount = self.internalNotifications.count
let notifications: NSArray? = self.internalNotifications[name] as? NSMutableArray
self.internalNotifications.removeObjectForKey(name)
if let notifications = notifications {
for notification in notifications {
(notification as! Notification<T>).hub = nil
}
}
let postCount = self.internalNotifications.count
return preCount != postCount
}
func removeAllNotificationsSender(sender:AnyObject) -> Bool {
#if DEBUG
NotificationHubMock.onRemoveMockHandler?(name:nil, sender:sender)
#endif
let count = self.internalNotifications.count
let notifications = self.internalNotifications.allValues as? [[Notification<T>]]
if let notifications = notifications {
for notificationList in notifications {
for notification in notificationList {
if notification.sender === sender { notification.remove() }
}
}
}
self.internalNotifications.removeAllObjects()
return count > 0
}
func removeAllNotifications() -> Bool {
#if DEBUG
NotificationHubMock.onRemoveMockHandler?(name:nil, sender:nil)
#endif
let count = self.internalNotifications.count
let notifications = self.internalNotifications.allValues as? [[Notification<T>]]
self.internalNotifications.removeAllObjects()
if let notifications = notifications {
for notificationList in notifications {
for notification in notificationList { notification.hub = nil }
}
}
self.internalNotifications.removeAllObjects()
return count > 0
}
}
extension Notification : Equatable {}
public func ==<T>(lhs: Notification<T>, rhs: Notification<T>) -> Bool { return lhs === rhs }
extension NotificationHub : Equatable {}
public func ==<T>(lhs: NotificationHub<T>, rhs: NotificationHub<T>) -> Bool { return lhs === rhs }
#if DEBUG
public struct NotificationHubMock {
private static var onPublishMockHandler:((name:String, sender:AnyObject?, userInfo:Any?) -> (Void))?
static func onPublishingMockHandler(handler:(name:String, sender:AnyObject?, userInfo:Any?) -> (Void)) {
self.onPublishMockHandler = handler
}
private static var onSubscribeMockHandler:((name:String, sender:AnyObject?) -> Void)?
static func onSubscribingMock(handler:(name:String, sender:AnyObject?) -> Void) {
self.onSubscribeMockHandler = handler
}
private static var onRemoveMockHandler:((name:String?, sender:AnyObject?) -> Void)?
static func onRemovingMockHandler(handler:(name:String?, sender:AnyObject?) -> Void) {
self.onRemoveMockHandler = handler
}
}
#endif
|
//
// EditTaskView.swift
// SwiftUIList
//
// Created by Stefan Gugarel on 12.12.19.
// Copyright © 2019 Stefan Gugarel. All rights reserved.
//
import SwiftUI
struct WorkingEditTaskView: View {
@Binding var pushed: Bool
let task: Task
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: WorkingBackButton(label: "Back") {
self.pushed = false
})
}
}
struct WorkingBackButton: View {
let label: String
let closure: () -> ()
var body: some View {
Button(action: { self.closure() }) {
HStack {
Image(systemName: "chevron.left")
Text(label)
}
}
}
}
struct WorkingEditTaskView_Previews: PreviewProvider {
@State private static var pushed: Bool = false
static var previews: some View {
WorkingEditTaskView(pushed: $pushed, task: Task(name: "", favourite: false))
}
}
|
//
// RecipeDetailViewController.swift
// Recipes
//
// Created by Lambda_School_Loaner_201 on 10/30/19.
// Copyright © 2019 Lambda Inc. All rights reserved.
//
import UIKit
class RecipeDetailViewController: UIViewController {
var recipe: Recipe? {
didSet {
updateViews()
}
}
@IBOutlet weak var recipeLabel: UILabel!
@IBOutlet weak var recipeTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
updateViews()
// Do any additional setup after loading the view.
}
func updateViews() {
if let recipe = recipe, self.isViewLoaded {
recipeLabel.text = recipe.name
recipeTextView.text = recipe.instructions
}
//collectionViewCellOutlet.text = photo.title
//imageViewOutlet.image = UIImage(data: photo.imageData)
}
}
|
//
// KikoCollectionViewCell.swift
// KikoBusiness
//
// Created by Leonardo Lanzinger on 16/05/15.
// Copyright (c) 2015 Massimo Frasson. All rights reserved.
//
import UIKit
class KikoCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var cellImage: UIImageView!
}
|
//
// 1684.swift
// LeetCode
//
// Created by mlch911 on 2021/5/19.
//
import Foundation
// 1684. 统计一致字符串的数目
func countConsistentStrings(_ allowed: String, _ words: [String]) -> Int {
words.filter({
$0.first(where: { character -> Bool in
!allowed.contains(character)
}) == nil
}).count
}
|
import Foundation
class Deadline: NSObject, NSCoding {
enum Frequency: Int {
case unique, daily, weekly
}
//MARK: Properties
var id: String
var date: Date
var frequency: Frequency
var category: String?
struct PropertyKeys {
static let id = "id"
static let date = "date"
static let frequency = "frequency"
static let category = "category"
}
init(date: Date, frequency: Frequency, category: String?) {
self.id = Utils.generateID()
self.date = date
self.frequency = frequency
self.category = category
}
init(id: String, date: Date, frequency: Frequency, category: String?) {
self.id = id
self.date = date
self.frequency = frequency
self.category = category
}
func getDueString() -> String {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.month, .day, .hour, .minute, .second]
formatter.maximumUnitCount = 2
let now = Date()
let nextDeadline = getNextDeadlineDate()
let timeString = formatter.string(from: now, to: nextDeadline)
var res = ""
if timeString != nil {
res = nextDeadline < now
? String(format: NSLocalizedString("DeadlinePast", comment: ""), timeString!.suffix(timeString!.count-1) as CVarArg)
: String(format: NSLocalizedString("DeadlineFuture", comment: ""), timeString!)
}
return res
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: PropertyKeys.id)
aCoder.encode(date, forKey: PropertyKeys.date)
aCoder.encode(frequency.rawValue, forKey: PropertyKeys.frequency)
aCoder.encode(category, forKey: PropertyKeys.category)
}
required init?(coder aDecoder: NSCoder) {
guard let id = aDecoder.decodeObject(forKey: PropertyKeys.id) as? String,
let date = aDecoder.decodeObject(forKey: PropertyKeys.date) as? Date,
let frequency = Frequency(rawValue: aDecoder.decodeInteger(forKey: PropertyKeys.frequency)) else {
fatalError("Error while decoding deadline object!")
}
self.id = id
self.date = date
self.frequency = frequency
self.category = aDecoder.decodeObject(forKey: PropertyKeys.category) as? String
}
//MARK: Private Methods
private func getNextDeadlineDate() -> Date {
let now = Date()
var nextDeadline = self.date
if self.frequency != .unique {
let dayTime = nextDeadline.timeIntervalSince1970.truncatingRemainder(dividingBy: 3600 * 24)
let pastMidnight = now.timeIntervalSince1970 - now.timeIntervalSince1970.truncatingRemainder(dividingBy: 3600 * 24)
if self.frequency == .daily {
// Create Date with current day, but time taken from the stored deadline
nextDeadline = Date(timeIntervalSince1970: pastMidnight + dayTime)
// if the time has already in the past, the next deadline will be on the next day
if nextDeadline < now {
nextDeadline.addTimeInterval(3600 * 24)
}
} else if self.frequency == .weekly {
let deadlineWeekday = Calendar.current.component(.weekday, from: nextDeadline)
let dayTime = nextDeadline.timeIntervalSince1970.truncatingRemainder(dividingBy: 3600 * 24)
// Special case: deadline is today
if deadlineWeekday == Calendar.current.component(.weekday, from: now) {
nextDeadline = Date(timeIntervalSince1970: pastMidnight + dayTime)
// Check if deadline has already passed
if nextDeadline < now {
nextDeadline.addTimeInterval(3600 * 24 * 7)
}
} else {
for i in 1..<7 {
let otherDate = now.addingTimeInterval(TimeInterval(i * 3600 * 24))
let otherWeekday = Calendar.current.component(.weekday, from: otherDate)
if deadlineWeekday == otherWeekday {
let weekdayMidnight = otherDate.timeIntervalSince1970 -
otherDate.timeIntervalSince1970.truncatingRemainder(dividingBy: TimeInterval(3600 * 24))
nextDeadline = Date(timeIntervalSince1970: weekdayMidnight + dayTime)
}
}
}
}
}
return nextDeadline
}
}
|
//
// RFC3339DateFormatter.swift
// Feedit
//
// Created by Tyler D Lawrence on 8/26/20.
//
import Foundation
/// Converts date and time textual representations within the RFC3339
/// date specification into `Date` objects
class RFC3339DateFormatter: DateFormatter {
let dateFormats = [
"MMM d, h:mm a"
//"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
//"yyyy-MM-dd'T'HH:mm:ss.SSZZZZZ",
//"yyyy-MM-dd'T'HH:mm:ss-SS:ZZ",
//"yyyy-MM-dd'T'HH:mm:ss"
]
override init() {
super.init()
self.timeZone = TimeZone(secondsFromGMT: 0)
self.locale = Locale(identifier: "en_US_POSIX")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
override func date(from string: String) -> Date? {
let string = string.trimmingCharacters(in: .whitespacesAndNewlines)
for dateFormat in self.dateFormats {
self.dateFormat = dateFormat
if let date = super.date(from: string) {
return date
}
}
return nil
}
}
|
//
// ViewController.swift
// ScrollingParallaxEffectApp
//
// Created by Marcus Vinícius on 28/07/19.
// Copyright © 2019 Marcus Vinícius. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private let data = [
[
"title": "Final Fantasy XIV - A Realm Reborn",
"image": "final-fantasy-xiv-a-realm-reborn"
],
[
"title": "Mario Kart 8 Deluxe",
"image": "mario-kart-8-deluxe"
],
[
"title": "Nier: Automata",
"image": "nier-automata"
],
[
"title": "Red Dead Redemption II",
"image": "red-dead-redemption-ii"
],
[
"title": "Rogue One - A Star Wars Story",
"image": "rogue-one-a-star-wars-story"
],
[
"title": "Shadow of the Colossus",
"image": "shadow-of-the-colossus"
],
[
"title": "Spider-Man Homecoming",
"image": "spider-man-homecoming"
],
[
"title": "Stranger Things 2",
"image": "stranger-things-2"
],
[
"title": "Super Mario Galaxy 2",
"image": "super-mario-galaxy-2"
],
[
"title": "Super Mario Odyssey",
"image": "super-mario-odyssey"
],
[
"title": "The Legend of Zelda - Breath of the Wild",
"image": "the-legend-of-zelda-breath-of-the-wild"
],
[
"title": "Uncharted - The Lost Legacy",
"image": "uncharted-the-lost-legacy"
],
[
"title": "Xenoblade Chronicles X",
"image": "xenoblade-chronicles-x"
],
]
@IBOutlet weak var tableView: UITableView!
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
var cellHeight: CGFloat = 216.0
var parallaxOffsetSpeed: CGFloat = 48.0
var parallaxImageHeight: CGFloat {
let maxOffset = (sqrt(pow(self.cellHeight, 2.0) + (4.0 * self.cellHeight * self.tableView.frame.height)) - self.cellHeight) / 2.0
return maxOffset + self.cellHeight
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.delegate = self
self.tableView.dataSource = self
}
func parallaxOffset(_ newOffsetY: CGFloat, cell: UITableViewCell) -> CGFloat {
return ((newOffsetY - cell.frame.origin.y) / self.parallaxImageHeight) * self.parallaxOffsetSpeed
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = self.tableView.contentOffset.y
for cell in self.tableView.visibleCells as! [TableViewCell] {
cell.parallaxImageTop.constant = parallaxOffset(offsetY, cell: cell)
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let index = self.data[indexPath.row]
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? TableViewCell else { return UITableViewCell() }
cell.configureCell(index["title"] ?? "Title", image: index["image"] ?? "")
cell.parallaxImageHeight.constant = self.parallaxImageHeight
cell.parallaxImageTop.constant = parallaxOffset(self.tableView.contentOffset.y, cell: cell)
return cell
}
}
|
//
// Cell.swift
// InterfaceBacked
//
// Created by Florian Burger on 18/08/16.
// Copyright © 2016 Florian Bürger. All rights reserved.
//
import UIKit
import InterfaceBacked
final class Cell: UITableViewCell, NibBackedCell {
@IBOutlet weak var label: UILabel!
}
|
//
// ImportFile.swift
// Pocket Clouds
//
// Created by Tyler on 15/06/2017.
// Copyright © 2017 TylerSwann. All rights reserved.
//
import Foundation
import Photos
class ImportFile
{
var isVideo: Bool
var thumbnail: UIImage
var duration: String
init(isVideo: Bool, thumbnail: UIImage, duration: String)
{
self.isVideo = isVideo
self.thumbnail = thumbnail
self.duration = duration
}
}
|
//
// ConvertToDictonary.swift
// TastingNotes
//
// Created by David Burke on 10/2/17.
// Copyright © 2017 amberfire. All rights reserved.
//
import Foundation
struct Blend {
let grape: String
let percentage: Int16
}
extension TastingSessionStore {
func convertSessionToDictionary () -> [String:Any] {
var sessionDictionary: [String:Any] = [:]
let session = self.session()
sessionDictionary["sessionName"] = session.sessionName
sessionDictionary["sessionLocation"] = session.sessionLocation
sessionDictionary["sessionDate"] = session.sessionDate! as Date
for note in self.notes()! {
sessionDictionary[String(describing: note.dateCreated)] = convertTastingNoteToDictionary(note)
}
return sessionDictionary
}
func convertTastingNoteToDictionary(_ note: TastingNotes) -> [String:Any] {
var noteDict: [String:Any] = [:]
noteDict["wineName"] = note.wineName
noteDict["vintage"] = note.vintage
noteDict["type"] = note.type
noteDict["region"] = note.region
noteDict["country"] = note.country
noteDict["type"] = note.type
noteDict["colour"] = note.colour
noteDict["price"] = note.price
noteDict["noseIntensity"] = note.noseIntensity
noteDict["noseCharacteristics"] = note.noseCharateristics
noteDict["noseNotes"] = note.noseNotes
noteDict["grapes"] = convertGrapesToArray()
return noteDict
}
func convertGrapesToArray() -> [Blend] {
var grapesInWine = [Blend]()
for grape in self.grapesForNote() {
let blend = Blend(grape: grape.grape!, percentage: grape.percentage)
grapesInWine.append(blend)
}
return grapesInWine
}
}
|
import UIKit
import OAuthSwift
class EditViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var saveNavItem: UIBarButtonItem!
@IBOutlet weak var cancelNavItem: UIBarButtonItem!
private let user : UserInfo = UserInfo.shared
private let network : NetworkManager = NetworkManager.sharedInstance
private let update : UpdateUser = UpdateUser.shared
private let oauth : OAuth = OAuth.shared
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib (nibName: "EditHeaderView", bundle: nil), forCellReuseIdentifier: "EditHeader")
tableView.register(UINib (nibName: "ChangeOtherDataTableViewCell", bundle: nil), forCellReuseIdentifier: "ChangeOtherData")
tableView.register(UINib (nibName: "ChangeBioTableViewCell", bundle: nil), forCellReuseIdentifier: "ChangeBio")
if network.reachability.connection != .none {
didConnect()
} else {
didDisconnect()
}
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
self.view.addGestureRecognizer(tap)
}
override func viewWillAppear(_ animated: Bool) {
network.delegate = self
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func cancelNavItemClick(_ sender: UIBarButtonItem) {
navigationController?.popViewController(animated: true)
}
@IBAction func saveNavItemClick(_ sender: UIBarButtonItem) {
if let cell = tableView.cellForRow(at: IndexPath(item: 1, section: 0)) as? ChangeOtherDataTableViewCell {
if let data = cell.userTextView.text {
if cell.isNotValidLbl.isHidden {
update.blog = data
} else {
return
}
}
}
if let cell = tableView.cellForRow(at: IndexPath(item: 0, section: 0)) as? ChangeOtherDataTableViewCell {
if let data = cell.userTextView.text {
update.name = data
}
}
if let cell = tableView.cellForRow(at: IndexPath(item: 2, section: 0)) as? ChangeOtherDataTableViewCell {
if let data = cell.userTextView.text {
update.company = data
}
}
if let cell = tableView.cellForRow(at: IndexPath(item: 3, section: 0)) as? ChangeOtherDataTableViewCell {
if let data = cell.userTextView.text {
update.location = data
}
}
if let cell = tableView.cellForRow(at: IndexPath(item: 4, section: 0)) as? ChangeBioTableViewCell {
if let data = cell.bioTextView.text {
update.bio = data
}
}
if network.reachability.connection != .none {
oauth.updateProfile(controller: self)
} else {
didDisconnect()
}
}
@objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
func setLineUnderTableViewCell(height : CGFloat, width : CGFloat) -> CALayer{
var bottomBorder = CALayer()
bottomBorder.backgroundColor = UIColor.lightGray.cgColor
bottomBorder .frame = CGRect(x: leadingConstrain, y: height, width: width, height: 1)
return bottomBorder
}
func setCells(cell : ChangeOtherDataTableViewCell?, indexPath : IndexPath) {
switch indexPath.item {
case 0:
cell?.userDataLbl.text = "nameLbl".localize()
cell?.userTextView.placeholder = "nickNamePlaceholder".localize()
cell?.userTextView.text = user.name
cell?.isNotValidLbl.isHidden = true
break
case 1:
cell?.userDataLbl.text = "blogLbl".localize()
cell?.userDataLbl.textColor = UIColor.black
cell?.userTextView.placeholder = "blogPlaceholder".localize()
cell?.userTextView.text = user.blog //Перевірка на валідність
//cell?.isNotValidLbl.isHidden = false
break
case 2:
cell?.userDataLbl.text = "companyLbl".localize()
cell?.userTextView.placeholder = "companyPlaceholder".localize()
cell?.userTextView.text = user.company
cell?.isNotValidLbl.isHidden = true
break
case 3:
cell?.userDataLbl.text = "locationLbl".localize()
cell?.userTextView.placeholder = "cityPlaceholder".localize()
cell?.userTextView.text = user.location
cell?.isNotValidLbl.isHidden = true
break
default:
break
}
}
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
func downloadImage(from url: URL, profileImg : UIImageView){
print("Download Started")
getData(from: url) { data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() {
profileImg.image = UIImage(data: data)
}
}
}
}
extension EditViewController: UITableViewDelegate{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.item == 4 {
return heightEditTableViewBioCell
} else if indexPath.item == 1{
return heightEditTableViewBlogCell
} else {
return 35
}
}
}
extension EditViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countEditTableViewRows
}
func numberOfSections(in tableView: UITableView) -> Int {
return countEditTableViewSection
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.item == 4 {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChangeBio", for: indexPath) as? ChangeBioTableViewCell
cell?.selectionStyle = UITableViewCell.SelectionStyle.none
cell?.bioLbl.text = "bioLbl".localize()
cell?.bioTextView.text = user.bio
return cell ?? ChangeBioTableViewCell()
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChangeOtherData", for: indexPath) as? ChangeOtherDataTableViewCell
cell?.selectionStyle = UITableViewCell.SelectionStyle.none
setCells(cell: cell, indexPath: indexPath)
cell?.layer.addSublayer(setLineUnderTableViewCell(height: (cell?.frame.size.height) ?? 1 - 1, width: cell?.frame.size.width ?? 1))
return cell ?? InfoAboutRepoTableViewCell()
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = EditHeaderView.fromNib()
let url = URL(string: user.avatar)!
downloadImage(from: url, profileImg: cell.profileImg)
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return heightEditTableHeader
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
}
extension EditViewController: CheckNetworkState {
func didConnect() {
saveNavItem.isEnabled = true
self.hideActivityIndicator()
}
func didDisconnect() {
saveNavItem.isEnabled = false
self.showActivityIndicator()
}
}
|
//
// DetailVC.swift
// trailguide
//
// Created by Daniel Bonehill on 21/03/2018.
// Copyright © 2018 Daniel Bonehill. All rights reserved.
//
import UIKit
class DetailVC: UIViewController {
@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var itemTitle: UILabel!
@IBOutlet weak var itemDescription: UILabel!
@IBOutlet weak var background: UIImageView!
public private(set) var image: String = ""
public private(set) var titleText: String = ""
public private(set) var desc: String = ""
public private(set) var bgImage: String = ""
override func viewDidLoad() {
super.viewDidLoad()
itemImage.image = UIImage(named: image)
itemTitle.text = titleText
itemDescription.text = desc
background.image = UIImage(named: bgImage)
}
func initItem(item: Item) {
image = item.image
titleText = item.title
desc = item.description
bgImage = "\(item.category)BG.png"
}
@IBAction func backBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
|
//
// InteractionRouter.swift
// GALiveApp
//
// Created by 陆广庆 on 16/2/29.
// Copyright © 2016年 luguangqing. All rights reserved.
//
import UIKit
class InteractionRouter: BaseRouter {
}
|
/*
* 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.
*/
//
// TestECC.swift
//
// Created by Michael Scott on 02/07/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
// test driver and function exerciser for ECDH/ECIES/ECDSA API Functions
import Foundation
import core // comment out for Xcode
import ed25519
import nist256
import ed448
import rsa2048
public func printBinary(_ array: [UInt8])
{
for i in 0 ..< array.count
{
let h=String(format:"%02x",array[i])
print("\(h)", terminator: "")
}
print(" ");
}
public func TestRSA_2048(_ rng: inout RAND)
{
let RFS=RSA.RFS
var message="Hello World\n"
var pub=rsa_public_key(Int(CONFIG_FF.FFLEN))
var priv=rsa_private_key(Int(CONFIG_FF.HFLEN))
var ML=[UInt8](repeating: 0,count: RFS)
var C=[UInt8](repeating: 0,count: RFS)
var S=[UInt8](repeating: 0,count: RFS)
print("\nGenerating RSA public/private key pair")
RSA.KEY_PAIR(&rng,65537,&priv,&pub)
let M=[UInt8](message.utf8)
print("Encrypting test string\n");
let E=HMAC.OAEP_ENCODE(RSA.HASH_TYPE,M,&rng,nil,RFS); // OAEP encode message m to e
RSA.ENCRYPT(pub,E,&C); // encrypt encoded message
print("Ciphertext= 0x", terminator: ""); printBinary(C)
print("Decrypting test string\n");
RSA.DECRYPT(priv,C,&ML)
let MS=HMAC.OAEP_DECODE(RSA.HASH_TYPE,nil,&ML,RFS) // OAEP encode message m to e
message=""
for i in 0 ..< MS.count
{
message+=String(UnicodeScalar(MS[i]))
}
print(message);
let T=HMAC.PSS_ENCODE(RSA.HASH_TYPE,M,&rng,RFS)
print("T= 0x",terminator: ""); printBinary(T)
if HMAC.PSS_VERIFY(RSA.HASH_TYPE,M,T) {
print("PSS Encoding OK\n");
} else {
print("PSS Encoding FAILED\n");
}
// Signature
print("Signing message")
HMAC.PKCS15(RSA.HASH_TYPE,M,&C,RFS)
RSA.DECRYPT(priv,C,&S); // create signature in S
print("Signature= 0x",terminator: ""); printBinary(S)
// Verification
var valid=false;
RSA.ENCRYPT(pub,S,&ML);
HMAC.PKCS15(RSA.HASH_TYPE,M,&C,RFS)
var cmp=true
for j in 0 ..< RFS {
if C[j] != ML[j] {cmp=false}
}
if cmp {
valid=true
} else {
HMAC.PKCS15b(RSA.HASH_TYPE,M,&C,RFS)
cmp=true
for j in 0 ..< RFS {
if C[j] != ML[j] {cmp=false}
}
if cmp {
valid=true
}
}
if valid {print("\nSignature is valid\n")}
else {print("\nSignature is INVALID\n")}
RSA.PRIVATE_KEY_KILL(priv);
}
public func TestECDH_ed25519(_ rng: inout RAND)
{
let pp=String("M0ng00se");
let EGS=ed25519.ECDH.EGS
let EFS=ed25519.ECDH.EFS
let EAS=ed25519.CONFIG_CURVE.AESKEY
let sha=ed25519.CONFIG_CURVE.HASH_TYPE
var S1=[UInt8](repeating: 0,count: EGS)
var W0=[UInt8](repeating: 0,count: 2*EFS+1)
var W1=[UInt8](repeating: 0,count: 2*EFS+1)
var Z0=[UInt8](repeating: 0,count: EFS)
var Z1=[UInt8](repeating: 0,count: EFS)
var SALT=[UInt8](repeating: 0,count: 8)
var P1=[UInt8](repeating: 0,count: 3)
var P2=[UInt8](repeating: 0,count: 4)
var V=[UInt8](repeating: 0,count: 2*EFS+1)
var M=[UInt8](repeating: 0,count: 17)
var T=[UInt8](repeating: 0,count: 12)
var CS=[UInt8](repeating: 0,count: EGS)
var DS=[UInt8](repeating: 0,count: EGS)
var NULLRNG : RAND? = nil
var REALRNG : RAND? = rng
for i in 0 ..< 8 {SALT[i]=UInt8(i+1)} // set Salt
print("\nTest Curve ed25519");
print("Alice's Passphrase= " + pp)
let PW=[UInt8]( (pp).utf8 )
// private key S0 of size EGS bytes derived from Password and Salt
// Note use of curve name here to disambiguate between supported curves!!
// Not needed if only one curve supported
var S0=HMAC.PBKDF2(HMAC.MC_SHA2,sha,PW,SALT,1000,EGS)
print("Alice's private key= 0x",terminator: ""); printBinary(S0)
// Generate Key pair S/W
ed25519.ECDH.KEY_PAIR_GENERATE(&NULLRNG,&S0,&W0);
print("Alice's public key= 0x",terminator: ""); printBinary(W0)
var res=ed25519.ECDH.PUBLIC_KEY_VALIDATE(W0);
if res != 0
{
print("ECP Public Key is invalid!");
return;
}
// Random private key for other party
ed25519.ECDH.KEY_PAIR_GENERATE(&REALRNG,&S1,&W1)
print("Servers private key= 0x",terminator: ""); printBinary(S1)
print("Servers public key= 0x",terminator: ""); printBinary(W1);
res=ed25519.ECDH.PUBLIC_KEY_VALIDATE(W1)
if res != 0
{
print("ECP Public Key is invalid!")
return
}
// Calculate common key using DH - IEEE 1363 method
ed25519.ECDH.ECPSVDP_DH(S0,W1,&Z0,0)
ed25519.ECDH.ECPSVDP_DH(S1,W0,&Z1,0)
var same=true
for i in 0 ..< EFS
{
if Z0[i] != Z1[i] {same=false}
}
if (!same)
{
print("*** ECPSVDP-DH Failed")
return
}
let KEY=HMAC.KDF2(HMAC.MC_SHA2,sha,Z0,nil,EAS)
print("Alice's DH Key= 0x",terminator: ""); printBinary(KEY)
print("Servers DH Key= 0x",terminator: ""); printBinary(KEY)
if ed25519.CONFIG_CURVE.CURVETYPE != ed25519.CONFIG_CURVE.MONTGOMERY
{
print("Testing ECIES")
P1[0]=0x0; P1[1]=0x1; P1[2]=0x2
P2[0]=0x0; P2[1]=0x1; P2[2]=0x2; P2[3]=0x3
for i in 0...16 {M[i]=UInt8(i&0xff)}
let C=ed25519.ECDH.ECIES_ENCRYPT(sha,P1,P2,&REALRNG,W1,M,&V,&T)
print("Ciphertext= ")
print("V= 0x",terminator: ""); printBinary(V)
print("C= 0x",terminator: ""); printBinary(C)
print("T= 0x",terminator: ""); printBinary(T)
M=ed25519.ECDH.ECIES_DECRYPT(sha,P1,P2,V,C,T,S1)
if M.count==0
{
print("*** ECIES Decryption Failed\n")
return
}
else {print("Decryption succeeded")}
print("Message is 0x",terminator: ""); printBinary(M)
print("Testing ECDSA")
if ed25519.ECDH.ECPSP_DSA(sha,&rng,S0,M,&CS,&DS) != 0
{
print("***ECDSA Signature Failed")
return
}
print("Signature= ")
print("C= 0x",terminator: ""); printBinary(CS)
print("D= 0x",terminator: ""); printBinary(DS)
if ed25519.ECDH.ECPVP_DSA(sha,W0,M,CS,DS) != 0
{
print("***ECDSA Verification Failed")
return
}
else {print("ECDSA Signature/Verification succeeded ")}
}
rng=REALRNG!
}
public func TestECDH_nist256(_ rng: inout RAND)
{
let pp=String("M0ng00se");
let EGS=nist256.ECDH.EGS
let EFS=nist256.ECDH.EFS
let EAS=nist256.CONFIG_CURVE.AESKEY
let sha=nist256.CONFIG_CURVE.HASH_TYPE
var S1=[UInt8](repeating: 0,count: EGS)
var W0=[UInt8](repeating: 0,count: 2*EFS+1)
var W1=[UInt8](repeating: 0,count: 2*EFS+1)
var Z0=[UInt8](repeating: 0,count: EFS)
var Z1=[UInt8](repeating: 0,count: EFS)
var SALT=[UInt8](repeating: 0,count: 8)
var P1=[UInt8](repeating: 0,count: 3)
var P2=[UInt8](repeating: 0,count: 4)
var V=[UInt8](repeating: 0,count: 2*EFS+1)
var M=[UInt8](repeating: 0,count: 17)
var T=[UInt8](repeating: 0,count: 12)
var CS=[UInt8](repeating: 0,count: EGS)
var DS=[UInt8](repeating: 0,count: EGS)
var NULLRNG : RAND? = nil
var REALRNG : RAND? = rng
for i in 0 ..< 8 {SALT[i]=UInt8(i+1)} // set Salt
print("\nTest Curve nist256");
print("Alice's Passphrase= " + pp)
let PW=[UInt8]( (pp).utf8 )
// private key S0 of size EGS bytes derived from Password and Salt
// Note use of curve name here to disambiguate between supported curves!!
// Not needed if only one curve supported
var S0=HMAC.PBKDF2(HMAC.MC_SHA2,sha,PW,SALT,1000,EGS)
print("Alice's private key= 0x",terminator: ""); printBinary(S0)
// Generate Key pair S/W
nist256.ECDH.KEY_PAIR_GENERATE(&NULLRNG,&S0,&W0)
print("Alice's public key= 0x",terminator: ""); printBinary(W0)
var res=nist256.ECDH.PUBLIC_KEY_VALIDATE(W0)
if res != 0
{
print("ECP Public Key is invalid!");
return;
}
// Random private key for other party
nist256.ECDH.KEY_PAIR_GENERATE(&REALRNG,&S1,&W1)
print("Servers private key= 0x",terminator: ""); printBinary(S1)
print("Servers public key= 0x",terminator: ""); printBinary(W1)
res=nist256.ECDH.PUBLIC_KEY_VALIDATE(W1)
if res != 0
{
print("ECP Public Key is invalid!")
return
}
// Calculate common key using DH - IEEE 1363 method
nist256.ECDH.ECPSVDP_DH(S0,W1,&Z0,0)
nist256.ECDH.ECPSVDP_DH(S1,W0,&Z1,0)
var same=true
for i in 0 ..< EFS
{
if Z0[i] != Z1[i] {same=false}
}
if (!same)
{
print("*** ECPSVDP-DH Failed")
return
}
let KEY=HMAC.KDF2(HMAC.MC_SHA2,sha,Z0,nil,EAS)
print("Alice's DH Key= 0x",terminator: ""); printBinary(KEY)
print("Servers DH Key= 0x",terminator: ""); printBinary(KEY)
if nist256.CONFIG_CURVE.CURVETYPE != nist256.CONFIG_CURVE.MONTGOMERY
{
print("Testing ECIES")
P1[0]=0x0; P1[1]=0x1; P1[2]=0x2
P2[0]=0x0; P2[1]=0x1; P2[2]=0x2; P2[3]=0x3
for i in 0...16 {M[i]=UInt8(i&0xff)}
let C=nist256.ECDH.ECIES_ENCRYPT(sha,P1,P2,&REALRNG,W1,M,&V,&T)
print("Ciphertext= ")
print("V= 0x",terminator: ""); printBinary(V)
print("C= 0x",terminator: ""); printBinary(C)
print("T= 0x",terminator: ""); printBinary(T)
M=nist256.ECDH.ECIES_DECRYPT(sha,P1,P2,V,C,T,S1)
if M.count==0
{
print("*** ECIES Decryption Failed\n")
return
}
else {print("Decryption succeeded")}
print("Message is 0x",terminator: ""); printBinary(M)
print("Testing ECDSA")
if nist256.ECDH.ECPSP_DSA(sha,&rng,S0,M,&CS,&DS) != 0
{
print("***ECDSA Signature Failed")
return
}
print("Signature= ")
print("C= 0x",terminator: ""); printBinary(CS)
print("D= 0x",terminator: ""); printBinary(DS)
if nist256.ECDH.ECPVP_DSA(sha,W0,M,CS,DS) != 0
{
print("***ECDSA Verification Failed")
return
}
else {print("ECDSA Signature/Verification succeeded ")}
}
rng=REALRNG!
}
public func TestECDH_ed448(_ rng: inout RAND)
{
let pp=String("M0ng00se");
let EGS=ed448.ECDH.EGS
let EFS=ed448.ECDH.EFS
let EAS=ed448.CONFIG_CURVE.AESKEY
let sha=ed448.CONFIG_CURVE.HASH_TYPE
var S1=[UInt8](repeating: 0,count: EGS)
var W0=[UInt8](repeating: 0,count: 2*EFS+1)
var W1=[UInt8](repeating: 0,count: 2*EFS+1)
var Z0=[UInt8](repeating: 0,count: EFS)
var Z1=[UInt8](repeating: 0,count: EFS)
var SALT=[UInt8](repeating: 0,count: 8)
var P1=[UInt8](repeating: 0,count: 3)
var P2=[UInt8](repeating: 0,count: 4)
var V=[UInt8](repeating: 0,count: 2*EFS+1)
var M=[UInt8](repeating: 0,count: 17)
var T=[UInt8](repeating: 0,count: 12)
var CS=[UInt8](repeating: 0,count: EGS)
var DS=[UInt8](repeating: 0,count: EGS)
var NULLRNG : RAND? = nil
var REALRNG : RAND? = rng
for i in 0 ..< 8 {SALT[i]=UInt8(i+1)} // set Salt
print("\nTest Curve ed448");
print("Alice's Passphrase= " + pp)
let PW=[UInt8]( (pp).utf8 )
// private key S0 of size EGS bytes derived from Password and Salt
// Note use of curve name here to disambiguate between supported curves!!
// Not needed if only one curve supported
var S0=HMAC.PBKDF2(HMAC.MC_SHA2,sha,PW,SALT,1000,EGS)
print("Alice's private key= 0x",terminator: ""); printBinary(S0)
// Generate Key pair S/W
ed448.ECDH.KEY_PAIR_GENERATE(&NULLRNG,&S0,&W0);
print("Alice's public key= 0x",terminator: ""); printBinary(W0)
var res=ed448.ECDH.PUBLIC_KEY_VALIDATE(W0);
if res != 0
{
print("ECP Public Key is invalid!");
return;
}
// Random private key for other party
ed448.ECDH.KEY_PAIR_GENERATE(&REALRNG,&S1,&W1)
print("Servers private key= 0x",terminator: ""); printBinary(S1)
print("Servers public key= 0x",terminator: ""); printBinary(W1);
res=ed448.ECDH.PUBLIC_KEY_VALIDATE(W1)
if res != 0
{
print("ECP Public Key is invalid!")
return
}
// Calculate common key using DH - IEEE 1363 method
ed448.ECDH.ECPSVDP_DH(S0,W1,&Z0,0)
ed448.ECDH.ECPSVDP_DH(S1,W0,&Z1,0)
var same=true
for i in 0 ..< EFS
{
if Z0[i] != Z1[i] {same=false}
}
if (!same)
{
print("*** ECPSVDP-DH Failed")
return
}
let KEY=HMAC.KDF2(HMAC.MC_SHA2,sha,Z0,nil,EAS)
print("Alice's DH Key= 0x",terminator: ""); printBinary(KEY)
print("Servers DH Key= 0x",terminator: ""); printBinary(KEY)
if ed448.CONFIG_CURVE.CURVETYPE != ed448.CONFIG_CURVE.MONTGOMERY
{
print("Testing ECIES")
P1[0]=0x0; P1[1]=0x1; P1[2]=0x2
P2[0]=0x0; P2[1]=0x1; P2[2]=0x2; P2[3]=0x3
for i in 0...16 {M[i]=UInt8(i&0xff)}
let C=ed448.ECDH.ECIES_ENCRYPT(sha,P1,P2,&REALRNG,W1,M,&V,&T)
print("Ciphertext= ")
print("V= 0x",terminator: ""); printBinary(V)
print("C= 0x",terminator: ""); printBinary(C)
print("T= 0x",terminator: ""); printBinary(T)
M=ed448.ECDH.ECIES_DECRYPT(sha,P1,P2,V,C,T,S1)
if M.count==0
{
print("*** ECIES Decryption Failed\n")
return
}
else {print("Decryption succeeded")}
print("Message is 0x",terminator: ""); printBinary(M)
print("Testing ECDSA")
if ed448.ECDH.ECPSP_DSA(sha,&rng,S0,M,&CS,&DS) != 0
{
print("***ECDSA Signature Failed")
return
}
print("Signature= ")
print("C= 0x",terminator: ""); printBinary(CS)
print("D= 0x",terminator: ""); printBinary(DS)
if ed448.ECDH.ECPVP_DSA(sha,W0,M,CS,DS) != 0
{
print("***ECDSA Verification Failed")
return
}
else {print("ECDSA Signature/Verification succeeded ")}
}
rng=REALRNG!
}
var RAW=[UInt8](repeating: 0,count: 100)
var rng=RAND()
rng.clean();
for i in 0 ..< 100 {RAW[i]=UInt8(i&0xff)}
rng.seed(100,RAW)
TestECDH_ed25519(&rng)
TestECDH_nist256(&rng)
TestECDH_ed448(&rng)
TestRSA_2048(&rng)
|
//
// PokemonData.swift
// Pokedex Final Exam
//
// Created by SBAUser on 4/27/20.
// Copyright © 2020 Michelle Espinosa. All rights reserved.
//
import Foundation
class PokemonData {
private struct Returned: Codable {
var count: Int
var next: String
var results: [Pokemon]
}
var count = 0
var url = "https://pokeapi.co/api/v2/pokemon/"
var pokeArray: [Pokemon] = []
func getData(completed: @escaping ()->()) {
let urlString = url
print("We are accessing the url \(urlString)")
guard let url = URL(string: urlString) else {
print("ERROR: Could not create a URL from \(urlString)")
completed()
return
}
let session = URLSession.shared
let task = session.dataTask(with: url) { (data, respone, error) in
if let error = error {
print("ERROR: \(error.localizedDescription)")
}
do {
let returned = try JSONDecoder().decode(Returned.self, from: data!)
self.count = returned.count
self.url = returned.next
self.pokeArray = self.pokeArray + returned.results
} catch {
print("JSON ERROR: \(error.localizedDescription)")
}
completed()
}
task.resume()
}
}
|
//
// ServiceTests.swift
// Customers
//
// Created by David Murphy on 13/06/2017.
// Copyright © 2017 Test. All rights reserved.
//
import XCTest
import RxSwift
@testable import Customers
class ServiceTests: XCTestCase {
let dispose = DisposeBag()
func testMapCustomers() {
guard let json = MockClient.shared.loadStubbedJSON("queueData") else {
XCTFail()
return
}
Observable.just(json).customers.subscribe(onNext: { customers in
XCTAssertEqual(customers.count, 4)
XCTAssertEqual(customers.first?.id, 12322316)
}).disposed(by: dispose)
}
func testSortCustomers() {
let first = Customer(id: 1, name: "test", expectedTime: Date().add(minutes: 10), email: nil, emailHash: nil)
let second = Customer(id: 2, name: "test", expectedTime: Date().add(minutes: 5), email: nil, emailHash: nil)
let third = Customer(id: 3, name: "test", expectedTime: Date(), email: nil, emailHash: nil)
Observable.just([first,second,third]).sort().subscribe(onNext: { customers in
XCTAssertEqual(customers[0].id, 3)
XCTAssertEqual(customers[1].id, 2)
XCTAssertEqual(customers[2].id, 1)
}).disposed(by: dispose)
}
let service = MockService()
func testGetCustomers() {
let expectation = self.expectation(description: "get customers")
service.fetchCustomers().subscribe(onNext: { customers in
XCTAssertTrue(Thread.isMainThread)
XCTAssertEqual(customers.count, 4)
XCTAssertEqual(customers.first?.id, 12322316)
expectation.fulfill()
}).disposed(by: dispose)
waitForExpectations(timeout: 10) { error in
print(error as Any)
}
}
}
extension Date {
func add(minutes: Int) -> Date {
return Calendar(identifier: .gregorian).date(byAdding: .minute, value: minutes, to: self)!
}
}
|
import Foundation
public struct Command<T> {
private let action: (T) -> Void
public init(with action: @escaping (T) -> Void) {
self.action = action
}
public func perform(with value: T) {
action(value)
}
}
public extension Command where T == Void {
public func perform() {
perform(with: ())
}
}
|
//
// Country+Extensions.swift
// CaptainDemo
//
// Created by Vincent Esche on 6/4/18.
// Copyright © 2018 Vincent Esche. All rights reserved.
//
import Foundation
import CoreData
extension Country {
static func all(context: NSManagedObjectContext) -> [Country] {
let fetchRequest: NSFetchRequest<Country> = Country.fetchRequest()
do {
return try context.fetch(fetchRequest)
} catch let error {
fatalError("Error: \(error)")
}
}
static func instance(id: Int64, context: NSManagedObjectContext) -> Country? {
let fetchRequest: NSFetchRequest<Country> = Country.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "id == %d", id)
do {
return try context.fetch(fetchRequest).first
} catch let error {
fatalError("Error: \(error)")
}
}
}
|
import Foundation
public class ModuleConfig {
public var name: String
public var desc: String
public var version: String
public var enabled: Bool
public var moduleClass: Module.Type
public var services: [ServiceName: AnyClass]
public var customEvents: [EventName]
/// Configuration parameter of Module.
///
/// - Parameters:
/// - name: module name
/// - desc: module description
/// - version: module version
/// - enabled: module enabled
/// - moduleClass: module class
/// - services: module services
/// - customEvents: customEvents
public init(name: String = "",
desc: String = "",
version: String = "",
enabled: Bool = true,
moduleClass: Module.Type,
services: [ServiceName: AnyClass] = [:],
customEvents: [EventName] = []) {
self.name = name
self.desc = desc
self.version = version
self.enabled = enabled
self.moduleClass = moduleClass
self.services = services
self.customEvents = customEvents
}
}
|
//
// UIViewController+Storage.swift
// Challenge
//
// Created by Camilo Castro on 08-09-20.
// Copyright © 2020 SoSafe. All rights reserved.
//
import UIKit
import API
import Storage
extension UIViewController {
func saveLocationToFavourites(annotation: GooglePlacePointAnnotation) {
let key = annotation.place!.uid
let content:String = annotation.place!.json
Storage.engine.save(key:key, content:content)
}
func removeLocationFromFavourites(annotation: GooglePlacePointAnnotation) {
let key = annotation.place!.uid
Storage.engine.delete(key:key)
}
}
|
//
// RandomGame.swift
// Calculator
//
// Created by Jason on 10/31/18.
// Copyright © 2018 Pursuit. All rights reserved.
//
import Foundation
func mathStuffFactoryRandom(opStringRandom: String) -> (Double, Double) -> Double {
switch opStringRandom {
case "+":
return {x, y in x + y }
case "-":
return {x, y in x - y }
case "*":
return {x, y in x * y }
case "/":
if y == 0 {
return {x, y in 0 / 9
}
}
else{
return {x, y in x / y
}
}
default:
return {x, y in x + y }
}
}
|
// coding: utf-8
//
// ONLY READ THIS IF YOU HAVE ALREADY SOLVED THIS PROBLEM!
// File created for http://projecteuler.net/
//
// Created by: Alex Dias Teixeira
// Name: 001_sum.py
// Date: 06 Sept 2013
//
// Problem: [1] - Multiples of 3 and 5
// If we list all the natural numbers below 10 that are multiples of
// 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
// Find the sum of all the multiples of 3 or 5 below 1000.
//
import UIKit
func sum_even_fib_numbers(x: Int) -> Int {
/*
(None) -> integer
This function will generate an integer. This integer is the sum of all the
even fibonacci number under 4.000.000.
Maximum fibonacci number to add to the total? [integer]
4000000
4613732
Maximum fibonacci number to add to the total? [integer]
5
10
*/
var a = 0
var b = 1
var c = 0
var total = 0
while total < x {
c = a + b
a = b
b = c
if c % 2 == 0 {
total = total + c
}
}
return total
}
println(sum_even_fib_numbers(4000000)) |
//
// CvsExport.swift
// GiftManager
//
// Created by David Johnson on 12/30/17.
// Copyright © 2017 David Johnson. All rights reserved.
//
import Foundation
/// A customer class to export data to a CSV file.
class CsvExport {
fileprivate var path:String = ""
fileprivate var separator:String = ","
fileprivate var lines:[String] = [""]
var delegate:FileCreationDelegate?
/// Create a new instance of CsvExport.
init() { }
/// Create a new instance of CsvExport.
///
/// - Parameter path: the path where the csv file will reside.
init(path:String) {
self.path = path
}
/// Set the file path where the CSV file will be written to.
///
/// - Parameter path: the path to use
func setPath(path:String) { self.path = path }
/// Set the separator between items. Defaults to a comma.
///
/// - Parameter separator: the separator to use
func setSeparator(separator:String) { self.separator = separator }
/// Add a line to the file. No conversion of items is made.
///
/// - Parameter line: the line of text to add
func appendLine(line:String) { self.lines.append(line) }
/// Convert an array of strings to a single line, ready to be appended.
///
/// - Parameters:
/// - strings: the array of string to merge into a single string
/// - useQuotes: if the merged strings should be quoted
/// - Returns: the single string
func convertToLine(strings:[String], useQuotes:Bool) -> String {
var contents = ""
for item:String in strings {
if useQuotes {
contents.append("\"")
}
contents.append(item)
if useQuotes {
contents.append("\"")
}
contents.append(self.separator)
}
contents = String(contents.dropLast())
contents.append("\n")
return contents
}
/// Convert an array of strings to a single line and appends it to the array of lines immediately.
///
/// - Parameters:
/// - items: the array of string to merge into one
/// - useQuotes: flag if all the strings should be quoted
func convertAndAppendLines(items:[String], useQuotes:Bool) {
let line = convertToLine(strings: items, useQuotes: useQuotes)
self.appendLine(line: line)
}
/// Write the array of lines to file on desktop.
func writeCsv() {
let urlPath = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop").appendingPathComponent(self.path)
var csvText = ""
for line in self.lines {
csvText.append(line)
}
do {
try csvText.write(to:urlPath, atomically: false, encoding: .utf8)
self.delegate?.handleWroteFile(success: true, filePath: urlPath.absoluteString, errorMessage: "")
} catch {
self.delegate?.handleWroteFile(success: false, filePath: "", errorMessage: "\(error)")
}
}
}
|
//
// ViewController.swift
// SRDemo_1
//
// Created by yMac on 2019/5/30.
// Copyright © 2019 cs. All rights reserved.
//
import UIKit
@_exported import ReplayKit
import AVKit
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
let sharePath = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.sss.fx.rtmpdemo")!.path + "/Library/Caches"
lazy var dataSource: [String] = {
[]
}()
var broadcastActivityVC: RPBroadcastActivityViewController?
var broadcastController: RPBroadcastController?
// var broadcastView: RPSystemBroadcastPickerView?
override func viewDidLoad() {
super.viewDidLoad()
// if #available(iOS 12.0, *) {
//
// let broadcastView = RPSystemBroadcastPickerView.init(frame: .init(x: 100, y: 200, width: 100, height: 100))
// // 不指定扩展,可以展示所有可用的扩展列表
// broadcastView.preferredExtension = "com.cs.ScreenRecordDemo.BroadcastUpload"
// // 是否显示麦克风按钮,默认true
//// broadcastView.showsMicrophoneButton = false
// view.addSubview(broadcastView)
// } else {
// // Fallback earily version
//
// }
// collectionView.cm_register(cell: VideoCollectionViewCell.self)
flowLayout.itemSize = CGSize.init(width: UIScreen.main.bounds.size.width/3, height: UIScreen.main.bounds.size.width/3)
getVideos()
print("===========uploadVideoSuccess.rawValue = \(CFNotificationName.uploadVideoSuccess.rawValue as String)")
let darwinNotificationCenter = DarwinNotificationsManager.sharedInstance()
darwinNotificationCenter!.register(forNotificationName: CFNotificationName.uploadVideoSuccess.rawValue as String) {
self.showAlert(message: "alert!")
}
}
@objc func uploadVideoSuccess() {
showAlert(message: getFileSize(folderPath: FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.sss.fx.rtmpdemo")!.path + "/Library/Caches/"))
getVideos()
}
func showAlert(message: String!) {
let alert = UIAlertController.init(title: "file size", message: message, preferredStyle: .alert)
let action = UIAlertAction.init(title: "ok", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func getVideos() {
let datas = getFileListInFolderWithPath(path: sharePath)
// print(datas)
// print("file size = \(getFileSize(folderPath: sharePath))")
dataSource.removeAll()
dataSource = datas
// for fileName in dataSource {
// do {
// try FileManager.default.removeItem(atPath: sharePath + "/" + fileName)
// } catch {
// print("remove item failed")
// }
// }
collectionView.reloadData()
}
}
// iOS 11
extension ViewController {
@IBAction func ios11BroadcastClick(_ sender: Any) {
// RPBroadcastActivityViewController.load { (broadcardtVC, error) in
// guard error == nil else {
// print("error = \(error!.localizedDescription)")
// return
// }
// if let broadcardtVC = broadcardtVC {
// self.broadcastActivityVC = broadcardtVC
// broadcardtVC.delegate = self
// self.present(broadcardtVC, animated: true, completion: nil)
// }
// }
RPBroadcastActivityViewController.load(withPreferredExtension: "com.cs.ScreenRecordDemo.BroadcastUI") { (broadcardtVC, error) in
guard error == nil else {
print("error = \(error!.localizedDescription)")
return
}
if let broadcardtVC = broadcardtVC {
self.broadcastActivityVC = broadcardtVC
broadcardtVC.delegate = self
self.present(broadcardtVC, animated: true, completion: nil)
}
}
}
}
extension ViewController: RPBroadcastActivityViewControllerDelegate, RPBroadcastControllerDelegate {
func broadcastActivityViewController(_ broadcastActivityViewController: RPBroadcastActivityViewController, didFinishWith broadcastController: RPBroadcastController?, error: Error?) {
print("broadcarstVC finished!")
DispatchQueue.main.async {
broadcastActivityViewController.dismiss(animated: true, completion: nil)
}
guard error == nil else {
print("Broadcast Activity Controller is not available. Reason: " + (error?.localizedDescription)! )
return
}
// self.broadcastController = broadcastController
// broadcastController?.delegate = self
broadcastController?.startBroadcast(handler: { (error) in
if let error = error {
print("error = \(error.localizedDescription)")
} else {
print("开始屏幕录制")
}
})
}
// func broadcastController(_ broadcastController: RPBroadcastController, didUpdateBroadcast broadcastURL: URL) {
// print("didUpdateBroadcast")
// }
// func broadcastController(_ broadcastController: RPBroadcastController, didUpdateServiceInfo serviceInfo: [String : NSCoding & NSObjectProtocol]) {
// print("didUpdateServiceInfo")
// }
//
// func broadcastController(_ broadcastController: RPBroadcastController, didFinishWithError error: Error?) {
//
// if let error = error {
// print("error = \(error.localizedDescription)")
// } else {
// print("broadcastController: didFinishWithError")
// }
// }
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: VideoCollectionViewCell = collectionView.cm_dequeueReusableCell(forIndexPath: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let videoUrl = URL.init(fileURLWithPath: sharePath + "/\(dataSource[indexPath.row])")
let player = AVPlayerViewController()
player.player = AVPlayer.init(url: videoUrl)
present(player, animated: true, completion: nil)
}
}
extension ViewController {
//获取文件夹下文件列表
func getFileListInFolderWithPath(path:String) -> Array<String> {
let fileManager = FileManager.default
let fileList = try! fileManager.contentsOfDirectory(atPath: path)
return fileList
}
//获取文件大小
func getFileSize(folderPath: String)-> String {
if folderPath.count == 0 {
return "0MB" as String
}
let manager = FileManager.default
if !manager.fileExists(atPath: folderPath){
return "0MB" as String
}
var fileSize:Float = 0.0
do {
let files = try manager.contentsOfDirectory(atPath: folderPath)
for file in files {
let path = folderPath + file
fileSize = fileSize + fileSizeAtPath(filePath: path)
}
}catch{
fileSize = fileSize + fileSizeAtPath(filePath: folderPath)
}
var resultSize = ""
if fileSize >= 1024.0*1024.0{
resultSize = NSString(format: "%.2fMB", fileSize/(1024.0 * 1024.0)) as String
}else if fileSize >= 1024.0{
resultSize = NSString(format: "%.fkb", fileSize/(1024.0 )) as String
}else{
resultSize = NSString(format: "%llub", fileSize) as String
}
return resultSize
}
/** 计算单个文件或文件夹的大小 */
func fileSizeAtPath(filePath:String) -> Float {
let manager = FileManager.default
var fileSize:Float = 0.0
if manager.fileExists(atPath: filePath) {
do {
let attributes = try manager.attributesOfItem(atPath: filePath)
if attributes.count != 0 {
fileSize = attributes[FileAttributeKey.size]! as! Float
}
}catch{
}
}
return fileSize;
}
}
|
//
// ViewController.swift
// Swift_Animation
//
// Created by coder on 16/2/15.
// Copyright © 2016年 coder. All rights reserved.
//
import UIKit
class ViewController: UIViewController ,HolderViewDelegate{
var holderView:HolderView?
let boxSize:CGFloat = 100.0;
override func viewDidLoad() {
super.viewDidLoad()
holderView = HolderView(frame: CGRect(x: self.view.center.x - boxSize / 2, y: self.view.center.y - boxSize / 2, width: boxSize, height: boxSize))
holderView?.parentFrame = self.view.frame
holderView!.addOval()
holderView!.addTriangleLayer()
holderView?.delegate = self
view.addSubview(self.holderView!);
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.None)
NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "wobble", userInfo: nil, repeats: false)
}
func wobble() {
holderView!.wobble()
}
func holderViewAnimationDidStop() {
let label:UILabel = UILabel(frame: CGRect(x: self.view.center.x - boxSize / 4, y: self.view.center.y - boxSize / 4, width: boxSize / 2, height: boxSize / 2))
label.textColor = UIColor.whiteColor()
label.text = "S"
label.font = UIFont(name: "HelveticaNeue-Thin", size: 60.0)
label.textAlignment = NSTextAlignment.Center
label.transform = CGAffineTransformScale(label.transform, 0.25, 0.25)
self.view.addSubview(label)
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
label.transform = CGAffineTransformScale(label.transform, 8.0, 8.0)
}) { (finish) -> Void in
}
}
}
|
//
// StationListCell.swift
// Departure Board
//
// Created by Cat Jia on 13/11/2018.
// Copyright © 2018 Cat Jia. All rights reserved.
//
import UIKit
protocol StationListCellDelegate: NSObjectProtocol {
func stationListCell(_ cell: StationListCell, didUpdateSelectStatus isSelected: Bool, for direction: MTRLine.Direction) -> Void
}
class StationListCell: UITableViewCell {
weak var delegate: StationListCellDelegate?
private let stackView = UIStackView()
private let buttons: [AddButton] = MTRLine.Direction.allCases.map { AddButton(direction: $0) }
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.textLabel?.adjustsFontSizeToFitWidth = true // TODO; not elegant
stackView.axis = .horizontal
stackView.spacing = 5
self.contentView.addSubview(stackView)
for button in buttons {
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
button.addTarget(self, action: #selector(didTapAddButton(_:)), for: .touchUpInside)
stackView.addArrangedSubview(button)
}
self.prepareForReuse()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
guard let textLabel = self.textLabel else {
stackView.isHidden = true
return
}
stackView.isHidden = false
let spacing = 10 as CGFloat
stackView.frame.size.width = stackView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width
stackView.frame.size.height = 28
stackView.frame.origin.x = textLabel.frame.maxX - stackView.frame.width
stackView.center.y = self.contentView.bounds.height / 2
textLabel.frame.size.width -= (stackView.frame.width + spacing)
}
func setLineStation(_ station: MTRStation, availableDirections: [MTRLine.Direction], selectedDirections: [MTRLine.Direction]) {
self.textLabel?.text = station.name
for button in buttons {
button.isEnabled = availableDirections.contains(button.direction)
button.configure(line: MTRLine.withCode(station.lineCode))
button.isSelected = selectedDirections.contains(button.direction)
}
}
override func prepareForReuse() {
super.prepareForReuse()
self.delegate = nil
self.textLabel?.text = nil
for button in buttons {
button.isEnabled = false
button.configure(line: nil)
button.isSelected = false
}
}
@objc private func didTapAddButton(_ button: AddButton) {
button.isSelected.toggle()
self.delegate?.stationListCell(self, didUpdateSelectStatus: button.isSelected, for: button.direction)
}
}
private class AddButton: UIButton {
static let defaultHeight = 28 as CGFloat
private let disabledColor: UIColor = .lightGray
override var isSelected: Bool {
didSet {
self.updateUI()
}
}
override var isEnabled: Bool {
didSet {
self.updateUI()
}
}
private var lineColor: UIColor?
let direction: MTRLine.Direction
init(direction: MTRLine.Direction) {
self.direction = direction
super.init(frame: .zero)
self.layer.cornerRadius = 4
self.titleLabel?.font = .systemFont(ofSize: 13)
self.setTitleColor(disabledColor, for: .disabled)
self.setTitleColor(.white, for: .selected)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(line: MTRLine?) {
self.setTitle(line?.destinationName(for: direction, withRoutingWord: true), for: .normal)
self.lineColor = line?.color
}
private func updateUI() {
let color: UIColor = isEnabled ? (self.lineColor ?? .mainTintColor) : disabledColor
self.setTitleColor(color, for: .normal)
if isSelected {
self.layer.borderWidth = 0
self.layer.borderColor = UIColor.clear.cgColor
self.layer.masksToBounds = true
self.backgroundColor = color
} else {
self.layer.borderWidth = 1
self.layer.borderColor = color.cgColor
self.layer.masksToBounds = false
self.backgroundColor = .clear
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.