text stringlengths 8 1.32M |
|---|
//
// TabBarUIAction.swift
// TabBarUIAction
//
// Created by Fabrizio Duroni on 21/03/21.
//
import SwiftUI
/**
The TabBArUIAction component.
This is the main component that contains all the other parts.
*/
public struct TabBarUIAction: View {
@Binding private var currentView: TabPosition
@Binding private var showModal: Bool
private var modal: TabModal
private let tabItemsProperties: [TabItemProperties]
private let colors: Colors
/**
Creates a `TabBarUIAction` instance.
- parameter currentTab: the current tab selected as `Binding` state object of type `TabPosition`.
- parameter showModal: the show modal toggle as `Binding` state object of type `Bool`.
- parameter colors: the colors of the tab bar. See `Colors`.
- parameter content: the content of the tab bar expressed as 3 items: first tab, modal and second tab.
*/
public init(
currentTab: Binding<TabPosition>,
showModal: Binding<Bool>,
colors: Colors,
@ViewBuilder content: () -> TupleView<(TabScreen, TabModal, TabScreen)>
) {
self._currentView = currentTab
self._showModal = showModal
let views = content().value
self.modal = views.1
self.tabItemsProperties = [
TabItemProperties(position: .tab1, screen: views.0),
TabItemProperties(position: .tab2, screen: views.2)
]
self.colors = colors
}
/**
Creates a `TabBarUIAction` instance.
- parameter currentTab: the current tab selected as `Binding` state object of type `TabPosition`.
- parameter showModal: the show modal toggle as `Binding` state object of type `Bool`.
- parameter colors: the colors of the tab bar. See `Colors`.
- parameter content: the content of the tab bar expressed as 5 items: first tab, second tab,
modal and third tab and forth tab.
*/
public init(
currentTab: Binding<TabPosition>,
showModal: Binding<Bool>,
colors: Colors,
@ViewBuilder content: () -> TupleView<(TabScreen, TabScreen, TabModal, TabScreen, TabScreen)>
) {
self._currentView = currentTab
self._showModal = showModal
let views = content().value
self.modal = views.2
self.tabItemsProperties = [
TabItemProperties(position: .tab1, screen: views.0),
TabItemProperties(position: .tab2, screen: views.1),
TabItemProperties(position: .tab3, screen: views.3),
TabItemProperties(position: .tab4, screen: views.4)
]
self.colors = colors
}
/// The body of TabBArUIAction. It creates a view with the modal tab content.
public var body: some View {
VStack {
tabItemsProperties[currentView.rawValue].screen
.accessibility(identifier: "TabScreen\(currentView.rawValue + 1)")
TabBar(
currentView: $currentView,
showModal: $showModal,
tabItemColors: colors.tabItemColors,
tabItems: tabItemsProperties,
modal: modal
)
.background(
colors.tabBarBackgroundColor
.ignoresSafeArea()
.accessibility(identifier: "TabBarUIActionBackground")
)
}
.ignoresSafeArea(.keyboard)
.accessibilityElement(children: .contain)
.accessibility(identifier: "TabBarUIAction")
}
}
|
//
// AccessibilityExtensions.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import UIKit
import SceneKit
class CoordinateAccessibilityElement: UIAccessibilityElement {
let coordinate: Coordinate
weak var world: GridWorld?
/// Override `accessibilityLabel` to always return updated information about world state.
override var accessibilityLabel: String? {
get {
return world?.speakableContents(of: coordinate)
}
set {}
}
init(coordinate: Coordinate, inWorld world: GridWorld, view: UIView) {
self.coordinate = coordinate
self.world = world
super.init(accessibilityContainer: view)
}
}
// MARK: WorldViewController Accessibility
extension WorldViewController {
func registerForAccessibilityNotifications() {
NotificationCenter.default().addObserver(self, selector: #selector(voiceOverStatusChanged), name: Notification.Name(rawValue: UIAccessibilityVoiceOverStatusChanged), object: nil)
}
func unregisterForAccessibilityNotifications() {
NotificationCenter.default().removeObserver(self, name: Notification.Name(rawValue: UIAccessibilityVoiceOverStatusChanged), object: nil)
}
func voiceOverStatusChanged() {
DispatchQueue.main.async { [unowned self] in
self.setVoiceOverForCurrentStatus()
}
}
func setVoiceOverForCurrentStatus() {
if UIAccessibilityIsVoiceOverRunning() {
scnView.gesturesEnabled = false
cameraController?.switchToOverheadView()
configureAccessibilityElementsForGrid()
// Add speedAdjust button manually because grid takes over view's `accessibilityElements`.
speedAdjustButton.accessibilityLabel = "Speed adjustment"
view.accessibilityElements?.append(speedAdjustButton)
// Add an AccessibilityComponent to each actor.
for actor in scene.actors {
actor.addComponent(AccessibilityComponent.self)
}
}
else {
// Set for UITesting.
view.isAccessibilityElement = true
view.accessibilityLabel = "The world is running."
scnView.gesturesEnabled = true
cameraController?.resetFromVoiceOver()
for actor in scene.actors {
actor.removeComponent(AccessibilityComponent.self)
}
}
}
func configureAccessibilityElementsForGrid() {
view.isAccessibilityElement = false
view.accessibilityElements = []
for coordinate in scene.gridWorld.columnRowSortedCoordinates {
let gridPosition = coordinate.position
let rootPosition = scene.gridWorld.grid.scnNode.convertPosition(gridPosition, to: nil)
let offset = WorldConfiguration.coordinateLength / 2
let upperLeft = scnView.projectPoint(SCNVector3Make(rootPosition.x - offset, rootPosition.y, rootPosition.z - offset))
let lowerRight = scnView.projectPoint(SCNVector3Make(rootPosition.x + offset, rootPosition.y, rootPosition.z + offset))
let point = CGPoint(x: CGFloat(upperLeft.x), y: CGFloat(upperLeft.y))
let size = CGSize (width: CGFloat(lowerRight.x - upperLeft.x), height: CGFloat(lowerRight.y - upperLeft.y))
let element = CoordinateAccessibilityElement(coordinate: coordinate, inWorld: scene.gridWorld, view: view)
element.accessibilityFrame = CGRect(origin: point, size: size)
view.accessibilityElements?.append(element)
}
}
}
extension GridWorld {
func speakableContents(of coordinate: Coordinate) -> String {
// FIXME: Needs to use `height(:)`
// Checks level of top block, otherwise equates to 0
let prefix = "\(coordinate.description), "
let contents = excludingNodes(ofType: Block.self, at: coordinate).reduce("") { str, node in
var tileDescription = str
switch node.identifier {
case .actor:
let actor = node as? Actor
let name = actor?.type.rawValue ?? "Actor"
tileDescription.append("\(name) at height \(node.level), ")
case .stair:
tileDescription.append("stair, facing \(node.heading), from level \(node.level - 1) to \(node.level), ")
default:
tileDescription.append("\(node.identifier.rawValue) at height \(node.level), ")
}
return tileDescription
}
let suffix = contents.isEmpty ? "is empty." : contents
return prefix + suffix
}
func columnRowSortPredicate(_ coor1: Coordinate, _ coor2: Coordinate) -> Bool {
if coor1.column == coor2.column {
return coor1.row < coor2.row
}
return coor1.column < coor2.column
}
var columnRowSortedCoordinates: [Coordinate] {
return allPossibleCoordinates.sorted(isOrderedBefore: columnRowSortPredicate)
}
var speakableDescription: String {
let sortedItems = grid.allItemsInGrid.sorted { item1, item2 in
return columnRowSortPredicate(item1.coordinate, item2.coordinate)
}
let actors = sortedItems.flatMap { $0 as? Actor }
let randomIdentifiers = sortedItems.filter { $0.identifier == .randomNode }
let goals = sortedItems.filter {
switch $0.identifier {
case .switch, .portal, .item, .platformLock: return true
default: return false
}
}
var description = "The world is \(columnCount) columns by \(rowCount) rows. "
if actors.isEmpty {
description += "There is no character placed in this world. You must place your own."
}
else {
for node in actors {
let name = node.type.rawValue
description += "\(name) starts at \(node.locationDescription)."
}
}
if !goals.isEmpty {
description += " The important locations are: "
for (index, goalNode) in goals.enumerated() {
description += "\(goalNode.identifier.rawValue) at \(goalNode.locationDescription)"
description += index == goals.endIndex ? "." : "; "
}
}
if !randomIdentifiers.isEmpty {
description += " Random items at: "
for (index, objectNode) in randomIdentifiers.enumerated() {
description += "\(objectNode.identifier.rawValue) at \(objectNode.locationDescription)"
description += index == randomIdentifiers.endIndex ? "." : "; "
}
}
return description
}
}
extension Actor {
var speakableName: String {
return type.rawValue
}
}
extension Item {
var locationDescription: String{
return "\(coordinate.description), height \(level)"
}
}
|
/// All possible notifications you can subscribe to with `Observer`.
/// - seeAlso: [Notificatons](https://developer.apple.com/library/mac/documentation/AppKit/Reference/NSAccessibility_Protocol_Reference/index.html#//apple_ref/c/data/NSAccessibilityAnnouncementRequestedNotification)
public enum AXNotification: String {
// Focus notifications
case mainWindowChanged = "AXMainWindowChanged"
case focusedWindowChanged = "AXFocusedWindowChanged"
case focusedUIElementChanged = "AXFocusedUIElementChanged"
// Application notifications
case applicationActivated = "AXApplicationActivated"
case applicationDeactivated = "AXApplicationDeactivated"
case applicationHidden = "AXApplicationHidden"
case applicationShown = "AXApplicationShown"
// Window notifications
case windowCreated = "AXWindowCreated"
case windowMoved = "AXWindowMoved"
case windowResized = "AXWindowResized"
case windowMiniaturized = "AXWindowMiniaturized"
case windowDeminiaturized = "AXWindowDeminiaturized"
// Drawer & sheet notifications
case drawerCreated = "AXDrawerCreated"
case sheetCreated = "AXSheetCreated"
// Element notifications
case uiElementDestroyed = "AXUIElementDestroyed"
case valueChanged = "AXValueChanged"
case titleChanged = "AXTitleChanged"
case resized = "AXResized"
case moved = "AXMoved"
case created = "AXCreated"
// Used when UI changes require the attention of assistive application. Pass along a user info
// dictionary with the key NSAccessibilityUIElementsKey and an array of elements that have been
// added or changed as a result of this layout change.
case layoutChanged = "AXLayoutChanged"
// Misc notifications
case helpTagCreated = "AXHelpTagCreated"
case selectedTextChanged = "AXSelectedTextChanged"
case rowCountChanged = "AXRowCountChanged"
case selectedChildrenChanged = "AXSelectedChildrenChanged"
case selectedRowsChanged = "AXSelectedRowsChanged"
case selectedColumnsChanged = "AXSelectedColumnsChanged"
case rowExpanded = "AXRowExpanded"
case rowCollapsed = "AXRowCollapsed"
// Cell-table notifications
case selectedCellsChanged = "AXSelectedCellsChanged"
// Layout area notifications
case unitsChanged = "AXUnitsChanged"
case selectedChildrenMoved = "AXSelectedChildrenMoved"
// This notification allows an application to request that an announcement be made to the user
// by an assistive application such as VoiceOver. The notification requires a user info
// dictionary with the key NSAccessibilityAnnouncementKey and the announcement as a localized
// string. In addition, the key NSAccessibilityAnnouncementPriorityKey should also be used to
// help an assistive application determine the importance of this announcement. This
// notification should be posted for the application element.
case announcementRequested = "AXAnnouncementRequested"
}
/// All UIElement roles.
/// - seeAlso: [Roles](https://developer.apple.com/library/mac/documentation/AppKit/Reference/NSAccessibility_Protocol_Reference/index.html#//apple_ref/doc/constant_group/Roles)
public enum Role: String {
case unknown = "AXUnknown"
case button = "AXButton"
case radioButton = "AXRadioButton"
case checkBox = "AXCheckBox"
case slider = "AXSlider"
case tabGroup = "AXTabGroup"
case textField = "AXTextField"
case staticText = "AXStaticText"
case textArea = "AXTextArea"
case scrollArea = "AXScrollArea"
case popUpButton = "AXPopUpButton"
case menuButton = "AXMenuButton"
case table = "AXTable"
case application = "AXApplication"
case group = "AXGroup"
case radioGroup = "AXRadioGroup"
case list = "AXList"
case scrollBar = "AXScrollBar"
case valueIndicator = "AXValueIndicator"
case image = "AXImage"
case menuBar = "AXMenuBar"
case menu = "AXMenu"
case menuItem = "AXMenuItem"
case column = "AXColumn"
case row = "AXRow"
case toolbar = "AXToolbar"
case busyIndicator = "AXBusyIndicator"
case progressIndicator = "AXProgressIndicator"
case window = "AXWindow"
case drawer = "AXDrawer"
case systemWide = "AXSystemWide"
case outline = "AXOutline"
case incrementor = "AXIncrementor"
case browser = "AXBrowser"
case comboBox = "AXComboBox"
case splitGroup = "AXSplitGroup"
case splitter = "AXSplitter"
case colorWell = "AXColorWell"
case growArea = "AXGrowArea"
case sheet = "AXSheet"
case helpTag = "AXHelpTag"
case matte = "AXMatte"
case ruler = "AXRuler"
case rulerMarker = "AXRulerMarker"
case link = "AXLink"
case disclosureTriangle = "AXDisclosureTriangle"
case grid = "AXGrid"
case relevanceIndicator = "AXRelevanceIndicator"
case levelIndicator = "AXLevelIndicator"
case cell = "AXCell"
case popover = "AXPopover"
case layoutArea = "AXLayoutArea"
case layoutItem = "AXLayoutItem"
case handle = "AXHandle"
}
/// All UIElement subroles.
/// - seeAlso: [Subroles](https://developer.apple.com/library/mac/documentation/AppKit/Reference/NSAccessibility_Protocol_Reference/index.html#//apple_ref/doc/constant_group/Subroles)
public enum Subrole: String {
case unknown = "AXUnknown"
case closeButton = "AXCloseButton"
case zoomButton = "AXZoomButton"
case minimizeButton = "AXMinimizeButton"
case toolbarButton = "AXToolbarButton"
case tableRow = "AXTableRow"
case outlineRow = "AXOutlineRow"
case secureTextField = "AXSecureTextField"
case standardWindow = "AXStandardWindow"
case dialog = "AXDialog"
case systemDialog = "AXSystemDialog"
case floatingWindow = "AXFloatingWindow"
case systemFloatingWindow = "AXSystemFloatingWindow"
case incrementArrow = "AXIncrementArrow"
case decrementArrow = "AXDecrementArrow"
case incrementPage = "AXIncrementPage"
case decrementPage = "AXDecrementPage"
case searchField = "AXSearchField"
case textAttachment = "AXTextAttachment"
case textLink = "AXTextLink"
case timeline = "AXTimeline"
case sortButton = "AXSortButton"
case ratingIndicator = "AXRatingIndicator"
case contentList = "AXContentList"
case definitionList = "AXDefinitionList"
case fullScreenButton = "AXFullScreenButton"
case toggle = "AXToggle"
case switchSubrole = "AXSwitch"
case descriptionList = "AXDescriptionList"
}
/// Orientations returned by the orientation property.
/// - seeAlso: [NSAccessibilityOrientation](https://developer.apple.com/library/mac/documentation/AppKit/Reference/NSAccessibility_Protocol_Reference/index.html#//apple_ref/c/tdef/NSAccessibilityOrientation)
public enum Orientation: Int {
case unknown = 0
case vertical = 1
case horizontal = 2
}
public enum Attribute: String {
// Standard attributes
case role = "AXRole" //(NSString *) - type, non-localized (e.g. radioButton)
case roleDescription = "AXRoleDescription" //(NSString *) - user readable role (e.g. "radio button")
case subrole = "AXSubrole" //(NSString *) - type, non-localized (e.g. closeButton)
case help = "AXHelp" //(NSString *) - instance description (e.g. a tool tip)
case value = "AXValue" //(id) - element's value
case minValue = "AXMinValue" //(id) - element's min value
case maxValue = "AXMaxValue" //(id) - element's max value
case enabled = "AXEnabled" //(NSNumber *) - (boolValue) responds to user?
case focused = "AXFocused" //(NSNumber *) - (boolValue) has keyboard focus?
case parent = "AXParent" //(id) - element containing you
case children = "AXChildren" //(NSArray *) - elements you contain
case window = "AXWindow" //(id) - UIElement for the containing window
case topLevelUIElement = "AXTopLevelUIElement" //(id) - UIElement for the containing top level element
case selectedChildren = "AXSelectedChildren" //(NSArray *) - child elements which are selected
case visibleChildren = "AXVisibleChildren" //(NSArray *) - child elements which are visible
case position = "AXPosition" //(NSValue *) - (pointValue) position in screen coords
case size = "AXSize" //(NSValue *) - (sizeValue) size
case frame = "AXFrame" //(NSValue *) - (rectValue) frame
case contents = "AXContents" //(NSArray *) - main elements
case title = "AXTitle" //(NSString *) - visible text (e.g. of a push button)
case description = "AXDescription" //(NSString *) - instance description
case shownMenu = "AXShownMenu" //(id) - menu being displayed
case valueDescription = "AXValueDescription" //(NSString *) - text description of value
case sharedFocusElements = "AXSharedFocusElements" //(NSArray *) - elements that share focus
// Misc attributes
case previousContents = "AXPreviousContents" //(NSArray *) - main elements
case nextContents = "AXNextContents" //(NSArray *) - main elements
case header = "AXHeader" //(id) - UIElement for header.
case edited = "AXEdited" //(NSNumber *) - (boolValue) is it dirty?
case tabs = "AXTabs" //(NSArray *) - UIElements for tabs
case horizontalScrollBar = "AXHorizontalScrollBar" //(id) - UIElement for the horizontal scroller
case verticalScrollBar = "AXVerticalScrollBar" //(id) - UIElement for the vertical scroller
case overflowButton = "AXOverflowButton" //(id) - UIElement for overflow
case incrementButton = "AXIncrementButton" //(id) - UIElement for increment
case decrementButton = "AXDecrementButton" //(id) - UIElement for decrement
case filename = "AXFilename" //(NSString *) - filename
case expanded = "AXExpanded" //(NSNumber *) - (boolValue) is expanded?
case selected = "AXSelected" //(NSNumber *) - (boolValue) is selected?
case splitters = "AXSplitters" //(NSArray *) - UIElements for splitters
case document = "AXDocument" //(NSString *) - url as string - for open document
case activationPoint = "AXActivationPoint" //(NSValue *) - (pointValue)
case url = "AXURL" //(NSURL *) - url
case index = "AXIndex" //(NSNumber *) - (intValue)
case rowCount = "AXRowCount" //(NSNumber *) - (intValue) number of rows
case columnCount = "AXColumnCount" //(NSNumber *) - (intValue) number of columns
case orderedByRow = "AXOrderedByRow" //(NSNumber *) - (boolValue) is ordered by row?
case warningValue = "AXWarningValue" //(id) - warning value of a level indicator, typically a number
case criticalValue = "AXCriticalValue" //(id) - critical value of a level indicator, typically a number
case placeholderValue = "AXPlaceholderValue" //(NSString *) - placeholder value of a control such as a text field
case containsProtectedContent = "AXContainsProtectedContent" // (NSNumber *) - (boolValue) contains protected content?
case alternateUIVisible = "AXAlternateUIVisible" //(NSNumber *) - (boolValue)
// Linkage attributes
case titleUIElement = "AXTitleUIElement" //(id) - UIElement for the title
case servesAsTitleForUIElements = "AXServesAsTitleForUIElements" //(NSArray *) - UIElements this titles
case linkedUIElements = "AXLinkedUIElements" //(NSArray *) - corresponding UIElements
// Text-specific attributes
case selectedText = "AXSelectedText" //(NSString *) - selected text
case selectedTextRange = "AXSelectedTextRange" //(NSValue *) - (rangeValue) range of selected text
case numberOfCharacters = "AXNumberOfCharacters" //(NSNumber *) - number of characters
case visibleCharacterRange = "AXVisibleCharacterRange" //(NSValue *) - (rangeValue) range of visible text
case sharedTextUIElements = "AXSharedTextUIElements" //(NSArray *) - text views sharing text
case sharedCharacterRange = "AXSharedCharacterRange" //(NSValue *) - (rangeValue) part of shared text in this view
case insertionPointLineNumber = "AXInsertionPointLineNumber" //(NSNumber *) - line# containing caret
case selectedTextRanges = "AXSelectedTextRanges" //(NSArray<NSValue *> *) - array of NSValue (rangeValue) ranges of selected text
/// - note: private/undocumented attribute
case textInputMarkedRange = "AXTextInputMarkedRange"
// Parameterized text-specific attributes
case lineForIndexParameterized = "AXLineForIndexParameterized" //(NSNumber *) - line# for char index; param:(NSNumber *)
case rangeForLineParameterized = "AXRangeForLineParameterized" //(NSValue *) - (rangeValue) range of line; param:(NSNumber *)
case stringForRangeParameterized = "AXStringForRangeParameterized" //(NSString *) - substring; param:(NSValue * - rangeValue)
case rangeForPositionParameterized = "AXRangeForPositionParameterized" //(NSValue *) - (rangeValue) composed char range; param:(NSValue * - pointValue)
case rangeForIndexParameterized = "AXRangeForIndexParameterized" //(NSValue *) - (rangeValue) composed char range; param:(NSNumber *)
case boundsForRangeParameterized = "AXBoundsForRangeParameterized" //(NSValue *) - (rectValue) bounds of text; param:(NSValue * - rangeValue)
case rtfForRangeParameterized = "AXRTFForRangeParameterized" //(NSData *) - rtf for text; param:(NSValue * - rangeValue)
case styleRangeForIndexParameterized = "AXStyleRangeForIndexParameterized" //(NSValue *) - (rangeValue) extent of style run; param:(NSNumber *)
case attributedStringForRangeParameterized = "AXAttributedStringForRangeParameterized" //(NSAttributedString *) - does _not_ use attributes from Appkit/AttributedString.h
// Text attributed string attributes and constants
case fontText = "AXFontText" //(NSDictionary *) - NSAccessibilityFontXXXKey's
case foregroundColorText = "AXForegroundColorText" //CGColorRef
case backgroundColorText = "AXBackgroundColorText" //CGColorRef
case underlineColorText = "AXUnderlineColorText" //CGColorRef
case strikethroughColorText = "AXStrikethroughColorText" //CGColorRef
case underlineText = "AXUnderlineText" //(NSNumber *) - underline style
case superscriptText = "AXSuperscriptText" //(NSNumber *) - superscript>0, subscript<0
case strikethroughText = "AXStrikethroughText" //(NSNumber *) - (boolValue)
case shadowText = "AXShadowText" //(NSNumber *) - (boolValue)
case attachmentText = "AXAttachmentText" //id - corresponding element
case linkText = "AXLinkText" //id - corresponding element
case autocorrectedText = "AXAutocorrectedText" //(NSNumber *) - (boolValue)
// Textual list attributes and constants. Examples: unordered or ordered lists in a document.
case listItemPrefixText = "AXListItemPrefixText" // NSAttributedString, the prepended string of the list item. If the string is a common unicode character (e.g. a bullet โข), return that unicode character. For lists with images before the text, return a reasonable label of the image.
case listItemIndexText = "AXListItemIndexText" // NSNumber, integerValue of the line index. Each list item increments the index, even for unordered lists. The first item should have index 0.
case listItemLevelText = "AXListItemLevelText" // NSNumber, integerValue of the indent level. Each sublist increments the level. The first item should have level 0.
// MisspelledText attributes
case misspelledText = "AXMisspelledText" //(NSNumber *) - (boolValue)
case markedMisspelledText = "AXMarkedMisspelledText" //(NSNumber *) - (boolValue)
// Window-specific attributes
case main = "AXMain" //(NSNumber *) - (boolValue) is it the main window?
case minimized = "AXMinimized" //(NSNumber *) - (boolValue) is window minimized?
case closeButton = "AXCloseButton" //(id) - UIElement for close box (or nil)
case zoomButton = "AXZoomButton" //(id) - UIElement for zoom box (or nil)
case minimizeButton = "AXMinimizeButton" //(id) - UIElement for miniaturize box (or nil)
case toolbarButton = "AXToolbarButton" //(id) - UIElement for toolbar box (or nil)
case proxy = "AXProxy" //(id) - UIElement for title's icon (or nil)
case growArea = "AXGrowArea" //(id) - UIElement for grow box (or nil)
case modal = "AXModal" //(NSNumber *) - (boolValue) is the window modal
case defaultButton = "AXDefaultButton" //(id) - UIElement for default button
case cancelButton = "AXCancelButton" //(id) - UIElement for cancel button
case fullScreenButton = "AXFullScreenButton" //(id) - UIElement for full screen button (or nil)
/// - note: private/undocumented attribute
case fullScreen = "AXFullScreen" //(NSNumber *) - (boolValue) is the window fullscreen
// Application-specific attributes
case menuBar = "AXMenuBar" //(id) - UIElement for the menu bar
case windows = "AXWindows" //(NSArray *) - UIElements for the windows
case frontmost = "AXFrontmost" //(NSNumber *) - (boolValue) is the app active?
case hidden = "AXHidden" //(NSNumber *) - (boolValue) is the app hidden?
case mainWindow = "AXMainWindow" //(id) - UIElement for the main window.
case focusedWindow = "AXFocusedWindow" //(id) - UIElement for the key window.
case focusedUIElement = "AXFocusedUIElement" //(id) - Currently focused UIElement.
case extrasMenuBar = "AXExtrasMenuBar" //(id) - UIElement for the application extras menu bar.
/// - note: private/undocumented attribute
case enhancedUserInterface = "AXEnhancedUserInterface" //(NSNumber *) - (boolValue) is the enhanced user interface active?
case orientation = "AXOrientation" //(NSString *) - NSAccessibilityXXXOrientationValue
case columnTitles = "AXColumnTitles" //(NSArray *) - UIElements for titles
case searchButton = "AXSearchButton" //(id) - UIElement for search field search btn
case searchMenu = "AXSearchMenu" //(id) - UIElement for search field menu
case clearButton = "AXClearButton" //(id) - UIElement for search field clear btn
// Table/outline view attributes
case rows = "AXRows" //(NSArray *) - UIElements for rows
case visibleRows = "AXVisibleRows" //(NSArray *) - UIElements for visible rows
case selectedRows = "AXSelectedRows" //(NSArray *) - UIElements for selected rows
case columns = "AXColumns" //(NSArray *) - UIElements for columns
case visibleColumns = "AXVisibleColumns" //(NSArray *) - UIElements for visible columns
case selectedColumns = "AXSelectedColumns" //(NSArray *) - UIElements for selected columns
case sortDirection = "AXSortDirection" //(NSString *) - see sort direction values below
// Cell-based table attributes
case selectedCells = "AXSelectedCells" //(NSArray *) - UIElements for selected cells
case visibleCells = "AXVisibleCells" //(NSArray *) - UIElements for visible cells
case rowHeaderUIElements = "AXRowHeaderUIElements" //(NSArray *) - UIElements for row headers
case columnHeaderUIElements = "AXColumnHeaderUIElements" //(NSArray *) - UIElements for column headers
// Cell-based table parameterized attributes. The parameter for this attribute is an NSArray containing two NSNumbers, the first NSNumber specifies the column index, the second NSNumber specifies the row index.
case cellForColumnAndRowParameterized = "AXCellForColumnAndRowParameterized" // (id) - UIElement for cell at specified row and column
// Cell attributes. The index range contains both the starting index, and the index span in a table.
case rowIndexRange = "AXRowIndexRange" //(NSValue *) - (rangeValue) location and row span
case columnIndexRange = "AXColumnIndexRange" //(NSValue *) - (rangeValue) location and column span
// Layout area attributes
case horizontalUnits = "AXHorizontalUnits" //(NSString *) - see ruler unit values below
case verticalUnits = "AXVerticalUnits" //(NSString *) - see ruler unit values below
case horizontalUnitDescription = "AXHorizontalUnitDescription" //(NSString *)
case verticalUnitDescription = "AXVerticalUnitDescription" //(NSString *)
// Layout area parameterized attributes
case layoutPointForScreenPointParameterized = "AXLayoutPointForScreenPointParameterized" //(NSValue *) - (pointValue); param:(NSValue * - pointValue)
case layoutSizeForScreenSizeParameterized = "AXLayoutSizeForScreenSizeParameterized" //(NSValue *) - (sizeValue); param:(NSValue * - sizeValue)
case screenPointForLayoutPointParameterized = "AXScreenPointForLayoutPointParameterized" //(NSValue *) - (pointValue); param:(NSValue * - pointValue)
case screenSizeForLayoutSizeParameterized = "AXScreenSizeForLayoutSizeParameterized" //(NSValue *) - (sizeValue); param:(NSValue * - sizeValue)
// Layout item attributes
case handles = "AXHandles" //(NSArray *) - UIElements for handles
// Outline attributes
case disclosing = "AXDisclosing" //(NSNumber *) - (boolValue) is disclosing rows?
case disclosedRows = "AXDisclosedRows" //(NSArray *) - UIElements for disclosed rows
case disclosedByRow = "AXDisclosedByRow" //(id) - UIElement for disclosing row
case disclosureLevel = "AXDisclosureLevel" //(NSNumber *) - indentation level
// Slider attributes
case allowedValues = "AXAllowedValues" //(NSArray<NSNumber *> *) - array of allowed values
case labelUIElements = "AXLabelUIElements" //(NSArray *) - array of label UIElements
case labelValue = "AXLabelValue" //(NSNumber *) - value of a label UIElement
// Matte attributes
// Attributes no longer supported
case matteHole = "AXMatteHole" //(NSValue *) - (rect value) bounds of matte hole in screen coords
case matteContentUIElement = "AXMatteContentUIElement" //(id) - UIElement clipped by the matte
// Ruler view attributes
case markerUIElements = "AXMarkerUIElements" //(NSArray *)
case markerValues = "AXMarkerValues" //
case markerGroupUIElement = "AXMarkerGroupUIElement" //(id)
case units = "AXUnits" //(NSString *) - see ruler unit values below
case unitDescription = "AXUnitDescription" //(NSString *)
case markerType = "AXMarkerType" //(NSString *) - see ruler marker type values below
case markerTypeDescription = "AXMarkerTypeDescription" //(NSString *)
// UI element identification attributes
case identifier = "AXIdentifier" //(NSString *)
// System-wide attributes
case focusedApplication = "AXFocusedApplication"
// Unknown attributes
case functionRowTopLevelElements = "AXFunctionRowTopLevelElements"
case childrenInNavigationOrder = "AXChildrenInNavigationOrder"
}
/// All actions a `UIElement` can support.
/// - seeAlso: [Actions](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Protocols/NSAccessibility_Protocol/#//apple_ref/doc/constant_group/Actions)
public enum Action: String {
case press = "AXPress"
case increment = "AXIncrement"
case decrement = "AXDecrement"
case confirm = "AXConfirm"
case pick = "AXPick"
case cancel = "AXCancel"
case raise = "AXRaise"
case showMenu = "AXShowMenu"
case delete = "AXDelete"
case showAlternateUI = "AXShowAlternateUI"
case showDefaultUI = "AXShowDefaultUI"
}
|
//
// Friend.swift
// Project-10-12-Challenge
//
// Created by Tino on 4/4/21.
//
import Foundation
struct FriendStruct: Codable, Identifiable {
let id: UUID
let name: String
}
|
//
// SecondViewController.swift
// Tiper_iOS
//
// Created by ืืื ืืืฉืจ on 22.12.2015.
// Copyright ยฉ 2015 gil osher. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDelegate, UITableViewDataSource{
var allShifts: [Shift]!;
var navBar: UINavigationBar!;
var datePicker: UIPickerView!;
var shiftTable: UITableView!;
var tableDetailsView: UIView!;
var lblTotalSummary: UILabel!;
var lblTotalSalary: UILabel!;
var lblTotalTips: UILabel!;
var lblAverageSalaryPerHour: UILabel!;
var totalSummary: Float!;
var totalSalary: Float!;
var totalTips: Int!;
var tabBarHeight: CGFloat!;
var averageSalaryPerHour: Float!;
//delegate fields
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate;
var selectedMonth: Int!;
var selectedYear: Int!;
let monthNames = ["ืื ืืืจ", "ืคืืจืืืจ", "ืืจืฅ", "ืืคืจืื", "ืืื", "ืืื ื", "ืืืื", "ืืืืืกื", "ืกืคืืืืจ", "ืืืงืืืืจ", "ื ืืืืืจ" ,"ืืฆืืืจ"];
var today: NSDate!;
var currentShifts: [Shift]!;
override func viewDidLoad() {
super.viewDidLoad()
//define main view
view.backgroundColor = UIColor(netHex: 0x2979FF);
let statusBar = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: UIApplication.sharedApplication().statusBarFrame.height));
statusBar.backgroundColor = UIColor(netHex: 0x1F2839);
view.addSubview(statusBar);
let storyBoard = UIStoryboard(name: "Main", bundle: nil);
tabBarHeight = (storyBoard.instantiateViewControllerWithIdentifier("TabBarController") as! UITabBarController).tabBar.frame.size.height;
navBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.sharedApplication().statusBarFrame.height, width: view.frame.width, height: 40))
let navItem = UINavigationItem();
navItem.title = "ืืืกืืืจืืืช ืืฉืืจืืช";
navBar.items = [navItem];
view.addSubview(navBar);
//load required fields
today = NSDate();
selectedMonth = NSCalendar.currentCalendar().component(NSCalendarUnit.Month, fromDate: today)-1;
selectedYear = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: today);
totalTips = 0;
totalSalary = 0;
totalSummary = 0;
averageSalaryPerHour = 0;
allShifts = appDelegate.getShifts();
currentShifts = [Shift]();
createViews();
}
func createViews(){
datePicker = UIPickerView(frame: CGRect(x: 0, y: navBar.frame.maxY, width: view.frame.width , height: 50));
datePicker.delegate = self;
datePicker.dataSource = self;
datePicker.backgroundColor = UIColor(netHex: 0xFFC107)
view.addSubview(datePicker);
let lblSaperateLine4 = UIView(frame: CGRect(x: datePicker.frame.width / 2, y: datePicker.frame.origin.y, width: 2, height: 50));
lblSaperateLine4.backgroundColor = UIColor.blackColor();
view.addSubview(lblSaperateLine4);
shiftTable = UITableView(frame: CGRect(x: 0, y: datePicker.frame.maxY, width: view.frame.width, height: view.frame.height - datePicker.frame.height - navBar.frame.height - UIApplication.sharedApplication().statusBarFrame.size.height - tabBarHeight - 60));
shiftTable.backgroundColor = UIColor(netHex: 0x0288D1);
shiftTable.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "shift_table");
shiftTable.delegate = self;
shiftTable.dataSource = self;
let nib = UINib(nibName: "viewTableCell", bundle: nil);
shiftTable.registerNib(nib, forCellReuseIdentifier: "cell");
view.addSubview(shiftTable);
tableDetailsView = UIView(frame: CGRect(x: 0, y: shiftTable.frame.maxY, width: view.frame.width, height: 60))
tableDetailsView.backgroundColor = UIColor(netHex: 0xFFC107);
lblTotalSummary = UILabel(frame: CGRect(x: 0, y: 0, width: tableDetailsView.frame.width/3, height: 30));
lblTotalSummary.textAlignment = .Center
lblTotalSummary.font = UIFont(name: lblTotalSummary.font.fontName, size: 14);
tableDetailsView.addSubview(lblTotalSummary);
let lblSaperateLine1 = UIView(frame: CGRect(x: lblTotalSummary.frame.maxX, y: 0, width: 2, height: 30));
lblSaperateLine1.backgroundColor = UIColor.blackColor();
tableDetailsView.addSubview(lblSaperateLine1);
lblTotalSalary = UILabel(frame: CGRect(x: lblTotalSummary.frame.maxX, y: 0, width: tableDetailsView.frame.width/3 + 10, height: 30));
lblTotalSalary.textAlignment = .Center
lblTotalSalary.font = UIFont(name: lblTotalSalary.font.fontName, size: 14);
tableDetailsView.addSubview(lblTotalSalary);
let lblSaperateLine2 = UIView(frame: CGRect(x: lblTotalSalary.frame.maxX, y: 0, width: 2, height: 30));
lblSaperateLine2.backgroundColor = UIColor.blackColor();
tableDetailsView.addSubview(lblSaperateLine2);
lblTotalTips = UILabel(frame: CGRect(x: lblTotalSalary.frame.maxX, y: 0, width: tableDetailsView.frame.width/3 - 10, height: 30));
lblTotalTips.textAlignment = .Center
lblTotalTips.font = UIFont(name: lblTotalTips.font.fontName, size: 14);
tableDetailsView.addSubview(lblTotalTips);
let lblSaperateLine3 = UIView(frame: CGRect(x: 0, y: lblTotalTips.frame.maxY, width: tableDetailsView.frame.width, height: 2));
lblSaperateLine3.backgroundColor = UIColor.blackColor();
tableDetailsView.addSubview(lblSaperateLine3);
lblAverageSalaryPerHour = UILabel(frame: CGRect(x: 0, y: lblTotalSummary.frame.maxY, width: view.frame.width, height: 30))
lblAverageSalaryPerHour.textAlignment = .Center;
lblAverageSalaryPerHour.font = UIFont.boldSystemFontOfSize(16);
tableDetailsView.addSubview(lblAverageSalaryPerHour);
view.addSubview(tableDetailsView);
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated);
shiftTable.resignFirstResponder();
datePicker.selectRow(selectedYear, inComponent: 0, animated: true);
datePicker.selectRow(selectedMonth, inComponent: 1, animated: true);
allShifts = appDelegate.getShifts();
print("number of shift: \(allShifts.count)");
for i in 0..<allShifts.count{
print("\(allShifts[i].id)");
}
notifyShiftTable();
shiftTable.reloadData();
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 2;
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 12;
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0{
let todayYear = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: today);
selectedYear = row + todayYear;
}else{
selectedMonth = row;
}
notifyShiftTable();
shiftTable.reloadData();
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0{
let todayYear = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: today);
return "\(todayYear + row)"
}else{
return monthNames[row];
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currentShifts.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// create custom TableViewCell
let cell:TableViewCell = shiftTable.dequeueReusableCellWithIdentifier("cell") as! TableViewCell;
let shift = allShifts[indexPath.row];
let fmt = NSNumberFormatter()
fmt.maximumFractionDigits = 2
cell.lblDate.text = "\(Shift.getDate(shift.startTime))";
cell.lblTimes.text = "\(Shift.getHourString(shift.startTime))-\(Shift.getHourString(shift.endTime))";
cell.lblSumOfHours.text = "ืฉืขืืช: \(shift.getSumOfHoursString())";
cell.lblTipsCount.text = "ืืืคืื: \(shift.tipsCount)";
cell.lblSalary.text = "ืฉืืจ: \(fmt.stringFromNumber(shift.salary)!)";
cell.lblSummary.text = "ืกืืดื \(fmt.stringFromNumber(shift.summary)!)";
fmt.maximumFractionDigits = 0;
cell.lblAverageSalaryPerHour.text = "ืฉืืจ ืืืืฆืข ืืฉืขื: \(fmt.stringFromNumber(shift.averageSalaryPerHour)!)";
cell.lblAverageSalaryPerHour.font = UIFont.boldSystemFontOfSize(16);
cell.lblTimes.textColor = UIColor.whiteColor();
cell.lblDate.textColor = UIColor.whiteColor();
cell.lblSumOfHours.textColor = UIColor.whiteColor();
cell.lblTipsCount.textColor = UIColor.whiteColor();
cell.lblSalary.textColor = UIColor.whiteColor();
cell.lblSummary.textColor = UIColor.whiteColor();
cell.lblAverageSalaryPerHour.textColor = UIColor.whiteColor();
cell.backgroundColor = UIColor(netHex: 0x0288D1);
cell.textLabel!.textColor = UIColor.whiteColor();
return cell;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 75;
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .Delete;
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let shiftId = currentShifts[indexPath.row].id;
let shiftDeleted = appDelegate.deleteFromDb(shiftId);
print("\(shiftDeleted)")
allShifts = appDelegate.getShifts();
notifyShiftTable();
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left);
shiftTable.reloadData();
}
func notifyShiftTable(){
//reset all fields
currentShifts.removeAll();
totalTips = 0;
totalSalary = 0;
totalSummary = 0;
averageSalaryPerHour = 0;
for i in 0..<allShifts.count{
let shiftToCheck = allShifts[i];
let month = NSCalendar.currentCalendar().component(NSCalendarUnit.Month, fromDate: shiftToCheck.startTime)-1; //month from 0 to 11
let year = NSCalendar.currentCalendar().component(NSCalendarUnit.Year, fromDate: shiftToCheck.startTime);
if month == selectedMonth && year == selectedYear{
currentShifts.append(shiftToCheck);
totalTips! += shiftToCheck.tipsCount;
totalSalary! += shiftToCheck.salary;
averageSalaryPerHour! += shiftToCheck.averageSalaryPerHour;
}
}
if currentShifts.count > 1 {
averageSalaryPerHour! /= Float(currentShifts.count);
}
totalSummary = Float(totalTips) + totalSalary;
//present all fields
let fmt = NSNumberFormatter()
fmt.maximumFractionDigits = 2;
lblTotalTips.text = "ืืืคืื: \(fmt.stringFromNumber(totalTips)!)โช";
lblTotalSalary.text = "ืฉืืจ: \(fmt.stringFromNumber(totalSalary)!)โช";
lblTotalSummary.text = "ืกืืดื: \(fmt.stringFromNumber(totalSummary)!)โช";
fmt.maximumFractionDigits = 0;
lblAverageSalaryPerHour.text = "ืฉืืจ ืืืืฆืข ืืฉืขื: \(fmt.stringFromNumber(averageSalaryPerHour)!)โช";
}
}
|
//
// Printable.swift
// SailingThroughHistory
//
// Created by Herald on 27/3/19.
// Copyright ยฉ 2019 Sailing Through History Team. All rights reserved.
//
protocol Printable {
var displayName: String { get }
}
|
//
// MessageCell.swift
// tennislike
//
// Created by Maik Nestler on 22.12.20.
//
import UIKit
class MessageCell: UICollectionViewCell {
// MARK: - Properties
var viewModel: ChatViewModel? {
didSet { configure() }
}
private let textView: UITextView = {
let tv = UITextView()
tv.backgroundColor = .clear
tv.font = .systemFont(ofSize: 20)
tv.isScrollEnabled = false
tv.isEditable = false
return tv
}()
let bubbleContainer = UIView(backgroundColor: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))
var anchoredConstraints: AnchoredConstraints!
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(bubbleContainer)
bubbleContainer.layer.cornerRadius = 12
anchoredConstraints = bubbleContainer.anchor(top: topAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor)
anchoredConstraints.leading?.constant = 20
anchoredConstraints.trailing?.isActive = false
anchoredConstraints.trailing?.constant = -20
bubbleContainer.widthAnchor.constraint(lessThanOrEqualToConstant: 250).isActive = true
bubbleContainer.addSubview(textView)
textView.fillSuperview(padding: .init(top: 4, left: 12, bottom: 4, right: 12))
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Helpers
func configure() {
guard let viewModel = viewModel else { return }
textView.text = viewModel.messageText
textView.textColor = viewModel.messageTextColor
bubbleContainer.backgroundColor = viewModel.messageBackgroundColor
anchoredConstraints.trailing?.isActive = viewModel.rightAnchorActive
anchoredConstraints.leading?.isActive = viewModel.leftAnchorActive
}
}
|
//
// DummyViewController.swift
// Mobile Store
//
// Created by Ashwinkarthik Srinivasan on 3/26/15.
// Copyright (c) 2015 Yun Zhang. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class DummyViewController: UIViewController,PTKViewDelegate {
var paymentView : PTKView?
override func viewDidLoad() {
super.viewDidLoad()
paymentView = PTKView(frame: CGRectMake(0, 20, 290, 55))
paymentView?.center = view.center
paymentView?.delegate = self
view.addSubview(paymentView!)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func nextCollectionLevel(sender: UIButton) {
println("Inside ....")
let shoppingCart : ShoppingCartViewController = ShoppingCartViewController(className: "Cart")
self.navigationController?.pushViewController(shoppingCart, animated: false)
self.addChildViewController(shoppingCart)
/*
let shoppingCart : CategoryCollectionView = CategoryCollectionView(nibName: "CategoryCollectionView", bundle: nil)
self.navigationController?.pushViewController(shoppingCart, animated: false)
*/
shoppingCart.title = "Shopping Cart"
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ContentView.swift
// BikeStore
//
// Created by Gilang Aditya R on 14/11/20.
//
import SwiftUI
//Model Data
struct ContentView: View {
let data: [DataModel] = [
DataModel(id: 1, namaproduk: "Sepeda 1", fotoproduk:"foto1", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100),
DataModel(id: 2, namaproduk: "Sepeda 2", fotoproduk:"foto2", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100),
DataModel(id: 3, namaproduk: "Sepeda 3", fotoproduk:"foto3", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100),
DataModel(id: 4, namaproduk: "Sepeda 4", fotoproduk:"foto4", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100),
DataModel(id: 5, namaproduk: "Sepeda 5", fotoproduk:"foto5", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100),
DataModel(id: 6, namaproduk: "Sepeda 6", fotoproduk:"foto6", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100),
DataModel(id: 7, namaproduk: "Sepeda 7", fotoproduk:"foto7", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100),
DataModel(id: 8, namaproduk: "Sepeda 8", fotoproduk:"foto8", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100),
DataModel(id: 9, namaproduk: "Sepeda 9", fotoproduk:"foto9", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100),
DataModel(id: 10, namaproduk: "Sepeda 10", fotoproduk:"foto10", hargaproduk: "2000000", lokasi: "Bekasi", ratingcount: 3, jumlahrating: 100)
]
//@State var jumlahkeranjang: Int = 0
@ObservedObject var keranjang = GlobalObject()
var body: some View {
//Product()
NavigationView{
ScrollView{
ForEach(data){ row in
VStack(spacing: 10){
Product(data: row, keranjang: self.keranjang)
}.padding()
}
}
.navigationBarTitle("Sepeda")
.navigationBarItems(
trailing:
HStack{
Button(action:{print("Ok")}){
Image(systemName: "person.fill")
}
NavigationLink(destination: DetailView(globaldata: keranjang)){
KeranjangView(keranjang: keranjang)
}
}
)
}.accentColor(Color.secondary)
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct KeranjangView: View{
//@Binding var jumlah: Int
@ObservedObject var keranjang: GlobalObject
var body: some View{
ZStack{
Image(systemName: "cart.fill")
Text("\(self.keranjang.jumlah)")
.foregroundColor(Color.white)
.frame(width:10, height:10)
.font(.body)
.padding(5)
.background(Color.red)
.clipShape(/*@START_MENU_TOKEN@*/Circle()/*@END_MENU_TOKEN@*/)
.offset(x: 10, y: -10)
}
}
}
struct Product: View{
let data: DataModel
//@Binding var jumlah: Int
@ObservedObject var keranjang: GlobalObject
var body: some View{
VStack(alignment: .leading){
ZStack(alignment: .topTrailing){
Image(self.data.fotoProduk)
.resizable().aspectRatio(contentMode:/*@START_MENU_TOKEN@*/.fill/*@END_MENU_TOKEN@*/)
.frame(height: 200)
.clipped()
Button(action: {print("OK")}){
Image(systemName: "heart")
.padding()
.foregroundColor(Color.red)
}
}
Text(self.data.namaProduk)
.font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
.bold()
.padding(.leading)
Text("Rp \(self.data.hargaProduk)")
.font(.title)
.foregroundColor(.red)
.padding(.leading)
.padding(.trailing)
HStack{
Image(systemName: "mappin.circle")
Text(self.data.lokasi)
}
.padding(.leading)
.padding(.trailing)
HStack{
HStack{
ForEach(0..<self.data.ratingCount){
item in
Image(systemName: "star.fill")
.foregroundColor(Color.yellow)
}
}
}
.padding(.trailing)
.padding(.leading)
TambahKeranjang(keranjang: keranjang)
}
.background(Color("warna"))
.cornerRadius(10)
}
}
struct TambahKeranjang: View{
//@Binding var jumlah: Int
@ObservedObject var keranjang: GlobalObject
var body: some View{
Button(action: {self.keranjang.jumlah += 1}){
HStack{
Spacer()
HStack{
Image(systemName: "cart")
Text("Tambah ke keranjang")
.font(.callout)
.padding()
}
Spacer()
}
}.background(Color.green)
.foregroundColor(.white)
.cornerRadius(10)
.padding()
}
}
struct DetailView: View{
@ObservedObject var globaldata: GlobalObject
var body: some View{
NavigationView{
Text("Detail")
.navigationBarTitle("Detail")
}
}
}
|
//
// AlbumDetailCoordinatorUnitTests.swift
// iTunesRSSFeedListTests
//
// Created by MacBook Pro 13 on 10/5/19.
// Copyright ยฉ 2019 Adolfo. All rights reserved.
//
import XCTest
@testable import iTunesRSSFeedList
class AlbumDetailCoordinatorUnitTests: XCTestCase {
func testAlbumDetailCoordinatorPresentsViewControllerWithCorrectViewModelDataSourceAlbum() {
let album = Album(artistName: "Micheal Jackson", name: "Thriller", artworkURL: nil, copyright: "Micheal Jackson", albumURL: nil, genres: nil, releaseDate: "1982-11-30")
let rootNavigationController = UINavigationController()
let albumDetailCoordinator = AlbumDetailCoordinator(presenter: rootNavigationController, viewModel: AlbumDetailViewModel(withAlbumModel: album))
albumDetailCoordinator.start()
if let topViewController = rootNavigationController.topViewController as? AlbumDetailViewController,
let currentAlbumModel = topViewController.viewModel?.albumDataSource {
XCTAssertEqual(currentAlbumModel, album)
} else {
XCTFail()
}
}
}
|
//
// DynamicTypeTextField.swift
// Dynamic Controls
//
// Created by Joseph Duffy on 10/12/2014.
// Copyright (c) 2014 Yetii Ltd. All rights reserved.
//
import UIKit
public class DynamicTypeTextField: UITextField {
convenience public init() {
self.init(frame: CGRect.zero)
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.updateFontSize()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contentSizeCategoryChanged:", name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.updateFontSize()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contentSizeCategoryChanged:", name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
private func updateFontSize() {
self.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
}
func contentSizeCategoryChanged(notification: NSNotification) {
self.updateFontSize()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
|
//
// CryptoPriceWatcherApp.swift
// CryptoPriceWatcher
//
// Created by Rokas Mikelionis on 2021-10-12.
//
import SwiftUI
@main
struct CryptoPriceWatcherApp: App {
var body: some Scene {
WindowGroup {
CryptoPriceWatcherView()
}
}
}
|
//
// Field.swift
// tictactoe
//
// Created by Eric Wong on 12/13/16.
// Copyright ยฉ 2016 Tawpy. All rights reserved.
//
import Foundation
import UIKit
protocol FieldTapRecognizerDelegate {
func tapRecognized()
}
class Field: UIView, UIGestureRecognizerDelegate {
var boardColumn: Int!
var boardRow: Int!
var delegate: FieldTapRecognizerDelegate!
init(boardColumn: Int, boardRow: Int, fieldWidth: CGFloat, fieldHeight: CGFloat) {
self.boardColumn = boardColumn
self.boardRow = boardRow
let fieldFrame = CGRect(x: CGFloat(boardColumn) * fieldWidth, y: CGFloat(boardRow) * fieldHeight, width: fieldHeight, height: fieldWidth)
super.init(frame: fieldFrame)
self.layer.borderWidth = 2
self.backgroundColor = UIColor.white
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(Field.handleTap(_:)))
gestureRecognizer.delegate = self
self.addGestureRecognizer(gestureRecognizer)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func handleTap(_ sender: UITapGestureRecognizer) {
_ = sender.location(in: self)
print(boardColumn, boardRow)
}
}
|
//
// Hero.swift
// DB
//
// Created by Danny huang on 4/12/15.
// Copyright (c) 2015 Chugga. All rights reserved.
//
import UIKit
class Hero: NSObject {
/// name of the hero
var name: String?
/// hero power name
var heroPower: String?
/// hero power description
var heroPowerDescription: String?
/// the set of cards the class owns
var cards = Array<CardSet> ()
init(name: String?, cards: Array<CardSet>?) {
self.name = name;
self.cards = cards!;
}
}
|
import Foundation
import UIKit
import SpriteKit
class SpriteFactory {
static private var _textures:[String: SKTexture] = [String: SKTexture]()
static private var _loaded:Bool = false
static func load(){
TextureLoader.load(imgName:"max", jsonName:"max", textures:&_textures)
_loaded = true
}
static func getTexture(name:String)->SKTexture{
if(!_loaded){
SpriteFactory.load()
}
return _textures[name]!
}
static func getSprite(name:String) -> SKSpriteNode{
let tileSprite = SKSpriteNode(texture: SpriteFactory.getTexture(name: name))
tileSprite.anchorPoint = CGPoint(x:0, y:0)
return tileSprite
}
}
|
import Foundation
import UIKit
final class RedColorCoordinator: Coordinatable, Finishable {
var finish: (() -> Void)?
var router: Presentable
init(router: Presentable) {
self.router = router
}
func start() {
var controller = RedFactory.makeRed()
controller.finish = { [weak self] in
self?.showMagenta()
}
router.push(controller: controller)
}
func showMagenta() {
var controller = RedFactory.makeMagenta()
controller.finish = { [weak self] in
self?.finish?()
}
router.push(controller: controller)
}
}
|
//
// UIText+Padding.swift
// Blinked
//
// Created by Fikret ลengรผl on 16.02.2019.
// Copyright ยฉ 2019 zer0-day. All rights reserved.
//
import UIKit
class UITextFieldPadding: UITextField {
let padding = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 10)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
}
class UITextViewPadding: UITextView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
textContainerInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
}
}
extension UITextField {
enum PaddingSide {
case left(CGFloat)
case right(CGFloat)
case both(CGFloat)
}
func addPadding(_ padding: PaddingSide) {
self.leftViewMode = .always
self.layer.masksToBounds = true
switch padding {
case .left(let spacing):
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
self.leftView = paddingView
self.rightViewMode = .always
case .right(let spacing):
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
self.rightView = paddingView
self.rightViewMode = .always
case .both(let spacing):
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
// left
self.leftView = paddingView
self.leftViewMode = .always
// right
self.rightView = paddingView
self.rightViewMode = .always
}
}
}
|
//
// BlueVC.swift
// FHXNavigationTarBar_Example
//
// Created by ๅฏๆฑๆ ฉ on 2018/8/3.
// Copyright ยฉ 2018ๅนด CocoaPods. All rights reserved.
//
import UIKit
class BlueVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
}
}
|
//
// ViewConstants.swift
// Multiplication Exercises
//
// Created by Nikolas Collina on 9/9/20.
// Copyright ยฉ 2020 Nikolas Collina. All rights reserved.
//
import SwiftUI
struct ViewConstants {
static let menuBackgroundColor = Color.red.opacity(0.70)
static let gameBackgroundColor = Color.blue.opacity(0.70)
static let buttonColor = Color.white.opacity(0.50)
static let progressColor = Color.gray.opacity(0.50)
static let startButtonTextColor = Color.blue
static let startButtonColor = Color.white
static let correctAnswer = Color.green
static let incorrectAnswer = Color.red
static let answerButtonText = Color.black
static let whiteFontColor = Color.white
static let answerButtonSize: CGFloat = 40.0
static let answerButtonCornerRadius: CGFloat = 5.0
static let otherButtonCornerRadius: CGFloat = 20.0
static let nextButtonHeight: CGFloat = 50.0
static let nextButtonWidth: CGFloat = 300.0
static let progressCircleSize: CGFloat = 40.0
static let menuSpacing: CGFloat = 50.0
static let equalBarHeight: CGFloat = 8.0
static let equalBarLength: CGFloat = 100.0
static let settingsButtonSize: CGFloat = 25.0
static let titleFont = Font.system(size: 50, weight: .bold, design: .rounded)
static let currentPreferencesFont = Font.system(size: 25, weight: .bold, design: .rounded)
static let otherButtonFont = Font.system(size: 25, weight: .bold, design: .rounded)
static let problemNumberFont = Font.system(size: 50, weight: .black, design: .rounded)
static let progressFont = Font.system(size: 20, weight:.bold, design: .rounded)
static let answerButtonFont = Font.system(size: 15, weight:.bold, design: .rounded)
static let otherFont = Font.system(size: 15, weight: .bold, design: .rounded)
}
|
//
// ProductCell.swift
// Triton King
//
// Created by Alexander on 01.11.2019.
// Copyright ยฉ 2019 Alexander Team. All rights reserved.
//
import UIKit
import Kingfisher
class ProductCell: UICollectionViewCell {
@IBOutlet weak var foodImageView: UIImageView!
@IBOutlet weak var foodNameLabel: UILabel!
func setup(for foodInfo: FoodInfo) {
let url = URL(string: foodInfo.imageCommonSizePath ?? "")
foodNameLabel.text = foodInfo.foodName
foodImageView.kf.setImage(with: url)
}
}
|
//
// TableViewController.swift
// project1_01
//
// Created by Isaac Sheets on 10/7/18.
// Copyright ยฉ 2018 Isaac Sheets. All rights reserved.
//
import UIKit
class HabitTableViewCell: UITableViewCell {
@IBOutlet weak var cellTitle: UILabel!
@IBOutlet weak var cellLastIndulged: UILabel!
@IBOutlet weak var cellSaved: UILabel!
}
class TableViewController: UITableViewController {
@IBAction func updateStats(_ sender: UIBarButtonItem) {
updateTimeSince()
tableView.reloadData()
}
var habitList = [Habit]()
// var habitList = [
// Habit(habitTitle: "test", numTimes: 2, timeInterval: 1, secBetween: 10, costPerTime: 3, costPerSec: 0.01, dateCreated: Date(), curDate: Date(), timeSince: "0", moneySaved: 4)
// ]
@IBAction func unwindToTableViewController(segue: UIStoryboardSegue){
print("unwind to tableview")
updateTimeSince()
tableView.reloadData()
}
@IBAction func saveToTableViewController(segue: UIStoryboardSegue){
updateTimeSince()
tableView.reloadData()
print("save to tableview now there's ")
print(habitList.count)
}
override func viewDidAppear(_ animated: Bool) {
}
func updateTimeSince() {
//loop through array
for i in 0..<habitList.count {
//update time since field
habitList[i].curDate = Date()
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [.weekOfMonth, .day, .hour, .minute, .second]
formatter.maximumUnitCount = 2
let string = formatter.string(from: habitList[i].dateCreated, to: habitList[i].curDate)
habitList[i].timeSince = string! + " ago"
//update money saved
let interval = DateInterval.init(start: habitList[i].dateCreated, end: habitList[i].curDate)
let dollars = round(100*(interval.duration * Double(habitList[i].costPerSec)))/100
habitList[i].moneySaved = dollars
}
}
override func viewDidLoad() {
//retrieve file and decode if it exists
if Storage.fileExists("habits.json", in: .documents) {
// we have messages to retrieve
habitList = Storage.retrieve("habits.json", from: .documents, as: [Habit].self)
print("file exists!")
}
//application instance
let app = UIApplication.shared
//subscribe to the UIApplicationWillResignActiveNotification notification
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillResignActive(_:)), name: Notification.Name.UIApplicationWillResignActive, object: app)
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem
}
//store data to JSON file
@objc func applicationWillResignActive(_ notification: Notification){
Storage.store(habitList, to: .documents, as: "habits.json")
print("stored data!")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return habitList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HabitCell", for: indexPath) as! HabitTableViewCell
// Configure the cell...
let habit = habitList[indexPath.row]
cell.cellTitle?.text = habit.habitTitle
cell.cellLastIndulged?.text = habit.timeSince
//format currency for money saved field
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale.current
let priceString = currencyFormatter.string(from: NSNumber(value:habit.moneySaved))!
cell.cellSaved?.text = priceString
//for bg color of cell, check how many times they haven't indulged
let interval = habit.curDate.timeIntervalSince(habit.dateCreated)
let timesResisted = interval/habit.secBetween
//set bg color accordingly, red is recent, orange = resisted once, orange/yellow = reisted twoice green = resisted thrice
if timesResisted < 1 {
cell.contentView.backgroundColor = UIColor(red: 255/255, green: 38/255, blue: 0/255, alpha: 0.25)
}
if timesResisted >= 1 && timesResisted < 2 {
cell.contentView.backgroundColor = UIColor(red: 255/255, green: 147/255, blue: 0/255, alpha: 0.25)
}
if timesResisted >= 2 && timesResisted < 3 {
cell.contentView.backgroundColor = UIColor(red: 255/255, green: 251/255, blue: 10/255, alpha: 0.25)
}
if timesResisted > 3 {
cell.contentView.backgroundColor = UIColor(red: 0/255, green: 249/255, blue: 0/255, alpha: 0.25)
}
print(timesResisted)
return cell
}
// func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// //see how
// let habit = habitList[indexPath.row]
//
// let interval = habit.dateCreated.timeIntervalSince(habit.curDate)
//
// let timesResisted = interval/habit.secBetween
//
// print(timesResisted)
//
// }
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
self.habitList.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.reloadData()
print(habitList.count)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "editHabitSegue",
let destination = segue.destination as? EditViewController,
let habitNumber = tableView.indexPathForSelectedRow?.row
{
destination.habitToEdit = habitList[habitNumber]
destination.editting = habitNumber
}
}
}
|
/* Copyright Airship and Contributors */
import AirshipCore
import UIKit
class PushSettingsViewController: UITableViewController, RegistrationDelegate {
@IBOutlet weak var pushEnabledCell: UITableViewCell!
@IBOutlet weak var channelIDCell: UITableViewCell!
@IBOutlet weak var namedUserCell: UITableViewCell!
@IBOutlet weak var tagsCell: UITableViewCell!
@IBOutlet weak var analyticsEnabledCell: UITableViewCell!
var pushEnabled: Bool = false
var namedUser: String = "Not Set"
var tags: Array = ["Not Set"]
var analytics: Bool = false
var defaultDetailVC:UIViewController!
var namedUserDetailVC:UIViewController!
var tagsDetailVC:UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
Airship.push.registrationDelegate = self
NotificationCenter.default.addObserver(
self,
selector: #selector(PushSettingsViewController.refreshView),
name: Channel.channelUpdatedEvent,
object: nil);
NotificationCenter.default.addObserver(
self,
selector: #selector(PushSettingsViewController.refreshView),
name: NSNotification.Name("refreshView"),
object: nil);
pushEnabled = Airship.push.userPushNotificationsEnabled
analytics = Airship.shared.privacyManager.isEnabled(.analytics)
refreshView()
defaultDetailVC = self.storyboard!.instantiateViewController(withIdentifier: "defaultDetailVC")
namedUserDetailVC = self.storyboard!.instantiateViewController(withIdentifier: "namedUserDetailVC");
tagsDetailVC = self.storyboard!.instantiateViewController(withIdentifier: "tagsDetailVC")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshView()
}
@objc func refreshView() {
channelIDCell?.detailTextLabel?.text = Airship.channel.identifier ?? "Not Set"
analyticsEnabledCell.accessoryType = analytics ? .checkmark : .none
namedUserCell.detailTextLabel?.text = Airship.contact.namedUserID ?? "Not Set"
tagsCell.detailTextLabel?.text = (Airship.channel.tags.count > 0) ?
Airship.channel.tags.joined(separator: ", ") : "Not Set"
}
override func tableView(_ tableView: UITableView, didUpdateFocusIn context: UITableViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
guard let focusedSection = context.nextFocusedIndexPath?.section,
let focusedRow = context.nextFocusedIndexPath?.row else {
return
}
let tagsIndexPath = tableView.indexPath(for: tagsCell)
let namedUserIndexPath = tableView.indexPath(for: namedUserCell)
switch (focusedSection, focusedRow) {
case (tagsIndexPath!.section, tagsIndexPath!.row) :
self.showDetailViewController(tagsDetailVC, sender: self)
break
case (namedUserIndexPath!.section, namedUserIndexPath!.row) :
self.showDetailViewController(namedUserDetailVC, sender: self)
break
default:
self.showDetailViewController(defaultDetailVC, sender: self)
break
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let pushEnabledIndexPath = tableView.indexPath(for: pushEnabledCell)
let analyticsEnabledIndexPath = tableView.indexPath(for: analyticsEnabledCell)
switch (indexPath.section, indexPath.row) {
case (pushEnabledIndexPath!.section, pushEnabledIndexPath!.row) :
if (!Airship.push.userPromptedForNotifications) {
Airship.push.userPushNotificationsEnabled = true
}
break
case (analyticsEnabledIndexPath!.section, analyticsEnabledIndexPath!.row) :
analytics = !analytics;
if analytics {
Airship.shared.privacyManager.enableFeatures(.analytics)
} else {
Airship.shared.privacyManager.disableFeatures(.analytics)
}
refreshView()
break
default:
break
}
}
func notificationAuthorizedSettingsDidChange(_ options: UAAuthorizedNotificationSettings = []) {
if (Airship.push.authorizedNotificationSettings.rawValue == 0) {
pushEnabledCell.detailTextLabel?.text = "Enable In System Settings"
pushEnabledCell.accessoryType = .none
} else {
pushEnabledCell.detailTextLabel?.text = "Disable In System Settings"
pushEnabledCell.accessoryType = .checkmark
}
}
}
|
//
// Point.swift
//
//
// Created by Mateus Reckziegel on 7/20/15.
//
//
import UIKit
import SpriteKit
class Point: NSObject {
var point:CGPoint
var connectedLines:NSArray
var mark = false
var node = SKShapeNode(circleOfRadius: Layout.pointRadius)
private var activeNode = SKShapeNode(circleOfRadius: Layout.pointRadius - 1)
var l1, l2:Line?
let color1 = (Layout.colorSet[Layout.colorIndex][0] as UIColor)
let color2 = (Layout.colorSet[Layout.colorIndex][1] as UIColor)
var highlighted:Bool {
willSet {
if newValue != self.highlighted {
self.highlighted = newValue
self.updateNodeAppearance(true)
}
}
}
init(point:CGPoint) {
self.point = point
self.connectedLines = NSArray()
self.highlighted = false
self.node.position = self.point
self.node.zPosition = 0.011
self.activeNode.zPosition = 0.021
self.node.addChild(self.activeNode)
super.init()
updateNodeAppearance(false)
}
func updateNodeAppearance(animated:Bool) {
self.node.lineWidth = 1.5
self.node.fillColor = color1
self.node.strokeColor = color1
if self.highlighted {
self.activeNode.lineWidth = 0.5
self.activeNode.strokeColor = color2
self.activeNode.fillColor = color1
self.activeNode.hidden = false
} else {
self.activeNode.hidden = true
}
}
func nextLine(line:Line) -> Line{
if self.l2 == nil{
return l1!
}
if self.l1! == line{
return l2!
}
return l1!
}
/*
In 2 line points, p1 will be the first element of the array and p2 the second.
In Multiple Joint Points, p1 will never change and the following lines of the array will relay on p2.
*/
func setLines(lines:NSArray){
self.l1 = nil
self.l2 = nil
if lines.count > 0 {
self.connectedLines = lines
self.l1 = (lines[0] as! Line)
if lines.count > 1 {
self.l2 = (lines[1] as! Line)
}
}
}
}
|
//
// InterestsMainTableViewController.swift
// Connect2U
//
// Created by Cory Green on 11/19/14.
// Copyright (c) 2014 com.Cory. All rights reserved.
//
import UIKit
class InterestsMainTableViewController: UITableViewController {
@IBOutlet weak var interestsList: UITableViewCell!
@IBOutlet weak var automotive: UITableViewCell!
@IBOutlet weak var collecting: UITableViewCell!
@IBOutlet weak var music: UITableViewCell!
@IBOutlet weak var games: UITableViewCell!
@IBOutlet weak var art: UITableViewCell!
@IBOutlet weak var science: UITableViewCell!
@IBOutlet weak var nature: UITableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
self.setColors()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// setting colors for the view //
func setColors(){
var colorPalette = ColorPalettes()
self.view.backgroundColor = colorPalette.lightBlueColor
interestsList.backgroundColor = colorPalette.greenColor
automotive.backgroundColor = colorPalette.greenColor
collecting.backgroundColor = colorPalette.greenColor
music.backgroundColor = colorPalette.greenColor
games.backgroundColor = colorPalette.greenColor
art.backgroundColor = colorPalette.greenColor
science.backgroundColor = colorPalette.greenColor
nature.backgroundColor = colorPalette.greenColor
}
}
|
//
// ViewController.swift
// BigLittleMatcherXcodeProj
//
// Created by Steven Penava Jr. on 7/31/17.
// Copyright ยฉ 2017 Steven Penava Jr. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet var BigsTextView: NSTextView!
@IBOutlet var LittlesTextView: NSTextView!
@IBAction func LoadCSV_Click(_ sender: Any) {
let fileOpener:NSOpenPanel = NSOpenPanel()
fileOpener.allowsMultipleSelection = false
fileOpener.canChooseFiles = true
fileOpener.canChooseDirectories = false
fileOpener.allowedFileTypes = ["csv"]
fileOpener.runModal()
let chosenCSV:String = fileOpener.url!.absoluteString
if (chosenCSV != nil) {
// file exists
}
else {
// file was not chosen
}
}
func disableTextViews() {
BigsTextView.isEditable = false
LittlesTextView.isEditable = false
}
override func viewDidLoad() {
super.viewDidLoad()
disableTextViews()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
|
//
// Observer.swift
// TMDb
//
// Created by Joshua Lamson on 3/19/21.
//
import Foundation
import UIKit
class ObservableViewModel<VC : UIViewController, Data> {
private(set) var current: Data? = nil
private(set) var observations: [UUID : (Data) -> Void] = [:]
@discardableResult
func observeForLifetime(
of observer: VC,
_ closure: @escaping (VC, Data) -> Void
) -> ObservationToken {
let id = UUID()
observations[id] = { [weak self, weak observer] data in
// If the observing object is no longer in memory, remove this observation
guard let observer = observer else {
self?.observations.removeValue(forKey: id)
return
}
// Call the provided closure
self?.onMain { closure(observer, data) }
}
let safeCurrent = current
if (safeCurrent != nil) {
onMain { closure(observer, safeCurrent!) }
}
return ObservationToken { [weak self] in
self?.observations.removeValue(forKey: id)
}
}
func publish(_ data: Data) {
for (_, observer) in observations {
onMain {
// Ignore UUID, our wrapped observer above will check for presence of observer
observer(data)
}
}
}
private func onMain(_ block: @escaping () -> Void) {
DispatchQueue.main.async {
block()
}
}
}
class ObservationToken {
private let cancellationClosure: () -> Void
init(cancellationClosure: @escaping () -> Void) {
self.cancellationClosure = cancellationClosure
}
func cancel() {
cancellationClosure()
}
}
|
//
// SecondViewController.swift
// Petgram
//
// Created by ๆฏใฌใค on 2019/04/08.
// Copyright ยฉ 2019ๅนด SHI LEI. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
|
//
// ValidParenthesesTest.swift
// LeetCode
//
// Created by ZhouMin on 2019/11/26.
// Copyright ยฉ 2019 ZhouMin. All rights reserved.
//
import Cocoa
class ValidParenthesesTest: NSObject {
override init() {
let string = "{[]}"
print(ValidParentheses1().isValid(string))
}
}
|
//
// NavigationViewController.swift
// IndianBibles
//
// Created by Admin on 25/04/21.
// Copyright ยฉ 2021 Rajeev Kalangi. All rights reserved.
//
import UIKit
class NavigationViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.prefersLargeTitles = true
navigationBar.isTranslucent = true
}
}
|
//
// RegionSelectVC.swift
// Shopping_W
//
// Created by wanwu on 2018/2/6.
// Copyright ยฉ 2018ๅนด wanwu. All rights reserved.
//
import UIKit
import RealmSwift
import Realm
class RegionSelectVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: CustomTableView!
var models: [String]!
var selectAction: ((Int) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let touch = touches.first {
let point = touch.location(in: self.view)
if !tableView.frame.contains(point) {
self.dismiss(animated: true, completion: nil)
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell!.textLabel?.text = models[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectAction?(indexPath.row)
self.dismiss(animated: true, completion: nil)
}
}
|
//
// Weather.swift
// CurrentWeatherApp
//
// Created by XCodeClub on 2019-01-23.
// Copyright ยฉ 2019 Kjonza. All rights reserved.
//
import Foundation
// This structure represents the encompassing object in the remote source data
struct Weather:Decodable {
var latitude: Float?
var longtitude: Float?
var timezone: String?
var currently: Currently?
var hourly: Hourly?
var offset: Float?
}
|
//
// DateAgoTests.swift
// DateAgoTests
//
// Created by Cristhian Leรณn on 9/19/18.
// Copyright ยฉ 2018 Cristhian Leรณn. All rights reserved.
//
import XCTest
import DateAgo
class DateAgoTests: XCTestCase {
let minute: TimeInterval = 60
let hour: TimeInterval = 3_600
let day: TimeInterval = 86_400
let week: TimeInterval = 604_800
let month: TimeInterval = 2_419_200
let year: TimeInterval = 29_030_400
func test_GetUnitAndQuotient_TwoMinutesAgo() {
let time = Date(timeIntervalSinceNow: -minute * 2)
let interval = time.timeAgo(as: .minute)
XCTAssertEqual(interval.value, 2)
XCTAssertEqual(interval.unit, .minute)
}
func test_GetUnitAndQuotient_TwoHoursAgo() {
let time = Date(timeIntervalSinceNow: -hour * 2)
let interval = time.timeAgo(as: .hour)
XCTAssertEqual(interval.value, 2)
XCTAssertEqual(interval.unit, .hour)
}
func test_GetUnitAndQuotient_TwoDaysAgo() {
let time = Date(timeIntervalSinceNow: -day * 2)
let interval = time.timeAgo(as: .day)
XCTAssertEqual(interval.value, 2)
XCTAssertEqual(interval.unit, .day)
}
func test_GetUnitAndQuotient_TwoWeeksAgo() {
let time = Date(timeIntervalSinceNow: -week * 2)
let interval = time.timeAgo(as: .week)
XCTAssertEqual(interval.value, 2)
XCTAssertEqual(interval.unit, .week)
}
func test_GetUnitAndQuotient_TwoMonthsAgo() {
let time = Date(timeIntervalSinceNow: -month * 2)
let interval = time.timeAgo(as: .month)
XCTAssertEqual(interval.value, 2)
XCTAssertEqual(interval.unit, .month)
}
func test_GetUnitAndQuotient_TwoYearsAgo() {
let time = Date(timeIntervalSinceNow: -year * 2)
let interval = time.timeAgo(as: .year)
XCTAssertEqual(interval.value, 2)
XCTAssertEqual(interval.unit, .year)
}
}
|
//
// CustomSessionDelegate.swift
// DesafioHurb
//
// Created by Guilherme Siepmann on 22/08/19.
// Copyright ยฉ 2019 Guilherme Siepmann. All rights reserved.
//
import Foundation
import Alamofire
class CustomSessionDelegate: SessionDelegate {
override init() {
super.init()
// Alamofire uses a block var here
sessionDidReceiveChallengeWithCompletion = { session, challenge, completion in
guard let trust = challenge.protectionSpace.serverTrust, SecTrustGetCertificateCount(trust) > 0 else {
// This case will probably get handled by ATS, but still...
completion(.cancelAuthenticationChallenge, nil)
return
}
// compare the public keys
if let serverCertificate = SecTrustGetCertificateAtIndex(trust, 0),
let serverCertificateKey = CustomSessionDelegate.publicKey(for: serverCertificate) {
if ServerTrustPolicy.publicKeys().contains(serverCertificateKey) {
completion(.useCredential, URLCredential(trust: trust))
return
}
}
completion(.cancelAuthenticationChallenge, nil)
}
}
// Implementation from Alamofire
private static func publicKey(for certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust, trustCreationStatus == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust)
}
return publicKey
}
}
|
//
// Data9.swift
// Covid19Layout
//
// Created by User on 6/24/20.
// Copyright ยฉ 2020 hung. All rights reserved.
//
import Foundation
struct Data9 {
let imageIcon: String
let nameLabel: String
}
func createData9() -> [Data9] {
let data1 = Data9(imageIcon: "iconlike", nameLabel: "Yes")
let data2 = Data9(imageIcon: "icondislike", nameLabel: "No")
return [data1, data2]
}
|
import UIKit
import SocketRocket
import Combine
// MARK: - Protocols
public protocol SocketManagerDelegate: NSObjectProtocol {
func socketDidConnect(_ socketManager: SocketManager)
func socketDidDisconnect(_ socketManager: SocketManager, reason: String, code: UInt16)
func didReceiveMessage(_ socketManager: SocketManager, message: SocketBaseMessage)
func route(_ route: SocketRoute, failedWith error: SocketErrorMessage, message: ATAErrorSocketMessage)
func didReceiveError(_ error: Error?)
}
public struct RouteFailure {
public let route: SocketRoute
public let error: SocketErrorMessage
public let message: ATAErrorSocketMessage
}
public enum WebSocketEvent {
case connected
case disconnected(String?, Int)
case text(String)
case binary(Data)
case pong(Data?)
case ping(Data?)
case error(Error?)
case viabilityChanged(Bool)
case reconnectSuggested(Bool)
case cancelled
}
// MARK: - SocketManager
public class SocketManager: NSObject, ObservableObject {
enum SMError: Error {
case invalidUrl
case invalidRoute
}
private var socket: SRWebSocket!
private var clientIdentifier: UUID!
private weak var delegate: SocketManagerDelegate!
private var handledTypes: [SocketBaseMessage.Type] = []
// the timeout duration for message sending after which the socket will try to send a new message
public var timeout: Double = 10.0
private var timeOutData: [ATAWriteSocketMessage: (date: Date, retries: Int)] = [:]
public var isVerbose: Bool = false
// the date at which the last package was went in order to delay at meast 10ms the sending of messages
private var lastSentPackage: Date = Date()
public enum ConnectionState {
case disconnecting, disconnected, connecting, connected
}
public func clearTimeOutData() {
timeOutData.removeAll()
}
public func clearTimeOutData(forRoute route: SocketRoute) {
guard let message = timeOutData.keys.filter({ $0.checkMethod == route }).first else { return }
timeOutData[message] = nil
}
@Published private(set) var state: ConnectionState = .disconnected
@Published public var isConnected: Bool = false
// combine values
private var subscriptions = Set<AnyCancellable>()
private var pingSubscriptions = Set<AnyCancellable>()
public var useCombine: Bool = false {
didSet {
if useCombine && subscriptions.isEmpty {
loadObservers()
} else if !useCombine && !subscriptions.isEmpty {
subscriptions.removeAll()
}
}
}
// errors
public var errorPublisher: AnyPublisher<Error?, Error> {
errorSubject.eraseToAnyPublisher()
}
private var errorSubject: PassthroughSubject<Error?, Error> = PassthroughSubject<Error?, Error>()
// messages
public var messagesPublisher: AnyPublisher<SocketBaseMessage, Error> {
messagesSubject.eraseToAnyPublisher()
}
private var messagesSubject: PassthroughSubject<SocketBaseMessage, Error> = PassthroughSubject<SocketBaseMessage, Error>()
// route fail
public var routeFailedPublisher: AnyPublisher<RouteFailure, Error> {
routeFailedSubject.eraseToAnyPublisher()
}
private var routeFailedSubject: PassthroughSubject<RouteFailure, Error> = PassthroughSubject<RouteFailure, Error>()
private var eventPublisher: PassthroughSubject<WebSocketEvent, Error> = PassthroughSubject<WebSocketEvent, Error>()
// conf
public var handleBackgroundMode: Bool = true
public var backgroundModeHandler: (() -> Void)?
public var handleConnectedStateAutomatically: Bool = true
public var timerDuration: Double! {
didSet {
startPings()
}
}
public init(root: URL,
requestCompletion: ((inout URLRequest) -> Void)? = nil,
clientIdentifier: UUID,
delegate: SocketManagerDelegate,
handledTypes: [SocketBaseMessage.Type]) {
super.init()
var request = URLRequest(url: root)
request.timeoutInterval = 30
requestCompletion?(&request)
socket = SRWebSocket(url: root, protocols: request.allHTTPHeaderFields?.values.compactMap({ $0 }))
socket.delegate = self
encoder.outputFormatting = .prettyPrinted
self.clientIdentifier = clientIdentifier
self.delegate = delegate
self.handledTypes = handledTypes
decoder.keyDecodingStrategy = .convertFromSnakeCase
if timerDuration == nil {
timerDuration = 30
}
handleLifeCycle()
loadObservers()
// set the isConected published value
$state
.sink { [weak self] state in
self?.log("Change state to \(state) ๐")
self?.isConnected = state == .connected
}
.store(in: &subscriptions)
}
private(set) public var appIsInForeground: Bool = true
private func handleLifeCycle() {
startPings()
NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { [weak self] _ in
guard let self = self else { return }
if self.handleBackgroundMode {
self.appIsInForeground = false
self.disconnect()
self.pingSubscriptions.removeAll()
} else {
self.backgroundModeHandler?()
}
}
NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { [weak self] _ in
self?.appIsInForeground = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
self?.connect()
self?.startPings()
}
}
}
public func socketDidlMoveToBackground() {
appIsInForeground = false
disconnect()
pingSubscriptions.removeAll()
}
private func startPings() {
pingSubscriptions.removeAll()
Timer
.publish(every: timerDuration, on: .main, in: .default)
.autoconnect()
.sink { [weak self] _ in
self?.ping()
}
.store(in: &pingSubscriptions)
}
// Combine stuff
private func loadObservers() {
}
public func publisher<T: SocketBaseMessage>() -> AnyPublisher<T, Error> {
eventPublisher
.compactMap { [weak self] event -> Data? in
switch event {
case .binary(let data): return data
case .text(let text):
self?.log("Received - \(text)")
if let data = text.data(using: .utf8) {
return data
}
default: ()
}
return nil
}
.decode(type: T.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
public func connect() {
log("CONNECT(๐)")
guard appIsInForeground, [.connecting, .connected].contains(state) == false else { return }
log("SEND CONNEXION MESSAGE ๐ง")
state = .connecting
socket.open()
}
public func disconnect() {
log("DISCONNECTING")
state = .disconnecting
socket.close()
}
public func update(to state: ConnectionState) {
self.state = state
}
// send/receive messages
private let decoder: JSONDecoder = JSONDecoder()
private let encoder: JSONEncoder = JSONEncoder()
func handle(_ data: Data) {
log("Received Data \(String(data: data, encoding: .utf8) ?? "")")
handledTypes.forEach { SocketType in
if let message = try? decoder.decode(SocketType, from: data) {
removeObserver(for: message)
if let ataMessage = message as? ATAErrorSocketMessage,
ataMessage.error.errorCode != 0 {
delegate?.route(ataMessage.method, failedWith: ataMessage.error, message: ataMessage)
if useCombine {
routeFailedSubject.send(RouteFailure(route: ataMessage.method, error: ataMessage.error, message: ataMessage))
}
} else {
delegate?.didReceiveMessage(self, message: message)
if useCombine {
messagesSubject.send(message)
}
}
}
}
}
// concurrence queues https://medium.com/cubo-ai/concurrency-thread-safety-in-swift-5281535f7d3a
private let messageQueue = DispatchQueue(label: "sendQueue", attributes: .concurrent)
private let minimumSendDelay: TimeInterval = 0.01
public func send(_ message: SocketBaseMessage) {
guard let data = try? encoder.encode(message) else { return }
log("Send \(String(data: data, encoding: .utf8) ?? "")")
// add a minimul delay of 10ms between each messages
let interval = Date().timeIntervalSince(lastSentPackage) / 100.0
let delay = interval <= minimumSendDelay ? minimumSendDelay : 0
lastSentPackage = Date().addingTimeInterval(minimumSendDelay)
messageQueue.asyncAfter(deadline: .now() + delay, flags: .barrier) { [weak self] in
try? self?.socket.send(data: data)
}
if let writeMsg = message as? ATAWriteSocketMessage, writeMsg.awaitsAnswer {
log("Observe response for \(message.id)")
timeOutData[writeMsg] = (date: Date(), retries: 0)
handleTimeout(for: writeMsg)
}
}
private func handleTimeout(for message: ATAWriteSocketMessage) {
log("Handle timeout for \(message.id)")
// if the message received an answer, donc't handle
guard let data = timeOutData[message] else {
log("๐ response already received for \(message.id)")
return
}
// if the message was already sent more than 1 time, thorw an error
guard data.retries < 1 else {
log("๐ฅ no response received for \(message.id), triggering an error")
delegate?.route(message.method, failedWith: SocketErrorMessage.retryFailed, message: ATAErrorSocketMessage(id: message.id, route: message.method))
return
}
// otherwise, dispatch a second attempt after timeout``
DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self] in
self?.retryToSend(message)
}
}
private func retryToSend(_ message: ATAWriteSocketMessage) {
log("retry To Send for \(message.id)")
guard var data = timeOutData[message] else {
log("๐ response already received for \(message.id)")
return
}
data.retries += 1
timeOutData[message] = data
handleTimeout(for: message)
send(message)
}
private func removeObserver(for message: SocketBaseMessage) {
log("Remove oObserver for \(message.id)")
if let index = timeOutData.firstIndex(where: { $0.key.id == message.id }) {
log("๐ removed")
timeOutData.remove(at: index)
} else {
log("๐ฅ no data found to remove")
}
}
public var logEmote: String = "๐งฆ"
func log(_ message: String) {
guard isVerbose == true else { return }
print("\(logEmote) \(String(describing: message))")
}
func reconnect(after seconds: Double = 0) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { [weak self] in
self?.connect()
}
}
public func ping() {
guard isConnected else { return }
log("send ping ๐")
try? socket.sendPing("".data(using: .utf8)!)
}
// MARK: - Combine
// private let
}
extension SocketManager: SRWebSocketDelegate {
public func webSocketDidOpen(_ webSocket: SRWebSocket) {
eventPublisher.send(.connected)
log("Connected")
if handleConnectedStateAutomatically {
state = .connected
}
delegate?.socketDidConnect(self)
}
public func webSocket(_ webSocket: SRWebSocket, didReceiveMessage message: Any) {
switch message {
case is Data:
let data = message as! Data
eventPublisher.send(.binary(data))
handle(data)
case is String:
guard let data = (message as? String)?.data(using: .utf8) else { return }
eventPublisher.send(.binary(data))
handle(data)
default: ()
}
}
public func webSocket(_ webSocket: SRWebSocket, didReceivePong pongData: Data?) {
eventPublisher.send(.pong(pongData))
log("pong")
}
public func webSocket(_ webSocket: SRWebSocket, didReceiveMessageWith string: String) {
eventPublisher.send(.text(string))
}
public func webSocket(_ webSocket: SRWebSocket, didFailWithError error: Error) {
eventPublisher.send(.error(error))
log("Error - \(String(describing: error))")
delegate.didReceiveError(error)
if useCombine {
errorSubject.send(error)
}
// if let wsError = error as? Starscream.WSError {
// switch (wsError.type, wsError.code) {
// case (.securityError, 1): reconnect(after: 5)
// default: ()
// }
// }
//
// if let httpError = error as? Starscream.HTTPUpgradeError {
// switch httpError {
// case .notAnUpgrade(200, _): reconnect(after: 5)
// default: ()
// }
// }
}
public func webSocket(_ webSocket: SRWebSocket, didCloseWithCode code: Int, reason: String?, wasClean: Bool) {
guard code != SRStatusCode.codeGoingAway.rawValue else {
reconnect(after: 5)
return
}
eventPublisher.send(.disconnected(reason, code))
log("Disonnected \(reason ?? "")")
state = .disconnected
delegate?.socketDidDisconnect(self, reason: reason ?? "", code: UInt16(code))
}
public func webSocket(_ webSocket: SRWebSocket, didReceivePingWith data: Data?) {
eventPublisher.send(.ping(data))
log("ping")
}
public func webSocket(_ webSocket: SRWebSocket, didReceiveMessageWith data: Data) {
eventPublisher.send(.binary(data))
handle(data)
}
public func webSocketShouldConvertTextFrameToString(_ webSocket: SRWebSocket) -> Bool {
true
}
}
//
//extension SocketManager: WebSocketDelegate {
// public func didReceive(event: WebSocketEvent, client: WebSocketClient) {
// eventPublisher.send(event)
//
// switch event {
// case .connected(_):
// log("Connected")
// if handleConnectedStateAutomatically {
// state = .connected
// }
// delegate?.socketDidConnect(self)
//
// case .disconnected(let reason, let code):
//
// case .text(let text):
// log("Received - \(text)")
// if let data = text.data(using: .utf8) {
// handle(data)
// }
//
// case .binary(let data):
// handle(data)
//
// case .error(let error):
// log("Error - \(String(describing: error))")
// delegate.didReceiveError(error)
// if useCombine {
// errorSubject.send(error)
// }
// if let wsError = error as? Starscream.WSError {
// switch (wsError.type, wsError.code) {
// case (.securityError, 1): reconnect(after: 5)
// default: ()
// }
// }
//
// if let httpError = error as? Starscream.HTTPUpgradeError {
// switch httpError {
// case .notAnUpgrade(200, _): reconnect(after: 5)
// default: ()
// }
// }
//
// case .reconnectSuggested:
// log("reconnectSuggested")
// state = .disconnected
// connect()
//
// case .cancelled:
// log("cancelled")
// if state != .disconnecting {
// // try to reconnect
// messageQueue.asyncAfter(deadline: .now() + 5, flags: .barrier) { [weak self] in
// self?.connect()
// }
// }
// state = .disconnected
//
// case .viabilityChanged(let success):
// log("viabilityChanged \(success)")
// if success == true, state == .disconnected {
// state = .connecting
// connect()
// }
// if state != .connecting {
// state = success ? .connected : .disconnected
// }
//
// case .pong: log("pong")
// case .ping: log("ping")
// }
// }
//}
|
import Quick
import Nimble
@testable import BestPractices
class ShiftTranslatorSpec: QuickSpec {
override func spec() {
var subject: ShiftTranslator!
beforeEach {
subject = ShiftTranslator()
}
describe(".translateSlider") {
it("returns 0.25 when at -2") {
expect(subject.translateSlider(value: -2)).to(beCloseTo(0.25))
}
it("returns 0.5 when at -1") {
expect(subject.translateSlider(value: -1)).to(beCloseTo(0.5))
}
it("returns 1 when at 0") {
expect(subject.translateSlider(value: 0)).to(equal(1))
}
it("returns 2 when at 1") {
expect(subject.translateSlider(value: 1)).to(beCloseTo(2))
}
it("returns 4 when at 2") {
expect(subject.translateSlider(value: 2)).to(beCloseTo(4))
}
}
}
}
|
//
// File.swift
// ScoutingApp2016
//
// Created by Oran Luzon on 1/26/16.
// Copyright ยฉ 2016 Sciborgs. All rights reserved.
//
import UIKit
class RoundSelectionView: UIView, UITableViewDelegate, UITableViewDataSource{
var title: UILabel!
var tableView: UITableView!
var cells: [UITableViewCell!]!
var matches: [JSON]!
var allJSONS: [String: JSON]! = [:]
init(){
super.init(frame: CGRect(x: 0, y: 0, width: Screen.width, height: Screen.height))
self.backgroundColor = UIColor.whiteColor()
self.addBackButton()
matches = []
cells = []
title = BasicLabel(frame: CGRect(x: 0, y: 0, width: Screen.width, height: Screen.height), text: "Matches", fontSize: 60, color: UIColor.darkGrayColor(), position: CGPoint(x: Screen.width/2, y: Screen.height/8))
tableView = UITableView(frame: CGRect(x: 0, y: 0, width: Screen.width, height: Screen.height - Screen.height/4), style: UITableViewStyle.Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
self.addBackButton()
BlueAlliance.sendRequestMatches(CompetitionCode.Javits, completion: {(matches: [JSON]) -> Void in
dispatch_async(dispatch_get_main_queue(), {
self.matches = matches
for match in matches {
var matchNum = String(match["match_number"].int!)
if(matchNum.characters.count != 2) {
matchNum = "0\(matchNum)"
}
self.makeCell("Qualifying Match", matchNumber: matchNum)
self.tableView.reloadData()
}
})
})
tableView.center = CGPoint(x: Screen.width/2, y: Screen.height/2 + Screen.height/8)
self.addSubview(tableView)
self.addSubview(title)
}
func back(){
self.goBack()
self.removeNavBar()
}
func makeCell(type: String, matchNumber: String){
let cell = UITableViewCell(frame: CGRect(x: 0, y: 0, width: Screen.width, height: Screen.height - Screen.height/8))
let matchType = UILabel(frame: cell.frame)
let matchNum = UILabel(frame: cell.frame)
matchType.text = type
matchNum.text = matchNumber
matchType.textAlignment = NSTextAlignment.Left
matchType.center = CGPoint(x: matchType.center.x + Screen.width * 0.05, y: matchType.center.y)
matchNum.textAlignment = NSTextAlignment.Center
if(UIDevice.currentDevice().modelName == "iPhone 5s" || UIDevice.currentDevice().modelName == "iPhone 5c" || UIDevice.currentDevice().modelName == "iPhone 5" || UIDevice.currentDevice().modelName == "iPhone 4") {
matchNum.center = CGPoint(x: matchNum.center.x + (Screen.width/2.5), y: matchNum.center.y)
}else if (UIDevice.currentDevice().modelName == "iPhone 6" || UIDevice.currentDevice().modelName == "iPhone 6s"){
matchNum.center = CGPoint(x: matchNum.center.x + (Screen.width/2.1), y: matchNum.center.y)
}else if (UIDevice.currentDevice().modelName == "iPhone 6 Plus" || UIDevice.currentDevice().modelName == "iPhone 6s Plus") {
matchNum.center = CGPoint(x: matchNum.center.x + (Screen.width/1.9), y: matchNum.center.y)
}else if (UIDevice.currentDevice().modelName == "iPad 2" || UIDevice.currentDevice().modelName == "iPad 3" || UIDevice.currentDevice().modelName == "iPad 4" || UIDevice.currentDevice().modelName == "iPad Air" || UIDevice.currentDevice().modelName == "iPad Air 2") {
matchNum.center = CGPoint(x: matchNum.center.x + (Screen.width/2.7), y: matchNum.center.y)
}else if (UIDevice.currentDevice().modelName.containsString("iPad")) {
matchNum.center = CGPoint(x: matchNum.center.x + (Screen.width/2.7), y: matchNum.center.y)
}else {
matchNum.center = CGPoint(x: matchNum.center.x + (Screen.width/2.1), y: matchNum.center.y)
}
cell.contentView.addSubview(matchType)
cell.contentView.addSubview(matchNum)
cells.append(cell)
tableView.insertSubview(cell, atIndex: cells.count-1)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cells.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return cells[indexPath.row]
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Link to team profile
getAllTeamJSONS(indexPath.row, teamIndex: 0, teamColor: "blue")
}
func getAllTeamJSONS(match: Int, teamIndex: Int, teamColor: String) {
var newColor = allJSONS.count < 3 ? "blue" : "red"
if(self.allJSONS.count < 6) {
DBManager.pull(ParseClass.SouthFlorida.rawValue, rowKey: "teamNumber", rowValue: BlueAlliance.getTeamsFromMatch(self.matches[match], color: teamColor)[teamIndex%3], finalKey: "TeamInfo", completion: {(result: JSON) -> Void in
var teamJSON = result
self.allJSONS["\(BlueAlliance.getTeamsFromMatch(self.matches[match], color: teamColor)[teamIndex%3])"] = teamJSON
self.getAllTeamJSONS(match, teamIndex: teamIndex + 1, teamColor: newColor)
})
}else {
print(self.allJSONS)
self.launchViewOnTop(TeamAssignmentView(
blueTeams: BlueAlliance.getTeamsFromMatch(self.matches[match], color: "blue"),
redTeams: BlueAlliance.getTeamsFromMatch(self.matches[match], color: "red"),
roundNumber: match+1,
mode: AssignmentMode.SCOUT,
teamJSON: self.allJSONS))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// RWItemsVC.swift
// RayWenderlich
//
// Created by Giuliano Soria Pazos on 2020-08-07.
//
import UIKit
protocol RWItemsVCDelegate: class {
func didSelectVC(with title: String)
}
class RWItemsVC: UIViewController {
enum Section { case main }
weak var delegate: RWItemsVCDelegate!
var collectionView: UICollectionView!
var cellRegistration: UICollectionView.CellRegistration<UICollectionViewListCell, String>!
var dataSource: UICollectionViewDiffableDataSource<Section, String>!
var items: [String] = ["Library", "Downloads", "My Tutorials"]
override func viewDidLoad() {
super.viewDidLoad()
configureViewController()
configureCollectionView()
configureCellRegistration()
configureDataSource()
updateData(with: self.items)
}
func configureViewController() {
view.backgroundColor = .secondarySystemBackground
navigationController?.navigationBar.tintColor = UIColor(hue:0.365, saturation:0.527, brightness:0.506, alpha:1)
title = "raywenderlich.com"
}
func configureCollectionView() {
let configuration = UICollectionLayoutListConfiguration(appearance: .sidebar)
let layout = UICollectionViewCompositionalLayout.list(using: configuration)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.addSubview(collectionView)
collectionView.pinToEdges(of: view)
collectionView.backgroundColor = .secondarySystemBackground
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "ItemCell")
// collectionView.dataSource = self
collectionView.delegate = self
}
func configureCellRegistration() {
cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, String>(handler: { cell, indexPath, name in
var configuration = UIListContentConfiguration.cell()
configuration.text = name
configuration.imageProperties.tintColor = UIColor(hue:0.365, saturation:0.527, brightness:0.506, alpha:1)
switch indexPath.row {
case 0:
configuration.image = Images.library
case 1:
configuration.image = Images.downloads
default:
configuration.image = Images.person
}
cell.contentConfiguration = configuration
cell.backgroundConfiguration = UIBackgroundConfiguration.listSidebarCell()
})
}
func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, String>(collectionView: collectionView, cellProvider: { collectionView, indexPath, name -> UICollectionViewCell? in
return collectionView.dequeueConfiguredReusableCell(using: self.cellRegistration, for: indexPath, item: name)
})
}
func updateData(with items: [String]) {
var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
snapshot.appendSections([.main])
snapshot.appendItems(items)
DispatchQueue.main.async { self.dataSource.apply(snapshot, animatingDifferences: true) }
}
}
//extension RWItemsVC: UICollectionViewDataSource {
// func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// return items.count
// }
//
// func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath)
// var contentConfiguration = UIListContentConfiguration.cell()
// contentConfiguration.text = items[indexPath.row]
//
// if indexPath.row == 0 {
// contentConfiguration.image = Images.library
// } else if indexPath.row == 1 {
// contentConfiguration.image = Images.downloads
// } else {
// contentConfiguration.image = Images.person
// }
//
// cell.contentConfiguration = contentConfiguration
// cell.backgroundConfiguration = UIBackgroundConfiguration.listSidebarCell()
// cell.tintColor = UIColor(hue:0.365, saturation:0.527, brightness:0.506, alpha:1)
//
// return cell
// }
//}
extension RWItemsVC: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let destVCTitle = items[indexPath.item]
delegate.didSelectVC(with: destVCTitle)
}
}
|
//
// ๐ฐ ๐ธ
// Project: RSSchool_T9
//
// Author: Anna Ershova
// On: 04.08.2021
//
// Copyright ยฉ 2021 RSSchool. All rights reserved.
import UIKit
extension CGPath {
static let story5path1: CGPath = {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 5.5, y: 63.5))
bezierPath.addLine(to: CGPoint(x: 7.5, y: 25.5))
bezierPath.addLine(to: CGPoint(x: 8.5, y: 20.5))
bezierPath.addLine(to: CGPoint(x: 11.5, y: 14.5))
bezierPath.addCurve(to: CGPoint(x: 19.5, y: 5.5), controlPoint1: CGPoint(x: 11.5, y: 14.5), controlPoint2: CGPoint(x: 13.5, y: 10.5))
bezierPath.addCurve(to: CGPoint(x: 55.5, y: 6.5), controlPoint1: CGPoint(x: 25.5, y: 0.5), controlPoint2: CGPoint(x: 43.5, y: -3.5))
bezierPath.addCurve(to: CGPoint(x: 65.5, y: 25.5), controlPoint1: CGPoint(x: 67.5, y: 16.5), controlPoint2: CGPoint(x: 65.5, y: 25.5))
bezierPath.addLine(to: CGPoint(x: 66.5, y: 27.5))
bezierPath.addLine(to: CGPoint(x: 69.5, y: 63.5))
bezierPath.addLine(to: CGPoint(x: 48.5, y: 78.5))
bezierPath.addLine(to: CGPoint(x: 26.5, y: 78.5))
bezierPath.addLine(to: CGPoint(x: 5.5, y: 63.5))
bezierPath.close()
bezierPath.append({
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 32, y: 76.5))
bezier2Path.addCurve(to: CGPoint(x: 32, y: 37.5), controlPoint1: CGPoint(x: 32, y: 76.5), controlPoint2: CGPoint(x: 32, y: 38.5))
bezier2Path.addCurve(to: CGPoint(x: 12, y: 32.5), controlPoint1: CGPoint(x: 32, y: 36.5), controlPoint2: CGPoint(x: 12, y: 32.5))
bezier2Path.addLine(to: CGPoint(x: 12, y: 28.5))
bezier2Path.addLine(to: CGPoint(x: 63, y: 28.5))
bezier2Path.addLine(to: CGPoint(x: 63, y: 32.5))
bezier2Path.addLine(to: CGPoint(x: 44, y: 37.5))
bezier2Path.addLine(to: CGPoint(x: 44, y: 76.5))
bezier2Path.addLine(to: CGPoint(x: 47, y: 76.5))
bezier2Path.addCurve(to: CGPoint(x: 50, y: 47.5), controlPoint1: CGPoint(x: 47, y: 76.5), controlPoint2: CGPoint(x: 46.14, y: 58.79))
bezier2Path.addCurve(to: CGPoint(x: 63, y: 37.5), controlPoint1: CGPoint(x: 52.6, y: 39.92), controlPoint2: CGPoint(x: 58.98, y: 37.1))
bezier2Path.addCurve(to: CGPoint(x: 65, y: 57.5), controlPoint1: CGPoint(x: 65.5, y: 37.75), controlPoint2: CGPoint(x: 65, y: 57.5))
bezier2Path.addLine(to: CGPoint(x: 65, y: 62.5))
bezier2Path.addLine(to: CGPoint(x: 67, y: 62.5))
bezier2Path.addLine(to: CGPoint(x: 65, y: 26.5))
bezier2Path.addLine(to: CGPoint(x: 10, y: 26.5))
bezier2Path.addLine(to: CGPoint(x: 7, y: 62.5))
bezier2Path.addLine(to: CGPoint(x: 10, y: 63.5))
bezier2Path.addLine(to: CGPoint(x: 12, y: 37.5))
bezier2Path.addCurve(to: CGPoint(x: 26, y: 50.5), controlPoint1: CGPoint(x: 12, y: 37.5), controlPoint2: CGPoint(x: 24, y: 36.5))
bezier2Path.addCurve(to: CGPoint(x: 28, y: 76.5), controlPoint1: CGPoint(x: 28, y: 64.5), controlPoint2: CGPoint(x: 28, y: 76.5))
bezier2Path.addLine(to: CGPoint(x: 32, y: 76.5))
bezier2Path.close()
return bezier2Path
}())
return bezierPath.cgPath
}()
static let story5path2: CGPath = {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 23.5, y: 59.5))
bezierPath.addLine(to: CGPoint(x: 26.5, y: 44.5))
bezierPath.addLine(to: CGPoint(x: 23.5, y: 42.5))
bezierPath.addLine(to: CGPoint(x: 26.5, y: 28.5))
bezierPath.addCurve(to: CGPoint(x: 11.5, y: 23.5), controlPoint1: CGPoint(x: 26.5, y: 28.5), controlPoint2: CGPoint(x: 18.5, y: 28.5))
bezierPath.addCurve(to: CGPoint(x: 7.5, y: 19.5), controlPoint1: CGPoint(x: 9.39, y: 21.99), controlPoint2: CGPoint(x: 8.78, y: 21.25))
bezierPath.addCurve(to: CGPoint(x: 3.5, y: 16.5), controlPoint1: CGPoint(x: 6.27, y: 17.82), controlPoint2: CGPoint(x: 4.53, y: 17.87))
bezierPath.addCurve(to: CGPoint(x: 1.5, y: 11.5), controlPoint1: CGPoint(x: 2.04, y: 14.56), controlPoint2: CGPoint(x: 1.5, y: 11.5))
bezierPath.addCurve(to: CGPoint(x: 28.5, y: 11.5), controlPoint1: CGPoint(x: 1.5, y: 11.5), controlPoint2: CGPoint(x: 23.5, y: 11.5))
bezierPath.addCurve(to: CGPoint(x: 34.5, y: 6.5), controlPoint1: CGPoint(x: 30.27, y: 11.5), controlPoint2: CGPoint(x: 31.76, y: 8.69))
bezierPath.addCurve(to: CGPoint(x: 43.5, y: 3.5), controlPoint1: CGPoint(x: 36.72, y: 4.73), controlPoint2: CGPoint(x: 42.5, y: 3.5))
bezierPath.addCurve(to: CGPoint(x: 51.5, y: 3.5), controlPoint1: CGPoint(x: 44.12, y: 3.5), controlPoint2: CGPoint(x: 48.49, y: 3.5))
bezierPath.addCurve(to: CGPoint(x: 58.5, y: 6.5), controlPoint1: CGPoint(x: 53.35, y: 3.5), controlPoint2: CGPoint(x: 58.5, y: 6.5))
bezierPath.addLine(to: CGPoint(x: 62.5, y: 9.5))
bezierPath.addLine(to: CGPoint(x: 65.5, y: 11.5))
bezierPath.addLine(to: CGPoint(x: 90.5, y: 11.5))
bezierPath.addCurve(to: CGPoint(x: 92.5, y: 13.5), controlPoint1: CGPoint(x: 90.5, y: 11.5), controlPoint2: CGPoint(x: 96.5, y: 8.5))
bezierPath.addCurve(to: CGPoint(x: 79.5, y: 26.5), controlPoint1: CGPoint(x: 88.5, y: 18.5), controlPoint2: CGPoint(x: 82.5, y: 24.5))
bezierPath.addCurve(to: CGPoint(x: 65.5, y: 28.5), controlPoint1: CGPoint(x: 76.5, y: 28.5), controlPoint2: CGPoint(x: 65.5, y: 28.5))
bezierPath.addLine(to: CGPoint(x: 69.5, y: 42.5))
bezierPath.addLine(to: CGPoint(x: 67.5, y: 44.5))
bezierPath.addLine(to: CGPoint(x: 71.5, y: 59.5))
bezierPath.addCurve(to: CGPoint(x: 47.5, y: 71.5), controlPoint1: CGPoint(x: 71.5, y: 59.5), controlPoint2: CGPoint(x: 64.5, y: 71.5))
bezierPath.addCurve(to: CGPoint(x: 23.5, y: 59.5), controlPoint1: CGPoint(x: 30.5, y: 71.5), controlPoint2: CGPoint(x: 23.5, y: 59.5))
bezierPath.close()
bezierPath.append({
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 36.5, y: 22.5))
bezier2Path.addCurve(to: CGPoint(x: 33.5, y: 16.5), controlPoint1: CGPoint(x: 33.32, y: 21.39), controlPoint2: CGPoint(x: 30.17, y: 18.5))
bezier2Path.addCurve(to: CGPoint(x: 40.5, y: 16.5), controlPoint1: CGPoint(x: 38.5, y: 13.5), controlPoint2: CGPoint(x: 40.5, y: 16.5))
bezier2Path.addCurve(to: CGPoint(x: 40.5, y: 22.5), controlPoint1: CGPoint(x: 40.5, y: 16.5), controlPoint2: CGPoint(x: 43.5, y: 22.5))
bezier2Path.addCurve(to: CGPoint(x: 36.5, y: 22.5), controlPoint1: CGPoint(x: 39.5, y: 22.5), controlPoint2: CGPoint(x: 38.1, y: 23.06))
bezier2Path.close()
return bezier2Path
}())
bezierPath.append({
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 55.42, y: 22.26))
bezier3Path.addCurve(to: CGPoint(x: 58.19, y: 16.46), controlPoint1: CGPoint(x: 58.36, y: 21.18), controlPoint2: CGPoint(x: 61.26, y: 18.39))
bezier3Path.addCurve(to: CGPoint(x: 51.73, y: 16.46), controlPoint1: CGPoint(x: 53.58, y: 13.55), controlPoint2: CGPoint(x: 51.73, y: 16.46))
bezier3Path.addCurve(to: CGPoint(x: 51.73, y: 22.26), controlPoint1: CGPoint(x: 51.73, y: 16.46), controlPoint2: CGPoint(x: 48.96, y: 22.26))
bezier3Path.addCurve(to: CGPoint(x: 55.42, y: 22.26), controlPoint1: CGPoint(x: 52.65, y: 22.26), controlPoint2: CGPoint(x: 53.95, y: 22.8))
bezier3Path.close()
return bezier3Path
}())
return bezierPath.cgPath
}()
}
|
//
// JSONCoders.swift
// NSMWebservice
//
// Created by Marc Bauer on 16.02.18.
// Copyright ยฉ 2018 nesiumdotcom. All rights reserved.
//
import Foundation
public class WSJSONEncoder: JSONEncoder {
public override init() {
super.init()
self.dateEncodingStrategy = .formatted(ISO8601DateTimeTransformer.formatter)
}
}
public class WSJSONDecoder: JSONDecoder {
public override init() {
super.init()
self.dateDecodingStrategy = .formatted(ISO8601DateTimeTransformer.formatter)
}
}
|
//: [Previous](@previous)
import Combine
import Foundation
import PlaygroundSupport
var cancellables = Set<AnyCancellable>()
// OutputใๅบๅใใชใใงใใใซComlpetion(Success)ใๅบๅใใ
run("Empty") {
Empty<Int, Never>()
.sink(receiveCompletion: { finished in
print("receivedCompletion: \(finished)")
}, receiveValue: { value in
print("receivedValue: \(value)")
}).store(in: &cancellables)
}
PlaygroundPage.current.needsIndefiniteExecution = true
//: [Next](@next)
|
//
// ContentView.swift
// movieApp
//
// Created by Shaimaa on 22/03/2022.
//
import SwiftUI
struct firstView: View {
var body: some View {
NavigationView{
List(myMovies){ movie in
NavigationLink(destination: secondView(movie: movie)) {
moviesRowList(movie: movie)
}
}
.navigationBarTitle("movies")
}.accentColor(.white)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
firstView()
}
}
|
//
// ChimpAppView.swift
// Chimp
//
// Created by Maximilian Gravemeyer on 27.08.20.
//
import SwiftUI
struct AppView: View {
@EnvironmentObject var contactsState: ContactsState
@EnvironmentObject var authState: AuthState
var body: some View {
ZStack {
Color.white
HStack {
SideNavigationView().environmentObject(authState)
VStack {
ContactsView()
}
}
}.frame(minWidth: 900, minHeight: 500)
}
func toggleSidebar() {
NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
}
func addContact() {
contactsState.addMenuePressed.toggle()
print("Added Contact")
}
}
struct TagView: View {
@State var tagText: String
var body: some View {
Text(tagText)
.frame(width: 100, height: 20)
.foregroundColor(Color.white)
.background(Color.orange)
.cornerRadius(10)
}
}
extension View {
func Print(_ vars: Any...) -> some View {
for v in vars { print(v) }
return EmptyView()
}
}
|
//
// AddPhotoCollectionViewCell.swift
// WishList2
//
// Created by Summer Crow on 03/01/2019.
// Copyright ยฉ 2019 ghourab. All rights reserved.
//
import UIKit
class AddPhotoCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var cellImage: UIImageView!
var cellType: String?
}
|
//
// CloudStorageTest.swift
// Networkd
//
// Created by Cloud Stream on 5/5/17.
// Copyright ยฉ 2017 CloudStream LLC. All rights reserved.
//
import XCTest
@testable import Networkd
class CloudStorageTest: NetworkdTestSuite {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testThatCanAuthenticateUser()
{
// given
let username = "cariosvertel@gmail.com"
let password = "carlos"
let fakeNetwork = NetworkFake()
fakeNetwork.responseType = ResponseType.Login(true)
fakeNetwork.response = self.getResponse(type: .Login(true))
let cloud = Cloud(adapter: fakeNetwork)
var responseUser:RPUser? = nil
// when
cloud.authenticateUser(username, password: password){
user, error in
responseUser = user
}
// then
validateUser(user: responseUser)
}
func testThatHandleErrorOnLogin()
{
// given
let username = "cariosvertel@gmail.com"
let password = "carlos"
let fakeNetwork = NetworkFake()
fakeNetwork.responseType = ResponseType.Login(false)
fakeNetwork.error = self.getResponse(type: .Login(false))
let cloud = Cloud(adapter: fakeNetwork)
var responseError:RPError? = nil
// when
cloud.authenticateUser(username, password: password){
user, error in
responseError = error
}
// then
XCTAssertNotNil((responseError))
XCTAssertEqual(responseError?.localizedDescription, "Invalid email or password.")
}
func testThatConvertEmailToMD5()
{
// give
let email = "MyEmailAddress@example.com"
// when
let md5 = Cloud.covertToMD5(email:email)
// when
XCTAssertEqual(md5, "0bc83cb571cd1c50ba6f3e8a78ef1346")
}
/*
Helpers methods
*/
func validateUser(user:RPUser?)
{
// validate personal info
validateUserInfo(user: user)
// extract work Experience
XCTAssertEqual(user?.workExperiences.count,2)
let experience = user?.workExperiences.first
validateWorkExperience(experience: experience)
// validate education
XCTAssertEqual(user?.educations.count,1)
let education = user?.educations.first
validateEducation(education)
// validate interests
XCTAssertEqual(user?.interests.count,7)
let interest = user?.interests.first
validateInterest(interest)
// validate skills
XCTAssertEqual(user?.skills.count,2)
let skill = user?.skills.first
validateSkill(skill)
}
func validateUserInfo(user: RPUser?)
{
XCTAssertNotNil(user)
XCTAssertEqual(user?.id, "1")
XCTAssertEqual(user?.firstName, "Carlos")
XCTAssertEqual(user?.lastName, "Rios")
XCTAssertEqual(user?.position, "Team Lead")
XCTAssertEqual(user?.company, "Refundo")
XCTAssertEqual(user?.industry, "IT")
XCTAssertEqual(user?.location, "Barranquilla, BQ, Colombia")
XCTAssertEqual(user?.school, "Univeridad Del Norte")
XCTAssertEqual(user?.degree, "Electronic Engineer")
XCTAssertEqual(user?.forHire, false)
XCTAssertEqual(user?.token, "ab97225b2d4e0ba27a130c8887a0979e9bb9da5b")
XCTAssertEqual(user?.about, "Soy carlos")
XCTAssertEqual(user?.email, "carlos@refundo.com")
XCTAssertEqual(user?.avatar, "")
}
func validateWorkExperience(experience:RPWorkExperience?)
{
XCTAssertEqual(experience?.title, "Asistente Tecnico")
XCTAssertEqual(experience?.location, "Bogota")
XCTAssertEqual(experience?.expDescription, "Asistente tecnico")
XCTAssertEqual(experience?.company, "Iglesia Manantial de Vida en Rahway, New Jersey")
XCTAssertEqual(experience?.currentlyHere, false)
XCTAssertEqual(experience?.id, "37")
XCTAssertEqual(experience?.companyLogo, "https://logo.clearbit.com/manantialcc.org")
XCTAssertTrue(experience?.dateFrom?.timeIntervalSince1970 == 1320123600)
XCTAssertTrue(experience?.dateTo?.timeIntervalSince1970 == 1488344400)
}
func validateEducation(_ education: RPEducation?)
{
XCTAssertEqual(education?.edDescription, "Bachiller")
XCTAssertEqual(education?.degree, "Bachiller Academico")
XCTAssertEqual(education?.institution, "ColegioSanFrancisco")
XCTAssertEqual(education?.averageScore, "4.8")
XCTAssertEqual(education?.universityLogo, "https://logo.clearbit.com/colegiosanfrancisco.edu.ec")
XCTAssertEqual(education?.id, "176")
XCTAssertTrue(education?.dateFrom?.timeIntervalSince1970 == 1041397200)
XCTAssertTrue(education?.dateTo?.timeIntervalSince1970 == 1130821200)
}
func validateInterest(_ interest: RPInterest?)
{
XCTAssertEqual(interest?.id, "50")
XCTAssertEqual(interest?.title, "Development")
}
func validateSkill(_ skill: RPSkill?)
{
XCTAssertEqual(skill?.id, "50")
XCTAssertEqual(skill?.title, "Development")
}
}
|
//
// Day.swift
// OmGTU
//
// Created by Dmitry Valov on 29.01.2018.
// Copyright ยฉ 2018 Dmitry Valov. All rights reserved.
//
import UIKit
class Day: NSObject, NSCoding {
private var title:String!
private var lessons:Array<String>!
private var times:Array<String>!
override init() {
self.title = ""
self.lessons = []
self.times = []
}
init(title: String, lessons: Array<String>, times: Array<String>) {
self.title = title
self.lessons = lessons
self.times = times
}
func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: "title")
aCoder.encode(lessons, forKey: "lessons")
aCoder.encode(times, forKey: "times")
}
required convenience init?(coder aDecoder: NSCoder) {
let title = (aDecoder.decodeObject(forKey: "title") as? String)!
let lessons = (aDecoder.decodeObject(forKey: "lessons") as? Array<String>)!
let times = (aDecoder.decodeObject(forKey: "times") as? Array<String>)!
self.init(title: title, lessons: lessons, times: times)
}
var dayTitle: String {
get {
return title
}
set {
title = newValue
}
}
var dayLessons: Array<String> {
get {
return lessons
}
set {
lessons = newValue
}
}
var dayTimes: Array<String> {
get {
return times
}
set {
times = newValue
}
}
}
|
//
// ViewController.swift
// MeMe
//
// Created by Leela Krishna Chaitanya Koravi on 11/24/20.
// Copyright ยฉ 2020 Leela Krishna Chaitanya Koravi. All rights reserved.
//
import UIKit
class EditorViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate,
UITextFieldDelegate {
@IBOutlet weak var imagePickerView: UIImageView!
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var topText: UITextField!
@IBOutlet weak var bottomText: UITextField!
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var bottomToolbar: UIToolbar!
var uiBarButtonItem_Share: UIBarButtonItem!
var uiBarButtonItem_Cancel: UIBarButtonItem!
let TOP_DISPLAY_TEXT = "TOP"
let BOTTOM_DISPLAY_TEXT = "BOTTOM"
let memeTextAttributes: [NSAttributedString.Key: Any] =
[
NSAttributedString.Key.strokeColor: UIColor.black,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-CondensedBlack", size: 30)!,
NSAttributedString.Key.strokeWidth: 3.0
//NSAttributedString.Key.backgroundColor: UIColor.white
]
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Add Share, Cancel button to UINavigationBar
let navigationItem = UINavigationItem()
uiBarButtonItem_Share = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.action, target: self, action: "shareMeme")
uiBarButtonItem_Cancel = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action:"cancelMeme")
navigationItem.leftBarButtonItem = uiBarButtonItem_Share
navigationItem.rightBarButtonItem = uiBarButtonItem_Cancel
navigationItem.title = "Meme Editor"
navigationBar.setItems([navigationItem], animated: true)
setLaunchStateConfiguration()
}
func setLaunchStateConfiguration(){
imagePickerView.image = nil
//Setup TextFields for Launch State
setupTextFieldForLaunchState(topText, TOP_DISPLAY_TEXT)
setupTextFieldForLaunchState(bottomText, BOTTOM_DISPLAY_TEXT)
//Disable share, cancel button as image is not set/selected yet.
uiBarButtonItem_Share.isEnabled = false
//uiBarButtonItem_Cancel.isEnabled = false
}
func setupTextFieldForLaunchState(_ textField: UITextField, _ defaultText: String) {
textField.delegate = self
textField.defaultTextAttributes = memeTextAttributes
textField.textAlignment = .center
textField.text = defaultText
textField.isHidden = true
}
func setMemeStateConfiguration(image: UIImage){
imagePickerView.image = image
//Enable share, cancel as image is set
uiBarButtonItem_Share.isEnabled = true
uiBarButtonItem_Cancel.isEnabled = true
//Setup TextFields for Meme State
setupTextFieldForMemeState(topText, TOP_DISPLAY_TEXT)
setupTextFieldForMemeState(bottomText, BOTTOM_DISPLAY_TEXT)
}
func setupTextFieldForMemeState(_ textField: UITextField, _ defaultText: String) {
textField.isHidden = false
textField.adjustsFontSizeToFitWidth = true
textField.text = defaultText
}
@objc func shareMeme(){
//Share
let image = generateMemedImage()
let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil)
self.present(controller, animated: true, completion: nil)
//Completion handler
controller.completionWithItemsHandler = { (activityType: UIActivity.ActivityType?, completed:
Bool, arrayReturnedItems: [Any]?, error: Error?) in
if completed {
print("share completed")
self.save()
self.setLaunchStateConfiguration()
return
} else {
print("cancel")
}
if let shareError = error {
print("error while sharing: \(shareError.localizedDescription)")
}
}
}
@objc func cancelMeme(){
setLaunchStateConfiguration()
dismiss(animated: true)
}
@IBAction func PickImageFromAlbum(_ sender: Any) {
pickFromSource(.photoLibrary)
}
@IBAction func PickImageFromCamera(_ sender: Any) {
pickFromSource(.camera)
}
func pickFromSource(_ source: UIImagePickerController.SourceType) {
let controller = UIImagePickerController()
controller.delegate = self;
controller.sourceType = source
present(controller, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
setMemeStateConfiguration(image: image)
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("imagePickerControllerDidCancel")
dismiss(animated: true, completion: nil)
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if (textField.text == TOP_DISPLAY_TEXT || textField.text == BOTTOM_DISPLAY_TEXT){
textField.text = ""
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification,
object: nil)
}
@objc func keyboardWillShow(_ notification:Notification) {
//If bottom textfield is being edited.
if(bottomText.isEditing){
view.frame.origin.y -= getKeyboardHeight(notification)
}
}
@objc func keyboardWillHide(_ notification:Notification){
//If bottom textfield is being edited.
if(bottomText.isEditing){
view.frame.origin.y = 0
}
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.cgRectValue.height
}
func save() {
// Create the meme
let meme = Meme(topText1: topText.text!, bottomText1: bottomText.text!, originalImage: imagePickerView.image!, memedImage: generateMemedImage())
//Append new meme to Memes array in AppDelegate.swift
let sharedDelegateObject = UIApplication.shared.delegate
let appDelegate = sharedDelegateObject as! AppDelegate
appDelegate.memes.append(meme)
print("Current size of memes: ", appDelegate.memes.count)
//Pop to root view
if let navigationController = navigationController{
navigationController.popToRootViewController(animated: true)
}
}
func generateMemedImage() -> UIImage {
// TODO: Hide toolbar and navbar
navigationBar.isHidden = true
bottomToolbar.isHidden = true
// Render view to an image
UIGraphicsBeginImageContext(self.view.frame.size)
view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
// TODO: Show toolbar and navbar
navigationBar.isHidden = false
bottomToolbar.isHidden = false
return memedImage
}
}
|
//
// TransitionManager.swift
// Sub_rent
//
// Created by ะะฐั
ะฐั ะกะตะณะฐะป on 12/09/2019.
// Copyright ยฉ 2019 ะะฐั
ะฐั ะกะตะณะฐะป. All rights reserved.
//
import Foundation
import UIKit
class TransitionManager: NSObject, UIViewControllerAnimatedTransitioning {
var presenting = true
var subviewFrame = CGRect(x: 0, y: 0, width: 0, height: 0)
// MARK: UIViewControllerAnimatedTransitioning
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
let transformIn = CGAffineTransform(translationX: 0,
y: subviewFrame.minY)
if self.presenting {
toView.transform = transformIn
container.addSubview(fromView)
container.addSubview(toView)
let duration = self.transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: { () -> Void in
toView.transform = CGAffineTransform.identity
}, completion: { (finished) -> Void in
transitionContext.completeTransition(true)
})
} else {
fromView.transform = CGAffineTransform.identity
container.addSubview(toView)
container.addSubview(fromView)
let duration = self.transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: { () -> Void in
fromView.transform = transformIn
}, completion: { (finished) -> Void in
transitionContext.completeTransition(true)
})
}
presenting = !presenting
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
// MARK: UIViewControllerTransitioningDelegate
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
}
|
//
// NewsType.swift
// TodayNews
//
// Created by Ron Rith on 1/18/18.
// Copyright ยฉ 2018 Ron Rith. All rights reserved.
//
import Foundation
import SwiftyJSON
class NewsType{
var id: Int
var desEn: String
var secUser: SecUser
init(_ data: JSON) {
id = data["id"].int ?? 0
desEn = data["desEn"].string ?? ""
secUser = SecUser(data["secUser"])
}
init(){
id = 0
desEn = ""
secUser = SecUser()
}
}
|
//
// ProfileImageCollectionViewCell.swift
// Brizeo
//
// Created by Arturo on 4/29/16.
// Copyright ยฉ 2016 Kogi Mobile. All rights reserved.
//
import UIKit
protocol ProfileImageCollectionViewCellDelegate {
func profileImageCollectionView(_ cell: ProfileImageCollectionViewCell, onDeleteButtonClicked button: UIButton)
}
class ProfileImageCollectionViewCell: UICollectionViewCell {
// MARK: - Properties
@IBOutlet weak var imageView: UIImageView!
@IBOutlet fileprivate weak var deleteButton: UIButton!
@IBOutlet fileprivate weak var editIconImageView: UIImageView!
var delegate : ProfileImageCollectionViewCellDelegate?
var isDeleteButtonHidden: Bool {
get {
return deleteButton.isHidden
}
set {
deleteButton.isHidden = newValue
editIconImageView.isHidden = newValue
}
}
// MARK: - Actions
@IBAction func deleteButtonTapped(_ sender: UIButton) {
delegate?.profileImageCollectionView(self, onDeleteButtonClicked: sender)
}
}
|
//
// DayPickerCell.swift
// WhatsNext
//
// Created by MetroStar on 8/9/17.
// Copyright ยฉ 2017 TamerBader. All rights reserved.
//
import UIKit
class DayPickerCell: UICollectionViewCell {
@IBOutlet weak var dayName: UILabel!
@IBOutlet weak var dayNumber: UILabel!
@IBOutlet weak var notification: UIImageView!
}
|
//
// StudentInfo.swift
// OnTheMap
//
// Created by Craig Vanderzwaag on 11/27/15.
// Copyright ยฉ 2015 blueHula Studios. All rights reserved.
//
import Foundation
struct StudentInfo {
var objectID: String?
var uniqueKey: String?
var firstName = ""
var lastName = ""
var mediaURL = ""
var mapString = ""
var lat: Double?
var lon: Double?
var createdAt: NSDate?
var updatedAt: NSDate?
init(dictionary: NSDictionary) {
objectID = dictionary[UdacityClient.JSONResponseKeys.ObjectID] as? String
uniqueKey = dictionary[UdacityClient.JSONResponseKeys.UniqueKey] as? String
firstName = dictionary[UdacityClient.JSONResponseKeys.ParseFirstName] as! String
lastName = dictionary[UdacityClient.JSONResponseKeys.ParseLastName] as! String
mapString = dictionary[UdacityClient.JSONResponseKeys.MapString] as! String
mediaURL = dictionary[UdacityClient.JSONResponseKeys.MediaURL] as! String
if let latString = dictionary[UdacityClient.JSONResponseKeys.Latitude] as? NSNumber {
lat = latString.doubleValue
}
if let lonString = dictionary[UdacityClient.JSONResponseKeys.Longitude] as? NSNumber {
lon = lonString.doubleValue
}
if let timeString = dictionary[UdacityClient.JSONResponseKeys.UpdatedAt] as? String {
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let timestamp = dateFormatter.dateFromString(timeString)
updatedAt = timestamp
}
}
static func studentsFromResults(results: [[String : AnyObject]]) -> [StudentInfo] {
var students = [StudentInfo]()
for result in results {
students.append(StudentInfo(dictionary: result))
}
return students
}
}
|
import Foundation
import RealmSwift
class RoutineRunner {
var routine:RoutineInProgress?
var currentWorkout:WorkoutInProgress?
var currentLift:LiftInProgress?
var previousLift:LiftInProgress?
var timer: Timer?
var position = Position()
init(routine:RoutineInProgress){
self.routine = routine
self.currentWorkout = routine.workout.first
self.currentLift = getFirstLiftOfWorkout()
}
func getFirstLiftOfWorkout() -> LiftInProgress? {
return currentWorkout?.lifts.first
}
func completeLift() {
currentLift?.completed = true
}
func nextLiftSet() {
guard let currentWorkout = currentWorkout else { return }
completeLift()
position.advanceLift()
if(currentWorkout.lifts.count <= position.liftIndex){
position.resetLifts()
self.currentWorkout = nextWorkout()
}
guard let currentWorkoutLifts = self.currentWorkout?.lifts else { return }
if currentWorkoutLifts.count > 0 {
self.currentLift = currentWorkoutLifts[position.liftIndex]
}
}
private func nextWorkout() -> WorkoutInProgress? {
guard let routine = routine else { return nil }
position.advanceWorkout()
if routineHasAnotherWorkout(routine: routine, index: position.workoutIndex) {
let next = routine.workout[position.workoutIndex]
currentWorkout = next
return next
}
return nil
}
func numberOfWorkoutsInRoutine() -> Int {
return routine?.workout.count ?? 0
}
func restTimeForCurrentWorkout() -> Int {
return currentWorkout?.rest.value ?? 0
}
func changeWorkoutPosition(to workoutIndex:Int, liftIndex:Int){
guard let routine = routine else { return }
self.currentWorkout = routine.workout[workoutIndex]
self.currentLift = currentWorkout?.lifts[liftIndex]
position.hop(to: workoutIndex, liftIndex: liftIndex)
}
func isOnFirstWorkout() -> Bool {
return position.workoutIndex <= 0
}
func isOnLastLiftOfLastWorkout() -> Bool {
guard let routine = routine else { return true }
if routine.workout.count < 1 {
return true
}
let lastWorkoutPosition = routine.workout.count > 0 ? routine.workout.count - 1 : 0
let lastWorkout = routine.workout[lastWorkoutPosition]
let lastLiftPosition = lastWorkout.lifts.count > 0 ? lastWorkout.lifts.count - 1 : 0
return (position.workoutIndex >= routine.workout.count - 1) && (position.liftIndex >= lastLiftPosition)
}
func skipRest() -> Bool {
guard let currentWorkout = currentWorkout,
let rest = currentWorkout.rest.value
else { return true }
return rest <= 0
}
private func routineHasAnotherWorkout(routine:RoutineInProgress, index:Int) -> Bool {
return routine.workout.count > index
}
private func workoutHasAnotherLift(workout:WorkoutInProgress, index:Int) -> Bool {
return workout.lifts.count > index
}
}
class Position {
var liftIndex = 0
var workoutIndex = 0
func hop(to workoutIndex:Int, liftIndex:Int){
self.workoutIndex = workoutIndex
self.liftIndex = liftIndex
}
func advanceWorkout(){
workoutIndex += 1
}
func advanceLift(){
liftIndex += 1
}
func resetWorkout(){
workoutIndex = 0
}
func resetLifts(){
liftIndex = 0
}
func coordinates() -> (Int, Int) {
return (workout: workoutIndex, lift: liftIndex)
}
}
|
//
// Stack.swift
// Evaluation
//
// Created by Filip Klembara on 8/5/17.
//
//
class Stack<T> {
private var items: Array<T>
init() {
items = [T]()
}
func push(item: T) {
items.append(item)
}
@discardableResult
func pop() -> T? {
if !isEmpty() {
return items.removeLast()
}
return nil
}
func top() -> T? {
if !isEmpty() {
return items.last
}
return nil
}
var count: Int {
return items.count
}
func isEmpty() -> Bool {
return items.isEmpty
}
}
|
//
// MovieDetailsViewController.swift
// MovieViewer
//
// Created by Zubair Khan on 2/6/16.
// Copyright ยฉ 2016 zapps. All rights reserved.
//
import UIKit
import AFNetworking
class MovieDetailsViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var releaseDateLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var runtimeLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var posterView: UIImageView!
@IBOutlet weak var detailsView: UIView!
@IBOutlet weak var detailsScrollView: UIScrollView!
var posterURL: NSURL?
var lowResPosterURL: NSURL?
var titleText: String = ""
var releaseDateText: String = ""
var ratingText: String = ""
var runtimeText: String = ""
var overviewText: String = ""
override func viewDidLoad() {
super.viewDidLoad()
detailsScrollView.contentInset = UIEdgeInsets.init()
detailsScrollView.contentInset.top = 470
initView()
}
func initView() {
if let lowResPosterURL = lowResPosterURL {
posterView.setImageWithURL(lowResPosterURL)
}
if let posterURL = posterURL {
posterView.setImageWithURL(posterURL)
}
titleLabel.text = titleText
ratingLabel.text = ratingText
releaseDateLabel.text = releaseDateText
runtimeLabel.text = runtimeText
overviewLabel.text = overviewText
overviewLabel.sizeToFit()
let contentWidth = detailsScrollView.bounds.width
let contentHeight = overviewLabel.frame.height + 85
var newFrame = detailsView.frame
newFrame.size.height = contentHeight
detailsView.frame = newFrame
detailsScrollView.contentSize = CGSizeMake(contentWidth, contentHeight)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// ProductTableviewCell.swift
// ISAT NEWS
//
// Created by kadin on 10/17/17.
// Copyright ยฉ 2017 Kadin Loehr. All rights reserved.
//
import UIKit
class ProductTableViewCell: UITableViewCell {
@IBOutlet weak var productName: UILabel!
@IBOutlet weak var productPrice: UILabel!
@IBOutlet weak var productDescription: UILabel!
@IBOutlet weak var productStatus: CustomButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
productStatus.layer.cornerRadius = 20
self.selectionStyle = .none
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// RunDataView.swift
// MapKitSwift
//
// Created by Jecky on 14/11/13.
// Copyright (c) 2014ๅนด Jecky. All rights reserved.
//
import UIKit
class RunDataView: UIView {
var topImageView:UIImageView?
var bottomImageView:UIImageView?
var timeLabel:UILabel?
var mileLabel:UILabel?
var speedLabel:UILabel?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
initUI()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initUI() {
topImageView = UIImageView(frame: CGRectMake(0, 0, CGRectGetWidth(self.frame), 94))
topImageView?.backgroundColor = UIColor.whiteColor()
timeLabel = UILabel(frame: CGRectMake(0, 27, CGRectGetWidth(self.frame), 40))
timeLabel?.backgroundColor = UIColor.clearColor()
timeLabel?.textColor = UIColor.blackColor()
timeLabel?.text = "00:00:00"
timeLabel?.textAlignment = NSTextAlignment.Center
timeLabel?.font = UIFont(name: "HelveticaNeue-CondensedBold", size: 50)
topImageView?.addSubview(timeLabel!)
self.addSubview(topImageView!)
bottomImageView = UIImageView(frame: CGRectMake(0, CGRectGetMaxY(topImageView!.frame), CGRectGetWidth(self.frame), 63))
bottomImageView?.backgroundColor = UIColor.clearColor()
bottomImageView?.image = UIImage(named: "bg_run_info")?.resizableImageWithCapInsets(UIEdgeInsetsMake(10, 100, 30, 100), resizingMode: UIImageResizingMode.Stretch)
mileLabel = UILabel(frame: CGRectMake(0, 20, CGRectGetWidth(self.frame)/2, 23))
mileLabel?.backgroundColor = UIColor.clearColor()
mileLabel?.textColor = UIColor.blackColor()
mileLabel?.text = "0.00km"
mileLabel?.textAlignment = NSTextAlignment.Center
mileLabel?.font = UIFont(name: "HelveticaNeue-CondensedBold", size: 30)
bottomImageView?.addSubview(mileLabel!)
speedLabel = UILabel(frame: CGRectMake(CGRectGetWidth(self.frame)/2, 20, CGRectGetWidth(self.frame)/2, 23))
speedLabel?.backgroundColor = UIColor.clearColor()
speedLabel?.textColor = UIColor.blackColor()
speedLabel?.text = "0.00km/h"
speedLabel?.textAlignment = NSTextAlignment.Center
speedLabel?.font = UIFont(name: "HelveticaNeue-CondensedBold", size: 30)
bottomImageView?.addSubview(speedLabel!)
self.addSubview(bottomImageView!)
}
func updateRunData(totalSecond:NSInteger, totalMile:Double) {
timeLabel?.text = MKUtil.dateStringFromSecond(totalSecond)
mileLabel?.text = NSString(format: "%.2f", Double(totalMile)/1000.0) + "km"
var kmPerH = (totalMile/1000.0)/(Double(totalSecond)/3600.0);
speedLabel?.text = NSString(format: "%.2f", kmPerH) + "km/h"
}
}
|
//
// CameraViewController.swift
// blueunicorn
//
// Created by Thomas Blom on 5/15/15.
// Copyright (c) 2015 Thomas Blom. All rights reserved.
//
import UIKit
import AVFoundation
class UploadViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
} |
//
// MenuCell.swift
// Reached
//
// Created by John Wu on 2016-08-13.
// Copyright ยฉ 2016 ReachedTechnologies. All rights reserved.
//
import UIKit
class MenuCell: UICollectionViewCell {
override var highlighted: Bool {
didSet {
backgroundColor = highlighted ? UIColor.lightGrayColor() : UIColor(red: 20.4/225, green: 20.4/225, blue: 20.4/225, alpha: 1)
text.textColor = highlighted ? UIColor.whiteColor() : UIColor(red: 232/255, green: 159/255, blue: 56/255, alpha: 1)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
let text: UILabel = {
let label = UILabel()
label.textColor = UIColor(red: 232/255, green: 159/255, blue: 56/255, alpha: 1)
label.font = UIFont(name: "Montserrat-SemiBold", size: 17.0)
label.textAlignment = NSTextAlignment.Center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupViews() {
addSubview(text)
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":text]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":text]))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} |
//
// AppCoordinator.swift
// Catty Project
//
// Created by ะกะตัะณะตะน ะะพัััะฝะพะฒ on 15.07.2020.
// Copyright ยฉ 2020 Sergey Korshunov. All rights reserved.
//
import UIKit
import RxSwift
final class AppCoordinator: BaseCoordinator<Void> {
private let window: UIWindow
init(window: UIWindow) {
self.window = window
window.makeKeyAndVisible()
}
override func start() -> Observable<Void> {
if User.shared.registerLastUser() {
showContent()
} else {
showLogin()
}
return .never()
}
private func showLogin() {
coordinate(to: LoginCoordinator(window: window)).map { _ in}
.subscribe(onNext: { [weak self] in self?.showContent() }).disposed(by: bag)
}
private func showContent() {
coordinate(to: TabBarCoordinator(window: window)).map { _ in}
.subscribe(onNext: { [weak self] in
User.shared.logOut()
self?.showLogin()
}).disposed(by: bag)
}
}
|
//
// ImageCacheService.swift
// SocialApp
//
// Created by ะะธะผะฐ ะะฐะฒัะดะพะฒ on 18.01.2021.
//
import Foundation
class CacheService {
let category: String
private var rootDirectory: URL {
return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent(category)
}
init(category: String) {
self.category = category
createDirectoryIfNotExists()
}
fileprivate func createDirectoryIfNotExists() {
if FileManager.default.fileExists(atPath: rootDirectory.path) { return }
// ัะพะทะดะฐัั ะดะธัะตะบัะพัะธั
try? FileManager.default.createDirectory(at: rootDirectory, withIntermediateDirectories: true, attributes: nil)
}
// ะผะตัะพะด ะดะปั ัะพั
ัะฐะฝะตะฝะธั ัะฐะนะปะฐ
func saveCachedFile(by url: URL, data: Data?) -> Bool {
return FileManager.default.createFile(atPath: getCachedFilePath(from: url) , contents: data, attributes: nil)
}
// ะผะตัะพะด ะดะปั ััะตะฝะธั ัะฐะนะปะฐ
func readCachedFile(from url: URL) -> Data? {
return FileManager.default.contents(atPath: getCachedFilePath(from: url))
}
// ะผะตัะพะด ะดะปั ะฟัะพะฒะตัะบะธ ะฝะฐะปะธัะธั ัะฐะนะปะฐ ะฒ ะบะตัะต
func isFileExists(url: URL) -> Bool {
let isExists = FileManager.default.fileExists(atPath: getCachedFilePath(from: url))
// print("[CacheService] isFileExists: \(url.relativePath) exists: \(isExists)")
return isExists
}
fileprivate func getCachedFilePath(from url: URL) -> String {
let path = rootDirectory.appendingPathComponent(getHashedFile(from: url)).path
// print("[CacheService] getCachedFilePath: \(path)")
return path
}
// ะฟะพะปััะธัั ะฒัะตะผั ัะพะทะดะฐะฝะธั ัะฐะนะปะฐ ะฒ ะบะตัะต
func getFileCreated(for url: URL) -> Int {
guard let info = try? FileManager.default.attributesOfItem(atPath: getCachedFilePath(from: url)),
let modificationDate = info[FileAttributeKey.modificationDate] as? Date else {
return 0
}
return Int(modificationDate.timeIntervalSince1970)
}
func deleteFile(url: URL) {
try? FileManager.default.removeItem(atPath: getCachedFilePath(from: url))
}
fileprivate func getHashedFile(from url: URL) -> String {
return "\(self.hash(external: url))"
}
// ะทะฐั
ะตัะธัะพะฒะฐัั url
fileprivate func hash(external url: URL) -> String {
return url.relativePath.split(separator: "/").joined(separator: "_")
}
}
|
//
// MessagesViewController.swift
// LPFeatures
//
// Created by Milos Jakovljevic on 18/03/2020.
// Copyright ยฉ 2022 Leanplum. All rights reserved.
//
import UIKit
import Eureka
import Leanplum
class MessagesViewController: FormViewController {
enum MessageSegments: String, CaseIterable, CustomStringConvertible {
case iam = "IAM"
case push = "Push"
case actionManager = "Action Manager"
var description: String {
return rawValue
}
static var items: [String] {
return MessageSegments.allCases.map({$0.rawValue})
}
}
private let segmentedControl = UISegmentedControl(items: MessageSegments.items)
let model = ActionManagerModel()
override func viewDidLoad() {
super.viewDidLoad()
addSegmentedControl()
buildIAM()
}
override func viewDidAppear(_ animated: Bool) {
LabelRow.defaultCellSetup = { cell, row in
cell.selectionStyle = .default
row.onCellSelection { (cell, row) in
row.deselect(animated: true)
if row.tag == "systemPush" {
self.requestSystemPushPermission()
} else if row.tag == "provisionalPush" {
Leanplum.enableProvisionalPushNotifications()
} else {
Leanplum.track(row.tag!)
}
}
}
}
override func viewWillDisappear(_ animated: Bool) {
LabelRow.defaultCellSetup = nil
}
func addSegmentedControl() {
segmentedControl.addTarget(self, action: #selector(MessagesViewController.didChangeSegment), for: .valueChanged)
segmentedControl.selectedSegmentIndex = 0;
segmentedControl.sizeToFit()
navigationItem.titleView = segmentedControl
}
@objc func didChangeSegment() {
title = segmentedControl.titleForSegment(at: segmentedControl.selectedSegmentIndex)
guard let title = title, let segment = MessageSegments(rawValue: title) else {
return
}
switch segment {
case .iam:
buildIAM()
case .push:
buildPush()
case .actionManager:
buildActionManager()
}
}
func requestSystemPushPermission() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
// Handle the error here.
Log.print("Error: \(error)")
}
// Enable or disable features based on the authorization.
if granted {
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
}
|
//
// Socomo+Customs.swift
// Fugu
//
// Created by Gagandeep Arora on 08/09/17.
// Copyright ยฉ 2017 CL-macmini-88. All rights reserved.
//
import Foundation
import UIKit
//@IBDesignable
class So_UIView: UIView {
}
//@IBDesignable
class So_CustomLabel: UILabel {
}
//@IBDesignable
class So_TableViewCell: UITableViewCell {
}
//@IBDesignable
class So_UIImageView: UIImageView {
@IBInspectable
var ImageColor: UIColor {
set {
self.image = self.image?.withRenderingMode(.alwaysTemplate)
self.tintColor = newValue
//self.font = UIFont.boldProximaNova(withSize: newValue)
}
get {
return .clear
}
}
}
|
//
// ReviewsRouter.swift
// GYG
//
// Created by Mohamed Hamed on 7/21/18.
// Copyright ยฉ 2018 Hamed. All rights reserved.
//
import Foundation
import Alamofire
enum ReviewsRouter: HURLRequestConvertible {
case get(tour: String, parameters: Parameters)
case create(parameters: Parameters)
var name: String {
switch self {
case .get(let tour, _): return tour
case .create( _): return ""
}
}
var path: String {
switch self {
case .get: return "\(name)"
case .create: return "\(name)"
}
}
var method: HTTPMethod {
switch self {
case .get: return .get
case .create: return .post
}
}
var parameters: Parameters? {
switch self {
case .get( _, let parameters) : return parameters
case .create(let parameters) : return parameters
}
}
}
|
import Metal
import MetalKit
import Darwin
import mtl_start
extension StartMTL {
public func createTexture(d device:MTLDevice, w width:Int, h height:Int) -> Int32 {
let texture_width = width
let texture_height = height
let texture_stride = getStride(width: width)
let textureDesc = MTLTextureDescriptor()
textureDesc.width = texture_width
textureDesc.height = texture_height
textureDesc.usage = .shaderRead
textureDesc.pixelFormat = MTLPixelFormat.bgra8Unorm
let texture_buff = device.makeBuffer(length: texture_stride * height)
let texture = texture_buff?.makeTexture(descriptor:textureDesc, offset:0, bytesPerRow:texture_stride)
if (texture != nil) {
let index = textures.count
textures.append(texture!)
return (Int32(index))
}
return (Int32(-1))
}
public func getStride(width : Int) -> Int {
// texture_sizeline = width * 4
// texture_sizeline = 256 * (texture_sizeline / 256 + (texture_sizeline%256 >= 1 ? 1 : 0) )
let stride = width * 4;
return (256 * (stride / 256 + (stride%256 >= 1 ? 1 : 0)))
}
public func getTexturePointer(index i:Int) -> UnsafeMutablePointer<UInt32>? {
if (i < 0 || i >= textures.count) {
return (nil);
}
guard let tmpptr = textures[i].buffer?.contents() else {return (nil)}
return (tmpptr.assumingMemoryBound(to:UInt32.self))
}
public func getTextureStride(index: Int32) -> Int32 {
let i = Int(index)
guard (i >= 0 && i < textures.count) else { return Int32(0) }
print("swift stride is \(getStride(width: (textures[i]).width))")
return (Int32(getStride(width: (textures[i]).width)))
}
public func getTextureWidth(index i : Int32) -> Int32 {
guard (i < 0 || i >= textures.count) else { return Int32(0) }
return (Int32(textures[Int(i)].width))
}
public func getTextureHeight(index i : Int32) -> Int32 {
guard (i < 0 || i >= textures.count) else { return Int32(0) }
return (Int32(textures[Int(i)].height))
}
}
|
//
// RickAndMortyError.swift
// RickAndMortySwiftUIDomain
//
// Created by Edgar Luis Diaz on 26/09/2019.
// Copyright ยฉ 2019 Edgar. All rights reserved.
//
import Foundation
public enum RickAndMortyError: Error {
case parse(description: String)
case api(description: String)
}
|
//
// ItemDetailViewModel.swift
// Item Lister
//
// Created by Cemil Kocaman on 19.01.2020.
// Copyright ยฉ 2020 Cemil Kocaman Software. All rights reserved.
//
import Foundation
final class ItemDetailViewModel {
private(set) var item: Item
private(set) var imageData: Data?
init(item: Item, imageData: Data?) {
self.item = item
self.imageData = imageData
}
}
|
//
// CameraPreviewTest.swift
// TikTokTrainer
//
// Created by Hunter Jarrell on 2/13/21.
//
import SwiftUI
import AVKit
import Vision
/// View the live feed from a camera with an overlayed PoseNet skeleton on top.
/// Uses a GeometryReady to determine where to draw the skeleton at.
struct CameraPreview: View {
@Binding var currentImage: UIImage?
@Binding var result: PoseNetResult?
@Binding var orientation: AVCaptureDevice.Position
let previewImageCoordName = "previewImageSpace"
var imgOverlay: some View {
return ZStack {
if result != nil && !(result?.points.isEmpty ?? true) {
GeometryReader { geo in
PoseNetOverlay(result: result,
currentImage: currentImage,
width: geo.frame(in: .named(previewImageCoordName)).width,
height: geo.frame(in: .named(previewImageCoordName)).height,
isFrontCamera: orientation == .front)
.stroke(Color.blue, lineWidth: 4)
}
}
}
}
var body: some View {
ZStack {
if currentImage != nil {
Image(uiImage: currentImage!)
.resizable()
.aspectRatio(contentMode: .fit)
.coordinateSpace(name: previewImageCoordName)
.overlay(imgOverlay)
}
}.drawingGroup()
}
}
struct PoseNetOverlay: Shape {
let drawingPairs: [(VNHumanBodyPoseObservation.JointName, VNHumanBodyPoseObservation.JointName)] = [
(.neck, .leftShoulder),
(.leftShoulder, .leftElbow),
(.leftElbow, .leftWrist),
(.neck, .rightShoulder),
(.rightShoulder, .rightElbow),
(.rightElbow, .rightWrist),
(.neck, .root),
(.root, .leftHip),
(.leftHip, .leftKnee),
(.leftKnee, .leftAnkle),
(.root, .rightHip),
(.rightHip, .rightKnee),
(.rightKnee, .rightAnkle),
(.neck, .nose),
(.nose, .leftEye),
(.leftEye, .leftEar),
(.nose, .rightEye),
(.rightEye, .rightEar)
]
static let nodeSizeLen = 4.0
let nodeSize = CGSize(width: nodeSizeLen, height: nodeSizeLen)
var result: PoseNetResult?
var currentImage: UIImage?
var width: CGFloat
var height: CGFloat
var isFrontCamera: Bool
/// Shift a **CGPoint** relative to the height and width of the image preview
private func normalizePoint(pnt: CGPoint) -> CGPoint {
let shifted: CGPoint = VNImagePointForNormalizedPoint(pnt, Int(width), Int(height))
.applying(CGAffineTransform(scaleX: 1.0, y: -1.0))
.applying(CGAffineTransform(translationX: 0, y: height))
return shifted
}
func path(in rect: CGRect) -> Path {
var path = Path()
guard result != nil && currentImage != nil && !(result?.points.isEmpty ?? true) else {
return path
}
let poseResult = result!
poseResult.points.forEach { (_, pnt) in
let shifted = normalizePoint(pnt: pnt)
path.move(to: shifted)
path.addEllipse(in: CGRect(origin: shifted, size: nodeSize))
}
for (startJoint, endJoint) in drawingPairs {
if poseResult.points[startJoint] != nil && poseResult.points[endJoint] != nil {
let shiftedStart = normalizePoint(pnt: poseResult.points[startJoint]!)
let shiftedEnd = normalizePoint(pnt: poseResult.points[endJoint]!)
path.move(to: shiftedStart)
path.addLine(to: shiftedEnd)
}
}
return path
}
}
struct CameraPreview_Previews: PreviewProvider {
static var previews: some View {
let resultTest = PoseNetResult(points: [
.neck: CGPoint(x: 0.2, y: 0.3),
.leftShoulder: CGPoint(x: 0.3, y: 0.3),
.leftElbow: CGPoint(x: 0.35, y: 0.35),
.leftHip: CGPoint(x: 0.1, y: 0.6)
],
imageSize: nil)
CameraPreview(currentImage: .constant(UIImage(contentsOfFile: Bundle.main.path(forResource: "TestImage", ofType: "PNG")!)), result: .constant(resultTest), orientation: .constant(.front))
}
}
|
//
// WaitingOnTestResultsSheetView.swift
// CovidAlert
//
// Created by Matthew Garlington on 12/26/20.
//
import SwiftUI
struct WaitingOnTestResultsSheetView: View {
var body: some View {
NavigationView {
ScrollView {
VStack(alignment: .leading, spacing: 10) {
Image(systemName: "clock.arrow.circlepath")
.foregroundColor(.yellow)
.font(.system(size: 40))
Text("What can I do while waiting for test results?")
.bold()
.font(.system(size: 35))
Text("The turnaround time for testing varies between testing sites.")
.frame(height: 100)
.font(.system(size: 20))
Spacer()
Text("What To Know")
.bold()
.font(.title)
Text("While waiting for test results, seek emergency care right away if you develop emergency warning signs, which include: severe, constant chest pain signs, which include: severe, constant chest pain or pressure; extreme difficulty breathing; severe, constant lightheadedness; serious disorientation or unresponsiveness; or blue-tinted face or lips.")
.frame(height: 250)
.font(.system(size: 20))
Text("If your symptoms worsen, call your doctor and tell them your symptoms. They will tell you what to do next.")
.frame(height: 100)
.font(.system(size: 20))
}.padding(.horizontal)
}.padding(.horizontal)
}
}
}
struct WaitingOnTestResultsSheetView_Previews: PreviewProvider {
static var previews: some View {
WaitingOnTestResultsSheetView()
}
}
|
//
// ProfileInformation+CoreDataClass.swift
// Parrot
//
// Created by Const. on 29.03.2020.
// Copyright ยฉ 2020 Oleginc. All rights reserved.
//
//
import Foundation
import CoreData
public class ProfileInformation: NSManagedObject {
}
|
//
// EntryDetailViewController.swift
// Journal
//
// Created by Arnold Mukasa on 5/3/17.
// Copyright ยฉ 2017 Arnold Mukasa. All rights reserved.
//
import UIKit
class EntryDetailViewController: UIViewController, UITextFieldDelegate {
var entry: Entry? {
didSet {
if isViewLoaded {
updateView()
}
}
}
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var bodyTextView: UITextView!
@IBAction func clearTapped(_ sender: Any) {
titleTextField.text = ""
bodyTextView.text = ""
}
@IBAction func saveTapped(_ sender: Any) {
guard let title = titleTextField.text, let text = bodyTextView.text else {return}
if let entry = self.entry {
EntryController.shared.update(entry: entry, name: title, text: text)
} else {
EntryController.shared.add(name: title, text: text)
}
let _ = self.navigationController?.popViewController(animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateView()
}
func updateView(){
guard let entry = entry else {return}
titleTextField.text = entry.name
bodyTextView.text = entry.text
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
//
// ProductModel.swift
// HuntTimehop
//
// Created by thomas on 1/5/15.
// Copyright (c) 2015 thomas. All rights reserved.
//
import Foundation
struct Product {
var id: Int
var name: String
var tagline: String
var comments: Int
var votes: Int
var phURL: String
var screenshotUrl: String
var makerInside: Bool
var exclusive: Bool
var hunter: String
func formatNumberWithComma(number: NSNumber) -> String {
let formatter = NSNumberFormatter()
formatter.groupingSeparator = ","
formatter.groupingSize = 3
formatter.usesGroupingSeparator = true
return formatter.stringFromNumber(number)!
}
}
|
//
// collectionViewDemoVC.swift
// lab7_exercise
//
// Created by taizhou on 2019/7/30.
// Copyright ยฉ 2019 taizhou. All rights reserved.
//
import UIKit
class collectionViewDemoVC: UIViewController {
@IBOutlet var collectionView: UICollectionView!
var fruitNameArr : [String]?
override func viewDidLoad() {
super.viewDidLoad()
collectionViewInit()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//ๅๅงๅๆฐดๆๅ็จฑ็้ฃๅ๏ผไฝฟ็จNSUserDefaultsๅผๅซไนๅ่จญๅฎ็้ฃๅ
let userDefault = UserDefaults.standard
fruitNameArr = userDefault.value(forKey: "fruitName") as? [String]
}
func collectionViewInit(){
//่จปๅCollectionViewCell่RusableView
collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "reuseCell")
let cellNib = UINib(nibName: "myCollectionViewCell", bundle: nil)
collectionView.register(cellNib, forCellWithReuseIdentifier: "myCollectionViewCell")
}
}
extension collectionViewDemoVC: UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int{
//่จญๅฎๆญคCollection Viewๅซๆๅ
ฉๅSection
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//่จญๅฎSection0ๆ่ๆฐดๆๅ็จฑ้ฃๅ็ธๅ็ๆธ้๏ผSection1้กฏ็คบ20ๅCell
if(section == 0){
return fruitNameArr?.count ?? 0
}
else{
return 20
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//Section0้กฏ็คบๅฎข่ฃฝๅ็Cell๏ผSection1้กฏ็คบ็ณป็ตฑๅ็็Cell
if(indexPath.section == 0){
//ๅฏๅ่7-1-4็Step6
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCollectionViewCell", for: indexPath) as! myCollectionViewCell
cell.setCell(imgName: fruitNameArr?[indexPath.row] ?? "", title: fruitNameArr?[indexPath.row] ?? "")
return cell
}
else{
//ๅฏๅ่7-1-3็ใcollectionView(_:, cellForItemAt: )ใๅฝๅผไป็ดน
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuseCell", for: indexPath)
cell.backgroundColor = UIColor(red: 10*CGFloat(indexPath.row)/255, green: 20*CGFloat(indexPath.row)/255, blue: 30*CGFloat(indexPath.row)/255, alpha: 1)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: cell.bounds.size.width, height: cell.bounds.size.height))
label.textAlignment = .center
label.text = String(format:"%d",indexPath.row)
label.textColor = UIColor.red
for subview in cell.contentView.subviews{
subview.removeFromSuperview()
}
cell.contentView.addSubview(label)
return cell
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
//่จญ็ฝฎCollection View็Header๏ผๅฏๅ่7-1-3็ใcollectionView(_: ,viewForSupplementaryElementOfKind: ,at: )ใๅฝๅผไป็ดน
if(kind == UICollectionView.elementKindSectionHeader){
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView", for: indexPath)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: headerView.bounds.size.width, height: headerView.bounds.size.height))
label.textAlignment = .center
if(indexPath.section == 0){
label.text = "ๅฎข่ฃฝๅ collection view cell"
}
else{
label.text = "ๅ็ collection view cell"
}
for subview in headerView.subviews{
subview.removeFromSuperview()
}
headerView.addSubview(label)
return headerView
}
return UICollectionReusableView()
}
}
extension collectionViewDemoVC: UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
//้ปๆCellไฝฟ็จprint()้กฏ็คบๅบCell็index path๏ผๅฆใ0-5ใ็บSection0็็ฌฌ5ๅCell
print(indexPath.section,"-",indexPath.row)
}
}
extension collectionViewDemoVC: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
//่จญๅฎๅ
ฉๅSectionไธญCell็ๅคงๅฐ
if(indexPath.section == 0){
let width = Int((collectionView.bounds.size.width-20)/3)
let height = Int(CGFloat(width)*1.5)
return CGSize(width: width, height: height)
}
else{
let width = Int((collectionView.bounds.size.width-40)/5)
return CGSize(width: width, height: width)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
//่จญๅฎไธไธ้่ท็บ10
return 10
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
//่จญๅฎๅทฆๅณ้่ท็บ10
return 10
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
//่จญๅฎSection Header็ๅคงๅฐ
let width = collectionView.bounds.size.width
return CGSize(width: width, height: 50)
}
}
|
//
// SecondView.swift
// CustomSchemeSample
//
// Created by Yusuke Hasegawa on 2021/06/10.
//
import SwiftUI
struct SecondView: View {
var body: some View {
Text("Hello, Second View!")
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}
|
//
// Social.swift
// Socials
//
// Created by Denis Litvinskiy on 03.08.16.
// Copyright ยฉ 2016 Denis Litvinskii. All rights reserved.
//
import Foundation
class Social {
var name: String!
init(name: String) {
self.name = name
}
} |
//
// NetworkingToolS.swift
// XWSwiftWB
//
// Created by ้ฑๅญฆไผ on 2016/11/4.
// Copyright ยฉ 2016ๅนด ้ฑๅญฆไผ. All rights reserved.
//
import UIKit
import AFNetworking
//ๅฎไนๆไธพ็ฑปๅๅฏน่ฑก
enum RequestType{
case GET
case POST
}
class NetworkingToolS: AFHTTPSessionManager {
//ๅไพๅฏน่ฑก
static let shareInstance : NetworkingToolS = {
let tools = NetworkingToolS()
tools.responseSerializer.acceptableContentTypes?.insert("text/html")
tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
return tools
}()
}
extension NetworkingToolS {
//็ฝ็ป่ฏทๆฑ
func request(requestType : RequestType, URLString : String, parameters : [String : AnyObject], finished : @escaping (_ result : Any?, _ error : Error?) -> ()){
let successCallBack = { (task : URLSessionDataTask, result : Any?) in
finished(result, nil)
}
let failureCallBack = { (task : URLSessionDataTask?, error : Error) in
finished(nil, error)
}
if requestType == .GET {
get(URLString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}else{
post(URLString, parameters: parameters, progress: nil, success:successCallBack, failure: failureCallBack)
}
}
}
// MARK:- ่ฏทๆฑAccessToken
extension NetworkingToolS {
func loadAccessToken(_ code : String, finished : @escaping (_ result : [String : AnyObject]?, _ error : Error?) -> ()) {
// 1.่ทๅ่ฏทๆฑ็URLString
let urlString = "https://api.weibo.com/oauth2/access_token"
// 2.่ทๅ่ฏทๆฑ็ๅๆฐ
let parameters = ["client_id" : sinaLogin_app_key, "client_secret" : sinaLogin_app_Secret, "grant_type" : "authorization_code", "redirect_uri" : sinalogin_redirect_uri, "code" : code]
// 3.ๅ้็ฝ็ป่ฏทๆฑ
request(requestType: .POST, URLString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
finished(result as? [String : AnyObject], error as NSError?)
}
}
}
//MARK: - ่ฏทๆฑ็จๆทๆฐๆฎ
extension NetworkingToolS {
func loadUserInfo(_ access_token : String, uid : String, finished : @escaping (_ result : [String : AnyObject]?, _ error : Error?) -> ()) {
//1.่ฏทๆฑ็URL
let urlString = "https://api.weibo.com/2/users/show.json"
//2.่ฏทๆฑๅๆฐ
let parameters = ["access_token" : access_token,"uid" : uid]
//3.ๅ้่ฏทๆฑ
request(requestType: .GET, URLString: urlString, parameters: parameters as [String : AnyObject]) {(result, error)->() in
finished(result as? [String : AnyObject], error)
}
}
}
//MARK: - ่ฏทๆฑ้ฆ้กตๆฐๆฎ
extension NetworkingToolS {
func loadStatuses(since_id : Int , max_id : Int ,finished: @escaping (_ result : [[String : AnyObject]]?, _ error : Error?) -> ()) {
//1.่ฏทๆฑ็URL
let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
//่ฏทๆฑๅๆฐ
var paramete : [String : String] = [String : String]()
if max_id == 0 {
paramete = ["access_token" : (UserAccountViewModel.shareInstance.account?.access_token!)!,"since_id" : "\(since_id)"]
}else{
paramete = ["access_token" : (UserAccountViewModel.shareInstance.account?.access_token!)!,"max_id" : "\(max_id-1)"]
}
//ๅ้่ฏทๆฑ
request(requestType: .GET, URLString: urlString, parameters: paramete as [String : AnyObject]){ (result, error) -> () in
guard let resultDict = result as? [String : AnyObject] else{
finished(nil,error)
return
}
finished(resultDict["statuses"] as? [[String : AnyObject]], error)
}
}
}
//MARK: - ๅ้ๅพฎๅ
extension NetworkingToolS {
func publishStatus(status : String , isSuccess : @escaping (_ isSuccess : Bool) -> ()) {
let path : String = "https://api.weibo.com/2/statuses/update.json"
let parameters : [String : AnyObject] = ["access_token" : (UserAccountViewModel.shareInstance.account?.access_token!)! as AnyObject,"status" : status as AnyObject]
request(requestType: .POST, URLString: path, parameters: parameters) { (result, error) -> () in
guard result != nil else {
XWLog(error)
isSuccess(false)
return
}
isSuccess(true)
XWLog(result)
}
}
}
//MARK: - ๅ้ๅธฆๅพ็็ๅพฎๅ
extension NetworkingToolS {
func publishStatusAndImage(status : String ,image : UIImage, isSuccess : @escaping (_ isSuccess : Bool) -> ()) {
let path : String = "https://api.weibo.com/2/statuses/upload.json"
let parameters : [String : AnyObject] = ["access_token" : (UserAccountViewModel.shareInstance.account?.access_token!)! as AnyObject,"status" : status as AnyObject]
post(path, parameters: parameters, constructingBodyWith: { (formData) in
guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
return
}
formData.appendPart(withFileData: imageData, name: "pic", fileName: "123.png", mimeType: "image/png")
}, progress: { (progress) in
print("\(progress)")
}, success: { (dataTask, resultData) in
XWLog("resultData:\(resultData)")
isSuccess(true)
}) { (_, error) in
XWLog("error:\(error)")
isSuccess(false)
}
}
}
|
import Foundation
class UseCaseSortParameterList {
class func action(transactionID: String, ordinality ids: [String]) -> Composed.Action<Any, PCList<PCParameter>> {
return Composed
.action(PCParameterRepository.fetchList(transactionID: transactionID))
.action(PCParameterRepository.sortList(ordinality: ids))
.action(PCParameterRepository.storeList(transactionID: transactionID))
.wrap()
}
}
|
//
// ARAudioPlayer.swift
// StreamTest
//
// Created by Andrew Roach on 7/21/18.
// Copyright ยฉ 2018 Andrew Roach. All rights reserved.
//
import UIKit
import AVKit
import MediaPlayer
import RealmSwift
class ARAudioPlayer: NSObject {
static let sharedInstance: ARAudioPlayer = {
let instance = ARAudioPlayer()
return instance
}()
var nowPlayingEpisode: Episode? {
didSet {
RealmInteractor().markEpisodeAsNowPlaying(episode: nowPlayingEpisode!)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "nowPlayingEpisodeSet"), object: nil)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showPlayerRemote"), object: nil)
nowPlayingPodcast = nowPlayingEpisode?.podcast
self.configureCommandCenter()
}
}
var nowPlayingPodcast: Podcast? {
didSet {
if nowPlayingPodcast?.artwork100x100 == nil {
Downloader().downloadImageForPodcast(podcast: nowPlayingPodcast!, highRes: false)
}
if nowPlayingPodcast?.artwork600x600 == nil {
Downloader().downloadImageForPodcast(podcast: nowPlayingPodcast!, highRes: true)
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "nowPlayingPodcastSet"), object: nil)
}
}
var asset: AVAsset!
var player: AVPlayer!
var playerItem: CachingPlayerItem!
var delegate: ARAudioPlayerDelegate!
let fileName = "testPodcast1"
var shouldStartPlaying = true
func startPlayingNowPlayingEpisode() {
let url = self.nowPlayingEpisode!.downloadURL!
self.prepareToPlay(url: URL(string: url)!)
shouldStartPlaying = true
}
var playerState: AudioPlayerState = .stopped {
didSet {
if oldValue != playerState && delegate != nil {
delegate.didChangeState(oldState: oldValue, newState: playerState)
print("New State is: \(playerState)")
}
}
}
// Key-value observing context
private var playerItemContext = 0
let requiredAssetKeys = [
"playable",
"hasProtectedContent"
]
func prepareToPlay(url: URL) {
if player != nil {
removePeriodicTimeObserver()
}
let episodeTreadSafeReference = ThreadSafeReference(to: nowPlayingEpisode!)
DispatchQueue.global(qos: .background).async {
// Create the asset to play
self.playerState = .waitingForConnection
self.asset = AVAsset(url: url)
// Create a new AVPlayerItem with the asset and an
// array of asset keys to be automatically loaded
let realm = try! Realm()
guard let episode = realm.resolve(episodeTreadSafeReference) else {
return
}
let fileName = "EpisodeData_" + (episode.guid?.replacingOccurrences(of: "/", with: ""))! + "_" + (episode.podcast?.iD)!
if let episodeData = FileSystemInteractor().openFileWithFileName(fileName: fileName) {
self.playerItem = CachingPlayerItem(data: episodeData, mimeType: "audio/mpeg", fileExtension: "mp3") //This is probably going to be a problem.
self.playerItem.episode = self.nowPlayingEpisode
}
else {
self.playerItem = CachingPlayerItem(url: url)
self.playerItem.episode = self.nowPlayingEpisode
}
self.playerItem.delegate = self
// Register as an observer of the player item's status property
self.playerItem.addObserver(self,forKeyPath: #keyPath(AVPlayerItem.status),options: [.old, .new],context: &self.playerItemContext)
// Associate the player item with the player
self.player = AVPlayer(playerItem: self.playerItem)
self.playerItem.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .new, context: nil)
self.playerItem.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: nil)
self.playerItem.addObserver(self, forKeyPath: "playbackBufferFull", options: .new, context: nil)
self.player.automaticallyWaitsToMinimizeStalling = false
self.delegate.didFindDuration(duration: Float(CMTimeGetSeconds(self.asset.duration)))
DispatchQueue.main.async {
self.updateNowPlayingInfoForCurrentPlaybackItem()
}
}
}
override func observeValue(forKeyPath keyPath: String?,of object: Any?,change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
switch status {
case .readyToPlay:
if shouldStartPlaying == true {
addPeriodicTimeObserver()
if nowPlayingEpisode?.currentPlaybackDuration != 0 {
self.seekTo(nowPlayingEpisode!.currentPlaybackDuration)
}
player.play()
print("starting to play")
playerState = .playing
shouldStartPlaying = false
}
case .failed:
print("failed")
case .unknown:
print("unknown")
}
}
else if object is AVPlayerItem {
switch keyPath {
case "playbackBufferEmpty":
playerState = .buffering
default:
break
}
}
}
func changePausePlay() {
if player != nil {
if(player.timeControlStatus == AVPlayerTimeControlStatus.paused)
{
player.play()
playerState = .playing
}
else if(player.timeControlStatus==AVPlayerTimeControlStatus.playing)
{
player.pause()
playerState = .paused
}
self.updateNowPlayingInfoForCurrentPlaybackItem()
}
else {
prepareToPlay(url: URL(string: nowPlayingEpisode!.downloadURL!)!)
}
}
fileprivate let seekDuration: Float64 = 15
func skipForward() {
guard let duration = player.currentItem?.duration else{
return
}
let playerCurrentTime = CMTimeGetSeconds(player.currentTime())
let newTime = playerCurrentTime + seekDuration
if newTime < CMTimeGetSeconds(duration) {
let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
player.seek(to: time2)
self.updatePlaybackRateMetadata()
}
}
func skipBackward() {
let playerCurrentTime = CMTimeGetSeconds(player.currentTime())
var newTime = playerCurrentTime - seekDuration
if newTime < 0 {
newTime = 0
}
let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
player.seek(to: time2)
self.updatePlaybackRateMetadata()
}
func seekTo(_ position: TimeInterval) {
guard asset != nil else { return }
let newPosition = CMTimeMakeWithSeconds(position, 1)
player.seek(to: newPosition, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero, completionHandler: { (_) in
self.updatePlaybackRateMetadata()
})
removePeriodicTimeObserver()
Timer.scheduledTimer(withTimeInterval: 0.25, repeats: false) { (timer) in
self.addPeriodicTimeObserver()
}
}
var timeObserverToken: Any?
func addPeriodicTimeObserver() {
// Notify every half second
removePeriodicTimeObserver()
timeObserverToken = player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(15.0 / 60.0, Int32(NSEC_PER_SEC)), queue: DispatchQueue.main, using: { [weak self] time in
if self?.delegate != nil {
self?.delegate.progressUpdated(timeUpdated: Float(CMTimeGetSeconds(time)))
}
})
}
func removePeriodicTimeObserver() {
if let timeObserverToken = timeObserverToken {
player.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}
//Info Center
let commandCenter = MPRemoteCommandCenter.shared()
func configureCommandCenter() {
self.commandCenter.playCommand.addTarget (handler: { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let sself = self else { return .commandFailed }
sself.player.play()
sself.playerState = .playing
return .success
})
self.commandCenter.pauseCommand.addTarget (handler: { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let sself = self else { return .commandFailed }
sself.player.pause()
sself.playerState = .paused
return .success
})
self.commandCenter.skipForwardCommand.addTarget (handler: { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let sself = self else { return .commandFailed }
sself.skipForward()
return .success
})
self.commandCenter.skipBackwardCommand.addTarget (handler: { [weak self] event -> MPRemoteCommandHandlerStatus in
guard let sself = self else { return .commandFailed }
sself.skipBackward()
return .success
})
self.commandCenter.changePlaybackPositionCommand.addTarget(self, action: #selector(ARAudioPlayer.handleChangePlaybackPositionCommandEvent(event:)))
}
func handleChangePlaybackPositionCommandEvent(event: MPChangePlaybackPositionCommandEvent) -> MPRemoteCommandHandlerStatus {
self.seekTo(event.positionTime)
return .success
}
//MARK: - Now Playing Info
var nowPlayingInfo: [String : Any]?
func updateNowPlayingInfoForCurrentPlaybackItem() {
guard let currentPlaybackItem = self.nowPlayingEpisode, let currentPlaybackPodcast = self.nowPlayingPodcast else {
self.configureNowPlayingInfo(nil)
return
}
var nowPlayingInfo = [MPMediaItemPropertyTitle: currentPlaybackItem.title!,
MPMediaItemPropertyArtist: currentPlaybackPodcast.name!] as [String : Any]
if let artworkData = nowPlayingPodcast!.artwork100x100 {
let image = UIImage(data: artworkData) ?? UIImage()
let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { (_) -> UIImage in
return image
})
nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork
}
self.configureNowPlayingInfo(nowPlayingInfo as [String : AnyObject]?)
self.updatePlaybackRateMetadata()
}
func updatePlaybackRateMetadata() {
guard player.currentItem != nil else {
MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
return
}
var nowPlayingInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo ?? [String: Any]()
let duration = Float(CMTimeGetSeconds(player.currentItem!.duration))
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = duration
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = CMTimeGetSeconds(player.currentItem!.currentTime())
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
nowPlayingInfo[MPNowPlayingInfoPropertyDefaultPlaybackRate] = player.rate
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
if player.rate == 0.0 {
playerState = .paused
}
else {
playerState = .playing
}
}
// func updateNowPlayingInfoElapsedTime() {
// guard var nowPlayingInfo = self.nowPlayingInfo else { return }
// nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = CMTimeGetSeconds(player.currentItem!.currentTime())
// self.configureNowPlayingInfo(nowPlayingInfo)
// }
func configureNowPlayingInfo(_ nowPlayingInfo: [String: Any]?) {
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
self.nowPlayingInfo = nowPlayingInfo
}
}
extension ARAudioPlayer: CachingPlayerItemDelegate {
func playerItem(_ playerItem: CachingPlayerItem, didFinishDownloadingData data: Data) {
print("Finished Download")
//Now write file to disk:
DispatchQueue.main.sync {
if nowPlayingPodcast?.isSubscribed == true {
if let episode = self.playerItem.episode {
RealmInteractor().markEpisodeAsDownloaded(episode: episode)
let fileName = "EpisodeData_" + (episode.guid?.replacingOccurrences(of: "/", with: ""))! + "_" + (episode.podcast?.iD)!
FileSystemInteractor().saveFileToDisk(file: data, fileName: fileName)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "nowPlayingEpisodeDownloaded"), object: nil)
}
}
}
}
func playerItem(_ playerItem: CachingPlayerItem, didDownloadBytesSoFar bytesDownloaded: Int, outOf bytesExpected: Int){
let progress = floor(Double(bytesDownloaded)/Double(bytesExpected) * 100)
if progress.truncatingRemainder(dividingBy: 10) == 0 {
// print(progress)
}
}
func playerItem(_ playerItem: CachingPlayerItem, downloadingFailedWith error: Error) {
print("Download failed with error: \(error)")
}
}
|
import Foundation
// Template for solving a Hacker Rank Problem
class ArraysLeftRotation: HackerRank {
// Set up your inputs variables
var inputParameters: [Int] = []
var length: Int = 0
var rotations: Int = 0
var array: [Int] = []
// Read in values to the inputs
override func setUpInputs() {
inputParameters = readLine()!.components(separatedBy: " ").map{ Int($0)! }
length = inputParameters.first!
rotations = inputParameters.last!
array = readLine()!.components(separatedBy: " ").map{ Int($0)! }
}
override func addSolutions() {
// n^2 slow solution (252 seconds)
// solutions.append(solutionSlow)
solutions.append(solutionBetter)
}
func solutionSlow() -> String {
for _ in 1...rotations {
let first = array.first!
var temp = array.dropFirst().map{ Int($0) }
temp.append(first)
array = temp
}
let solution = array.flatMap { String($0) }.joined(separator: (" "))
return(solution)
}
func solutionBetter() -> String {
let firstElements = array[0..<rotations]
for i in 0..<length-rotations {
array[i] = array[i+rotations]
}
for i in 0..<rotations {
let index = length-rotations
array[index + i] = firstElements[i]
}
let solution = array.flatMap { String($0) }.joined(separator: (" "))
return(solution)
}
}
|
//
// RecordSoundsViewController.swift
// The Danya App
//
// Created by Gershy Lev on 9/8/17.
// Copyright ยฉ 2017 Gershy Lev. All rights reserved.
//
import UIKit
import AVFoundation
class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {
@IBOutlet weak var recordingLabel: UILabel!
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var microphoneButton: UIButton!
var audioRecorder:AVAudioRecorder!
var recordedAudio:RecordedAudio!
var recordingSession: AVAudioSession!
override func viewDidLoad() {
super.viewDidLoad()
recordingSession = AVAudioSession.sharedInstance()
self.navigationItem.titleView = CustomTitleLabel(text: "Voice Changer")
do {
try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try recordingSession.setActive(true)
recordingSession.requestRecordPermission({ (allowed: Bool) in
DispatchQueue.main.async {
if allowed {
} else {
// failed to record!
}
}
})
} catch {
// failed to record!
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
microphoneButton.isEnabled = true;
recordingLabel.text = "Tap to record"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func recordAudio(_ sender: UIButton) {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.recordingLabel.alpha = 0.0
self.stopButton.alpha = 0.0
}) { (Bool) -> Void in
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.recordingLabel.text = "Recording"
self.recordingLabel.alpha = 1.0
self.stopButton.alpha = 1.0
self.stopButton.isHidden = false
})
}
microphoneButton.isEnabled = false;
let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
} catch {
finishRecording(success: false)
}
}
func finishRecording(success: Bool) {
audioRecorder.stop()
audioRecorder = nil
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
@IBAction func stopButtonTapped(_ sender: UIButton) {
stopButton.isHidden = true;
microphoneButton.isEnabled = true;
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(false)
} catch {
//
}
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if flag {
recordedAudio = RecordedAudio(filePath: recorder.url, title: recorder.url.lastPathComponent)
self.performSegue(withIdentifier: "stopRecording", sender: recordedAudio)
} else {
print("Recording was not successful")
microphoneButton.isEnabled = true
stopButton.isHidden = true
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "stopRecording" {
let playSoundsVC:PlaySoundsViewController = segue.destination as! PlaySoundsViewController
let data = sender as! RecordedAudio
playSoundsVC.receivedAudio = data
}
}
}
|
//
// VehiclesViewController.swift
// assignment
//
// Created by Sahej Kaur on 07/06/18.
// Copyright ยฉ 2018 Sahej. All rights reserved.
//
import Foundation
public typealias JSONObject = [String : Any]
public enum ReturnError : Error {
case apiError(code: String, header: String?, message: String?)
case invalidJSON
}
public enum Result<T> {
case success(result: T)
case failure(error: Error)
}
public enum ValidationError: Error {
case missing(String)
case invalid(String, Any)
}
public enum Content<T> {
case empty
case success(value: T)
}
protocol RestInterface {
func get(path: String, query: String?, headers: [String: String]?, completion:@escaping (JSONObject) -> Void);
}
open class Rest: NSObject, RestInterface {
public enum HTTPMethod: String {
case put = "PUT"
case get = "GET"
case post = "POST"
case delete = "DELETE"
}
public enum APIURLs: String {
case baseUrl = "https://api.flickr.com/services/rest/"
}
/// Make a REST connection
internal func connect(method: String,
path: String,
query: String? = nil,
headers: [String: String]? = nil,
jsonObject: JSONObject? = nil,
completion: @escaping (JSONObject) -> Void) throws {
let apiURL = APIURLs.baseUrl.rawValue
guard var components = URLComponents(string: apiURL) else {
throw ValidationError.invalid("baseURL", apiURL)
}
components.path += path
if let validQuery = query, !validQuery.isEmpty {
components.query = validQuery
}
guard let url = components.url else {
throw ValidationError.invalid("path", components.path)
}
// Setup Request
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
request.httpMethod = method
request.allHTTPHeaderFields = headers
request.timeoutInterval = 30
// Setup JSON
if let jsonObject = jsonObject {
guard JSONSerialization.isValidJSONObject(jsonObject) else {
print("Invalid JSON Object: \(jsonObject)")
throw ValidationError.invalid("jsonObject", jsonObject)
}
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject,
options: [])
request.setValue("application/json", forHTTPHeaderField: "content-type")
request.httpBody = jsonData
}
let urlSession: URLSession = URLSession.shared
// Make the call
urlSession.dataTask(with: request, completionHandler: { data, response, error in
DispatchQueue.main.async {
do {
// Check response errors
if let responseError = error { throw responseError }
let jsonObject = try self.validJson(from: data)
// Successful result
completion(jsonObject)
} catch {
print("Rest Error: \(error.localizedDescription)")
completion([:])
}
}
}).resume()
}
// MARK: - Public methods
func get(path: String, query: String? = nil, headers: [String: String]? = nil, completion:@escaping (JSONObject) -> Void) {
do {
try connect(method: HTTPMethod.get.rawValue, path: path, query: query,
headers: headers, jsonObject: nil, completion: completion)
} catch {
completion([:])
}
}
}
public protocol JSONValidation {
func validJson(from data: Data?) throws -> JSONObject
}
extension Rest : JSONValidation {
public func validJson(from data: Data?) throws -> JSONObject {
guard let responseData = data else {
throw ReturnError.invalidJSON
}
// Convert JSON data to Swift JSON Object
let responseJson = try JSONSerialization.jsonObject(with: responseData, options: [])
guard let jsonObject = responseJson as? JSONObject else {
throw ReturnError.invalidJSON
}
return jsonObject
}
}
|
//
// JeopardyModel.swift
// AC-iOS-MidUnit3-Assessment
//
// Created by C4Q on 11/21/17.
// Copyright ยฉ 2017 C4Q . All rights reserved.
//
import Foundation
class Player{
var questions: [JeopardyQuestion]
var score = 0
var nextQuestionCounter = 1
var currentQuestion: JeopardyQuestion
var answer = ""
init(questions: [JeopardyQuestion]) {
self.currentQuestion = questions.first!
self.questions = questions
}
func checkAnswer(inputAnswer: String) -> Bool {
if inputAnswer.lowercased() == currentQuestion.answer.lowercased(){
score += 1
return true
}
else{
guard score != 0 else{
return false
}
score -= 1
return false
}
}
func nextQuestion() {
guard nextQuestionCounter < questions.count else{
nextQuestionCounter = 0
currentQuestion = questions.first!
return
}
currentQuestion = questions[nextQuestionCounter]
nextQuestionCounter += 1
return
}
}
|
//
// Route.swift
// ArtMap
//
// Created by Andrea Mantani on 17/02/16.
// Copyright ยฉ 2016 Andrea Mantani. All rights reserved.
//
import UIKit
import GoogleMaps
import MapKit
class Route : NSObject{
private var route : [Step]
private var polyLine : MKPolyline
private var boundingRegion : MKMapRect
//private var viewToPopulate : TourIndicationController
init(from: Marker, to: Marker, toView: UIViewController){
self.route = [Step]()
self.polyLine = MKPolyline()
self.boundingRegion = MKMapRect()
super.init()
createStep(from.getMarker().position, to: to.getMarker().position, viewToPopulate: toView)
//self.steps.append(Step(from: direction[0], to: direction[1]))
}
func createStep(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D, viewToPopulate : UIViewController){
let mapManager = MapManager()
mapManager.directions(from: from, to: to) { (route, directionInformation, boundingRegion, error) -> () in
let sendToView = viewToPopulate as! IndicatorView
if(route != nil){
self.polyLine = route!
self.boundingRegion = boundingRegion!
var distance : Double
var instructions : String
if error == nil{
for index in 0...directionInformation!["steps"]!.count - 1{
distance = Double(directionInformation!["steps"]![index]["distance"] as! String)!
instructions = directionInformation!["steps"]![index]["instructions"] as! String
self.route.append(Step(distance: distance, instructions: instructions))
}
}
sendToView.addOverlay(self.polyLine, boundingRegion: self.boundingRegion, steps: self.route)
}else{
sendToView.addOverlay(self.polyLine, boundingRegion: self.boundingRegion, steps: self.route)
}
}
}
func getRoute() -> [Step]{
return self.route
}
func getRoutePolyline() -> MKPolyline{
return self.polyLine
}
func getStepsNumber()->Int{
print(route.count)
return self.route.count
}
func getBoundingRegion() -> MKMapRect{
print(boundingRegion.size)
return self.boundingRegion
}
}
|
//
// ViewController.swift
// To Do
//
// Created by alper on 5/11/17.
// Copyright ยฉ 2017 alper. All rights reserved.
//
import UIKit
import Firebase
class ListItemTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, ButtonDelegate {
//MARK: Outlets
@IBOutlet weak var tableView: UITableView!
var isbuttonPressed: Bool = false
var didselect: Int!
var contentHeights : [CGFloat] = [0.0, 0.0]
var addNewItemView = AddNewItemViewController()
//MARK:
let database = FirebaseDataAdapter()
var addNavBarButton: UIButton!
var todoListsArray = [Users]()
var currentCellDataToBeEdited: Users?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = false
self.setNavigationBar()
self.fetchTodoList()
// self.uiimageHeightContstraint.constant = 0
Auth.auth().addStateDidChangeListener() { (auth, user) in
if user != nil {
// User is Logged in.
UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
UserDefaults.standard.synchronize()
} else {
self.navigationController?.popViewController(animated: true)
}
}
}
// MARK: Nav Bar
func setNavigationBar() {
let navItem = UINavigationItem(title: "back")
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(addNewTodo))
navItem.rightBarButtonItem = doneItem
self.navigationItem.setRightBarButton(doneItem, animated: true)
}
// MARK: Table View
internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.todoListsArray.count
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "itemListCell") as? ListItemTableViewCell ?? ListItemTableViewCell(style: .default, reuseIdentifier: "itemListCell")
//UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "itemListCell")
let user = self.todoListsArray[indexPath.row]
cell.todoLabel.text = user.value
DispatchQueue.main.async {
self.database.retriveScreenshotOfMapview(uuid: user.uniqueID) { (image) in
cell.uiimage.image = image
}
}
// if user.sharedEmail != nil {
user.sharedEmail == "" ? (cell.sharedWithLabel.isHidden = true) : (cell.sharedWithLabel.isHidden = false)
user.sharedEmail == "" ? (cell.sharedWith.isHidden = true) : (cell.sharedWith.isHidden = false)
cell.sharedWithLabel.text = user.sharedEmail!
cell.sharedButton.isHidden = true
cell.sharedButton.isEnabled = true
// }
cell.delegate = self
return cell
}
func fetchTodoList() {
self.database.getTodoList() { (snapshot) in
if let dict = snapshot.value as? [String: AnyObject] {
let user = Users()
user.setValuesForKeys(dict)
self.todoListsArray.append(user)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// var imageExist: Bool = false
// let cell = self.tableView.dequeueReusableCell(withIdentifier: "itemListCell") as? ListItemTableViewCell ?? ListItemTableViewCell(style: .default, reuseIdentifier: "itemListCell")
// if cell.imageView?.image != nil {
// imageExist = true
// }
// let user = self.todoListsArray[indexPath.row]
//
// if user.locationAdded == "false" {
// print("false")
// }
if self.didselect != nil && indexPath.row == self.didselect {
contentHeights = [250.0]
if self.todoListsArray[indexPath.row].locationAdded == "true" {
return 250
} else {
// cell.uiImageViewHeightConstraint.constant = 0
return 250
}
} else {
contentHeights = [65.0]
return 65
}
}
//MARK: Button action
func ButtonPressed(_ userAccept: UIButton, tableViewCell: ListItemTableViewCell) {
guard let buttonName = userAccept.titleLabel?.text else {
return
}
switch buttonName {
case "Edit":
let vc = UIStoryboard(name:"AddNewItem", bundle:nil).instantiateViewController(withIdentifier: "addNewView") as? AddNewItemViewController
vc?.currentCellDataToBeEdited = self.currentCellDataToBeEdited
vc?.modeCheck = .dataEdit
self.navigationController?.pushViewController(vc!, animated:true)
case "I am done":
//TODO: DB call to save the new data back to DB
break
default:
break
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("didselect", indexPath.row)
self.currentCellDataToBeEdited = self.todoListsArray[indexPath.row]
if self.didselect == nil || self.didselect != indexPath.row {
self.didselect = indexPath.row
} else {
self.didselect = nil
}
self.tableView.beginUpdates()
self.tableView.endUpdates()
// DispatchQueue.main.async {
// self.tableView.reloadData()
// }
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
}
func addNewTodo() {
let vc = UIStoryboard(name:"AddNewItem", bundle:nil).instantiateViewController(withIdentifier: "addNewView") as? AddNewItemViewController
vc?.modeCheck = .dataNew
self.navigationController?.pushViewController(vc!, animated:true)
}
}
|
import UIKit
public class QuizPage: Page {
public static var page: UIView?
public static var close: IconEffectButton?
private static var quiz : Quiz = Quiz()
public class func setup(in screen: UIView) {
QuizPage.page = UIView(frame: screen.bounds)
QuizPage.close = IconEffectButton(frame: .zero)
QuizPage.quiz = Quiz(information:
.init(question: "What will you do?", options: [
.init(title: "Confess to the police", scenarios: [
"You will either not go to prison,",
"Or go for 2 years."
]),
.init(title: "Hold out from the police", scenarios: [
"You will either go to prison for 1 year,",
"Or go for 4 years."
])
])
)
QuizPage.quiz.setFrame(frame: QuizPage.page!.bounds)
QuizPage.quiz.setCorrectAnswer(at: 0)
QuizPage.quiz.setCallback {
QuizPage.dismiss(QuizPage.close!.base())
}
QuizPage.page!.addSubview(QuizPage.quiz)
screen.addSubview(QuizPage.page!)
}
public class func present() {
QuizPage.quiz.present()
}
public class func dismiss(_ sender: UIButton!) {
QuizPage.page!.fade(type: .Out) { _ in
QuizPage.page!.removeFromSuperview()
ExplanationStory.present()
}
}
}
|
//
// NearbyPlacesTableViewCell.swift
// Spoint
//
// Created by kalyan on 18/12/17.
// Copyright ยฉ 2017 Personal. All rights reserved.
//
import UIKit
class NearbyPlacesTableViewCell: UITableViewCell {
@IBOutlet var imageview:UIImageView!
@IBOutlet var title:UILabel!
@IBOutlet var descriptionLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// Move.swift
// Skating Friends
//
// Created by Jake Oscar Te Lem on 6/11/18.
// Copyright ยฉ 2018 Jake Oscar Te Lem. All rights reserved.
//
import Foundation
enum Move : String {
case lutzTakeoff
case flipTakeoff
case loopTakeoff
case toeTakeoff
case salTakeoff
case axelTakeoff
case skating
case midair
case rotate
case fall
case backTurn
case landing
case bow
case layback
case comboSpin
}
enum Tech : String {
case Lutz
case Flip
case Loop
case Toe
case Salchow
case Axel
case Steps
case Layback
case ComboSpin
case Spiral
case JumpCombo
case None
}
enum Motion : String {
case Skating
case Spinning
case Spiral
case Midair
case Stationary
case Transition
case Landing
}
enum Goal : String {
case TechRun
case TechTotal
case CoinsRun
case CoinsTotal
case ItemsRun
case ItemsTotal
case ObstaclesRun
case ObstaclesTotal
case DoublesRun
case DoublesTotal
case TriplesRun
case TriplesTotal
case QuadsRun
case QuadsTotal
case DoubleCombo
case TriplesCombo
case QuadCombo
case SpinsRun
case SpinsTotal
case SpiralsRun
case SpiralsTotal
case Blank
}
|
//
// SearchHistory.swift
// Smashtag
//
// Created by Caroline Liu on 2015-09-19.
// Copyright (c) 2015 Caroline Liu. All rights reserved.
//
import Foundation
class SearchHistory {
static let sharedHistory = SearchHistory()
let defaults = NSUserDefaults.standardUserDefaults()
struct UserDefaultsKeys {
static let SearchHistory = "last100Searches"
}
var last100Searches: [String] {
get {
return defaults.objectForKey(UserDefaultsKeys.SearchHistory) as? [String] ?? [String]()
}
set {
defaults.setObject(newValue, forKey: UserDefaultsKeys.SearchHistory)
}
}
func addSearchTerm(searchTerm: String) {
// store the last 100 search terms
if last100Searches.count > 100 {
last100Searches.removeAtIndex(0)
}
last100Searches.append(searchTerm)
println("Added search to history: \(searchTerm)")
}
}
|
//
// RegistViewController.swift
// Mob_SMS
//
// Created by Steven on 14/11/15.
// Copyright (c) 2014ๅนด DevStore. All rights reserved.
//
import UIKit
class RegistViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,CountryViewControllerDelegate,UIAlertViewDelegate {
var defaultCode:String?
var defaultCountryName:String?
var areaArray:NSMutableArray?
var data2:CountryAndAreaCode?
var telString:String?
var Verify: VerifyViewController?
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var areaCodeField: UITextField!
@IBOutlet weak var telField: UITextField!
@IBOutlet weak var nextBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
Verify = storyboard?.instantiateViewControllerWithIdentifier("Veri") as? VerifyViewController
//่ฏทๆฑๆๆฏๆ็ๅบๅท
SMS_SDK.getZone { (state, array) -> Void in
if state.value == 1{
println("่ทๅๅบๅทๆๅ")
self.areaArray = NSMutableArray(array: array)
}else if state.value == 0{
println("่ทๅๅบๅทๅคฑ่ดฅ")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func nextStep(sender: AnyObject) {
var compareResult:Bool = false
for (var i:Int = 0;i<areaArray?.count;i++) {
var dict1:NSDictionary = areaArray?.objectAtIndex(i) as! NSDictionary
var code1:String = dict1.valueForKey("zone") as! String
println("areaCode:\(code1)")
if code1 == areaCodeField.text.stringByReplacingOccurrencesOfString("+", withString: "") {
compareResult = true
var rule1:String = dict1.valueForKey("rule") as! String
var pred:NSPredicate = NSPredicate(format:"SELF MATCHES %@",rule1)
var isMatch:Bool = pred.evaluateWithObject(telField.text)
if isMatch == false {
var alert:UIAlertView = UIAlertView(title: "ๆ็คบ", message: "ๆๆบๅท็ ๆ่ฏฏ", delegate: nil, cancelButtonTitle: "็กฎๅฎ")
alert.show()
return
}
break
}
}
if compareResult == false {
if count(telField.text) != 11 {
var alert:UIAlertView = UIAlertView(title: "ๆ็คบ", message: "ๆๆบๅท็ ๆ่ฏฏ", delegate: nil, cancelButtonTitle: "็กฎๅฎ")
alert.show()
return
}
}
var str:String = "ๅณๅฐๅ้้ช่ฏ็ ็ญไฟกๅฐ่ฟไธชๅท็ :\(areaCodeField.text) \(telField.text)"
telString = telField.text
var alert:UIAlertView = UIAlertView(title: "็กฎ่ฎคๆๆบๅท็ ", message: str, delegate: self, cancelButtonTitle: "ๅๆถ", otherButtonTitles: "็กฎๅฎ")
alert.show()
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 {
var str = areaCodeField.text.stringByReplacingOccurrencesOfString("+", withString: "")
Verify?.setPhoneAndAreaCode(telField.text, areaCodeString: str)
//่ทๅ้ช่ฏ็
SMS_SDK.getVerifyCodeByPhoneNumber(telField.text, andZone: str, result: { (state) -> Void in
switch state.value {
case 0: println("่ทๅ้ช่ฏ็ ๅคฑ่ดฅ")
var alert:UIAlertView = UIAlertView(title: "ๆ็คบ", message: "่ทๅ้ช่ฏ็ ๅคฑ่ดฅ", delegate: nil, cancelButtonTitle: "็กฎๅฎ")
alert.show()
break
case 1: println("่ทๅ้ช่ฏ็ ๆๅ")
self.presentViewController(self.Verify!, animated: true, completion: nil)
break
case 2: var alert:UIAlertView = UIAlertView(title: "่ถ
่ฟไธ้", message: "่ฏทๆฑ้ช่ฏ็ ่ถ
ไธ้๏ผ่ฏท็จๅ้่ฏใ", delegate: nil, cancelButtonTitle: "็กฎๅฎ")
alert.show()
break
default: var alert:UIAlertView = UIAlertView(title: "ๆ็คบ", message: "ๅฎขๆท็ซฏ่ฏทๆฑๅ้็ญไฟก้ช่ฏ่ฟไบ้ข็นใ", delegate: nil, cancelButtonTitle: "็กฎๅฎ")
alert.show()
break
}
})
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
}
cell?.textLabel!.text = "ๅฝๅฎถๅๅฐๅบ"
cell?.textLabel!.textColor = UIColor.darkGrayColor()
cell?.detailTextLabel?.textColor = UIColor.blackColor()
cell?.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
if data2 != nil {
cell?.detailTextLabel?.text = data2?.countryName
}else{
cell?.detailTextLabel?.text = "China"
}
var tempView = UIView(frame: CGRectMake(0, 0, 0, 0))
cell?.backgroundView = tempView
cell?.backgroundColor = UIColor.clearColor()
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("CountryVC", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "CountryVC"{
var page1 = segue.destinationViewController as! CountryViewController
page1.delegate = self
page1.areaArray = areaArray
//page1.setAreaArray(areaArray!)
}
}
func setSecondData(data: CountryAndAreaCode) {
data2 = data
println("ไปSecondไผ ่ฟๆฅ็ๆฐๆฎ๏ผ\(data.areaCode)\(data.countryName)")
areaCodeField.text = "+\(data.areaCode)"
self.tableView.reloadData()
}
}
|
//
// ViewController.swift
// HiU
//
// Created by Lady Diana Cortes on 18/09/17.
// Copyright ยฉ 2017 developer. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var splashView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
splashView.animationRepeatCount=1
let jeremyGif = UIImage.gif(name: "gif_splash")
// Uncomment the next line to prevent stretching the image
// imageView.contentMode = .ScaleAspectFit
// Uncomment the next line to set a gray color.
// You can also set a default image which get's displayed
// after the animation
// imageView.backgroundColor = UIColor.grayColor()
// Set the images from the UIImage
splashView.animationImages = jeremyGif?.images
// Set the duration of the UIImage
splashView.animationDuration = jeremyGif!.duration
// Set the repetitioncount
splashView.animationRepeatCount = 1
// Start the animation
splashView.startAnimating()
//
// let vc = self.storyboard?.instantiateViewController(withIdentifier: "Login") as! Login
// self.present(vc, animated: true, completion: nil)
let viewController:UIViewController = UIStoryboard(name: "Login", bundle: nil).instantiateViewController(withIdentifier: "Login")
self.present(viewController, animated: false, completion: nil)
// let storyboard = UIStoryboard(name: "Login", bundle: nil)
// let controller = storyboard.instantiateViewController(withIdentifier: "Login")
// self.present(controller, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// LargestKAndNegativeK.swift
// LeetCodeTests
//
// Created by dos Santos, Diego on 10/03/21.
//
import XCTest
@testable import LeetCode
//Largest K such that both K and -K exist in array
class LargestKAndNegativeK: XCTestCase {
func getLargest(_ arr: [Int]) -> Int {
let numbers = arr.sorted()
let setNumbers = Set(numbers)
for number in numbers {
if setNumbers.contains(-number) {
return -number
}
}
return 0
}
func tests() throws {
XCTAssertEqual(self.getLargest([3, 2, -2, 5, -3]), 3)
XCTAssertEqual(self.getLargest([1, 2, 3, -4]), 0)
}
}
|
import Foundation
import UIKit
import PlaygroundSupport
public class realSkeleton: UIView {
let directionLabel = UILabel()
let backgroundImage = UIImageView()
let ginningImage = UIImageView()
let spinningImage = UIImageView()
let weavingImage = UIImageView()
let dyeingImage = UIImageView()
let knittingImage = UIImageView()
let stepToGinning1 = UIImageView()
let stepToGinning2 = UIImageView()
let stepToGinning3 = UIImageView()
let stepToGinning4 = UIImageView()
let stepToGinning5 = UIImageView()
let stepToGinning6 = UIImageView()
let stepToGinning7 = UIImageView()
let stepToGinning8 = UIImageView()
let stepToGinning9 = UIImageView()
let stepToSpinning1 = UIImageView()
let stepToSpinning2 = UIImageView()
let stepToSpinning3 = UIImageView()
let stepToSpinning4 = UIImageView()
let stepToSpinning5 = UIImageView()
let stepToWeaving1 = UIImageView()
let stepToWeaving2 = UIImageView()
let stepToDyeing1 = UIImageView()
let stepToKnitting1 = UIImageView()
let ginningButton = UIButton()
let spinningButton = UIButton()
let weavingButton = UIButton()
let dyeingButton = UIButton()
let knittingButton = UIButton()
var timer = Timer()
public init(scene: UIView, stage: Int) { // Basically the viewDidLoad
super.init(frame:CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight))
setupUI()
loadSteps()
if stage == 0 {
stageGinning()
} else if stage == 1 {
stageSpinning()
} else if stage == 2 {
stageWeaving()
} else if stage == 3 {
stageDyeing()
} else if stage == 4 {
stageKnitting()
} else if stage == 5 {
goToNextScreen()
}
}
required public init(coder aDecoder: NSCoder) {
fatalError("Public Init Coder NOT working...")
}
func setupUI() {
self.frame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight)
self.backgroundColor = UIColor(red: 242, green: 242, blue: 242, alpha: 1.0)
backgroundImage.image = UIImage(named: "skeleton background.jpg")
backgroundImage.frame = CGRect(x: 0, y: 0, width: 780, height: 750)
backgroundImage.contentMode = .scaleToFill
backgroundImage.alpha = 0.1
self.addSubview(backgroundImage)
ginningImage.image = UIImage(named: "ginning process.jpeg")
ginningImage.frame = CGRect(x: 77, y: 529, width: 150, height: 150)
ginningImage.contentMode = .scaleAspectFit
ginningImage.isHidden = true
self.addSubview(ginningImage)
spinningImage.image = UIImage(named: "spinning process.jpeg")
spinningImage.frame = CGRect(x: 71, y: 281, width: 150, height: 150)
spinningImage.contentMode = .scaleAspectFit
spinningImage.isHidden = true
self.addSubview(spinningImage)
weavingImage.image = UIImage(named: "weaving process.jpeg")
weavingImage.frame = CGRect(x: 325, y: 275, width: 150, height: 150)
weavingImage.contentMode = .scaleAspectFit
weavingImage.isHidden = true
self.addSubview(weavingImage)
dyeingImage.image = UIImage(named: "dyeing process.jpeg")
dyeingImage.frame = CGRect(x: 555, y: 255, width: 150, height: 150)
dyeingImage.contentMode = .scaleAspectFit
dyeingImage.isHidden = true
self.addSubview(dyeingImage)
knittingImage.image = UIImage(named: "knitting process.jpeg")
knittingImage.frame = CGRect(x: 565, y: 19, width: 150, height: 150)
knittingImage.contentMode = .scaleAspectFit
knittingImage.isHidden = true
self.addSubview(knittingImage)
ginningButton.frame = CGRect(x: 77, y: 529, width: 150, height: 150)
ginningButton.addTarget(self, action: #selector(ginningButtonPressed), for: .touchUpInside)
ginningButton.isHidden = true
self.addSubview(ginningButton)
spinningButton.frame = CGRect(x: 71, y: 281, width: 150, height: 150)
spinningButton.addTarget(self, action: #selector(spinningButtonPressed), for: .touchUpInside)
spinningButton.isHidden = true
self.addSubview(spinningButton)
weavingButton.frame = CGRect(x: 325, y: 275, width: 150, height: 150)
weavingButton.addTarget(self, action: #selector(weavingButtonPressed), for: .touchUpInside)
weavingButton.isHidden = true
self.addSubview(weavingButton)
dyeingButton.frame = CGRect(x: 555, y: 255, width: 150, height: 150)
dyeingButton.addTarget(self, action: #selector(dyeingButtonPressed), for: .touchUpInside)
dyeingButton.isHidden = true
self.addSubview(dyeingButton)
knittingButton.frame = CGRect(x: 565, y: 19, width: 150, height: 150)
knittingButton.addTarget(self, action: #selector(knittingButtonPressed), for: .touchUpInside)
knittingButton.isHidden = true
self.addSubview(knittingButton)
directionLabel.text = "Process flow"
directionLabel.frame = CGRect(x: 16, y: 16, width: 300, height: 200)
directionLabel.numberOfLines = 2
directionLabel.textColor = UIColor.darkGray
directionLabel.font = UIFont(name: "Savoye LET", size: 80)
self.addSubview(directionLabel)
}
func loadSteps() {
stepToGinning1.image = UIImage(named: "shoe steps right.png")
stepToGinning1.frame = CGRect(x: 35, y: 705, width: 40, height: 40)
stepToGinning1.contentMode = .scaleAspectFit
stepToGinning1.isHidden = true
self.addSubview(stepToGinning1)
stepToGinning2.image = UIImage(named: "shoe steps right.png")
stepToGinning2.frame = CGRect(x: 95, y: 705, width: 40, height: 40)
stepToGinning2.contentMode = .scaleAspectFit
stepToGinning2.isHidden = true
self.addSubview(stepToGinning2)
stepToGinning3.image = UIImage(named: "shoe steps right.png")
stepToGinning3.frame = CGRect(x: 155, y: 705, width: 40, height: 40)
stepToGinning3.contentMode = .scaleAspectFit
stepToGinning3.isHidden = true
self.addSubview(stepToGinning3)
stepToGinning4.image = UIImage(named: "shoe steps right.png")
stepToGinning4.frame = CGRect(x: 215, y: 705, width: 40, height: 40)
stepToGinning4.contentMode = .scaleAspectFit
stepToGinning4.isHidden = true
self.addSubview(stepToGinning4)
stepToGinning5.image = UIImage(named: "shoe steps right.png")
stepToGinning5.frame = CGRect(x: 275, y: 705, width: 40, height: 40)
stepToGinning5.contentMode = .scaleAspectFit
stepToGinning5.isHidden = true
self.addSubview(stepToGinning5)
stepToGinning6.image = UIImage(named: "shoe steps.png")
stepToGinning6.frame = CGRect(x: 335, y: 695, width: 40, height: 40)
stepToGinning6.contentMode = .scaleAspectFit
stepToGinning6.transform = CGAffineTransform(rotationAngle: 45)
stepToGinning6.isHidden = true
self.addSubview(stepToGinning6)
stepToGinning7.image = UIImage(named: "shoe steps.png")
stepToGinning7.frame = CGRect(x: 335, y: 635, width: 40, height: 40)
stepToGinning7.contentMode = .scaleAspectFit
stepToGinning7.isHidden = true
self.addSubview(stepToGinning7)
stepToGinning8.image = UIImage(named: "shoe steps.png")
stepToGinning8.frame = CGRect(x: 305, y: 575, width: 40, height: 40)
stepToGinning8.contentMode = .scaleAspectFit
stepToGinning8.transform = CGAffineTransform(rotationAngle: -45)
stepToGinning8.isHidden = true
self.addSubview(stepToGinning8)
stepToGinning9.image = UIImage(named: "shoe steps left.png")
stepToGinning9.frame = CGRect(x: 245, y: 555, width: 40, height: 40)
stepToGinning9.contentMode = .scaleAspectFit
stepToGinning9.transform = CGAffineTransform(rotationAngle: -45)
stepToGinning9.isHidden = true
self.addSubview(stepToGinning9)
stepToSpinning1.image = UIImage(named: "shoe steps left.png")
stepToSpinning1.frame = CGRect(x: 35, y: 575, width: 40, height: 40)
stepToSpinning1.contentMode = .scaleAspectFit
stepToSpinning1.transform = CGAffineTransform(rotationAngle: -45)
stepToSpinning1.isHidden = true
self.addSubview(stepToSpinning1)
stepToSpinning2.image = UIImage(named: "shoe steps.png")
stepToSpinning2.frame = CGRect(x: 25, y: 515, width: 40, height: 40)
stepToSpinning2.contentMode = .scaleAspectFit
stepToSpinning2.isHidden = true
self.addSubview(stepToSpinning2)
stepToSpinning3.image = UIImage(named: "shoe steps.png")
stepToSpinning3.frame = CGRect(x: 25, y: 455, width: 40, height: 40)
stepToSpinning3.contentMode = .scaleAspectFit
stepToSpinning3.isHidden = true
self.addSubview(stepToSpinning3)
stepToSpinning4.image = UIImage(named: "shoe steps.png")
stepToSpinning4.frame = CGRect(x: 25, y: 395, width: 40, height: 40)
stepToSpinning4.contentMode = .scaleAspectFit
stepToSpinning4.isHidden = true
self.addSubview(stepToSpinning4)
stepToSpinning5.image = UIImage(named: "shoe steps.png")
stepToSpinning5.frame = CGRect(x: 25, y: 335, width: 40, height: 40)
stepToSpinning5.contentMode = .scaleAspectFit
stepToSpinning5.transform = CGAffineTransform(rotationAngle: 45)
stepToSpinning5.isHidden = true
self.addSubview(stepToSpinning5)
stepToWeaving1.image = UIImage(named: "shoe steps right.png")
stepToWeaving1.frame = CGRect(x: 211, y: 335, width: 40, height: 40)
stepToWeaving1.contentMode = .scaleAspectFit
stepToWeaving1.isHidden = true
self.addSubview(stepToWeaving1)
stepToWeaving2.image = UIImage(named: "shoe steps right.png")
stepToWeaving2.frame = CGRect(x:271, y: 335, width: 40, height: 40)
stepToWeaving2.contentMode = .scaleAspectFit
stepToWeaving2.isHidden = true
self.addSubview(stepToWeaving2)
stepToDyeing1.image = UIImage(named: "shoe steps right.png")
stepToDyeing1.frame = CGRect(x:490, y: 335, width: 40, height: 40)
stepToDyeing1.contentMode = .scaleAspectFit
stepToDyeing1.isHidden = true
self.addSubview(stepToDyeing1)
stepToKnitting1.image = UIImage(named: "shoe steps.png")
stepToKnitting1.frame = CGRect(x:615, y: 190, width: 40, height: 40)
stepToKnitting1.contentMode = .scaleAspectFit
stepToKnitting1.isHidden = true
self.addSubview(stepToKnitting1)
}
func stageGinning() {
var countVar = 0
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { (time) in
if countVar == 0 {
self.stepToGinning1.isHidden = false
} else if countVar == 1 {
self.stepToGinning2.isHidden = false
} else if countVar == 2 {
self.stepToGinning3.isHidden = false
} else if countVar == 3 {
self.stepToGinning4.isHidden = false
} else if countVar == 4 {
self.stepToGinning5.isHidden = false
} else if countVar == 5 {
self.stepToGinning6.isHidden = false
} else if countVar == 6 {
self.stepToGinning7.isHidden = false
} else if countVar == 7 {
self.stepToGinning8.isHidden = false
} else if countVar == 8 {
self.stepToGinning9.isHidden = false
} else {
self.ginningImage.isHidden = false
self.ginningButton.isHidden = false
self.timer.invalidate()
}
countVar += 1
}
}
func stageSpinning() {
var countVar = 0
self.stepToGinning1.isHidden = false
self.stepToGinning2.isHidden = false
self.stepToGinning3.isHidden = false
self.stepToGinning4.isHidden = false
self.stepToGinning5.isHidden = false
self.stepToGinning6.isHidden = false
self.stepToGinning7.isHidden = false
self.stepToGinning8.isHidden = false
self.stepToGinning9.isHidden = false
self.ginningImage.isHidden = false
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { (time) in
if countVar == 0 {
self.stepToSpinning1.isHidden = false
} else if countVar == 1 {
self.stepToSpinning2.isHidden = false
} else if countVar == 2 {
self.stepToSpinning3.isHidden = false
} else if countVar == 3 {
self.stepToSpinning4.isHidden = false
} else if countVar == 4 {
self.stepToSpinning5.isHidden = false
} else {
self.spinningImage.isHidden = false
self.spinningButton.isHidden = false
self.timer.invalidate()
}
countVar += 1
})
}
func stageWeaving() {
var countVar = 0
self.stepToGinning1.isHidden = false
self.stepToGinning2.isHidden = false
self.stepToGinning3.isHidden = false
self.stepToGinning4.isHidden = false
self.stepToGinning5.isHidden = false
self.stepToGinning6.isHidden = false
self.stepToGinning7.isHidden = false
self.stepToGinning8.isHidden = false
self.stepToGinning9.isHidden = false
self.ginningImage.isHidden = false
self.stepToSpinning1.isHidden = false
self.stepToSpinning2.isHidden = false
self.stepToSpinning3.isHidden = false
self.stepToSpinning4.isHidden = false
self.stepToSpinning5.isHidden = false
self.spinningImage.isHidden = false
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { (time) in
if countVar == 0 {
self.stepToWeaving1.isHidden = false
} else if countVar == 1 {
self.stepToWeaving2.isHidden = false
} else {
self.weavingImage.isHidden = false
self.weavingButton.isHidden = false
self.timer.invalidate()
}
countVar += 1
})
}
func stageDyeing() {
var countVar = 0
self.stepToGinning1.isHidden = false
self.stepToGinning2.isHidden = false
self.stepToGinning3.isHidden = false
self.stepToGinning4.isHidden = false
self.stepToGinning5.isHidden = false
self.stepToGinning6.isHidden = false
self.stepToGinning7.isHidden = false
self.stepToGinning8.isHidden = false
self.stepToGinning9.isHidden = false
self.ginningImage.isHidden = false
self.stepToSpinning1.isHidden = false
self.stepToSpinning2.isHidden = false
self.stepToSpinning3.isHidden = false
self.stepToSpinning4.isHidden = false
self.stepToSpinning5.isHidden = false
self.spinningImage.isHidden = false
self.stepToWeaving1.isHidden = false
self.stepToWeaving2.isHidden = false
self.weavingImage.isHidden = false
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { (time) in
if countVar == 0 {
self.stepToDyeing1.isHidden = false
} else {
self.dyeingImage.isHidden = false
self.dyeingButton.isHidden = false
self.timer.invalidate()
}
countVar += 1
})
}
func stageKnitting() {
var countVar = 0
self.stepToGinning1.isHidden = false
self.stepToGinning2.isHidden = false
self.stepToGinning3.isHidden = false
self.stepToGinning4.isHidden = false
self.stepToGinning5.isHidden = false
self.stepToGinning6.isHidden = false
self.stepToGinning7.isHidden = false
self.stepToGinning8.isHidden = false
self.stepToGinning9.isHidden = false
self.ginningImage.isHidden = false
self.stepToSpinning1.isHidden = false
self.stepToSpinning2.isHidden = false
self.stepToSpinning3.isHidden = false
self.stepToSpinning4.isHidden = false
self.stepToSpinning5.isHidden = false
self.spinningImage.isHidden = false
self.stepToWeaving1.isHidden = false
self.stepToWeaving2.isHidden = false
self.weavingImage.isHidden = false
self.stepToDyeing1.isHidden = false
self.dyeingImage.isHidden = false
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { (time) in
if countVar == 0 {
self.stepToKnitting1.isHidden = false
} else {
self.knittingImage.isHidden = false
self.knittingButton.isHidden = false
self.timer.invalidate()
}
countVar += 1
})
}
@objc func ginningButtonPressed() {
self.removeFromSuperview()
let ginningView = ginning(scene: self)
PlaygroundPage.current.liveView = ginningView
}
@objc func spinningButtonPressed() {
self.removeFromSuperview()
let spinningView = spinning(scene: self)
PlaygroundPage.current.liveView = spinningView
}
@objc func weavingButtonPressed() {
self.removeFromSuperview()
let weavingView = weaving(scene: self)
PlaygroundPage.current.liveView = weavingView
}
@objc func dyeingButtonPressed() {
self.removeFromSuperview()
let dyeingView = dying(scene: self)
PlaygroundPage.current.liveView = dyeingView
}
@objc func knittingButtonPressed() {
self.removeFromSuperview()
let knittingView = knitting(scene: self)
PlaygroundPage.current.liveView = knittingView
}
func goToNextScreen() {
self.removeFromSuperview()
let byebyeView = byebye(scene: self)
PlaygroundPage.current.liveView = byebyeView
}
}
|
class Solution {
func longestPalindrome(_ s: String) -> Int {
var letterCounts: [Character : Int] = [Character : Int]()
for l in s {
letterCounts[l] = letterCounts[l] == nil ? 1 : letterCounts[l]! + 1
}
var ans: Int = 0
for (k, v) in letterCounts {
ans += v / 2 * 2
if (ans % 2 == 0 && v % 2 == 1) {
ans += 1
}
}
return ans
}
}
|
//
// AllString.swift
// Hippo
//
// Created by Arohi Sharma on 23/06/20.
// Copyright ยฉ 2020 CL-macmini-88. All rights reserved.
//
import Foundation
class AllString{
class func getAllStrings(completion: @escaping HippoResponseRecieved) {
var params = [String: Any]()
params["request_source"] = HippoConfig.shared.appUserType == .agent ? 1 : 0
params["lang"] = getCurrentLanguageLocale()
params["offering"] = HippoConfig.shared.offering
params["device_type"] = Device_Type_iOS
if HippoConfig.shared.appUserType == .customer{
if let enUserID = HippoUserDetail.fuguEnUserID{
params["en_user_id"] = enUserID
}
if let userIdenficationSecret = HippoConfig.shared.userDetail?.userIdenficationSecret{
if userIdenficationSecret.trimWhiteSpacesAndNewLine().isEmpty == false {
params["user_identification_secret"] = userIdenficationSecret
}
}
params["app_secret_key"] = HippoConfig.shared.appSecretKey
}
if HippoConfig.shared.appUserType == .agent{
params["access_token"] = HippoConfig.shared.agentDetail?.fuguToken
}
HippoConfig.shared.log.trace(params, level: .request)
HTTPClient.makeConcurrentConnectionWith(method: .POST, enCodingType: .json, para: params, extendedUrl: FuguEndPoints.getLanguage.rawValue) { (responseObject, error, tag, statusCode) in
guard let unwrappedStatusCode = statusCode, error == nil, unwrappedStatusCode == STATUS_CODE_SUCCESS, error == nil else {
HippoConfig.shared.log.debug(error ?? "", level: .error)
completion(error as? HippoError, nil)
return
}
guard let apiResponse = responseObject as? [String : Any], let data = apiResponse["data"] as? [String : Any], let response = data["business_data"] as? [String: Any] else {
return
}
if HippoConfig.shared.appUserType == .agent{
agentParsing(response)
}else{
customerParsing(response)
}
HippoStrings.updateHippoCallClientStrings()
completion(error as? HippoError, nil)
}
}
class func customerParsing(_ response: [String : Any]){
if response["app_guarantee"] is String{
}
if let callAgain = response["call_again"] as? String{
HippoStrings.callAgain = callAgain
}
if let cancelPayment = response["cancel_payment_text"] as? String{
HippoStrings.cancelPayment = cancelPayment
}
if response["float_label_start_chat"] is String{
}
if response["fugu_agent_actions"] is String{
}
if response["fugu_attachment"] is String{
}
if let audio = response["fugu_audio"] as? String{
HippoStrings.audio = audio
}
if let camera = response["fugu_camera"] as? String{
HippoStrings.camera = camera
}
if let cancel = response["fugu_cancel"] as? String{
HippoStrings.cancel = cancel
}
if let connected = response["fugu_connected"] as? String{
HippoStrings.connected = connected
}
if let connecting = response["fugu_connecting"] as? String{
HippoStrings.connecting = connecting
}
if let document = response["fugu_document"] as? String{
HippoStrings.document = document
}
if response["fugu_file_not_found"] is String{
}
if response["fugu_leave_comment"] is String{
}
if let error_msg_yellow_bar = response["error_msg_yellow_bar"] as? String{
HippoStrings.slowInternet = error_msg_yellow_bar
}
if let loading = response["fugu_loading"] as? String{
HippoStrings.loading = loading
}
if let retry = response["fugu_menu_retry"] as? String{
HippoStrings.retry = retry
}
if let newConversation = response["fugu_new_conversation"] as? String{
HippoConfig.shared.strings.newConversation = newConversation
}
if response["fugu_no_data_found"] is String{
}
if let ok = response["fugu_ok"] as? String{
HippoStrings.ok = ok
}
if let payment = response["fugu_payment"] as? String{
HippoStrings.payment = payment
}
if let document = response["fugu_pdf"] as? String{
HippoStrings.document = document
}
if response["fugu_powered_by"] is String{
// HippoStrings.powered_by = powered_by
}
if let send_message = response["fugu_send_message"] as? String{
HippoStrings.messagePlaceHolderText = send_message
}
if response["fugu_show_more"] is String{
}
if let support = response["fugu_support"] as? String{
HippoStrings.support = support
}
if response["fugu_tap_to_view"] is String{
}
if response["fugu_text"] is String{
}
if let title = response["fugu_title"] as? String{
HippoStrings.title = title
}
if response["fugu_unable_to_connect_internet"] is String{
}
if let video = response["fugu_video"] as? String{
HippoStrings.video = video
}
if let voice = response["fugu_voice"] as? String{
HippoStrings.voice = voice
}
if response["hippo_activity_image_trans"] is String{
}
if let hippo_add_an_option = response["hippo_add_an_option"] as? String{
HippoStrings.addOption = hippo_add_an_option
}
if let hippo_alert = response["hippo_alert"] as? String{
HippoStrings.alert = hippo_alert
}
if response["hippo_all_agents_busy"] is String{
}
if let hippo_at = response["hippo_at"] as? String{
HippoStrings.at = hippo_at
}
if response["hippo_attachment_file"] is String{
}
if response["hippo_audio_call"] is String{
}
if let hippo_broadcast_detail = response["hippo_broadcast_detail"] as? String{
HippoStrings.broadcastDetails = hippo_broadcast_detail
}
if response["hippo_browse_other_doc"] is String{
}
if let hippo_busy_on_call = response["hippo_busy_on_call"] as? String{
HippoStrings.busyAnotherCall = hippo_busy_on_call
}
if let hippo_call = response["hippo_call"] as? String{
HippoStrings.call = hippo_call
}
if let hippo_call_back = response["hippo_call_back"] as? String{
HippoStrings.callback = hippo_call_back
}
if let hippo_call_calling = response["hippo_call_calling"] as? String{
HippoStrings.calling = hippo_call_calling
}
if let hippo_call_declined = response["hippo_call_declined"] as? String{
HippoStrings.callDeclined = hippo_call_declined
}
if response["hippo_call_ended"] is String{
}
if response["hippo_call_hungup"] is String{
}
if response["hippo_call_incoming"] is String{
//HippoStrings.incomingCall = hippo_call_incoming
}
if response["hippo_call_incoming_audio_call"] is String{
}
if response["hippo_call_incoming_video_call"] is String{
}
if response["hippo_call_outgoing"] is String{
}
if response["hippo_call_rejected"] is String{
}
if let hippo_calling_connection = response["hippo_calling_connection"] as? String{
HippoStrings.connectingToMeeting = hippo_calling_connection
}
if let hippo_establishing_connection = response["hippo_establishing_connection"] as? String{
HippoStrings.establishingConnection = hippo_establishing_connection
}
if let hippo_call_ringing = response["hippo_call_ringing"] as? String{
HippoStrings.ringing = hippo_call_ringing
}
if response["hippo_call_with"] is String{
}
if response["hippo_call_with_you"] is String{
}
if let hippo_calling_from_old = response["hippo_calling_from_old"] as? String{
HippoStrings.callOldSdk = hippo_calling_from_old
}
if let hippo_cancel_payment = response["hippo_cancel_payment"] as? String{
HippoStrings.cancelPaymentTitle = hippo_cancel_payment
}
if response["hippo_card"] is String{
}
if response["hippo_chat"] is String{
}
if response["hippo_chat_support"] is String{
}
if response["hippo_chats"] is String{
}
if let hippo_clear_all_notification = response["hippo_clear_all_notification"] as? String{
HippoStrings.clearAll = hippo_clear_all_notification
}
if response["hippo_copy_to_clipboard"] is String{
}
if response["hippo_could_not_send_message"] is String{
}
if response["hippo_country_picker_header"] is String{
}
if let hippo_currency = response["hippo_currency"] as? String{
HippoStrings.currency = hippo_currency
}
if let hippo_current = response["hippo_current"] as? String{
HippoStrings.ongoing = hippo_current
}
if response["hippo_customer_missed_a"] is String{
}
if response["hippo_disconnect"] is String{
}
if response["hippo_empty_other_user_unique_keys"] is String{
}
if response["hippo_empty_transaction_id"] is String{
}
if let hippo_emptymessage = response["hippo_emptymessage"] as? String{
HippoStrings.enterSomeText = hippo_emptymessage
}
if response["hippo_enter_number_only"] is String{
}
if response["hippo_enter_phone_number"] is String{
}
if let hippo_enter_title = response["hippo_enter_title"] as? String{
HippoStrings.enterTitle = hippo_enter_title
}
if let hippo_enter_valid_email = response["hippo_enter_valid_email"] as? String{
HippoStrings.enterValidEmail = hippo_enter_valid_email
}
if response["hippo_enter_valid_phn_no"] is String{
}
if response["hippo_enter_valid_price"] is String{
}
if response["hippo_error_msg_sending"] is String{
}
if response["hippo_error_no_countries_found"] is String{
}
if response["hippo_feature_no_supported"] is String{
}
if response["hippo_fetching_payment_methods"] is String{
}
if let hippo_field_cant_empty = response["hippo_field_cant_empty"] as? String{
HippoStrings.requiredField = hippo_field_cant_empty
}
if response["hippo_file_already_in_queue"] is String{
}
if response["hippo_file_not_supported"] is String{
}
if response["hippo_files"] is String{
}
if response["hippo_fill_pre_field"] is String{
}
if response["hippo_find_an_expert"] is String{
}
if let hippo_free = response["hippo_free"] as? String{
HippoStrings.free = hippo_free
}
if response["hippo_grant_permission"] is String{
}
if let hippo_history = response["hippo_history"] as? String{
HippoStrings.chatHistory = hippo_history
}
if response["hippo_invalid_price"] is String{
}
if let hippo_item_description = response["hippo_item_description"] as? String{
HippoStrings.enterDescription = hippo_item_description
}
if let hippo_item_price = response["hippo_item_price"] as? String{
HippoStrings.enterPrice = hippo_item_price
}
if response["hippo_large_file"] is String{
}
if let hippo_logout_msg = response["hippo_logout_msg"] as? String{
HippoStrings.logout = hippo_logout_msg
}
if let hippo_message_sucessfully = response["hippo_message_sucessfully"] as? String{
HippoStrings.hippoDefaultText = hippo_message_sucessfully
}
if let hippo_minimum_Multiselection = response["hippo_minimum_Multiselection"] as? String{
HippoStrings.noMinSelection = hippo_minimum_Multiselection
}
if let hippo_missed = response["hippo_missed"] as? String{
HippoStrings.missed = hippo_missed
}
if response["hippo_missed_call"] is String{
}
if response["hippo_netbanking"] is String{
}
if let hippo_no = response["hippo_no"] as? String{
HippoStrings.no = hippo_no
}
if let hippo_no_chat = response["hippo_no_chat"] as? String{
HippoStrings.noChatStarted = hippo_no_chat
}
if response["hippo_no_chat_init"] is String{
}
if let hippo_no_internet_connected = response["hippo_no_internet_connected"] as? String{
HippoStrings.noNetworkConnection = hippo_no_internet_connected
}
if let hippo_no_notifications = response["hippo_no_notifications"] as? String{
HippoStrings.noNotificationFound = hippo_no_notifications
}
if let hippo_no_payment_methods = response["hippo_no_payment_methods"] as? String{
HippoStrings.noPaymentMethod = hippo_no_payment_methods
}
if let hippo_nochats = response["hippo_nochats"] as? String{
HippoStrings.noChatInCatagory = hippo_nochats
}
if let hippo_notifications = response["hippo_notifications"] as? String{
HippoStrings.notifications = hippo_notifications
}
if response["hippo_notifications_deleted"] is String{
}
if response["hippo_notifications_title"] is String{
}
if let hippo_ongoing = response["hippo_ongoing"] as? String{
HippoStrings.ongoing_call = hippo_ongoing
}
if let hippo_paid = response["hippo_paid"] as? String{
HippoStrings.paymentPaid = hippo_paid
}
if let hippo_past = response["hippo_past"] as? String{
HippoStrings.past = hippo_past
}
if let hippo_pay_btnText = response["hippo_pay_btnText"] as? String{
HippoStrings.Pay = hippo_pay_btnText
}
if response["hippo_pay_with_netbanking"] is String{
}
if response["hippo_pay_with_paymob"] is String{
}
if response["hippo_pay_with_paytm"] is String{
}
if response["hippo_pay_with_razorpay"] is String{
}
if response["hippo_payfort"] is String{
}
if response["hippo_payment_loader"] is String{
}
if let hippo_payment_title = response["hippo_payment_title"] as? String{
HippoStrings.payment = hippo_payment_title
}
if response["hippo_paytm"] is String{
}
if let hippo_pending = response["hippo_pending"] as? String{
HippoStrings.paymentPending = hippo_pending
}
if let hippo_photo_video_library = response["hippo_photo_video_library"] as? String{
HippoStrings.photoLibrary = hippo_photo_video_library
}
if let hippo_proceed_to_pay = response["hippo_proceed_to_pay"] as? String{
HippoStrings.proccedToPay = hippo_proceed_to_pay
}
if let hippo_rating_review = response["hippo_rating_review"] as? String{
HippoStrings.ratingReview = hippo_rating_review
}
if response["hippo_rationale_ask"] is String{
}
if response["hippo_rationale_ask_again"] is String{
}
if let hippo_read_less = response["hippo_read_less"] as? String{
HippoStrings.readLess = hippo_read_less
}
if let hippo_read_more = response["hippo_read_more"] as? String{
HippoStrings.readMore = hippo_read_more
}
if let hippo_recipients = response["hippo_recipients"] as? String{
HippoStrings.recipients = hippo_recipients
}
if let hippo_request_payment = response["hippo_request_payment"] as? String{
HippoStrings.requestPayment = hippo_request_payment
}
if let hippo_save_plan = response["hippo_save_plan"] as? String{
HippoStrings.savePlan = hippo_save_plan
}
if response["hippo_search"] is String{
}
if let hippo_select_string = response["hippo_select_string"] as? String{
HippoStrings.selectString = hippo_select_string
}
if let hippo_sent_a_msg = response["hippo_sent_a_msg"] as? String{
HippoStrings.messageSent = hippo_sent_a_msg
}
if let hippo_something_went_wrong = response["hippo_something_went_wrong"] as? String{
HippoStrings.somethingWentWrong = hippo_something_went_wrong
}
if response["hippo_something_wentwrong"] is String{
}
if response["hippo_something_wrong"] is String{
}
if response["hippo_storage_permission"] is String{
}
if response["hippo_stripe"] is String{
}
if let hippo_submit = response["hippo_submit"] as? String{
HippoStrings.submit = hippo_submit
}
if response["hippo_tap_to_retry"] is String{
}
if response["hippo_text"] is String{
}
if let hippo_the = response["hippo_the"] as? String{
HippoStrings.the = hippo_the
}
if response["hippo_the_video_call"] is String{
}
if response["hippo_the_video_call_ended"] is String{
}
if response["hippo_the_voice_call"] is String{
}
if response["hippo_the_voice_call_ended"] is String{
}
if let hippo_title_item_description = response["hippo_title_item_description"] as? String{
HippoStrings.description = hippo_title_item_description
}
if let hippo_title_item_price = response["hippo_title_item_price"] as? String{
HippoStrings.price = hippo_title_item_price
}
if let hippo_today = response["hippo_today"] as? String{
HippoStrings.today = hippo_today
}
if let hippo_total_count = response["hippo_total_count"] as? String{
HippoStrings.totalPrice = hippo_total_count
}
if let hippo_update_plan = response["hippo_update_plan"] as? String{
HippoStrings.updatePlan = hippo_update_plan
}
if response["hippo_video"] is String{
}
if response["hippo_with_country_code"] is String{
}
if let hippo_writereview = response["hippo_writereview"] as? String{
HippoStrings.writeReview = hippo_writereview
}
if let hippo_yes = response["hippo_yes"] as? String{
HippoStrings.yes = hippo_yes
}
if let hippo_yes_cancel = response["hippo_yes_cancel"] as? String{
HippoStrings.yesCancel = hippo_yes_cancel
}
if let hippo_yesterday = response["hippo_yesterday"] as? String{
HippoStrings.yesterday = hippo_yesterday
}
if let hippo_you = response["hippo_you"] as? String{
HippoStrings.you = hippo_you
}
if response["hippo_you_have_no_chats"] is String{
}
if response["hippo_you_missed_a"] is String{
}
if let logout = response["logout"] as? String{
HippoStrings.logoutTitle = logout
}
if response["talk_to"] is String{
}
if response["title_settings_dialog"] is String{
}
if let unknown_message = response["unknown_message"] as? String{
HippoStrings.unknownMessage = unknown_message
}
if response["uploading_in_progress"] is String{
}
if let vw_all = response["vw_all"] as? String{
HippoStrings.allAgentsString = vw_all
}
if let vw_confirm = response["vw_confirm"] as? String{
HippoStrings.Done = vw_confirm
}
if let hippo_call_ended = response["hippo_call_ended"] as? String{
HippoStrings.callEnded = hippo_call_ended
}
if response["vw_no_photo_app"] is String{
}
if response["vw_no_video_app"] is String{
}
if response["vw_rationale_storage"] is String{
}
if response["vw_up_to_max"] is String{
}
if let hippo_secure_payment = response["hippo_secure_payment"] as? String{
HippoStrings.hippoSecurePayment = hippo_secure_payment
}
if let PAYMENT_REQUESTED = response["PAYMENT_REQUESTED"] as? String{
HippoStrings.paymentRequested = PAYMENT_REQUESTED
}
if let hippo_clear = response["hippo_clear"] as? String{
HippoStrings.clear = hippo_clear
}
if let hippo_calling_you = response["hippo_calling_you"] as? String{
HippoStrings.isCallingYou = hippo_calling_you
}
if let hippo_select_a_plan = response["hippo_select_a_plan"] as? String{
HippoStrings.selectaPlan = hippo_select_a_plan
}
if let hippo_message_not_allow = response["hippo_message_not_allow"] as? String{
HippoStrings.donotAllowPersonalInfo = hippo_message_not_allow
}
if let hippo_Thankyou_Feedback = response["hippo_Thankyou_Feedback"] as? String{
HippoStrings.thanksForFeedback = hippo_Thankyou_Feedback
}
if let hippo_edit_text = response["hippo_edit_text"] as? String{
HippoStrings.edit = hippo_edit_text
}
if let hippo_delete_text = response["hippo_delete_text"] as? String{
HippoStrings.delete = hippo_delete_text
}
if let hippo_edited = response["hippo_edited"] as? String{
HippoStrings.edited = hippo_edited
}
if let hippo_delete_for_everyone = response["hippo_delete_for_everyone"] as? String{
HippoStrings.deleteForEveryone = hippo_delete_for_everyone
}
if let hippo_copy_text = response["hippo_copy_text"] as? String{
HippoStrings.copy = hippo_copy_text
}
if let hippo_delete_this_message = response["hippo_delete_this_message"] as? String{
HippoStrings.deleteMessagePopup = hippo_delete_this_message
}
if let hippo_message_deleted = response["hippo_message_deleted"] as? String{
HippoStrings.deleteMessage = hippo_message_deleted
}
}
class func agentParsing(_ response: [String: Any]){
if let hippo_message_deleted = response["hippo_message_deleted"] as? String{
HippoStrings.deleteMessage = hippo_message_deleted
}
if let hippo_edit_text = response["hippo_edit_text"] as? String{
HippoStrings.edit = hippo_edit_text
}
if let hippo_delete_text = response["hippo_delete_text"] as? String{
HippoStrings.delete = hippo_delete_text
}
if let hippo_edited = response["hippo_edited"] as? String{
HippoStrings.edited = hippo_edited
}
if let hippo_delete_for_everyone = response["hippo_delete_for_everyone"] as? String{
HippoStrings.deleteForEveryone = hippo_delete_for_everyone
}
if let hippo_copy_text = response["hippo_copy_text"] as? String{
HippoStrings.copy = hippo_copy_text
}
if let hippo_delete_this_message = response["hippo_delete_this_message"] as? String{
HippoStrings.deleteMessagePopup = hippo_delete_this_message
}
if let hippo_message_not_allow = response["hippo_message_not_allow"] as? String{
HippoStrings.donotAllowPersonalInfo = hippo_message_not_allow
}
if let hippo_save_plan = response["hippo_save_plan"] as? String{
HippoStrings.savePlan = hippo_save_plan
}
if let hippo_pending = response["hippo_pending"] as? String{
HippoStrings.paymentPending = hippo_pending
}
if let hippo_request_payment = response["hippo_request_payment"] as? String{
HippoStrings.requestPayment = hippo_request_payment
}
if let hippo_day_ago = response["hippo_day_ago"] as? String{
HippoStrings.daysAgo = hippo_day_ago
}
if let hippo_call = response["hippo_call"] as? String{
HippoStrings.call = hippo_call
}
if let hippo_imagesaved_title = response["hippo_imagesaved_title"] as? String{
HippoStrings.saved = hippo_imagesaved_title
}
if let hippo_image_saved = response["hippo_image_saved"] as? String{
HippoStrings.imageSaved = hippo_image_saved
}
if let hippo_photo_video_library = response["hippo_photo_video_library"] as? String{
HippoStrings.photoLibrary = hippo_photo_video_library
}
if let FILE_IMAGE = response["FILE_IMAGE"] as? String{
HippoStrings.sentAPhoto = FILE_IMAGE
}
if let FILE_ATTACHMENT = response["FILE_ATTACHMENT"] as? String{
HippoStrings.sentAFile = FILE_ATTACHMENT
}
if let PAYMENT_REQUESTED = response["PAYMENT_REQUESTED"] as? String{
HippoStrings.paymentRequested = PAYMENT_REQUESTED
}
if let ASSIGNED_TO_THEMSELVES = response["ASSIGNED_TO_THEMSELVES"] as? String{
HippoStrings.assignedToThemselves = ASSIGNED_TO_THEMSELVES
}
if let NEW_CHAT_ASSIGNED_TO_YOU = response["NEW_CHAT_ASSIGNED_TO_YOU"] as? String{
HippoStrings.newChatAssignedToYou = NEW_CHAT_ASSIGNED_TO_YOU
}
if let ASSIGNED_CHAT_TO = response["ASSIGNED_CHAT_TO"] as? String{
HippoStrings.chatAssigned = ASSIGNED_CHAT_TO
}
if let CHAT_REOPENED_BY = response["CHAT_REOPENED_BY"] as? String{
HippoStrings.chatReopenedby = CHAT_REOPENED_BY
}
if let CHAT_WAS_AUTO_OPENED = response["CHAT_WAS_AUTO_OPENED"] as? String{
HippoStrings.chatAutoOpened = CHAT_WAS_AUTO_OPENED
}
if let CHAT_WAS_AUTO_CLOSED = response["CHAT_WAS_AUTO_CLOSED"] as? String{
HippoStrings.chatAutoClosed = CHAT_WAS_AUTO_CLOSED
}
if let CHAT_WAS_RE_OPENED = response["CHAT_WAS_RE_OPENED"] as? String{
HippoStrings.chatReopened = CHAT_WAS_RE_OPENED
}
if let CHAT_WAS_CLOSED = response["CHAT_WAS_CLOSED"] as? String{
HippoStrings.chatClosedBy = CHAT_WAS_CLOSED
}
if let WAS_AUTO_ASSIGNED = response["WAS_AUTO_ASSIGNED"] as? String{
HippoStrings.chatAutoAssigned = WAS_AUTO_ASSIGNED
}
if let WAS_FORCE_ASSIGNED = response["WAS_FORCE_ASSIGNED"] as? String{
HippoStrings.forceAssigned = WAS_FORCE_ASSIGNED
}
if let TAGGED = response["TAGGED"] as? String{
HippoStrings.tagged = TAGGED
}
if let MENTIONED_YOU = response["MENTIONED_YOU"] as? String{
HippoStrings.mentionedYou = MENTIONED_YOU
}
if let CALLING_YOU = response["CALLING_YOU"] as? String{
HippoStrings.isCallingYou = CALLING_YOU
}
if let MISSED_CALL_FROM = response["MISSED_CALL_FROM"] as? String{
HippoStrings.missedCallFrom = MISSED_CALL_FROM
}
if let RATING_AND_REVIEW = response["RATING_AND_REVIEW"] as? String{
HippoStrings.ratingReview = RATING_AND_REVIEW
}
if let BOT_SKIPPED_FOR_THIS_SESSION = response["BOT_SKIPPED_FOR_THIS_SESSION"] as? String{
HippoStrings.botSkipped = BOT_SKIPPED_FOR_THIS_SESSION
}
if let NEW_CUSTOMER = response["NEW_CUSTOMER"] as? String{
HippoStrings.newCustomer = NEW_CUSTOMER
}
if let hippo_call_calling = response["hippo_call_calling"] as? String{
HippoStrings.calling = hippo_call_calling
}
if let hippo_call_ringing = response["hippo_call_ringing"] as? String{
HippoStrings.ringing = hippo_call_ringing
}
if let hippo_call_declined = response["hippo_call_declined"] as? String{
HippoStrings.callDeclined = hippo_call_declined
}
if let hippo_busy_on_call = response["hippo_busy_on_call"] as? String{
HippoStrings.busyAnotherCall = hippo_busy_on_call
}
if let closed = response["closed"] as? String{
HippoStrings.closed = closed
}
if let hippo_Reopen_Chat = response["hippo_Reopen_Chat"] as? String{
HippoStrings.reopenChat = hippo_Reopen_Chat
}
if response["hello_blank_fragment"] is String{
}
if response["open_conversations"] is String{
}
if response["closed_conversations"] is String{
}
if response["fugu_unable_to_connect_internet"] is String{
}
if response["fugu_no_internet_connection_retry"] is String{
}
if response["hippo_something_wrong_api"] is String{
}
if let fugu_new_conversation = response["fugu_new_conversation"] as? String{
HippoStrings.newConversation = fugu_new_conversation
}
if response["fugu_new_conversations"] is String{
}
if let fugu_loading = response["fugu_loading"] as? String{
HippoStrings.loading = fugu_loading
}
if response["fugu_powered_by"] is String{
}
if response["fugu_menu_refresh"] is String{
}
if response["forgot_password"] is String{
}
if response["dont_have_account"] is String{
}
if response["confirmation"] is String{
}
if response["register_your_business"] is String{
}
if response["sign_in"] is String{
}
if response["sign_up"] is String{
}
if response["password"] is String{
}
if response["business_name"] is String{
}
if response["new_password"] is String{
}
if response["old_password"] is String{
}
if response["confirm_password"] is String{
}
if response["email_address"] is String{
}
if response["login_to_continue"] is String{
}
if response["err_msg_email"] is String{
}
if response["err_msg_search"] is String{
}
if response["err_msg_password"] is String{
}
if response["err_msg_name"] is String{
}
if response["err_msg_business_name"] is String{
}
if response["err_msg_phone"] is String{
}
if response["err_msg_phone_invalid"] is String{
}
if response["forgot_password_desc"] is String{
}
if response["done"] is String{
}
if let hippo_you = response["hippo_you"] as? String{
HippoStrings.you = hippo_you
}
if response["hippo_user"] is String{
}
if response["details"] is String{
}
if let actions = response["actions"] as? String{
HippoStrings.actions = actions
}
if let close_conversation = response["close_conversation"] as? String{
HippoStrings.closeChat = close_conversation
}
if response["assign_conversation"] is String{
}
if response["participants"] is String{
}
if response["type_message_only"] is String{
}
if response["type_a_message"] is String{
}
if response["type_a_normal_message"] is String{
}
if let type_a_internal_note = response["type_a_internal_note"] as? String{
HippoStrings.privateMessagePlaceHolder = type_a_internal_note
}
if response["reopen_conversation"] is String{
}
if response["pick_image_from"] is String{
}
if let camera = response["camera"] as? String{
HippoStrings.camera = camera
}
if response["gallery"] is String{
}
if response["no_gallery"] is String{
}
if response["permission_was_not_granted_text"] is String{
}
if let retry = response["retry"] as? String{
HippoStrings.retry = retry
}
if let attachment = response["attachment"] as? String{
HippoStrings.attachmentImage = attachment
}
if let send_message = response["send_message"] as? String{
HippoStrings.messagePlaceHolderText = send_message
}
if response["leave_an_internal_note"] is String{
}
if response["saved_replies"] is String{
}
if let no_conversation_found = response["no_conversation_found"] as? String{
HippoStrings.noConversationFound = no_conversation_found
}
if response["no_previous_conversation_found"] is String{
}
if response["we_could_not_found_any_conversation"] is String{
}
if response["we_could_not_found_previous_conversation"] is String{
}
if response["enter_code"] is String{
}
if let status = response["status"] as? String{
HippoStrings.status = status
}
if let closed_chats = response["closed_chats"] as? String{
HippoStrings.closedChat = closed_chats
}
if let open_chats = response["open_chats"] as? String{
HippoStrings.openChat = open_chats
}
if response["type"] is String{
}
if let my_chats = response["my_chats"] as? String{
HippoStrings.myChats = my_chats
}
if let unassigned = response["unassigned"] as? String{
HippoStrings.unassigned = unassigned
}
if response["tagged"] is String{
}
if response["labels"] is String{
}
if response["logout_message"] is String{
}
if response["proceed"] is String{
}
if let cancel = response["cancel"] as? String{
HippoStrings.cancel = cancel
}
if let assign_agent_message = response["assign_agent_message"] as? String{
HippoStrings.reasignChat = assign_agent_message
}
if let self_assign_agent_message = response["self_assign_agent_message"] as? String{
HippoStrings.reasignChatToYou = self_assign_agent_message
}
if response["confirm"] is String{
}
if let close_chat_message = response["close_chat_message"] as? String{
HippoStrings.closeChatPopup = close_chat_message
}
if response["close"] is String{
}
if let reopen_chat_message = response["reopen_chat_message"] as? String{
HippoStrings.reopenChatPopup = reopen_chat_message
}
if response["reopen_caps"] is String{
}
if response["logout_caps"] is String{
}
if response["logout"] is String{
}
if response["tap_to_view"] is String{
}
if let conversation_closed = response["conversation_closed"] as? String{
HippoStrings.coversationClosed = conversation_closed
}
if let conversation_re_opend = response["conversation_re_opend"] as? String{
HippoStrings.conversationReopened = conversation_re_opend
}
if let conversation_assigned = response["conversation_assigned"] as? String{
HippoStrings.conversationAssigned = conversation_assigned
}
if response["tool_tip_filter"] is String{
}
if response["analytics"] is String{
}
if response["volume_trends"] is String{
}
if response["time_trends"] is String{
}
if response["agent_wise_trends"] is String{
}
if response["support"] is String{
}
if response["chat_with_fugu"] is String{
}
if let all_chats = response["all_chats"] as? String{
HippoStrings.allChats = all_chats
}
if response["profile"] is String{
}
if response["all_agents"] is String{
}
if response["all_channels"] is String{
}
if response["all_tags"] is String{
}
if response["agents"] is String{
}
if response["new_text"] is String{
}
if response["replied"] is String{
}
if response["assigned"] is String{
}
if let apply = response["apply"] as? String{
HippoStrings.apply = apply
}
if response["date"] is String{
}
if let today = response["today"] as? String{
HippoStrings.today = today
}
if let yesterday = response["yesterday"] as? String{
HippoStrings.yesterday = yesterday
}
if response["last_7_days"] is String{
}
if response["last_30_days"] is String{
}
if response["agent_wise_data"] is String{
}
if response["avg_resp_time"] is String{
}
if response["avg_close_time"] is String{
}
if response["avg_response_time"] is String{
}
if response["channels"] is String{
}
if let tags = response["tags"] as? String{
HippoStrings.tags = tags
}
if let channel_info = response["channel_info"] as? String{
HippoStrings.channelInfo = channel_info
}
if response["close_small"] is String{
}
if response["my_analytics"] is String{
}
if response["edit_profile"] is String{
}
if response["first_visit"] is String{
}
if response["url"] is String{
}
if response["device"] is String{
}
if response["no_of_visits"] is String{
}
if response["last_visit"] is String{
}
if response["business"] is String{
}
if response["name"] is String{
}
if response["name_caps"] is String{
}
if response["phone_no_caps"] is String{
}
if response["email_add_caps"] is String{
}
if response["no_of_visitors"] is String{
}
if response["social_profile"] is String{
}
if response["past_chats"] is String{
}
if response["view_more"] is String{
}
if response["shared_images"] is String{
}
if response["basic_info"] is String{
}
if response["custom_data"] is String{
}
if response["reassign_conversation"] is String{
}
if response["ok"] is String{
}
if response["user_info"] is String{
}
if let info = response["info"] as? String{
HippoStrings.info = info
}
if response["change_password"] is String{
}
if response["your_profile"] is String{
}
if response["available"] is String{
}
if response["offline"] is String{
}
if response["away"] is String{
}
if response["away_message"] is String{
}
if response["updating_conversation"] is String{
}
if response["available_message"] is String{
}
if response["save"] is String{
}
if response["profile_save_succ"] is String{
}
if response["pass_save_succ"] is String{
}
if response["same_pass_err"] is String{
}
if let empty_msg = response["empty_msg"] as? String{
HippoStrings.fieldEmpty = empty_msg
}
if response["PleaseEnterAddressType"] is String{
}
if response["PasswordDoesntMatch"] is String{
}
if response["PleaseEnterFirstName"] is String{
}
if response["PleaseEnterAddress"] is String{
}
if response["PleaseEnterDob"] is String{
}
if response["NameThreeCharLong"] is String{
}
if response["NameCannotContainSpecialCharacters"] is String{
}
if response["PleaseEnterLastName"] is String{
}
if response["LastNameCannotContainSpecialChar"] is String{
}
if response["PleaseEnterEmailId"] is String{
}
if response["PleaseEnterValidEmail"] is String{
}
if response["PleaseEnterPassword"] is String{
}
if response["PasswordContainAtleastSixChar"] is String{
}
if response["PleaseEnterPhoneNo"] is String{
}
if response["PhoneNoCannotStartFromZero"] is String{
}
if response["PhoneLengthAtmostfifteen"] is String{
}
if response["PhoneLengthAtleastSix"] is String{
}
if response["PleaseEnterValidPhoneNo"] is String{
}
if response["PleaseEnterFourDigitOtp"] is String{
}
if response["PleaseEnterCountryCode"] is String{
}
if response["PleaseEnterValidCountryCode"] is String{
}
if response["PleaseSelectYourRole"] is String{
}
if response["EmailNotVerified"] is String{
}
if response["PhoneNotVerified"] is String{
}
if response["RefNotVerify"] is String{
}
if response["PleaseFenceMsg"] is String{
}
if response["PleaseEnterOtp"] is String{
}
if response["Search"] is String{
}
if response["people"] is String{
}
if response["custom_attributes"] is String{
}
if response["visitor_info"] is String{
}
if response["utm_source"] is String{
}
if response["utm_medium"] is String{
}
if response["utm_product"] is String{
}
if response["utm_continent_code"] is String{
}
if response["utm_referrer"] is String{
}
if response["utm_vertical_page"] is String{
}
if response["utm_previous_page"] is String{
}
if response["utm_term"] is String{
}
if response["utm_web_referrer"] is String{
}
if response["utm_old_source"] is String{
}
if response["utm_old_medium"] is String{
}
if response["utm_gclid"] is String{
}
if response["old_utm_campaign"] is String{
}
if response["utm_campaign"] is String{
}
if response["utm_session_ip"] is String{
}
if response["show_more"] is String{
}
if response["show_less"] is String{
}
if response["day_list"] is String{
}
if response["hippo_feedback_text"] is String{
}
if response["default_feedback_msg"] is String{
}
if response["hippo_rating_title"] is String{
}
if response["hippo_rating_title_text"] is String{
}
if response["hippo_thanks"] is String{
}
if let hippo_rated_message = response["hippo_rated_message"] as? String{
HippoStrings.thanksForFeedback = hippo_rated_message
}
if response["feedback_pending"] is String{
}
if response["feedback_popup"] is String{
}
if response["feedback_sent"] is String{
}
if response["terms_of_service"] is String{
}
if response["privacy_policy"] is String{
}
if response["tnc_title"] is String{
}
if response["tnc_message"] is String{
}
if response["decline"] is String{
}
if response["accept"] is String{
}
if response["no_bot_found"] is String{
}
if response["next"] is String{
}
if response["update_profile"] is String{
}
if response["assign_the_deal_to_me"] is String{
}
if response["could_not_send_message"] is String{
}
if response["tap_to_retry"] is String{
}
if response["no_internet_cancel"] is String{
}
if response["load_more"] is String{
}
if let reset = response["reset"] as? String{
HippoStrings.reset = reset
}
if let filter = response["filter"] as? String{
HippoStrings.filter = filter
}
if let no_data_found = response["no_data_found"] as? String{
HippoStrings.noDataFound = no_data_found
}
if response["search_here"] is String{
}
if response["fetching_messages"] is String{
}
if response["video_call"] is String{
}
if let call_again = response["call_again"] as? String{
HippoStrings.callAgain = call_again
}
if let hippo_call_back = response["hippo_call_back"] as? String{
HippoStrings.callback = hippo_call_back
}
if response["agent_video_call"] is String{
}
if response["fugu_audio"] is String{
}
if response["fugu_document"] is String{
}
if response["video"] is String{
}
if response["no_handler"] is String{
}
if response["hippo_large_file"] is String{
}
if response["uploading"] is String{
}
if response["uploading_in_progress"] is String{
}
if let hippo_something_wrong = response["hippo_something_wrong"] as? String{
HippoStrings.somethingWentWrong = hippo_something_wrong
}
if response["broadcast_text"] is String{
}
if response["broadcast"] is String{
}
if response["broadcast_history"] is String{
}
if response["recipients"] is String{
}
if let broadcast_detail = response["broadcast_detail"] as? String{
HippoStrings.broadcastDetails = broadcast_detail
}
if response["no_broadcast_found"] is String{
}
if response["peerchat"] is String{
}
if response["members"] is String{
}
if response["close_reason"] is String{
}
if response["conversation_history"] is String{
}
if response["history"] is String{
}
if response["no_change_found"] is String{
}
if let fugu_pdf = response["fugu_pdf"] as? String{
HippoStrings.document = fugu_pdf
}
if let fugu_camera = response["fugu_camera"] as? String{
HippoStrings.camera = fugu_camera
}
if response["facing_connectivity_issues"] is String{
}
if let take_over = response["take_over"] as? String{
HippoStrings.takeOver = take_over
}
if response["custom_date"] is String{
}
if response["channel_journey"] is String{
}
if response["update"] is String{
}
if let title = response["title"] as? String{
HippoStrings.title = title
}
if let hippo_enter_title = response["hippo_enter_title"] as? String{
HippoStrings.enterTitle = hippo_enter_title
}
if let hippo_title_item_price = response["hippo_title_item_price"] as? String{
HippoStrings.price = hippo_title_item_price
}
if let hippo_title_item_description = response["hippo_title_item_description"] as? String{
HippoStrings.description = hippo_title_item_description
}
if response["hippo_total_count"] is String{
}
if let hippo_add_an_option = response["hippo_add_an_option"] as? String{
HippoStrings.addOption = hippo_add_an_option
}
if response["hippo_request_payment"] is String{
}
if let hippo_item_price = response["hippo_item_price"] as? String{
HippoStrings.enterPrice = hippo_item_price
}
if let hippo_item_description = response["hippo_item_description"] as? String{
HippoStrings.enterDescription = hippo_item_description
}
if let hippo_currency = response["hippo_currency"] as? String{
HippoStrings.currency = hippo_currency
}
if response["hippo_search"] is String{
}
if response["hippo_no_sim_detected"] is String{
}
if response["hippo_error_no_countries_found"] is String{
}
if response["hippo_country_picker_header"] is String{
}
if let hippo_send_payment = response["hippo_send_payment"] as? String{
HippoStrings.sendPayment = hippo_send_payment
}
if response["notes"] is String{
}
if response["required"] is String{
}
if response["add_text_here_text"] is String{
}
if response["unverified_account"] is String{
}
if response["pending_verification"] is String{
}
if response["refresh"] is String{
}
if response["hippo_additional_information"] is String{
}
if response["hippo_verify"] is String{
}
if let saved_plan = response["saved_plan"] as? String{
HippoStrings.savedPlans = saved_plan
}
if response["hippo_plan_title"] is String{
}
if let plan_name = response["plan_name"] as? String{
HippoStrings.planName = plan_name
}
if response["no_plan_available"] is String{
}
if response["deal_name"] is String{
}
if let email = response["email"] as? String{
HippoStrings.email = email
}
if response["phone"] is String{
}
if response["company"] is String{
}
if response["pipe_line"] is String{
}
if response["deal_owner"] is String{
}
if response["deal_follow"] is String{
}
if response["deal_location"] is String{
}
if response["add_deal"] is String{
}
if response["edit_deal"] is String{
}
if let error_msg_yellow_bar = response["error_msg_yellow_bar"] as? String{
HippoStrings.slowInternet = error_msg_yellow_bar
}
if let fugu_connecting = response["fugu_connecting"] as? String{
HippoStrings.connecting = fugu_connecting
}
if let fugu_connected = response["fugu_connected"] as? String{
HippoStrings.connected = fugu_connected
}
if let hippo_support = response["hippo_support"] as? String{
HippoStrings.support = hippo_support
}
if response["hippo_rating_review"] is String{
}
if let hippo_in_app = response["hippo_in_app"] as? String{
HippoStrings.inApp = hippo_in_app
}
if response["hippo_sender_name"] is String{
}
if response["hippo_date"] is String{
}
if response["hippo_title"] is String{
}
if response["hippo_message"] is String{
}
if response["hippo_fallback_name"] is String{
}
if response["hippo_broadcast_type"] is String{
}
if let hippo_channel_info = response["hippo_channel_info"] as? String{
HippoStrings.channelInfo = hippo_channel_info
}
if response["hippo_no_channel_journey"] is String{
}
if response["hippo_no_member_found"] is String{
}
if response["hippo_please_select_valid_date"] is String{
}
if response["hippo_no_user_found"] is String{
}
if response["hippo_from"] is String{
}
if response["hippo_to"] is String{
}
if let hippo_update_plan = response["hippo_update_plan"] as? String{
HippoStrings.updatePlan = hippo_update_plan
}
if response["hippo_add_plan"] is String{
}
if let hippo_payment_request = response["hippo_payment_request"] as? String{
HippoStrings.paymentRequest = hippo_payment_request
}
if response["hippo_fill_pre_field"] is String{
}
if let hippo_field_cant_empty = response["hippo_field_cant_empty"] as? String{
HippoStrings.requiredField = hippo_field_cant_empty
}
if response["hippo_invalid_price"] is String{
}
if let hippo_payment = response["hippo_payment"] as? String{
HippoStrings.payment = hippo_payment
}
if response["hippo_verify_details"] is String{
}
if response["hippo_save_card"] is String{
}
if response["hippo_delete_this_plan"] is String{
}
if let hippo_yes = response["hippo_yes"] as? String{
HippoStrings.yes = hippo_yes
}
if let hippo_no = response["hippo_no"] as? String{
HippoStrings.no = hippo_no
}
if response["hippo_business"] is String{
}
if let hippo_self = response["hippo_self"] as? String{
HippoStrings.selfTag = hippo_self
}
if let hippo_plan_id = response["hippo_plan_id"] as? String{
HippoStrings.planId = hippo_plan_id
}
if let hippo_plan_name = response["hippo_plan_name"] as? String{
HippoStrings.planNameTitle = hippo_plan_name
}
if let hippo_plan_type = response["hippo_plan_type"] as? String{
HippoStrings.planOwner = hippo_plan_type
}
if let hippo_updated_at = response["hippo_updated_at"] as? String{
HippoStrings.updatedAt = hippo_updated_at
}
if response["file_not_supported"] is String{
}
if response["hippo_revoked"] is String{
}
if response["hippo_active"] is String{
}
if response["hippo_inactive"] is String{
}
if response["hippo_invited"] is String{
}
if response["hippo_read_at"] is String{
}
if let hippo_delivered = response["hippo_delivered"] as? String{
HippoStrings.delivered = hippo_delivered
}
if let hippo_paid = response["hippo_paid"] as? String{
HippoStrings.paymentPaid = hippo_paid
}
if response["hippo_new_chat"] is String{
}
if let hippo_me = response["hippo_me"] as? String{
HippoStrings.me = hippo_me
}
if response["hippo_na"] is String{
}
if response["hippo_no_saved_data_found"] is String{
}
if response["hippo_files"] is String{
}
if response["hippo_photos"] is String{
}
if response["hippo_site_visit"] is String{
}
if response["hippo_please_select_field"] is String{
}
if let hippo_send = response["hippo_send"] as? String{
HippoStrings.sendTitle = hippo_send
}
if response["hippo_copy_text"] is String{
}
if response["p2p_chats"] is String{
}
if response["hippo_server_disconnected"] is String{
}
if response["hippo_server_connecting"] is String{
}
if response["hippo_you_sent_a_payment"] is String{
}
if let hippo_sent_a_photo = response["hippo_sent_a_photo"] as? String{
HippoStrings.sentAPhoto = hippo_sent_a_photo
}
if response["you_receive_a_payment"] is String{
}
if response["hippo_you_received_a_photo"] is String{
}
if let hippo_sent_a_file = response["hippo_sent_a_file"] as? String{
HippoStrings.sentAFile = hippo_sent_a_file
}
if let hippo_voice = response["hippo_voice"] as? String{
HippoStrings.voice = hippo_voice
}
if let hippo_customer = response["hippo_customer"] as? String{
HippoStrings.customer = hippo_customer
}
if let hippo_call_ended = response["hippo_call_ended"] as? String{
HippoStrings.callEnded = hippo_call_ended
}
if response["hippo_call_with"] is String{
}
if let hippo_missed = response["hippo_missed"] as? String{
HippoStrings.missed = hippo_missed
}
if let hippo_the = response["hippo_the"] as? String{
HippoStrings.the = hippo_the
}
if let hippo_bot_in_progress = response["hippo_bot_in_progress"] as? String{
HippoStrings.botInProgress = hippo_bot_in_progress
}
if let hippo_no_internet_connected = response["hippo_no_internet_connected"] as? String{
HippoStrings.noNetworkConnection = hippo_no_internet_connected
}
if response["hippo_close_conversation"] is String{
}
if response["hippo_closing_notes"] is String{
}
if response["hippo_conversation_closed"] is String{
}
if response["hippo_assigned_to"] is String{
}
if let hippo_assign_conversation = response["hippo_assign_conversation"] as? String{
HippoStrings.assignConversation = hippo_assign_conversation
}
if let hippo_internal_notes = response["hippo_internal_notes"] as? String{
HippoStrings.internalNotes = hippo_internal_notes
}
if let hippo_text = response["hippo_text"] as? String{
HippoStrings.text = hippo_text
}
if let hippo_Bot = response["hippo_Bot"] as? String{
HippoStrings.bot = hippo_Bot
}
if let hippo_savePaymentPlan = response["hippo_savePaymentPlan"] as? String{
HippoStrings.savePaymentPlan = hippo_savePaymentPlan
}
if let hippo_EditPaymentPlanPopup = response["hippo_EditPaymentPlanPopup"] as? String{
HippoStrings.editPaymentPlan = hippo_EditPaymentPlanPopup
}
if let hippo_DeletePaymentPlanPopup = response["hippo_DeletePaymentPlanPopup"] as? String{
HippoStrings.deletePaymentPlan = hippo_DeletePaymentPlanPopup
}
if let hippo_send_this_plan = response["hippo_send_this_plan"] as? String{
HippoStrings.sendPaymentRequestPopup = hippo_send_this_plan
}
if let hippo_is_required = response["hippo_is_required"] as? String{
HippoStrings.isRequired = hippo_is_required
}
if let hippo_enter_planname = response["hippo_enter_planname"] as? String{
HippoStrings.enterPlanName = hippo_enter_planname
}
if let hippo_invalid_price = response["hippo_invalid_price"] as? String{
HippoStrings.invalidPriceAmount = hippo_invalid_price
}
if let hippo_takeover_chat = response["hippo_takeover_chat"] as? String{
HippoStrings.takeOverChat = hippo_takeover_chat
}
if let video = response["video"] as? String{
HippoStrings.video = video
}
if let hippo_assigned_to = response["hippo_assigned_to"] as? String{
HippoStrings.assignedTo = hippo_assigned_to
}
if let hippo_calling_connection = response["hippo_calling_connection"] as? String{
HippoStrings.connectingToMeeting = hippo_calling_connection
}
if let hippo_establishing_connection = response["hippo_establishing_connection"] as? String{
HippoStrings.establishingConnection = hippo_establishing_connection
}
if let hippo_emptymessage = response["hippo_emptymessage"] as? String{
HippoStrings.enterSomeText = hippo_emptymessage
}
}
class func updateLanguageApi() {
var params = [String: Any]()
params["en_user_id"] = HippoUserDetail.fuguEnUserID
params["app_secret_key"] = HippoConfig.shared.appSecretKey
params["update_lang"] = getCurrentLanguageLocale()
params["offering"] = HippoConfig.shared.offering
params["device_type"] = Device_Type_iOS
if let userIdenficationSecret = HippoConfig.shared.userDetail?.userIdenficationSecret{
if userIdenficationSecret.trimWhiteSpacesAndNewLine().isEmpty == false {
params["user_identification_secret"] = userIdenficationSecret
}
}
HippoConfig.shared.log.trace(params, level: .request)
HTTPClient.makeConcurrentConnectionWith(method: .POST, enCodingType: .json, para: params, extendedUrl: FuguEndPoints.updateLanguage.rawValue) { (responseObject, error, tag, statusCode) in
}
}
}
|
//
// Player.swift
// app-Swoosh
//
// Created by Tucker Mogren on 6/30/18.
// Copyright ยฉ 2018 TuckerMogren. All rights reserved.
//
import Foundation
struct Player {
var desiredLeague: String!
var selectedSkillLvl: String!
}
|
//
// LocalParticipantRepository.swift
// CenaNavidad
//
// Created by Alberto gurpegui on 6/1/19.
// Copyright ยฉ 2019 Alberto gurpegui. All rights reserved.
//
import Foundation
import RealmSwift
class LocalParticipantRepository: Repository {
func getAll() -> [Participant] {
var participants: [Participant] = []
do {
let entities = try Realm().objects(ParticipantEntity.self).sorted(byKeyPath: "creationDate", ascending: false)
for entity in entities {
let model = entity.participantModel()
participants.append(model)
}
}
catch let error as NSError {
print("ERROR getAll Participants: ", error.description)
}
return participants
}
func get(identifier: String) -> Participant? {
do{
let realm = try Realm()
if let entity = realm.objects(ParticipantEntity.self).filter("id == %@", identifier).first{
let model = entity.participantModel()
return model
}
}
catch {
return nil
}
return nil
}
func get(name: String) -> Participant? {
do{
let realm = try Realm()
if let entity = realm.objects(ParticipantEntity.self).filter("name == %@", name).first{
let model = entity.participantModel()
return model
}
}
catch {
return nil
}
return nil
}
func get(isPaid: Bool) -> Participant? {
do{
let realm = try Realm()
if let entity = realm.objects(ParticipantEntity.self).filter("isPaid == %@", true).first{
let model = entity.participantModel()
return model
}
}
catch {
return nil
}
return nil
}
func getCount(name: String) -> Int? {
do{
let realm = try Realm()
return realm.objects(ParticipantEntity.self).filter("name == %@", name).count
}
catch {
return nil
}
return nil
}
func create(a: Participant) -> Bool {
do{
let realm = try Realm()
let entity = ParticipantEntity(participant: a)
try realm.write{
realm.add(entity,update: true)
}
}
catch{
return false
}
return true
}
func delete(a: Participant) -> Bool {
do{
let realm = try Realm()
try realm.write {
let entityToDelete = realm.objects(ParticipantEntity.self).filter("id == %@", a.id)
realm.delete(entityToDelete)
}
}
catch{
return false
}
return true
}
func update(a: Participant) -> Bool {
return create(a:a)
}
}
|
//
// Message.swift
// chatengie
//
// Created by Ilia Batiy on 17/02/16.
// Copyright ยฉ 2016 engie. All rights reserved.
//
import Foundation
class Message {
var id: Int?
var from: User
var to: User
var message: String
init(id: Int? = nil, to: User, from: User, message: String){
self.id = id
self.from = from
self.to = to
self.message = message
}
var chatHashValue: Int {
get {
return [to.name, from.name]
.sort()
.joinWithSeparator("__")
.hashValue
}
}
}
|
//
// ContractorProfileModel.swift
// TooliDemo
//
// Created by Azharhussain on 23/08/17.
// Copyright ยฉ 2017 Impero IT. All rights reserved.
//
import Foundation
import UIKit
import ObjectMapper
class ContractorProfileModel:NSObject, Mappable {
var Status = 0
var Message = ""
var Result : ResultsContractorProfileModel = ResultsContractorProfileModel()
override init()
{
}
required init?(map: Map){
Status <- map["Status"]
Message <- map["Message"]
Result <- map["Result"]
}
func mapping(map: Map) {
Status <- map["Status"]
Message <- map["Message"]
Result <- map["Result"]
}
}
class ResultsContractorProfileModel: NSObject, Mappable {
var IsSaved : Bool = false
var JobRoleName = ""
var TotalFollower = 0
var TotalFollowing = 0
var IsFollow : Bool = false
var IsFollowing = false
var BirthDate = ""
var IsEmailPublic : Bool = false
var IsPhonePublic : Bool = false
var IsMobilePublic : Bool = false
var MobileNumber = ""
var PhoneNumber = ""
var CompanyEmailID = ""
var Website = ""
var DistanceRadius = 0
var PerHourRate = ""
var IsPerHourRatePublic : Bool = false
var PerDayRate = ""
var IsPerDayRatePublic : Bool = false
var IsOwnVehicle : Bool = false
var IsLicenceHeld : Bool = false
var UserID = ""
var FullName = ""
var CompanyName = ""
var ProfileImageLink = ""
var TradeName = ""
var CityName = ""
var DistanceAwayText = ""
var Description = ""
var TradeNameList : [String] = []
var SectorNameList : [String] = []
var ServiceNameList : [String] = []
var ExperinceList : [ExperienceM] = []
var CertificateList : [DefualtCertificateM] = []
var ActivityList : [DashboardNM] = []
var PortfolioList : [PortfolioViewM] = []
var FollowerUserList : [FollowerUserListM] = []
var FollowingUserList : [FollowingUserListM] = []
override init()
{
}
required init?(map: Map){
IsSaved <- map["IsSaved"]
JobRoleName <- map["JobRoleName"]
TotalFollower <- map["TotalFollower"]
TotalFollowing <- map["TotalFollowing"]
IsFollow <- map["IsFollow"]
IsFollowing <- map["IsFollowing"]
BirthDate <- map["BirthDate"]
IsEmailPublic <- map["IsEmailPublic"]
IsPhonePublic <- map["IsPhonePublic"]
IsMobilePublic <- map["IsMobilePublic"]
MobileNumber <- map["MobileNumber"]
PhoneNumber <- map["PhoneNumber"]
CompanyEmailID <- map["CompanyEmailID"]
Website <- map["Website"]
DistanceRadius <- map["DistanceRadius"]
PerHourRate <- map["PerHourRate"]
IsPerHourRatePublic <- map["IsPerHourRatePublic"]
PerDayRate <- map["PerDayRate"]
IsPerDayRatePublic <- map["IsPerDayRatePublic"]
IsOwnVehicle <- map["IsOwnVehicle"]
IsLicenceHeld <- map["IsLicenceHeld"]
UserID <- map["UserID"]
FullName <- map["FullName"]
CompanyName <- map["CompanyName"]
ProfileImageLink <- map["ProfileImageLink"]
TradeName <- map["TradeName"]
CityName <- map["CityName"]
DistanceAwayText <- map["DistanceAwayText"]
Description <- map["Description"]
TradeNameList <- map["TradeNameList"]
SectorNameList <- map["SectorNameList"]
ServiceNameList <- map["ServiceNameList"]
ExperinceList <- map["ExperinceList"]
CertificateList <- map["CertificateList"]
ActivityList <- map["ActivityList"]
PortfolioList <- map["PortfolioList"]
FollowerUserList <- map["FollowerUserList"]
FollowingUserList <- map["FollowingUserList"]
}
func mapping(map: Map) {
IsSaved <- map["IsSaved"]
JobRoleName <- map["JobRoleName"]
TotalFollower <- map["TotalFollower"]
TotalFollowing <- map["TotalFollowing"]
IsFollow <- map["IsFollow"]
IsFollowing <- map["IsFollowing"]
BirthDate <- map["BirthDate"]
IsEmailPublic <- map["IsEmailPublic"]
IsPhonePublic <- map["IsPhonePublic"]
IsMobilePublic <- map["IsMobilePublic"]
MobileNumber <- map["MobileNumber"]
PhoneNumber <- map["PhoneNumber"]
CompanyEmailID <- map["CompanyEmailID"]
Website <- map["Website"]
DistanceRadius <- map["DistanceRadius"]
PerHourRate <- map["PerHourRate"]
IsPerHourRatePublic <- map["IsPerHourRatePublic"]
PerDayRate <- map["PerDayRate"]
IsPerDayRatePublic <- map["IsPerDayRatePublic"]
IsOwnVehicle <- map["IsOwnVehicle"]
IsLicenceHeld <- map["IsLicenceHeld"]
UserID <- map["UserID"]
FullName <- map["FullName"]
CompanyName <- map["CompanyName"]
ProfileImageLink <- map["ProfileImageLink"]
TradeName <- map["TradeName"]
CityName <- map["CityName"]
DistanceAwayText <- map["DistanceAwayText"]
Description <- map["Description"]
TradeNameList <- map["TradeNameList"]
SectorNameList <- map["SectorNameList"]
ServiceNameList <- map["ServiceNameList"]
ExperinceList <- map["ExperinceList"]
CertificateList <- map["CertificateList"]
ActivityList <- map["ActivityList"]
PortfolioList <- map["PortfolioList"]
FollowerUserList <- map["FollowerUserList"]
FollowingUserList <- map["FollowingUserList"]
}
}
|
//
// EventImageLink.swift
// IsisCalendar
//
// Created by jorge Sanmartin on 8/9/15.
// Copyright (c) 2015 isis. All rights reserved.
//
import Foundation
class SessionImageLink{
var rel: String!
var href: String!
var mediaType: String!
static func parseImageLink(item:NSDictionary) -> SessionImageLink{
let imageLink = SessionImageLink()
if let rel = item["rel"] as? String {
imageLink.rel = rel
}
if let href = item["href"] as? String {
imageLink.href = href
}
if let mediaType = item["mediaType"] as? String {
imageLink.mediaType = mediaType
}
return imageLink
}
} |
//
// SaveUpdateTableViewController.swift
// TodayNews
//
// Created by Ron Rith on 1/28/18.
// Copyright ยฉ 2018 Ron Rith. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
import SCLAlertView
import SwiftyJSON
class SaveUpdateTableViewController: UITableViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate ,NewsServiceDelegate,NVActivityIndicatorViewable,UIPickerViewDelegate,UIPickerViewDataSource{
// Property
let imagePicker = UIImagePickerController()
@IBOutlet var newsTitleTextField: UITextField!
@IBOutlet var newsShortDescription: UITextField!
@IBOutlet var newsDescriptionTextView: UITextView!
@IBOutlet var newsImageView: UIImageView!
@IBOutlet var saveUpdateNewNavigationBar: UINavigationItem!
@IBOutlet var newsTypeAuthorPickerView: UIPickerView!
var newsService = NewsService()
var newsTypeValue: String = "Sport"
var authorEmailValue: String = "author1@gmail.com"
var jsonDictHolder: [String: Any]?
var newsType: [NewsType] = []
var authors: [Author] = []
var data: [[String]] = [[String]]()
var arrn: [String] = [String]()
var arra: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
newsService.delegate = self
newsTypeAuthorPickerView.delegate = self
newsTypeAuthorPickerView.dataSource = self
imagePicker.delegate = self
if let newsData = jsonDictHolder {
print("********view did load*********")
print("NEWSDATA: \(newsData)")
for (key,value) in newsData{
print("KEY: \(key); VALUE: \(value)")
if(key == "newsObj"){
var nob: News?
nob = value as! News
newsTitleTextField.text = nob?.name ?? ""
newsShortDescription.text = nob?.dec ?? ""
newsDescriptionTextView.text = nob?.desEn ?? ""
let url = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Angkor_Wat.jpg/1280px-Angkor_Wat.jpg"
newsImageView.downloadImageWith(urlString: url, completion: {
self.newsImageView.image
})
newsImageView.clipsToBounds = true
self.title = "EDIT: \(nob?.name ?? "")"
}else if(key == "newsTypes"){
self.newsType = value as! [NewsType]
print("self.newsType: \(self.newsType)")
} else if(key == "authors"){
self.authors = value as! [Author]
print("self.authors: \(self.authors)")
}
}
for nwi in self.newsType {
arrn.append(nwi.desEn)
}
for ath in self.authors{
arra.append(ath.email)
}
self.data = [
arrn,
arra
]
}
else {
self.title = "ADD NEWS"
}
setUpView()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
print("(numberOfComponents) self.data.count.count = \(self.data.count)")
return self.data.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.data[component].count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return "\(data[component][row])"
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("Selected Row: \(row) Component: \(component)")
print("\(data[component][row])")
if component == 0 {
self.newsTypeValue = data[component][row]
}else if component == 1{
self.authorEmailValue = data[component][row]
}
}
// func getAllNewsType(){
// getNewsTypeData()
// }
func setUpView(){
setupNavigationBar()
setupViewCornerRadius(view: newsImageView)
setupViewCornerRadius(view: newsDescriptionTextView)
}
func setupViewCornerRadius(view: UIView) {
let layer = view.layer
// Corner
layer.cornerRadius = 5
layer.masksToBounds = true
// Border
layer.borderColor = #colorLiteral(red: 0.06274510175, green: 0, blue: 0.1921568662, alpha: 1)
layer.borderWidth = 1
}
func setupNavigationBar() {
if #available(iOS 11.0, *) {
saveUpdateNewNavigationBar.largeTitleDisplayMode = .never
}
navigationController?.navigationBar.barTintColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
}
func testUpload(){
if let imageData = UIImageJPEGRepresentation(self.newsImageView.image!, 1){
print("imageData: \(imageData)")
newsService.uploadFile(file: imageData) { (imageUrl, error) in
// Check error
if let err = error { SCLAlertView().showError("Error", subTitle: err.localizedDescription); return }
print("imageUrl: \(imageUrl!)")
}
}
}
func testUploadDev(){
if let imageData = UIImageJPEGRepresentation(self.newsImageView.image!, 0.1){
print("imageData: \(imageData)")
newsService.uploadFile(file: imageData) { (imageUrl, error) in
// Check error
if let err = error { SCLAlertView().showError("Error", subTitle: err.localizedDescription); return }
print("imageUrl: \(imageUrl!)")
}
}
}
@IBAction func browsNewsImage(_ sender: Any) {
print(#function)
imagePicker.allowsEditing = false // or true
imagePicker.sourceType = .photoLibrary // or .camera
// imagePicker.mediaTypes = [kUTTypeImage as String] or [kUTTypeMovie as String] or [kUTTypeImage as String, kUTTypeMovie as String]
present(imagePicker, animated: true, completion: nil)
}
// view image in news view
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print(#function)
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
newsImageView.contentMode = .scaleAspectFit
newsImageView.image = pickedImage
}
let imageURL = info[UIImagePickerControllerReferenceURL] as! NSURL
let fileName = imageURL.absoluteString
print("File Name: \(fileName!)")
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print(#function)
dismiss(animated: true, completion: nil)
}
@IBAction func backToMain(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func SaveNewsData(_ sender: Any) {
print("Start Function Save \(#function)")
// Read Image
let imageData = UIImageJPEGRepresentation(self.newsImageView.image!, 1)
print("imageData: \(imageData!)")
newsService.uploadFile(file: imageData!) { (imageUrl, error) in
// Check error
if let err = error { SCLAlertView().showError("Error", subTitle: err.localizedDescription); return }
let paramaters = [
"name": self.newsTitleTextField.text!,
"dec": self.newsShortDescription.text!,
"desEn": self.newsDescriptionTextView.text!,
"objectStatus": true,
"realImageUrl": imageUrl ?? ""
] as [String : Any]
if let news = self.jsonDictHolder {
for (key,value) in news{
print("KEY: \(key); VALUE: \(value)")
if(key == "newsObj"){
var nob: News?
nob = value as! News
let nob_id = nob?.id as! Int
self.newsService.updateNews(with: self.newsTypeValue, with: "rithronlkh@gmail.com", with: self.authorEmailValue,with: "\(nob_id)", parameters: paramaters)
}else if(key == "newsTypes"){
self.newsType = value as! [NewsType]
} else if(key == "authors"){
self.authors = value as! [Author]
}
}
}else {
print("news: save")
self.newsService.saveNews(with: self.newsTypeValue, with: "rithronlkh@gmail.com", with: self.authorEmailValue, paramaters: paramaters)
}
}
print("End Function Save \(#function)")
}
func didUpdateNews(error: Error?) {
stopAnimating()
if let err = error { SCLAlertView().showError("Error", subTitle: err.localizedDescription); return }
self.navigationController?.popViewController(animated: true)
}
func SaveNews(error: Error?) {
stopAnimating()
if let err = error { SCLAlertView().showError("Error", subTitle: err.localizedDescription); return }
self.navigationController?.popViewController(animated: true)
}
override func viewDidAppear(_ animated: Bool) {
print("viewdidappear*****")
print("viewdidappear news type: \(self.newsType)")
print("viewdidappear authors: \(self.authors)")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.