repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
huangboju/Moots
|
UICollectionViewLayout/CollectionViewSlantedLayout-master/Sources/CollectionViewSlantedLayout.swift
|
1
|
10616
|
/**
This file is part of the CollectionViewSlantedLayout package.
Copyright (c) 2016 Yassir Barchi <dev.yassir@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit;
/**
CollectionViewSlantedLayout is a subclass of UICollectionViewLayout
allowing the display of slanted content on UICollectionView.
By default, this UICollectionViewLayout has initialize a set
of properties to work as designed.
*/
@objc open class CollectionViewSlantedLayout: UICollectionViewLayout {
/**
The slanting size.
The default value of this property is `75`.
*/
@IBInspectable open var slantingSize: UInt = 75 {
didSet {
updateRotationAngle()
invalidateLayout()
}
}
/**
The slanting direction.
The default value of this property is `upward`.
*/
@objc open var slantingDirection: SlantingDirection = .upward {
didSet {
updateRotationAngle()
invalidateLayout()
}
}
/**
The angle, in radians, of the slanting.
The value of this property could be used to apply a rotation transform on the cell's contentView in the
`collectionView(_:cellForItemAt:)` method implementation.
```
if let layout = collectionView.collectionViewLayout as? CollectionViewSlantedLayout {
cell.contentView.transform = CGAffineTransform(rotationAngle: layout.rotationAngle)
}
```
*/
@objc open fileprivate(set) var slantingAngle: CGFloat = 0
/**
The scroll direction of the grid.
The grid layout scrolls along one axis only, either horizontally or vertically.
The default value of this property is `vertical`.
*/
@objc open var scrollDirection: UICollectionViewScrollDirection = .vertical{
didSet {
updateRotationAngle()
invalidateLayout()
}
}
/**
Allows to disable the slanting for the first cell.
Set it to `true` to disable the slanting for the first cell. The default value of this property is `false`.
*/
@IBInspectable open var isFistCellExcluded: Bool = false {
didSet {
invalidateLayout()
}
}
/**
Allows to disable the slanting for the last cell.
Set it to `true` to disable the slanting for the last cell. The default value of this property is `false`.
*/
@IBInspectable open var isLastCellExcluded: Bool = false {
didSet {
invalidateLayout()
}
}
/**
The spacing to use between two items.
The default value of this property is 10.0.
*/
@IBInspectable open var lineSpacing: CGFloat = 10 {
didSet {
invalidateLayout()
}
}
/**
The default size to use for cells.
If the delegate does not implement the `collectionView(_:layout:sizeForItemAt:)` method, the slanted layout
uses the value in this property to set the size of each cell. This results in cells that all have the same size.
The default value of this property is 225.
*/
@IBInspectable open var itemSize: CGFloat = 225 {
didSet {
invalidateLayout()
}
}
/**
The zIndex order of the items in the layout.
The default value of this property is `ascending`.
*/
@objc open var zIndexOrder: ZIndexOrder = .ascending {
didSet {
invalidateLayout()
}
}
//MARK: Private
// :nodoc:
internal var cachedAttributes = [CollectionViewSlantedLayoutAttributes]()
// :nodoc:
internal var cachedContentSize: CGFloat = 0
// :nodoc:
fileprivate func itemSize(forItemAt indexPath: IndexPath) -> CGFloat {
guard let collectionView = collectionView,
let delegate = collectionView.delegate as? CollectionViewDelegateSlantedLayout else {
return max(itemSize, 0)
}
let size = delegate.collectionView?(collectionView, layout: self, sizeForItemAt: indexPath)
return max(size ?? itemSize, 0)
}
/// :nodoc:
fileprivate func maskForItemAtIndexPath(_ indexPath: IndexPath) -> CAShapeLayer {
let slantedLayerMask = CAShapeLayer()
let bezierPath = UIBezierPath()
let disableSlantingForTheFirstCell = indexPath.row == 0 && isFistCellExcluded;
let disableSlantingForTheFirstLastCell = indexPath.row == numberOfItems-1 && isLastCellExcluded;
let size = itemSize(forItemAt: indexPath)
if ( scrollDirection.isVertical ) {
switch self.slantingDirection {
case .downward:
bezierPath.move(to: CGPoint.init(x: 0, y: 0))
bezierPath.addLine(to: CGPoint.init(x: width, y: disableSlantingForTheFirstCell ? 0 : CGFloat(slantingSize)))
bezierPath.addLine(to: CGPoint.init(x: width, y: size))
bezierPath.addLine(to: CGPoint.init(x: 0, y: disableSlantingForTheFirstLastCell ? size : size-CGFloat(slantingSize)))
bezierPath.addLine(to: CGPoint.init(x: 0, y: 0))
default:
let startPoint = CGPoint.init(x: 0, y: disableSlantingForTheFirstCell ? 0 : CGFloat(self.slantingSize))
bezierPath.move(to: startPoint)
bezierPath.addLine(to: CGPoint.init(x: width, y: 0))
bezierPath.addLine(to: CGPoint.init(x: width, y: disableSlantingForTheFirstLastCell ? size : size-CGFloat(slantingSize)))
bezierPath.addLine(to: CGPoint.init(x: 0, y: size))
bezierPath.addLine(to: startPoint)
}
}
else {
switch self.slantingDirection {
case .upward:
let startPoint = CGPoint.init(x: disableSlantingForTheFirstCell ? 0 : CGFloat(slantingSize), y: 0)
bezierPath.move(to: startPoint)
bezierPath.addLine(to: CGPoint.init(x: size, y: 0))
bezierPath.addLine(to: CGPoint.init(x: disableSlantingForTheFirstLastCell ? size : size-CGFloat(slantingSize), y: height))
bezierPath.addLine(to: CGPoint.init(x: 0, y: height))
bezierPath.addLine(to: startPoint)
default:
bezierPath.move(to: CGPoint.init(x: 0, y: 0))
bezierPath.addLine(to: CGPoint.init(x: disableSlantingForTheFirstLastCell ? size : size-CGFloat(slantingSize), y: 0))
bezierPath.addLine(to: CGPoint.init(x: size, y: height))
bezierPath.addLine(to: CGPoint.init(x: disableSlantingForTheFirstCell ? 0 : CGFloat(slantingSize), y: height))
bezierPath.addLine(to: CGPoint.init(x: 0, y: 0))
}
}
bezierPath.close()
slantedLayerMask.path = bezierPath.cgPath
return slantedLayerMask
}
/// :nodoc:
fileprivate func updateRotationAngle() {
let oppositeSide = CGFloat(slantingSize)
var factor = slantingDirection == .upward ? -1 : 1
var adjacentSide = width
if !scrollDirection.isVertical {
adjacentSide = height
factor *= -1
}
let angle = atan(tan(oppositeSide / adjacentSide))
slantingAngle = angle * CGFloat(factor)
}
}
//MARK: CollectionViewLayout methods overriding
extension CollectionViewSlantedLayout {
/// :nodoc:
override open var collectionViewContentSize : CGSize {
let contentSize = CGFloat(numberOfItems - 1) * (lineSpacing - CGFloat(slantingSize)) + cachedContentSize
return scrollDirection.isVertical ? CGSize(width: width, height: contentSize) : CGSize(width: contentSize, height: height)
}
/// :nodoc:
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true;
}
/// :nodoc:
override open func prepare() {
updateRotationAngle()
cachedAttributes = [CollectionViewSlantedLayoutAttributes]()
cachedContentSize = 0
var position: CGFloat = 0
for item in 0..<numberOfItems {
let indexPath = IndexPath(item: item, section: 0)
let attributes = CollectionViewSlantedLayoutAttributes(forCellWith: indexPath)
let size = itemSize(forItemAt: indexPath)
let frame : CGRect
if ( scrollDirection.isVertical ) {
frame = CGRect(x: 0, y: position, width: width, height: size)
}
else {
frame = CGRect(x: position, y: 0, width: size, height: height)
}
attributes.frame = frame
attributes.size = frame.size
attributes.zIndex = zIndexOrder.isAscending ? item : (numberOfItems - item)
attributes.slantedLayerMask = self.maskForItemAtIndexPath(indexPath)
cachedAttributes.append(attributes)
cachedContentSize += size
position += size + lineSpacing - CGFloat(slantingSize)
}
}
/// :nodoc:
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return cachedAttributes.filter { attributes in
return attributes.frame.intersects(rect)
}
}
/// :nodoc:
override open func layoutAttributesForItem(at indexPath: IndexPath) -> CollectionViewSlantedLayoutAttributes? {
return cachedAttributes[indexPath.item]
}
}
|
mit
|
7ed354bca736b35c8e5ff469e634ffa0
| 36.118881 | 138 | 0.63442 | 4.843066 | false | false | false | false |
edx/edx-app-ios
|
Source/AccessibilityCLButton.swift
|
2
|
1221
|
//
// AccessibilityCLButton.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 28/07/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
class AccessibilityCLButton: CustomPlayerButton {
private var selectedAccessibilityLabel : String?
private var normalAccessibilityLabel : String?
override public var isSelected: Bool {
didSet {
if isSelected {
if let selectedLabel = selectedAccessibilityLabel {
self.accessibilityLabel = selectedLabel
}
}
else {
if let normalLabel = normalAccessibilityLabel {
self.accessibilityLabel = normalLabel
}
}
}
}
public func setAccessibilityLabelsForStateNormal(normalStateLabel normalLabel: String?, selectedStateLabel selectedLabel: String?) {
self.selectedAccessibilityLabel = selectedLabel
self.normalAccessibilityLabel = normalLabel
}
public override func draw(_ rect: CGRect) {
let r = UIBezierPath(ovalIn: rect)
UIColor.black.withAlphaComponent(0.65).setFill()
r.fill()
super.draw(rect)
}
}
|
apache-2.0
|
cd3e09b38b89f7149519c7c99b8a11a4
| 28.071429 | 136 | 0.619984 | 5.402655 | false | false | false | false |
huonw/swift
|
test/SILGen/access_marker_gen.swift
|
1
|
6150
|
// RUN: %target-swift-emit-silgen -module-name access_marker_gen -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -enable-sil-ownership %s | %FileCheck %s
func modify<T>(_ x: inout T) {}
public struct S {
var i: Int
var o: AnyObject?
}
// CHECK-LABEL: sil hidden [noinline] @$S17access_marker_gen5initSyAA1SVyXlSgF : $@convention(thin) (@guaranteed Optional<AnyObject>) -> @owned S {
// CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>):
// CHECK: [[BOX:%.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [var] [[BOX]] : ${ var S }
// CHECK: [[ADDR:%.*]] = project_box [[MARKED_BOX]] : ${ var S }, 0
// CHECK: cond_br %{{.*}}, bb1, bb2
// CHECK: bb1:
// CHECK: [[ACCESS1:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS1]] : $*S
// CHECK: end_access [[ACCESS1]] : $*S
// CHECK: bb2:
// CHECK: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS2]] : $*S
// CHECK: end_access [[ACCESS2]] : $*S
// CHECK: bb3:
// CHECK: [[ACCESS3:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*S
// CHECK: [[RET:%.*]] = load [copy] [[ACCESS3]] : $*S
// CHECK: end_access [[ACCESS3]] : $*S
// CHECK: return [[RET]] : $S
// CHECK-LABEL: } // end sil function '$S17access_marker_gen5initSyAA1SVyXlSgF'
@inline(never)
func initS(_ o: AnyObject?) -> S {
var s: S
if o == nil {
s = S(i: 0, o: nil)
} else {
s = S(i: 1, o: o)
}
return s
}
@inline(never)
func takeS(_ s: S) {}
// CHECK-LABEL: sil @$S17access_marker_gen14modifyAndReadSyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: %[[BOX:.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: %[[ADDRS:.*]] = project_box %[[BOX]] : ${ var S }, 0
// CHECK: %[[ACCESS1:.*]] = begin_access [modify] [unknown] %[[ADDRS]] : $*S
// CHECK: %[[ADDRI:.*]] = struct_element_addr %[[ACCESS1]] : $*S, #S.i
// CHECK: assign %{{.*}} to %[[ADDRI]] : $*Int
// CHECK: end_access %[[ACCESS1]] : $*S
// CHECK: %[[ACCESS2:.*]] = begin_access [read] [unknown] %[[ADDRS]] : $*S
// CHECK: %{{.*}} = load [copy] %[[ACCESS2]] : $*S
// CHECK: end_access %[[ACCESS2]] : $*S
// CHECK-LABEL: } // end sil function '$S17access_marker_gen14modifyAndReadSyyF'
public func modifyAndReadS() {
var s = initS(nil)
s.i = 42
takeS(s)
}
var global = S(i: 0, o: nil)
func readGlobal() -> AnyObject? {
return global.o
}
// CHECK-LABEL: sil hidden @$S17access_marker_gen10readGlobalyXlSgyF
// CHECK: [[ADDRESSOR:%.*]] = function_ref @$S17access_marker_gen6globalAA1SVvau :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]()
// CHECK-NEXT: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*S
// CHECK-NEXT: [[T2:%.*]] = begin_access [read] [dynamic] [[T1]]
// CHECK-NEXT: [[T3:%.*]] = struct_element_addr [[T2]] : $*S, #S.o
// CHECK-NEXT: [[T4:%.*]] = load [copy] [[T3]]
// CHECK-NEXT: end_access [[T2]]
// CHECK-NEXT: return [[T4]]
public struct HasTwoStoredProperties {
var f: Int = 7
var g: Int = 9
// CHECK-LABEL: sil hidden @$S17access_marker_gen22HasTwoStoredPropertiesV027noOverlapOnAssignFromPropToM0yyF : $@convention(method) (@inout HasTwoStoredProperties) -> ()
// CHECK: [[ACCESS1:%.*]] = begin_access [read] [unknown] [[SELF_ADDR:%.*]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[G_ADDR:%.*]] = struct_element_addr [[ACCESS1]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.g
// CHECK-NEXT: [[G_VAL:%.*]] = load [trivial] [[G_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS1]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[F_ADDR:%.*]] = struct_element_addr [[ACCESS2]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.f
// CHECK-NEXT: assign [[G_VAL]] to [[F_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS2]] : $*HasTwoStoredProperties
mutating func noOverlapOnAssignFromPropToProp() {
f = g
}
}
class C {
final var x: Int = 0
let z: Int = 0
}
func testClassInstanceProperties(c: C) {
let y = c.x
c.x = y
}
// CHECK-LABEL: sil hidden @$S17access_marker_gen27testClassInstanceProperties1cyAA1CC_tF :
// CHECK: bb0([[C:%.*]] : @guaranteed $C
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: [[Y:%.*]] = load [trivial] [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: assign [[Y]] to [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
func testClassLetProperty(c: C) -> Int {
return c.z
}
// CHECK-LABEL: sil hidden @$S17access_marker_gen20testClassLetProperty1cSiAA1CC_tF : $@convention(thin) (@guaranteed C) -> Int {
// CHECK: bb0(%0 : @guaranteed $C):
// CHECK: [[ADR:%.*]] = ref_element_addr %{{.*}} : $C, #C.z
// CHECK-NOT: begin_access
// CHECK: %{{.*}} = load [trivial] [[ADR]] : $*Int
// CHECK-NOT: end_access
// CHECK-NOT: destroy_value %0 : $C
// CHECK: return %{{.*}} : $Int
// CHECK-LABEL: } // end sil function '$S17access_marker_gen20testClassLetProperty1cSiAA1CC_tF'
class D {
var x: Int = 0
}
// materializeForSet callback
// CHECK-LABEL: sil private [transparent] @$S17access_marker_gen1DC1xSivmytfU_
// CHECK: end_unpaired_access [dynamic] %1 : $*Builtin.UnsafeValueBuffer
// materializeForSet
// CHECK-LABEL: sil hidden [transparent] @$S17access_marker_gen1DC1xSivm
// CHECK: [[T0:%.*]] = ref_element_addr %2 : $D, #D.x
// CHECK-NEXT: begin_unpaired_access [modify] [dynamic] [[T0]] : $*Int
func testDispatchedClassInstanceProperty(d: D) {
modify(&d.x)
}
// CHECK-LABEL: sil hidden @$S17access_marker_gen35testDispatchedClassInstanceProperty1dyAA1DC_tF
// CHECK: bb0([[D:%.*]] : @guaranteed $D
// CHECK: [[METHOD:%.*]] = class_method [[D]] : $D, #D.x!materializeForSet.1
// CHECK: apply [[METHOD]]({{.*}}, [[D]])
// CHECK-NOT: begin_access
|
apache-2.0
|
667015663775724f0f138a90599296c2
| 38.935065 | 178 | 0.605528 | 3.052109 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift
|
Sources/Search/34_SearchForARange.swift
|
1
|
1459
|
//
// 34_SearchForARange.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-09-04.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:34 Search for a Range
URL: https://leetcode.com/problems/search-for-a-range/
Space: O(1)
Time: O(lgn)
*/
class SearchForARange_Solution {
func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
guard nums.count > 1 else {
if nums.count == 1 && nums[0] == target {
return [0, 0]
}
return [-1, -1]
}
var start = 0
var end = nums.count - 1
// Firstly, find the last element that equals to target.
while start + 1 < end {
let mid = start + (end - start) / 2
if nums[mid] >= target {
end = mid
} else {
start = mid
}
}
var leftBound: Int = -1
if nums[end] == target {
leftBound = end
}
if nums[start] == target {
leftBound = start
}
if leftBound == -1 {
return [-1, -1]
}
start = 0
end = nums.count - 1
// Secondly, find the first element that equals to target.
while start + 1 < end {
let mid = start + (end - start) / 2
if nums[mid] <= target {
start = mid
} else {
end = mid
}
}
var rightBound: Int = -1
if nums[start] == target {
rightBound = start
}
if nums[end] == target {
rightBound = end
}
return [leftBound, rightBound]
}
}
|
mit
|
5a65c43aaaf1d701ca3e3e2ab5418dad
| 20.761194 | 62 | 0.534294 | 3.422535 | false | false | false | false |
Volcanoscar/ShadowVPNiOS
|
tunnel/PacketTunnelProvider.swift
|
1
|
3616
|
//
// PacketTunnelProvider.swift
// tunnel
//
// Created by clowwindy on 7/18/15.
// Copyright © 2015 clowwindy. All rights reserved.
//
import NetworkExtension
class PacketTunnelProvider: NEPacketTunnelProvider {
var session: NWUDPSession? = nil
var pendingStartCompletion: (NSError? -> Void)?
override func startTunnelWithOptions(options: [String : NSObject]?, completionHandler: (NSError?) -> Void) {
// Add code here to start the process of connecting the tunnel
if let serverAddress = self.protocolConfiguration.serverAddress {
session = self.createUDPSessionToEndpoint(NWHostEndpoint(hostname: serverAddress, port: "1123"), fromEndpoint: nil)
self.pendingStartCompletion = completionHandler
self.updateNetwork()
} else {
completionHandler(NSError(domain:"PacketTunnelProviderDomain", code:-1, userInfo:[NSLocalizedDescriptionKey:"Configuration is missing serverAddress"]))
}
}
func log(data: String) {
self.session?.writeDatagram(data.dataUsingEncoding(NSUTF8StringEncoding)!, completionHandler: { (error: NSError?) -> Void in
})
}
func updateNetwork() {
let newSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: self.protocolConfiguration.serverAddress!)
newSettings.IPv4Settings = NEIPv4Settings(addresses: ["10.7.0.2"], subnetMasks: ["255.255.0.0"])
newSettings.IPv4Settings!.includedRoutes = [NEIPv4Route.defaultRoute()]
newSettings.tunnelOverheadBytes = 64
newSettings.DNSSettings = NEDNSSettings(servers: ["8.8.8.8"])
SVCrypto.setPassword("my_password")
self.setTunnelNetworkSettings(newSettings) { (error: NSError?) -> Void in
self.readPacketsFromTUN()
self.readPacketsFromUDP()
if let completionHandler = self.pendingStartCompletion {
// send an packet
// self.log("completion")
completionHandler(error)
}
}
}
func readPacketsFromTUN() {
self.packetFlow.readPacketsWithCompletionHandler {
packets, protocols in
// self.log("readPacketsWithCompletionHandler")
// for p in protocols {
// self.log("protocol: " + p.stringValue)
// }
for packet in packets {
self.session?.writeDatagram(SVCrypto.encrypt(packet), completionHandler: { (error: NSError?) -> Void in
})
}
self.readPacketsFromTUN()
}
}
func readPacketsFromUDP() {
session?.setReadHandler({ (newPackets: [NSData]?, error: NSError?) -> Void in
// self.log("readPacketsFromUDP")
guard let packets = newPackets else { return }
var protocols = [NSNumber]()
var decryptedPackets = [NSData]()
for packet in packets {
// currently IPv4 only
decryptedPackets.append(SVCrypto.decrypt(packet))
protocols.append(2)
}
self.packetFlow.writePackets(decryptedPackets, withProtocols: protocols)
}, maxDatagrams: 1024)
}
override func stopTunnelWithReason(reason: NEProviderStopReason, completionHandler: () -> Void) {
// Add code here to start the process of stopping the tunnel
// self.log("stop tunnel")
session?.cancel()
completionHandler()
super.stopTunnelWithReason(reason, completionHandler: completionHandler)
}
override func handleAppMessage(messageData: NSData, completionHandler: ((NSData?) -> Void)?) {
// Add code here to handle the message
if let handler = completionHandler {
handler(messageData)
}
}
override func sleepWithCompletionHandler(completionHandler: () -> Void) {
// Add code here to get ready to sleep
completionHandler()
}
override func wake() {
// Add code here to wake up
}
}
|
gpl-3.0
|
27ae31add9b8cdd19a0db897c2ffaba3
| 34.097087 | 154 | 0.702628 | 4.150402 | false | false | false | false |
squall09s/VegOresto
|
VegoResto/RechercheViewController.swift
|
1
|
11924
|
//
// RechercheViewController.swift
// VegoResto
//
// Created by Laurent Nicolas on 30/03/2016.
// Copyright © 2016 Nicolas Laurent. All rights reserved.
//
import UIKit
import MGSwipeTableCell
import DGElasticPullToRefresh
class RechercheViewController: VGAbstractFilterViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet weak var varIB_searchBar: UISearchBar?
@IBOutlet weak var varIB_tableView: UITableView?
var afficherUniquementFavoris = false
let TAG_CELL_LABEL_NAME = 501
let TAG_CELL_LABEL_ADRESS = 502
let TAG_CELL_LABEL_DISTANCE = 505
let TAG_CELL_LABEL_VILLE = 506
let TAG_CELL_IMAGE_LOC = 507
let TAG_CELL_VIEW_CATEGORIE_COLOR = 510
let TAG_CELL_IMAGE_FAVORIS = 520
var array_restaurants: [Restaurant] = [Restaurant]()
override func viewDidLoad() {
super.viewDidLoad()
self.varIB_searchBar?.backgroundImage = UIImage()
self.loadRestaurantsWithWord(key: nil)
let loadingView = DGElasticPullToRefreshLoadingViewCircle()
loadingView.tintColor = COLOR_ORANGE
self.varIB_tableView?.dg_addPullToRefreshWithActionHandler({ () -> Void in
// Add your logic here
// Do not forget to call dg_stopLoading() at the end
(self.parent as? NavigationAccueilViewController)?.updateData(forced: true) { (_) in
self.varIB_tableView?.dg_stopLoading()
}
}, loadingView: loadingView)
self.varIB_tableView?.dg_setPullToRefreshFillColor( UIColor(hexString: "EDEDED") )
self.varIB_tableView?.dg_setPullToRefreshBackgroundColor(UIColor.white)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch StoryboardSegue.Main(rawValue: segue.identifier! )! {
case .segueToDetail:
// Prepare for your custom segue transition
if let detailRestaurantVC: DetailRestaurantViewController = segue.destination as? DetailRestaurantViewController {
if let index = self.varIB_tableView?.indexPathForSelectedRow?.row {
detailRestaurantVC.current_restaurant = self.array_restaurants[index]
}
}
default :
break
}
}
// MARK: UITableViewDelegate Delegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let current_restaurant: Restaurant = self.array_restaurants[indexPath.row]
let reuseIdentifier = current_restaurant.favoris.boolValue ? "cell_restaurant_identifer_favoris_on" : "cell_restaurant_identifer_favoris_off"
var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as? MGSwipeTableCell
if cell == nil {
cell = MGSwipeTableCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: reuseIdentifier)
}
// Configure the cell...
let label_name = cell?.viewWithTag(TAG_CELL_LABEL_NAME) as? UILabel
let label_adress = cell?.viewWithTag(TAG_CELL_LABEL_ADRESS) as? UILabel
let label_distance = cell?.viewWithTag(TAG_CELL_LABEL_DISTANCE) as? UILabel
let label_ville = cell?.viewWithTag(TAG_CELL_LABEL_VILLE) as? UILabel
let image_loc = cell?.viewWithTag(TAG_CELL_IMAGE_LOC) as? UIImageView
label_name?.text = current_restaurant.name
label_adress?.text = current_restaurant.address
label_ville?.text = current_restaurant.ville
let view_color_categorie = cell?.viewWithTag(TAG_CELL_VIEW_CATEGORIE_COLOR)
let imageview_favoris = cell?.viewWithTag(TAG_CELL_IMAGE_FAVORIS) as? UIImageView
var imageSwipe: UIImage = Asset.imgFavorisOff.image
switch current_restaurant.categorie() {
case CategorieRestaurant.Vegan :
view_color_categorie?.backgroundColor = COLOR_VERT
if current_restaurant.favoris.boolValue {
imageview_favoris?.image = Asset.imgFavoris0.image
} else {
imageSwipe = Asset.imgFavorisOn0.image
}
case CategorieRestaurant.Végétarien :
view_color_categorie?.backgroundColor = COLOR_VIOLET
if current_restaurant.favoris.boolValue {
imageview_favoris?.image = Asset.imgFavoris1.image
} else {
imageSwipe = Asset.imgFavorisOn1.image
}
case CategorieRestaurant.VeganFriendly :
view_color_categorie?.backgroundColor = COLOR_BLEU
if current_restaurant.favoris.boolValue {
imageview_favoris?.image = Asset.imgFavoris2.image
} else {
imageSwipe = Asset.imgFavorisOn2.image
}
}
let bt1 = MGSwipeButton(title: "", icon: imageSwipe, backgroundColor: COLOR_GRIS_BACKGROUND ) { (_) -> Bool in
current_restaurant.favoris = !(current_restaurant.favoris.boolValue) as NSNumber
self.afficherUniquementFavoris ? self.updateData() : self.varIB_tableView?.reloadData()
return true
}
bt1.buttonWidth = 110
cell?.rightButtons = [ bt1]
cell?.rightSwipeSettings.transition = .static
cell?.rightSwipeSettings.threshold = 10
cell?.rightExpansion.buttonIndex = 0
cell?.rightExpansion.fillOnTrigger = true
label_distance?.text = ""
image_loc?.isHidden = true
if current_restaurant.distance > 0 && current_restaurant.distance < 1000 {
label_distance?.text = String(Int(current_restaurant.distance)) + " m"
image_loc?.isHidden = false
} else if current_restaurant.distance >= 1000 {
label_distance?.text = String(format: "%.1f Km", current_restaurant.distance/1000.0 )
image_loc?.isHidden = false
}
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.array_restaurants.count
}
// MARK: UISearchBar Delegate
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
let textField: UITextField? = self.findTextFieldInView( view: searchBar)
if let _textField = textField {
_textField.enablesReturnKeyAutomatically = false
}
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.resignFirstResponder()
return true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.loadRestaurantsWithWord(key: searchText)
self.varIB_tableView?.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.loadRestaurantsWithWord(key: nil)
self.varIB_tableView?.reloadData()
}
func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func findTextFieldInView(view: UIView) -> UITextField? {
if view is UITextField {
return view as? UITextField
}
for subview: UIView in view.subviews {
let textField: UITextField? = self.findTextFieldInView(view: subview)
if let _textField = textField {
return _textField
}
}
return nil
}
func loadRestaurantsWithWord(key: String?) {
self.array_restaurants = UserData.sharedInstance.getRestaurants()
if self.afficherUniquementFavoris {
self.array_restaurants = self.array_restaurants.flatMap({ (current_restaurant: Restaurant) -> Restaurant? in
if current_restaurant.favoris.boolValue == true {
return current_restaurant
}
return nil
})
}
self.varIB_tableView?.reloadData()
if let _key = key?.lowercased() {
if _key.characters.count > 3 {
self.array_restaurants = self.array_restaurants.flatMap({ (current_restaurant: Restaurant) -> Restaurant? in
if let clean_name: String = current_restaurant.name?.lowercased().folding(options : .diacriticInsensitive, locale: Locale.current ) {
if clean_name.contains(_key) {
return current_restaurant
}
}
if let clean_adress: String = current_restaurant.address?.lowercased().folding(options: .diacriticInsensitive, locale: Locale.current ) {
if clean_adress.contains(_key) {
return current_restaurant
}
}
return nil
})
}
}
self.array_restaurants = self.array_restaurants.flatMap({ (currentResto: Restaurant) -> Restaurant? in
if self.filtre_categorie_VeganFriendly_active && self.filtre_categorie_Vegetarien_active && self.filtre_categorie_Vegan_active {
return currentResto
} else {
switch currentResto.categorie() {
case CategorieRestaurant.Vegan :
if self.filtre_categorie_Vegan_active {
return currentResto
}
case CategorieRestaurant.Végétarien :
if self.filtre_categorie_Vegetarien_active {
return currentResto
}
case CategorieRestaurant.VeganFriendly :
if self.filtre_categorie_VeganFriendly_active {
return currentResto
}
}
return nil
}
})
}
func update_resultats_for_user_location() {
if let location = UserData.sharedInstance.location {
for restaurant in self.array_restaurants {
restaurant.update_distance_avec_localisation( seconde_localisation: location )
}
self.array_restaurants.sort(by: { (restaurantA, restaurantB) -> Bool in
restaurantA.distance < restaurantB.distance
})
self.varIB_tableView?.reloadData()
self.varIB_tableView?.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: false)
}
}
func updateDataAfterDelay() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.updateData()
}
}
override func updateData() {
Debug.log(object: "RechercheViewController - updateData")
self.loadRestaurantsWithWord(key: self.varIB_searchBar?.text)
self.varIB_tableView?.reloadData()
self.varIB_tableView?.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
}
}
// -----------------------------------------
// MARK: Protocol - UIScrollViewDelegate
// -----------------------------------------
extension RechercheViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > 50 {
self.view.endEditing(true)
}
}
}
|
gpl-3.0
|
aa8e429c8a18fddf744afc3b2aae8b06
| 29.02267 | 157 | 0.612803 | 4.831374 | false | false | false | false |
5calls/ios
|
FiveCalls/FiveCalls/IssueDetailViewController.swift
|
1
|
10849
|
//
// IssueDetailViewController.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/2/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
import CoreLocation
import Down
class IssueDetailViewController : UIViewController, IssueShareable {
var issuesManager: IssuesManager!
var issue: Issue!
var logs: ContactLogs?
var contacts: [Contact] = []
var contactsManager: ContactsManager!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(IssueDetailViewController.shareButtonPressed(_ :)))
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableView.automaticDimension
NotificationCenter.default.addObserver(self, selector: #selector(madeCall), name: .callMade, object: nil)
trackEvent("Topic", properties: ["IssueID": String(issue.id), "IssueTitle": issue.name])
loadContacts()
}
private func loadContacts() {
print("Loading contacts for: \(issue.contactAreas)")
// we pass this contact manager around and there's some case where it doesn't make it here,
// create it here if it doesnt exist, with the addition of some latency in fetchContacts for getting contacts again
if contactsManager == nil {
contactsManager = ContactsManager()
}
contactsManager.fetchContacts(location: UserLocation.current) { result in
switch result {
case .success(let contacts):
self.contacts = contacts.filter {
self.issue.contactAreas.contains($0.area)
}
self.tableView.reloadData()
case .failed(let error):
let alert = UIAlertController(title: "Loading Error", message: "There was an error loading your representatives. \(error.localizedDescription)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Retry", style: .default, handler: { _ in
self.loadContacts()
}))
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
@objc func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard section == IssueSections.header.rawValue else {
return nil
}
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 40.0))
let label = UILabel(frame: CGRect(x: 16, y: 0, width: tableView.frame.width - 32.0, height: 40))
let button = UIButton(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 40))
view.addSubview(label)
view.addSubview(button)
view.backgroundColor = R.color.lightGrayBackground()
label.text = R.string.localizable.callYourReps()
label.textAlignment = .center
label.font = .fvc_header
button.addTarget(self, action: #selector(footerAction(_:)), for: .touchUpInside)
return view
}
@objc func footerAction(_ sender: UIButton) {
self.tableView.scrollToRow(at: IndexPath(item: 0, section: 1), at: .top, animated: true)
}
@objc func madeCall() {
logs = ContactLogs.load()
tableView.reloadRows(at: tableView.indexPathsForVisibleRows ?? [], with: .none)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if issue == nil {
return assertionFailure("there was no issue for our issue detail controller")
}
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
logs = ContactLogs.load()
if self.splitViewController == nil {
navigationController?.setNavigationBarHidden(false, animated: true)
} else {
tableView.contentInset = UIEdgeInsets(top: IssuesContainerViewController.headerHeight, left: 0, bottom: 0, right: 0)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadSections(IndexSet(integer: IssueSections.contacts.rawValue), with: .none)
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == R.segue.issueDetailViewController.callScript.identifier, self.splitViewController != nil, let indexPath = tableView.indexPathForSelectedRow {
let controller = R.storyboard.main.callScriptController()!
controller.issuesManager = issuesManager
controller.issue = issue
controller.contact = contacts[indexPath.row]
controller.contacts = contacts
let nav = UINavigationController(rootViewController: controller)
nav.modalPresentationStyle = .formSheet
self.present(nav, animated: true, completion: nil)
return false
}
return true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let nav = segue.destination as? UINavigationController,
let loc = nav.viewControllers.first as? EditLocationViewController {
loc.delegate = self
} else if let call = segue.destination as? CallScriptViewController {
guard let indexPath = tableView.indexPathForSelectedRow else { return }
call.issuesManager = issuesManager
call.issue = issue
call.contact = contacts[indexPath.row]
call.contacts = contacts
}
}
@objc func shareButtonPressed(_ button: UIBarButtonItem) {
shareIssue(from: button)
}
}
enum IssueSections : Int {
case header
case contacts
case count
}
enum IssueHeaderRows : Int {
case title
case description
case count
}
extension IssueDetailViewController : UITableViewDataSource {
var isSplitDistrict: Bool {
// FIXME: determine split district another way
return false
}
func numberOfSections(in tableView: UITableView) -> Int {
return IssueSections.count.rawValue
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == IssueSections.header.rawValue {
return IssueHeaderRows.count.rawValue
} else {
return max(1, contacts.count)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case IssueSections.header.rawValue:
return headerCell(at: indexPath)
default:
if contacts.isEmpty {
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.setLocationCell, for: indexPath)! as SetLocationCell
if isSplitDistrict {
cell.messageLabel.text = R.string.localizable.splitDistrictMessage()
} else {
cell.messageLabel.text = R.string.localizable.setYourLocation()
}
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.contactCell, for: indexPath)!
cell.borderTop = indexPath.row == 0
let contact = contacts[indexPath.row]
let hasContacted = logs?.hasContacted(contact: contact, forIssue: issue) ?? false
cell.configure(contact: contact, hasContacted: hasContacted)
return cell
}
}
}
private func headerCell(at indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case IssueHeaderRows.title.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.titleCell, for: indexPath)!
cell.issueLabel.text = issue.name
return cell
case IssueHeaderRows.description.rawValue:
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.descriptionCell, for: indexPath)!
cell.issueTextView.isScrollEnabled = false
cell.issueTextView.isEditable = false
let markdown = Down.init(markdownString: issue.reason)
if let converted = try? markdown.toAttributedString(styler: DownStyler()) {
cell.issueTextView.attributedText = converted
} else {
cell.issueTextView.text = issue.reason
}
return cell
default:
return UITableViewCell()
}
}
func scrollToBottom() {
let s = self.tableView.contentSize
var b = self.tableView.bounds
b.origin.y = max(0,s.height - b.height)
self.tableView.scrollRectToVisible(b, animated: true)
}
}
extension IssueDetailViewController : EditLocationViewControllerDelegate {
func editLocationViewControllerDidCancel(_ vc: EditLocationViewController) {
dismiss(animated: true, completion: nil)
}
func editLocationViewController(_ vc: EditLocationViewController, didUpdateLocation location: UserLocation) {
loadContacts()
dismiss(animated: true, completion: nil)
// issuesManager.fetchContacts(location: location) { result in
//
// if self.isSplitDistrict {
// let alertController = UIAlertController(title: R.string.localizable.splitDistrictTitle(), message: R.string.localizable.splitDistrictMessage(), preferredStyle: .alert)
// alertController.addAction(UIAlertAction(title: R.string.localizable.okButtonTitle(), style: .default ,handler: nil))
// vc.present(alertController, animated: true, completion: nil)
// } else {
// self.dismiss(animated: true, completion: nil)
// }
//
//
// if let issue = self.issuesManager.issue(withId: self.issue.id) {
// self.issue = issue
// self.tableView.reloadSections([IssueSections.contacts.rawValue], with: .automatic)
// self.scrollToBottom()
// } else {
// // weird state to be in, but the issue we're looking at
// // no longer exists, so we'll just quietly (read: not quietly)
// // pop back to the issues list
// _ = self.navigationController?.popViewController(animated: true)
// }
// }
}
}
|
mit
|
9c71e64ad1a5e73726c2f98a09c35427
| 38.591241 | 185 | 0.627765 | 5.052632 | false | false | false | false |
mozilla-mobile/firefox-ios
|
Client/Frontend/Reader/View/ReaderModeFontSizeButton.swift
|
1
|
1101
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
enum FontSizeAction {
case smaller
case reset
case bigger
}
class ReaderModeFontSizeButton: UIButton {
var fontSizeAction: FontSizeAction = .bigger
convenience init(fontSizeAction: FontSizeAction) {
self.init(frame: .zero)
self.fontSizeAction = fontSizeAction
switch fontSizeAction {
case .smaller:
setTitle(.ReaderModeStyleSmallerLabel, for: [])
accessibilityLabel = .ReaderModeStyleSmallerAccessibilityLabel
case .bigger:
setTitle(.ReaderModeStyleLargerLabel, for: [])
accessibilityLabel = .ReaderModeStyleLargerAccessibilityLabel
case .reset:
accessibilityLabel = .ReaderModeResetFontSizeAccessibilityLabel
}
titleLabel?.font = UIFont(name: "SF-Pro-Text-Regular", size: DynamicFontHelper.defaultHelper.ReaderBigFontSize)
}
}
|
mpl-2.0
|
93dc6a33d9d6c2eed353d21d822f610c
| 32.363636 | 119 | 0.694823 | 5.12093 | false | false | false | false |
HeartRateLearning/HRLApp
|
HRLApp/Modules/AddWorkout/View/AddWorkoutViewController.swift
|
1
|
2001
|
//
// AddWorkoutAddWorkoutViewController.swift
// HRLApp
//
// Created by Enrique de la Torre on 18/01/2017.
// Copyright © 2017 Enrique de la Torre. All rights reserved.
//
import UIKit
// MARK: - Main body
final class AddWorkoutViewController: UIViewController {
// MARK: - Dependencies
var output: AddWorkoutViewOutput!
// MARK: - Outlets
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var workoutPicker: UIPickerView!
// MARK: - Private properties
fileprivate var workouts = [] as [String]
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
output.viewIsReady()
}
// MARK: - Actions
@IBAction func done(_ sender: Any) {
let index = workoutPicker.selectedRow(inComponent: Constants.numberOfComponents - 1)
let date = datePicker.date
output.addWorkout(at: index, startingOn: date)
}
}
// MARK: - UIPickerViewDataSource methods
extension AddWorkoutViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return Constants.numberOfComponents
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return workouts.count
}
}
// MARK: - UIPickerViewDelegate methods
extension AddWorkoutViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView,
titleForRow row: Int,
forComponent component: Int) -> String? {
return workouts[row]
}
}
// MARK: - AddWorkoutViewInput methods
extension AddWorkoutViewController: AddWorkoutViewInput {
func setup(with workouts: [String]) {
self.workouts = workouts
if isViewLoaded {
workoutPicker.reloadAllComponents()
}
}
}
// MARK: - Private body
private extension AddWorkoutViewController {
enum Constants {
static let numberOfComponents = 1
}
}
|
mit
|
c9468ad3b045d9b5c5ec249c9e9ed871
| 22.255814 | 96 | 0.6675 | 4.807692 | false | false | false | false |
seivan/SpriteKitComposition
|
TestsAndSample/Sample/Components/GroundMoving.swift
|
1
|
1236
|
//
// GroundMoving.swift
// TestsAndSample
//
// Created by Seivan Heidari on 21/12/14.
// Copyright (c) 2014 Seivan Heidari. All rights reserved.
//
import SpriteKit
class GroundMoving : Component {
let texture:SKTexture
init(texture:SKTexture) {
self.texture = texture
}
func didAddToNode(node:SKNode) {
let groundTexture = self.texture
let moveGroundSprite = SKAction.moveByX(-groundTexture.size().width * 2.0, y: 0, duration: NSTimeInterval(0.02 * groundTexture.size().width * 2.0))
let resetGroundSprite = SKAction.moveByX(groundTexture.size().width * 2.0, y: 0, duration: 0.0)
let moveGroundSpritesForever = SKAction.repeatActionForever(SKAction.sequence([moveGroundSprite,resetGroundSprite]))
let width = self.node?.scene?.frame.size.width
for var i:CGFloat = 0; i < 2.0 + width! / ( groundTexture.size().width * 2.0 ); ++i {
let sprite = SKSpriteNode(texture: self.texture)
sprite.setScale(2.0)
sprite.position = CGPointMake(i * sprite.size.width, sprite.size.height / 2.0)
sprite.runAction(moveGroundSpritesForever)
self.node?.addChild(sprite)
}
}
}
|
mit
|
659c0af1d7193e168dc7917333d53cba
| 37.625 | 155 | 0.644822 | 3.850467 | false | false | false | false |
jpedrosa/sua_nc
|
Sources/momentum.swift
|
2
|
6052
|
public typealias MomentumHandler = (req: Request, res: Response) throws -> Void
public class Momentum {
public static func listen(port: UInt16, hostName: String = "127.0.0.1",
handler: MomentumHandler) throws {
try doListen(port, hostName: hostName) { socket in
defer { socket.close() }
do {
let request = try Request(socket: socket)
let response = Response(socket: socket)
// Look for static handlers.
var handled = false
if Momentum.haveHandlers {
if request.method == "GET" {
if let ah = Momentum.handlersGet[request.uri] {
handled = true
try ah(req: request, res: response)
}
} else if request.method == "POST" {
if let ah = Momentum.handlersPost[request.uri] {
handled = true
try ah(req: request, res: response)
}
}
}
if !handled {
try handler(req: request, res: response)
}
response.doFlush()
} catch (let e) {
// Ignore it. By catching the errors here the server can continue to
// operate. The user code can catch its own errors in its handler
// callback in case they want to log it or some such.
print("Momentum error: \(e)")
}
}
}
public static func doListen(port: UInt16, hostName: String = "127.0.0.1",
handler: (socket: Socket) -> Void) throws {
let server = try ServerSocket(hostName: hostName, port: port)
while true {
try server.spawnAccept(handler)
}
}
public static var haveHandlers = false
static var handlersGet = [String: MomentumHandler]()
public static func get(uri: String, handler: MomentumHandler) {
handlersGet[uri] = handler
haveHandlers = true
}
static var handlersPost = [String: MomentumHandler]()
public static func post(uri: String, handler: MomentumHandler) {
handlersPost[uri] = handler
haveHandlers = true
}
}
public class Request: CustomStringConvertible {
var header: Header
var _body: Body?
init(socket: Socket) throws {
var headerParser = HeaderParser()
header = headerParser.header
let len = 1024
var buffer = [UInt8](count: len, repeatedValue: 0)
var n = 0
repeat {
n = socket.read(&buffer, maxBytes: len)
try headerParser.parse(buffer, maxBytes: n)
} while n > 0 && !headerParser.isDone
header = headerParser.header
if n != 0 && headerParser.isDone && header.method == "POST" {
var bodyParser = BodyParser()
let bi = headerParser.bodyIndex
if bi != -1 && buffer[bi] != 0 {
try bodyParser.parse(buffer, index: bi, maxBytes: len)
}
if !bodyParser.isDone {
repeat {
n = socket.read(&buffer, maxBytes: len)
try bodyParser.parse(buffer, index: 0, maxBytes: n)
} while n > 0 && !bodyParser.isDone
}
_body = bodyParser.body
}
}
public var method: String { return header.method }
public var uri: String { return header.uri }
public var httpVersion: String { return header.httpVersion }
public var fields: [String: String] { return header.fields }
public subscript(key: String) -> String? { return header[key] }
public var body: Body? { return _body }
public var description: String {
return "Request(method: \(inspect(method)), " +
"uri: \(inspect(uri)), " +
"httpVersion: \(inspect(httpVersion)), " +
"fields: \(inspect(fields)), " +
"body: \(inspect(_body)))"
}
}
public class Response {
public let socket: Socket
public var statusCode = 200
public var fields = ["Content-Type": "text/html"]
var contentQueue = [[UInt8]]()
public var contentLength = 0
var flushed = false
init(socket: Socket) {
self.socket = socket
}
public subscript(key: String) -> String? {
get { return fields[key] }
set { fields[key] = newValue }
}
public func write(string: String) {
writeBytes([UInt8](string.utf8))
}
public func writeBytes(bytes: [UInt8]) {
contentLength += bytes.count
contentQueue.append(bytes)
}
public func sendFile(path: String) throws {
writeBytes(try IO.readAllBytes(path))
}
func concatFields() -> String {
var s = ""
for (k, v) in fields {
s += "\(k): \(v)\r\n"
}
return s
}
public func doFlush() {
if flushed { return }
socket.write("HTTP/1.1 \(statusCode) \(STATUS_CODE[statusCode])" +
"\r\n\(concatFields())Content-Length: \(contentLength)\r\n\r\n")
for a in contentQueue {
socket.writeBytes(a, maxBytes: a.count)
}
flushed = true
}
public func redirectTo(url: String) {
statusCode = 302
fields["Location"] = url
}
public var contentType: String? {
get { return fields["Content-Type"] }
set { fields["Content-Type"] = newValue }
}
}
public let STATUS_CODE: [Int: String] = [
100: "Continue",
101: "Switching Protocols",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
306: "(Unused)",
307: "Temporary Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Request Entity Too Large",
414: "Request-URI Too Long",
415: "Unsupported Media Type",
416: "Requested Range Not Satisfiable",
417: "Expectation Failed",
451: "Unavailable For Legal Reasons",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported"
]
|
apache-2.0
|
1a6e281671168f9139f96b4e0f7a29ac
| 24.863248 | 79 | 0.615499 | 3.808685 | false | false | false | false |
curiousurick/Rye
|
Login/HouseQueries.swift
|
1
|
1990
|
//
// HouseQueries.swift
// Login
//
// Created by George Urick on 2/8/15.
// Copyright (c) 2015 Jason Kwok. All rights reserved.
//
import Foundation
import Parse
class HouseQuery {
class func GetHouses(program: ProgramNames, reloading: () -> Void) -> Array<House> {
var query = PFQuery(className: "HackHousing")
var mf_houses = [House]()
var data_source: String = ""
if program == ProgramNames.MFH {
data_source = "MultiFamily"
}
if program == ProgramNames.PH {
data_source = "PublicHousing"
}
query.whereKey("DataSource", equalTo: data_source)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
var address = object["Address"] as String
var coordinates = Coordinates(lat: 0, long: 0)
var price = object["Value"] as Int
var details = object["Details"] as String
var type : ProgramNames = ProgramNames.MFH
var house: House = House(coordinates: coordinates, address: address, price: price, type: type, details: details)
mf_houses.append(house)
}
}
}
// var objectsBlah = query.findObjects()
// for object in objectsBlah {
// var address = object["Address"] as String
// var coordinates = Coordinates(lat: 0, long: 0)
// var price = object["Value"] as Double
// var details = object["Details"] as String
// var type : ProgramNames = ProgramNames.MFH
// var house: House = House(coordinates: coordinates, address: address, price: price, type: type, details: details)
// mf_houses.append(house)
// }
return mf_houses
}
}
|
mit
|
de52c56a887ac46ce06e04d9aaa9d58a
| 32.745763 | 132 | 0.541206 | 4.47191 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/CryptoAssets/Sources/BitcoinKit/Services/Activity/Bitcoin/BitcoinActivityItemEventDetails.swift
|
1
|
1949
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BitcoinChainKit
import MoneyKit
import PlatformKit
public struct BitcoinActivityItemEventDetails: Equatable {
public struct Confirmation: Equatable {
public let needConfirmation: Bool
public let confirmations: Int
public let requiredConfirmations: Int
public let factor: Float
}
public let identifier: String
public let amount: CryptoValue
public let from: BitcoinAssetAddress
public let to: BitcoinAssetAddress
public let createdAt: Date
public let confirmation: Confirmation
public let fee: CryptoValue
init(transaction: BitcoinHistoricalTransaction) {
self.init(
amount: transaction.amount,
requiredConfirmations: BitcoinHistoricalTransaction.requiredConfirmations,
transactionHash: transaction.transactionHash,
createdAt: transaction.createdAt,
isConfirmed: transaction.isConfirmed,
confirmations: transaction.confirmations,
from: transaction.fromAddress,
to: transaction.toAddress,
fee: transaction.fee
)
}
init(
amount: CryptoValue,
requiredConfirmations: Int,
transactionHash: String,
createdAt: Date,
isConfirmed: Bool,
confirmations: Int,
from: BitcoinAssetAddress,
to: BitcoinAssetAddress,
fee: CryptoValue?
) {
identifier = transactionHash
self.createdAt = createdAt
confirmation = .init(
needConfirmation: !isConfirmed,
confirmations: confirmations,
requiredConfirmations: requiredConfirmations,
factor: Float(confirmations) / Float(requiredConfirmations)
)
self.from = from
self.to = to
self.fee = fee ?? .zero(currency: amount.currency)
self.amount = amount
}
}
|
lgpl-3.0
|
8a8056c8bfc281a66ccff6c0a5b912dd
| 30.419355 | 86 | 0.657084 | 5.549858 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/CryptoAssets/Sources/ERC20Kit/Domain/Activity/ERC20ContractGasActivityModel.swift
|
1
|
1496
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import DIKit
import EthereumKit
import MoneyKit
import PlatformKit
public struct ERC20ContractGasActivityModel {
public let cryptoCurrency: CryptoCurrency
public let cryptoValue: CryptoValue?
public let to: EthereumAddress?
public init?(details: EthereumActivityItemEventDetails) {
guard let cryptoCurrency = ERC20ContractGasActivityModel.token(address: details.to) else {
return nil
}
self.cryptoCurrency = cryptoCurrency
switch ERC20Function(data: details.data) {
case .transfer(to: let address, amount: let hexAmount):
cryptoValue = ERC20ContractGasActivityModel.gasCryptoValue(
hexAmount: hexAmount,
cryptoCurrency: cryptoCurrency
)
to = EthereumAddress(address: address)
case nil:
cryptoValue = nil
to = nil
}
}
private static func gasCryptoValue(hexAmount: String?, cryptoCurrency: CryptoCurrency) -> CryptoValue? {
guard
let hexAmount = hexAmount,
let decimalAmount = BigInt(hexAmount, radix: 16)
else { return nil }
return CryptoValue.create(minor: decimalAmount, currency: cryptoCurrency)
}
private static func token(address: EthereumAddress) -> CryptoCurrency? {
CryptoCurrency(
erc20Address: address.publicKey.lowercased()
)
}
}
|
lgpl-3.0
|
61e35eb2358ae92e0607463169803e16
| 31.5 | 108 | 0.66087 | 5.102389 | false | false | false | false |
1738004401/Swift3.0--
|
SwiftCW/SwiftCW/AppDelegate.swift
|
1
|
2550
|
//
// AppDelegate.swift
// Swift实战
//
// Created by YiXue on 17/3/14.
// Copyright © 2017年 赵刘磊. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: kScreen_Bounds)
if SWUser.isLogin() {
let rootController = RootTabBarController()
window?.rootViewController = rootController
}else{
let loginController = SWLoginController()
window?.rootViewController = loginController
}
window?.makeKeyAndVisible()
DAOManager.shareManager().openDB(DBName: "swSqlite.sqlite")
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
38f69094b517ed979ec941828655eeea
| 42.741379 | 285 | 0.72566 | 5.563596 | false | false | false | false |
mightydeveloper/swift
|
test/Interpreter/failable_initializers.swift
|
9
|
7596
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
var FailableInitTestSuite = TestSuite("FailableInit")
class Canary {
static var count: Int = 0
init() {
Canary.count++
}
deinit {
Canary.count--
}
}
class Bear {
let x: Canary
/* Designated */
init(n: Int) {
x = Canary()
}
init?(n: Int, before: Bool) {
if before {
return nil
}
self.x = Canary()
}
init?(n: Int, after: Bool) {
self.x = Canary()
if after {
return nil
}
}
init?(n: Int, before: Bool, after: Bool) {
if before {
return nil
}
self.x = Canary()
if after {
return nil
}
}
/* Convenience */
convenience init?(before: Bool) {
if before {
return nil
}
self.init(n: 0)
}
convenience init?(during: Bool) {
self.init(n: 0, after: during)
}
convenience init?(before: Bool, during: Bool) {
if before {
return nil
}
self.init(n: 0, after: during)
}
convenience init?(after: Bool) {
self.init(n: 0)
if after {
return nil
}
}
convenience init?(before: Bool, after: Bool) {
if before {
return nil
}
self.init(n: 0)
if after {
return nil
}
}
convenience init?(during: Bool, after: Bool) {
self.init(n: 0, after: during)
if after {
return nil
}
}
convenience init?(before: Bool, during: Bool, after: Bool) {
if before {
return nil
}
self.init(n: 0, after: during)
if after {
return nil
}
}
/* Exotic */
convenience init!(IUO: Bool) {
self.init(before: IUO)
}
convenience init(force: Bool) {
self.init(before: force)!
}
}
class PolarBear : Bear {
let y: Canary
/* Designated */
override init(n: Int) {
self.y = Canary()
super.init(n: n)
}
override init?(n: Int, before: Bool) {
if before {
return nil
}
self.y = Canary()
super.init(n: n)
}
init?(n: Int, during: Bool) {
self.y = Canary()
super.init(n: n, before: during)
}
init?(n: Int, before: Bool, during: Bool) {
self.y = Canary()
if before {
return nil
}
super.init(n: n, before: during)
}
override init?(n: Int, after: Bool) {
self.y = Canary()
super.init(n: n)
if after {
return nil
}
}
init?(n: Int, during: Bool, after: Bool) {
self.y = Canary()
super.init(n: n, before: during)
if after {
return nil
}
}
override init?(n: Int, before: Bool, after: Bool) {
if before {
return nil
}
self.y = Canary()
super.init(n: n)
if after {
return nil
}
}
init?(n: Int, before: Bool, during: Bool, after: Bool) {
if before {
return nil
}
self.y = Canary()
super.init(n: n, before: during)
if after {
return nil
}
}
}
class GuineaPig<T> : Bear {
let y: Canary
let t: T
init?(t: T, during: Bool) {
self.y = Canary()
self.t = t
super.init(n: 0, before: during)
}
}
struct Chimera {
let x: Canary
let y: Canary
init?(before: Bool) {
if before {
return nil
}
x = Canary()
y = Canary()
}
init?(during: Bool) {
x = Canary()
if during {
return nil
}
y = Canary()
}
init?(before: Bool, during: Bool) {
if before {
return nil
}
x = Canary()
if during {
return nil
}
y = Canary()
}
init?(after: Bool) {
x = Canary()
y = Canary()
if after {
return nil
}
}
init?(before: Bool, after: Bool) {
if before {
return nil
}
x = Canary()
y = Canary()
if after {
return nil
}
}
init?(during: Bool, after: Bool) {
x = Canary()
if during {
return nil
}
y = Canary()
if after {
return nil
}
}
init?(before: Bool, during: Bool, after: Bool) {
if before {
return nil
}
x = Canary()
if during {
return nil
}
y = Canary()
if after {
return nil
}
}
}
func mustFail<T>(f: () -> T?) {
if f() != nil {
preconditionFailure("Didn't fail")
}
}
FailableInitTestSuite.test("FailableInitFailure_Root") {
mustFail { Bear(n: 0, before: true) }
mustFail { Bear(n: 0, after: true) }
mustFail { Bear(n: 0, before: true, after: false) }
mustFail { Bear(n: 0, before: false, after: true) }
expectEqual(0, Canary.count)
}
FailableInitTestSuite.test("FailableInitFailure_Derived") {
mustFail { PolarBear(n: 0, before: true) }
mustFail { PolarBear(n: 0, during: true) }
mustFail { PolarBear(n: 0, before: true, during: false) }
mustFail { PolarBear(n: 0, before: false, during: true) }
mustFail { PolarBear(n: 0, after: true) }
mustFail { PolarBear(n: 0, during: true, after: false) }
mustFail { PolarBear(n: 0, during: false, after: true) }
mustFail { PolarBear(n: 0, before: true, after: false) }
mustFail { PolarBear(n: 0, before: false, after: true) }
mustFail { PolarBear(n: 0, before: true, during: false, after: false) }
mustFail { PolarBear(n: 0, before: false, during: true, after: false) }
mustFail { PolarBear(n: 0, before: false, during: false, after: true) }
expectEqual(0, Canary.count)
}
FailableInitTestSuite.test("DesignatedInitFailure_DerivedGeneric") {
mustFail { GuineaPig<Canary>(t: Canary(), during: true) }
expectEqual(0, Canary.count)
}
FailableInitTestSuite.test("ConvenienceInitFailure_Root") {
mustFail { Bear(before: true) }
mustFail { Bear(during: true) }
mustFail { Bear(before: true, during: false) }
mustFail { Bear(before: false, during: true) }
mustFail { Bear(after: true) }
mustFail { Bear(before: true, after: false) }
mustFail { Bear(before: false, after: true) }
mustFail { Bear(during: true, after: false) }
mustFail { Bear(during: false, after: true) }
mustFail { Bear(before: true, during: false, after: false) }
mustFail { Bear(before: false, during: true, after: false) }
mustFail { Bear(before: false, during: false, after: true) }
_ = Bear(IUO: false)
_ = Bear(force: false)
expectEqual(0, Canary.count)
}
FailableInitTestSuite.test("ConvenienceInitFailure_Derived") {
mustFail { PolarBear(before: true) }
mustFail { PolarBear(during: true) }
mustFail { PolarBear(before: true, during: false) }
mustFail { PolarBear(before: false, during: true) }
mustFail { PolarBear(after: true) }
mustFail { PolarBear(before: true, after: false) }
mustFail { PolarBear(before: false, after: true) }
mustFail { PolarBear(during: true, after: false) }
mustFail { PolarBear(during: false, after: true) }
mustFail { PolarBear(before: true, during: false, after: false) }
mustFail { PolarBear(before: false, during: true, after: false) }
mustFail { PolarBear(before: false, during: false, after: true) }
expectEqual(0, Canary.count)
}
FailableInitTestSuite.test("InitFailure_Struct") {
mustFail { Chimera(before: true) }
mustFail { Chimera(during: true) }
mustFail { Chimera(before: true, during: false) }
mustFail { Chimera(before: false, during: true) }
mustFail { Chimera(after: true) }
mustFail { Chimera(before: true, after: false) }
mustFail { Chimera(before: false, after: true) }
mustFail { Chimera(during: true, after: false) }
mustFail { Chimera(during: false, after: true) }
mustFail { Chimera(before: true, during: false, after: false) }
mustFail { Chimera(before: false, during: true, after: false) }
mustFail { Chimera(before: false, during: false, after: true) }
expectEqual(0, Canary.count)
}
runAllTests()
|
apache-2.0
|
0191d17a105caf6597fe945c81b25038
| 19.92562 | 73 | 0.596367 | 3.344782 | false | false | false | false |
cdtschange/SwiftMKit
|
SwiftMKit/UI/Schema/BaseListFetchKitViewController.swift
|
1
|
2750
|
//
// BaseListFetchKitViewController.swift
// SwiftMKitDemo
//
// Created by Mao on 4/27/16.
// Copyright © 2016 cdts. All rights reserved.
//
import UIKit
import CoreData
import CocoaLumberjack
import ReactiveCocoa
open class BaseListFetchKitViewController: BaseListKitViewController {
open var listFetchViewModel: BaseListFetchKitViewModel! {
get {
return viewModel as! BaseListFetchKitViewModel
}
}
open var listFetchView: UITableView! {
get {
return self.listView as! UITableView
}
}
fileprivate var _fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>?
open var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>? {
get {
if _fetchedResultsController == nil {
if let request = self.listFetchViewModel.fetchRequest {
_fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: NSManagedObjectContext.mr_default(), sectionNameKeyPath: nil, cacheName: nil)
}
}
return _fetchedResultsController
}
}
open override func loadData() {
super.loadData()
listFetchViewModel.fetchCachedData()
}
override open func objectByIndexPath(_ indexPath: IndexPath) -> Any? {
let object = fetchedResultsController?.sections?[indexPath.section].objects?[safe: indexPath.row]
return object as AnyObject?
}
override open func numberOfSections(in tableView: UITableView) -> Int {
let sections = fetchedResultsController?.sections?.count
return sections ?? 0
}
override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows = 0
if (fetchedResultsController?.sections?.count ?? 0) > 0 {
rows = fetchedResultsController?.sections?[section].numberOfObjects ?? 0
}
return rows
}
override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = getCell(withTableView: tableView, indexPath: indexPath)!
if let object = objectByIndexPath(indexPath) {
configureCell(cell, object: object, indexPath: indexPath)
}
return cell
}
override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = getCell(withTableView: tableView, indexPath: indexPath)!
if let object = objectByIndexPath(indexPath) {
didSelectCell(cell, object: object, indexPath: indexPath)
}
}
}
|
mit
|
d2886fb01d7e7947d200ca51637a1715
| 37.180556 | 197 | 0.6737 | 5.587398 | false | false | false | false |
vector-im/vector-ios
|
Riot/Categories/UIImage.swift
|
1
|
3739
|
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
extension UIImage {
class func vc_image(from color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIGraphicsBeginImageContext(size)
image?.draw(in: rect)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
@objc func vc_tintedImage(usingColor tintColor: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let drawRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
self.draw(in: drawRect)
tintColor.set()
UIRectFillUsingBlendMode(drawRect, .sourceAtop)
let tintedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage
}
@objc func vc_withAlpha(_ alpha: CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: .zero, blendMode: .normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
// Based on https://stackoverflow.com/a/31314494
@objc func vc_resized(with targetSize: CGSize) -> UIImage? {
let originalRenderingMode = self.renderingMode
let size = self.size
let widthRatio = targetSize.width/size.width
let heightRatio = targetSize.height/size.height
// Figure out what our orientation is, and use that to form the rectangle
let newSize: CGSize
if widthRatio > heightRatio {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
let rect = CGRect(origin: .zero, size: newSize)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage?.withRenderingMode(originalRenderingMode)
}
@objc func vc_notRenderedImage() -> UIImage {
if let cgImage = cgImage {
return NotRenderedImage(cgImage: cgImage, scale: UIScreen.main.scale, orientation: .up)
} else if let ciImage = ciImage {
return NotRenderedImage(ciImage: ciImage, scale: UIScreen.main.scale, orientation: .up)
}
return self
}
// inline class to disable rendering
private class NotRenderedImage: UIImage {
override func withRenderingMode(_ renderingMode: UIImage.RenderingMode) -> UIImage {
return self
}
}
}
|
apache-2.0
|
d2cb904da0f54f3c4619f42a27122e3d
| 36.019802 | 102 | 0.671035 | 5.107923 | false | false | false | false |
devgabrielcoman/woodhouse
|
Pod/Classes/Transformers/Transform+Locu+OpenMenu.swift
|
1
|
4066
|
//
// Map+Locu+OpenMenu.swift
// Pods
//
// Created by Gabriel Coman on 08/03/2016.
//
//
import UIKit
import KeyPathTransformer
import Dollar
func mapLocuToOMenu(locu: [String:AnyObject]) -> [String:AnyObject] {
let woodhouse_id = String.createUUID(32)
let t = Transform<AnyObject>(locu)
// [OK] metadata
t["uuid"] = String.createOmfUUID()
t["accuracy"] = 1
t["created_date"] = NSDate.omfNowDate()
t["open_menu.version"] = "1.6"
// [OK] restaurant info
// details subset
t["restaurant_info.restaurant_name"] = t["name"]
t["restaurant_info.brief_description"] = t["description"]
t["restaurant_info.business_type"] = "independent"
// location subset
t["restaurant_info.address_1"] = t["location.address1"]
t["restaurant_info.city_town"] = t["location.locality"]
t["restaurant_info.country"] = t["location.country"]
t["restaurant_info.postal_code"] = t["location.postal_code"]
t["location.geo.coordinates"] => { (i, coord: Double) in
if i == 0 { t["restaurant_info.longitude"] = coord }
if i == 1 { t["restaurant_info.latitude"] = coord }
}
// contact subset
t["restaurant_info.phone"] = t["contact.phone"]
t["restaurant_info.website_url"] = t["website_url"]
t["restaurant_info.omf_file_url"] = "http://sa-test-moat.herokuapp.com/static/sample.xml"
// [OK] Environment
// cuisine_type_primary subset
var fname: [String] = []
t["categories.name"] => { (i, name: String) in
fname.append(name)
}
t["restaurant_info.environment.cuisine_type_primary"] = fname.joinWithSeparator(" / ")
// seating_locations subset
var seating_locations: [String] = ["indoor"]
if let outdoor = t["extended.outdoor_seating"] as? Bool where outdoor == true {
seating_locations.append("outdoor")
}
t["restaurant_info.environment.seating_locations"] = seating_locations
// accepted_currencies subset
var accepted_currencies: [String] = []
if let symbol = t["currency.symbol"] as? String {
accepted_currencies.append(symbol)
}
if accepted_currencies.count == 0 {
accepted_currencies.append("USD")
}
t["restaurant_info.environment.accepted_currencies"] = accepted_currencies
// operating days subset
t["operating_days"] = {
let days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
var array:[AnyObject] = []
$.each(days) { (i, day: String) in
let ot = Transform<AnyObject>()
t["open_hours.\(day)"] => { (j, openHour: String) in
let time = (j == 0 ? "open_time" : "close_time")
ot[time] = openHour
ot["day_of_week"] = (i+1)
ot["day"] = day.upercaseFirst()
ot["day_short"] = day.sub(0, 3).upercaseFirst()
}
array.append(ot.result())
}
return array
}()
// // Menus
// t1 <> "menus" => "menus" => { (i, menu) -> (Dictionary<String, AnyObject>) in
// let t2 = KeyPathTransformer(menu)
// t2 <> "menu_name" => "menuName"
// t2 <> "currency_symbol" => "currencySymbol"
//
// t2 <> "sections.subsections" => "group" => { (i, subsection) -> (Dictionary<String, AnyObject>) in
// let t3 = KeyPathTransformer(subsection)
// t3 <> "subsection_name" => "group_name"
//
// t3 <> "contents" => "menuItems" => { (i, content) -> (Dictionary<String, AnyObject>) in
// let t4 = KeyPathTransformer(content)
// t4 <> "name" => "menuItemName"
// t4 <> "description" => "menuItemDescription"
// t4 <> "price" => "menuItemPrice"
// return t4.transform()
// }
//
// return t3.transform()
// }
//
// return t2.transform()
// }
//
// return t1.transform()
return t.result()
}
|
gpl-3.0
|
dea9f8424e7e60c7a7b5539a2d6e1ab8
| 33.168067 | 108 | 0.554599 | 3.59823 | false | false | false | false |
TimothyChilvers/Cartography
|
CartographyTests/EdgesSpec.swift
|
4
|
3243
|
import Cartography
import Nimble
import Quick
class EdgesSpec: QuickSpec {
override func spec() {
var window: TestWindow!
var view: TestView!
beforeEach {
window = TestWindow(frame: CGRectMake(0, 0, 400, 400))
view = TestView(frame: CGRectZero)
window.addSubview(view)
}
describe("LayoutProxy.edges") {
it("should support relative equalities") {
constrain(view) { view in
view.edges == view.superview!.edges
}
window.layoutIfNeeded()
expect(view.frame).to(equal(view.superview?.frame))
}
}
describe("LayoutProxy.edges") {
it("should support relative inequalities") {
constrain(view) { view in
view.edges <= view.superview!.edges
view.edges >= view.superview!.edges
}
window.layoutIfNeeded()
expect(view.frame).to(equal(view.superview?.frame))
}
}
describe("inset") {
it("should inset all edges with the same amount") {
constrain(view) { view in
view.edges == inset(view.superview!.edges, 20)
}
window.layoutIfNeeded()
expect(view.frame).to(equal(CGRectMake(20, 20, 360, 360)))
}
it("should inset the horizontal and vertical edge individually") {
constrain(view) { view in
view.edges == inset(view.superview!.edges, 20, 30)
}
window.layoutIfNeeded()
expect(view.frame).to(equal(CGRectMake(20, 30, 360, 340)))
}
it("should inset all edges individually") {
constrain(view) { view in
view.edges == inset(view.superview!.edges, 10, 20, 30, 40)
}
window.layoutIfNeeded()
expect(view.frame).to(equal(CGRectMake(20, 10, 340, 360)))
}
}
#if os(iOS) || os(tvOS)
describe("on iOS only") {
beforeEach {
window.layoutMargins = UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)
}
describe("LayoutProxy.edgesWithinMargins") {
it("should support relative equalities") {
constrain(view) { view in
view.edges == view.superview!.edgesWithinMargins
}
window.layoutIfNeeded()
expect(view.frame).to(equal(CGRectMake(20, 10, 340, 360)))
}
}
}
describe("on iOS only, inset using UIEdgeInsets") {
it("should inset all edges individually") {
constrain(view) { view in
let insets = UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)
view.edges == inset(view.superview!.edges, insets)
}
window.layoutIfNeeded()
expect(view.frame).to(equal(CGRectMake(20, 10, 340, 360)))
}
}
#endif
}
}
|
mit
|
2832a5769e7ae63b5603c59c6c853409
| 29.027778 | 93 | 0.488745 | 4.981567 | false | false | false | false |
calebd/swift
|
test/SILGen/dso_handle.swift
|
1
|
648
|
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s
// CHECK: sil_global hidden_external [[DSO:@__dso_handle]] : $Builtin.RawPointer
// CHECK-LABEL: sil @main : $@convention(c)
// CHECK: bb0
// CHECK: [[DSOAddr:%[0-9]+]] = global_addr [[DSO]] : $*Builtin.RawPointer
// CHECK-NEXT: [[DSOPtr:%[0-9]+]] = address_to_pointer [[DSOAddr]] : $*Builtin.RawPointer to $Builtin.RawPointer
// CHECK-NEXT: [[DSOPtrStruct:[0-9]+]] = struct $UnsafeRawPointer ([[DSOPtr]] : $Builtin.RawPointer)
func printDSOHandle(dso: UnsafeRawPointer = #dsohandle) -> UnsafeRawPointer {
print(dso)
return dso
}
_ = printDSOHandle()
|
apache-2.0
|
df15fb1e9ad702842a1053c7ce65eebd
| 39.5 | 112 | 0.674383 | 3.223881 | false | false | false | false |
maisa/iConv
|
App_iOS/iConv/APIManager.swift
|
1
|
3133
|
//
// APIManager.swift
// MusicVideo
//
// Created by Michael Rudowsky on 9/10/15.
// Copyright © 2015 Michael Rudowsky. All rights reserved.
//
import Foundation
//import SwiftyJSON
class APIManager {
func loadData(urlString:String, completion: ([Municipio], Metadados) -> Void ) {
let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let session = NSURLSession(configuration: config)
// let session = NSURLSession.sharedSession()
let url = NSURL(string: urlString)!
let task = session.dataTaskWithURL(url) {
(data, response, error) -> Void in
if error != nil {
print(error!.localizedDescription)
} else {
//Added for JSONSerialization
//print(data)
do {
/* .AllowFragments - top level object is not Array or Dictionary.
Any type of string or value
NSJSONSerialization requires the Do / Try / Catch
Converts the NSDATA into a JSON Object and cast it to a Dictionary */
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? [String: AnyObject] {
if let muni = json["municipios"] as? [[String: AnyObject]]{
// print(" ")
// print("ENTRI AQUI")
var cidades = [Municipio]()
var dados : Metadados!
for entry in muni {
let data = Municipio(data: entry)
cidades.append(data)
let i = cidades.count
// print("Numero de Eventos/Lugares --> \(i)")
}
if let meta = json["metadados"] as? [String: AnyObject]{
dados = Metadados(data: meta)
}
let priority = DISPATCH_QUEUE_PRIORITY_HIGH
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(dispatch_get_main_queue()) {
completion(cidades, dados)
}
}
}
}
} catch {
print("error in NSJSONSerialization")
}
}
}
task.resume()
}
}
|
gpl-2.0
|
cfce77debaa4c7ff99e73e2bcfa22771
| 35 | 135 | 0.383461 | 6.538622 | false | true | false | false |
crspybits/SMSyncServer
|
iOS/iOSTests/Pods/SMSyncServer/SMSyncServer/Classes/Internal/SMServerAPI+Sharing.swift
|
1
|
9746
|
//
// SMServerAPI+Sharing.swift
// SMSyncServer
//
// Created by Christopher Prince on 6/11/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
// Server calls for sharing with non-owning users
import Foundation
import SMCoreLib
internal extension SMServerAPI {
// Create sharing invitation of current owning user's cloud storage data.
// An owning user must currently be signed in. Doesn't require a lock. The capabilities must not be empty.
// capabilities is an optional value only to allow for error case testing on the server. In production builds, it *must* not be nil.
internal func createSharingInvitation(capabilities capabilities:SMSharingUserCapabilityMask?, completion:((invitationCode:String?, apiResult:SMServerAPIResult)->(Void))?) {
var capabilitiesStringArray:[String]?
if capabilities != nil {
capabilitiesStringArray = capabilities!.stringArray
}
self.createSharingInvitation(capabilities: capabilitiesStringArray) { (invitationCode, apiResult) in
completion?(invitationCode: invitationCode, apiResult: apiResult)
}
}
// This is only marked as "internal" (and not private) for testing purposes. In regular (non-testing code), call the method above.
internal func createSharingInvitation(capabilities capabilities:[String]?, completion:((invitationCode:String?, apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
var parameters = userParams!
#if !DEBUG
if capabilities == nil || capabilities!.count == 0 {
completion?(invitationCode: nil,
apiResult: SMServerAPIResult(returnCode: nil,
error: Error.Create("There were no capabilities!")))
return
}
#endif
parameters[SMServerConstants.userCapabilities] = capabilities
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationCreateSharingInvitation)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: parameters) { (serverResponse:[String:AnyObject]?, error:NSError?) in
var result = self.initialServerResponseProcessing(serverResponse, error: error)
var invitationCode:String?
if nil == result.error {
invitationCode = serverResponse![SMServerConstants.sharingInvitationCode] as? String
if nil == invitationCode {
result.error = Error.Create("Didn't get a Sharing Invitation Code back from server")
}
}
completion?(invitationCode: invitationCode, apiResult: result)
}
}
// This method is really just for testing. It's useful for looking up invitation info to make sure the invitation was stored on the server in its database.
// You can only lookup invitations that you own/have sent. i.e., you can't lookup other people's invitations.
internal func lookupSharingInvitation(invitationCode invitationCode:String, completion:((invitationContents:[String:AnyObject]?, apiResult:SMServerAPIResult)->(Void))?) {
let userParams = self.userDelegate.userCredentialParams
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
var parameters = userParams!
parameters[SMServerConstants.sharingInvitationCode] = invitationCode
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationLookupSharingInvitation)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: parameters) { (serverResponse:[String:AnyObject]?, error:NSError?) in
var result = self.initialServerResponseProcessing(serverResponse, error: error)
var invitationContents:[String:AnyObject]?
if nil == result.error {
invitationContents = serverResponse![SMServerConstants.resultInvitationContentsKey] as? [String:AnyObject]
if nil == invitationContents {
result.error = Error.Create("Didn't get Sharing Invitation Contents back from server")
}
}
completion?(invitationContents: invitationContents, apiResult: result)
}
}
// Does one of two main things: (a) user is already known to the system, it links the account/capabilities represented by the invitation to that user, (b) if the current user is not known to the system, this creates a new sharing user, and does the same kind of linking.
// The user must be a sharing user. Will fail if the invitation has expired, or if the invitation has already been redeemed.
// All user credentials parameters must be provided by serverCredentialParams.
// Return code is SMServerConstants.rcCouldNotRedeemSharingInvitation when we could not redeem the sharing invitation.
internal func redeemSharingInvitation(serverCredentialParams:[String:AnyObject],invitationCode:String, completion:((linkedOwningUserId: SMInternalUserId?, internalUserId:SMInternalUserId?, apiResult:SMServerAPIResult)->(Void))?) {
var parameters = serverCredentialParams
parameters[SMServerConstants.sharingInvitationCode] = invitationCode
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationRedeemSharingInvitation)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: parameters) { (serverResponse:[String:AnyObject]?, error:NSError?) in
var result = self.initialServerResponseProcessing(serverResponse, error: error)
var internalUserId:SMInternalUserId?
var linkedOwningUserId:SMInternalUserId?
if nil == result.error || result.returnCode == SMServerConstants.rcUserOnSystem {
internalUserId = serverResponse![SMServerConstants.internalUserId] as? String
if nil == internalUserId {
result.error = Error.Create("Didn't get internalUserId back from server")
}
linkedOwningUserId = serverResponse![SMServerConstants.linkedOwningUserId] as? String
if nil == linkedOwningUserId {
result.error = Error.Create("Didn't get linkedOwningUserId back from server")
}
}
completion?(linkedOwningUserId:linkedOwningUserId, internalUserId: internalUserId, apiResult: result)
}
}
// Look up the accounts that are shared with the current sharing user. serverCredentialParams is allowed as a parameter so that we can
internal func getLinkedAccountsForSharingUser(serverCredentialParams:[String:AnyObject]?,completion:((linkedAccounts:[SMLinkedAccount]?, apiResult:SMServerAPIResult)->(Void))?) {
var userParams:[String:AnyObject]?
if serverCredentialParams == nil {
userParams = self.userDelegate.userCredentialParams
}
else {
userParams = serverCredentialParams
}
Assert.If(nil == userParams, thenPrintThisString: "No user server params!")
let serverOpURL = NSURL(string: self.serverURLString +
"/" + SMServerConstants.operationGetLinkedAccountsForSharingUser)!
SMServerNetworking.session.sendServerRequestTo(toURL: serverOpURL, withParameters: userParams!) { (serverResponse:[String:AnyObject]?, error:NSError?) in
var result = self.initialServerResponseProcessing(serverResponse, error: error)
var linkedAccounts:[SMLinkedAccount]! = [SMLinkedAccount]()
if nil == result.error {
if let dictArray = serverResponse![SMServerConstants.resultLinkedAccountsKey] as? [[String:AnyObject]] {
Log.msg("dictArray: \(dictArray)")
for dict in dictArray {
if let internalUserId = dict[SMServerConstants.internalUserId] as? String,
let userName = dict[SMServerConstants.accountUserName] as? String,
let capabilities = dict[SMServerConstants.accountCapabilities] as? [String],
let capabilityMask = SMSharingUserCapabilityMask(capabilityNameArray:capabilities) {
let linkedAccount = SMLinkedAccount(internalUserId: internalUserId, userName: userName, capabilityMask: capabilityMask)
linkedAccounts.append(linkedAccount)
}
else {
result.error = Error.Create("Didn't get expected dict element keys back from server: \(dict)")
}
}
} else {
result.error = Error.Create("Didn't get array of dictionaries back from server: \(serverResponse![SMServerConstants.resultLinkedAccountsKey])")
}
}
if linkedAccounts.count == 0 {
linkedAccounts = nil
}
completion?(linkedAccounts: linkedAccounts, apiResult: result)
}
}
}
|
gpl-3.0
|
deedfce47592d743a1db791c0518adac
| 51.675676 | 274 | 0.643202 | 5.619954 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
Client/Frontend/Browser/Tab.swift
|
1
|
28395
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import Storage
import Shared
import SwiftyJSON
import XCGLogger
fileprivate var debugTabCount = 0
func mostRecentTab(inTabs tabs: [Tab]) -> Tab? {
var recent = tabs.first
tabs.forEach { tab in
if let time = tab.lastExecutedTime, time > (recent?.lastExecutedTime ?? 0) {
recent = tab
}
}
return recent
}
protocol TabContentScript {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol TabDelegate {
func tab(_ tab: Tab, didAddSnackbar bar: SnackBar)
func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar)
func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String)
func tab(_ tab: Tab, didSelectSearchWithFirefoxForSelection selection: String)
@objc optional func tab(_ tab: Tab, didCreateWebView webView: WKWebView)
@objc optional func tab(_ tab: Tab, willDeleteWebView webView: WKWebView)
}
@objc
protocol URLChangeDelegate {
func tab(_ tab: Tab, urlDidChangeTo url: URL)
}
struct TabState {
var isPrivate: Bool = false
var url: URL?
var title: String?
var favicon: Favicon?
}
enum TabUrlType: String {
case regular
case search
case followOnSearch
case organicSearch
case googleTopSite
case googleTopSiteFollowOn
}
class Tab: NSObject {
fileprivate var _isPrivate: Bool = false
internal fileprivate(set) var isPrivate: Bool {
get {
return _isPrivate
}
set {
if _isPrivate != newValue {
_isPrivate = newValue
}
}
}
var urlType: TabUrlType = .regular
var tabState: TabState {
return TabState(isPrivate: _isPrivate, url: url, title: displayTitle, favicon: displayFavicon)
}
// PageMetadata is derived from the page content itself, and as such lags behind the
// rest of the tab.
var pageMetadata: PageMetadata?
var consecutiveCrashes: UInt = 0
// Setting defualt page as topsites
var newTabPageType: NewTabPage = .topSites
var tabUUID: String = UUID().uuidString
// To check if current URL is the starting page i.e. either blank page or internal page like topsites
var isURLStartingPage: Bool {
guard url != nil else {
return true
}
if url!.absoluteString.hasPrefix("internal://") {
return true
}
return false
}
var canonicalURL: URL? {
if let string = pageMetadata?.siteURL,
let siteURL = URL(string: string) {
// If the canonical URL from the page metadata doesn't contain the
// "#" fragment, check if the tab's URL has a fragment and if so,
// append it to the canonical URL.
if siteURL.fragment == nil,
let fragment = self.url?.fragment,
let siteURLWithFragment = URL(string: "\(string)#\(fragment)") {
return siteURLWithFragment
}
return siteURL
}
return self.url
}
var userActivity: NSUserActivity?
var webView: WKWebView?
var tabDelegate: TabDelegate?
weak var urlDidChangeDelegate: URLChangeDelegate? // TODO: generalize this.
var bars = [SnackBar]()
var favicons = [Favicon]() {
didSet {
updateFaviconCache()
}
}
var lastExecutedTime: Timestamp?
var sessionData: SessionData?
fileprivate var lastRequest: URLRequest?
var restoring: Bool = false
var pendingScreenshot = false
var url: URL? {
didSet {
if let _url = url, let internalUrl = InternalURL(_url), internalUrl.isAuthorized {
url = URL(string: internalUrl.stripAuthorization)
}
}
}
var mimeType: String?
var isEditing: Bool = false
var currentFaviconUrl: URL?
// When viewing a non-HTML content type in the webview (like a PDF document), this URL will
// point to a tempfile containing the content so it can be shared to external applications.
var temporaryDocument: TemporaryDocument?
/// Returns true if this tab's URL is known, and it's longer than we want to store.
var urlIsTooLong: Bool {
guard let url = self.url else {
return false
}
return url.absoluteString.lengthOfBytes(using: .utf8) > AppConstants.DB_URL_LENGTH_MAX
}
// Use computed property so @available can be used to guard `noImageMode`.
var noImageMode: Bool {
didSet {
guard noImageMode != oldValue else {
return
}
contentBlocker?.noImageMode(enabled: noImageMode)
UserScriptManager.shared.injectUserScriptsIntoTab(self, nightMode: nightMode, noImageMode: noImageMode)
}
}
var nightMode: Bool {
didSet {
guard nightMode != oldValue else {
return
}
webView?.evaluateJavascriptInDefaultContentWorld("window.__firefox__.NightMode.setEnabled(\(nightMode))")
// For WKWebView background color to take effect, isOpaque must be false,
// which is counter-intuitive. Default is true. The color is previously
// set to black in the WKWebView init.
webView?.isOpaque = !nightMode
UserScriptManager.shared.injectUserScriptsIntoTab(self, nightMode: nightMode, noImageMode: noImageMode)
}
}
var contentBlocker: FirefoxTabContentBlocker?
/// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs.
var lastTitle: String?
/// Whether or not the desktop site was requested with the last request, reload or navigation.
var changedUserAgent: Bool = false {
didSet {
if changedUserAgent != oldValue {
TabEvent.post(.didToggleDesktopMode, for: self)
}
}
}
var readerModeAvailableOrActive: Bool {
if let readerMode = self.getContentScript(name: "ReaderMode") as? ReaderMode {
return readerMode.state != .unavailable
}
return false
}
fileprivate(set) var screenshot: UIImage?
var screenshotUUID: UUID?
// If this tab has been opened from another, its parent will point to the tab from which it was opened
weak var parent: Tab?
fileprivate var contentScriptManager = TabContentScriptManager()
fileprivate let configuration: WKWebViewConfiguration
/// Any time a tab tries to make requests to display a Javascript Alert and we are not the active
/// tab instance, queue it for later until we become foregrounded.
fileprivate var alertQueue = [JSAlertInfo]()
weak var browserViewController: BrowserViewController?
init(bvc: BrowserViewController, configuration: WKWebViewConfiguration, isPrivate: Bool = false) {
self.configuration = configuration
self.nightMode = false
self.noImageMode = false
self.browserViewController = bvc
super.init()
self.isPrivate = isPrivate
debugTabCount += 1
TelemetryWrapper.recordEvent(category: .action, method: .add, object: .tab, value: isPrivate ? .privateTab : .normalTab)
}
class func toRemoteTab(_ tab: Tab) -> RemoteTab? {
if tab.isPrivate {
return nil
}
if let displayURL = tab.url?.displayURL, RemoteTab.shouldIncludeURL(displayURL) {
let history = Array(tab.historyList.filter(RemoteTab.shouldIncludeURL).reversed())
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: Date.now(),
icon: nil)
} else if let sessionData = tab.sessionData, !sessionData.urls.isEmpty {
let history = Array(sessionData.urls.filter(RemoteTab.shouldIncludeURL).reversed())
if let displayURL = history.first {
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: sessionData.lastUsedTime,
icon: nil)
}
}
return nil
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
configuration.userContentController = WKUserContentController()
configuration.allowsInlineMediaPlayback = true
let webView = TabWebView(frame: .zero, configuration: configuration)
webView.delegate = self
webView.accessibilityLabel = .WebViewAccessibilityLabel
webView.allowsBackForwardNavigationGestures = true
if #available(iOS 13, *) {
webView.allowsLinkPreview = true
} else {
webView.allowsLinkPreview = false
}
// Night mode enables this by toggling WKWebView.isOpaque, otherwise this has no effect.
webView.backgroundColor = .black
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
restore(webView)
self.webView = webView
self.webView?.addObserver(self, forKeyPath: KVOConstants.URL.rawValue, options: .new, context: nil)
UserScriptManager.shared.injectUserScriptsIntoTab(self, nightMode: nightMode, noImageMode: noImageMode)
tabDelegate?.tab?(self, didCreateWebView: webView)
}
}
func restore(_ webView: WKWebView) {
// Pulls restored session data from a previous SavedTab to load into the Tab. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
restoring = true
var urls = [String]()
for url in sessionData.urls {
urls.append(url.absoluteString)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = urls as AnyObject?
jsonDict["currentPage"] = currentPage as AnyObject?
guard let json = JSON(jsonDict).stringify()?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
return
}
if let restoreURL = URL(string: "\(InternalURL.baseUrl)/\(SessionRestoreHandler.path)?history=\(json)") {
let request = PrivilegedRequest(url: restoreURL) as URLRequest
webView.load(request)
lastRequest = request
}
} else if let request = lastRequest {
webView.load(request)
} else {
print("creating webview with no lastRequest and no session data: \(self.url?.description ?? "nil")")
}
}
deinit {
debugTabCount -= 1
#if DEBUG
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
func checkTabCount(failures: Int) {
// Need delay for pool to drain.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
if appDelegate.tabManager.remoteTabs.count == debugTabCount {
return
}
// If this assert has false positives, remove it and just log an error.
assert(failures < 3, "Tab init/deinit imbalance, possible memory leak.")
checkTabCount(failures: failures + 1)
}
}
checkTabCount(failures: 0)
#endif
}
func close() {
contentScriptManager.uninstall(tab: self)
webView?.removeObserver(self, forKeyPath: KVOConstants.URL.rawValue)
if let webView = webView {
tabDelegate?.tab?(self, willDeleteWebView: webView)
}
webView?.navigationDelegate = nil
webView?.removeFromSuperview()
webView = nil
}
var loading: Bool {
return webView?.isLoading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList
}
var historyList: [URL] {
func listToUrl(_ item: WKBackForwardListItem) -> URL { return item.url }
var tabs = self.backList?.map(listToUrl) ?? [URL]()
if let url = url {
tabs.append(url)
}
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title, !title.isEmpty {
return title
}
// When picking a display title. Tabs with sessionData are pending a restore so show their old title.
// To prevent flickering of the display title. If a tab is restoring make sure to use its lastTitle.
if let url = self.url, InternalURL(url)?.isAboutHomeURL ?? false, sessionData == nil, !restoring {
return Strings.AppMenuOpenHomePageTitleString
}
//lets double check the sessionData in case this is a non-restored new tab
if let firstURL = sessionData?.urls.first, sessionData?.urls.count == 1, InternalURL(firstURL)?.isAboutHomeURL ?? false {
return Strings.AppMenuOpenHomePageTitleString
}
if let url = self.url, !InternalURL.isValid(url: url), let shownUrl = url.displayURL?.absoluteString {
return shownUrl
}
guard let lastTitle = lastTitle, !lastTitle.isEmpty else {
return self.url?.displayURL?.absoluteString ?? ""
}
return lastTitle
}
var displayFavicon: Favicon? {
return favicons.max { $0.width! < $1.width! }
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
_ = webView?.goBack()
}
func goForward() {
_ = webView?.goForward()
}
func goToBackForwardListItem(_ item: WKBackForwardListItem) {
_ = webView?.go(to: item)
}
@discardableResult func loadRequest(_ request: URLRequest) -> WKNavigation? {
if let webView = webView {
// Convert about:reader?url=http://example.com URLs to local ReaderMode URLs
if let url = request.url, let syncedReaderModeURL = url.decodeReaderModeURL, let localReaderModeURL = syncedReaderModeURL.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) {
let readerModeRequest = PrivilegedRequest(url: localReaderModeURL) as URLRequest
lastRequest = readerModeRequest
return webView.load(readerModeRequest)
}
lastRequest = request
if let url = request.url, url.isFileURL, request.isPrivileged {
return webView.loadFileURL(url, allowingReadAccessTo: url)
}
return webView.load(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
// If the current page is an error page, and the reload button is tapped, load the original URL
if let url = webView?.url, let internalUrl = InternalURL(url), let page = internalUrl.originalURLFromErrorPage {
webView?.replaceLocation(with: page)
return
}
if let _ = webView?.reloadFromOrigin() {
print("reloaded zombified tab from origin")
return
}
if let webView = self.webView {
print("restoring webView from scratch")
restore(webView)
}
}
func addContentScript(_ helper: TabContentScript, name: String) {
contentScriptManager.addContentScript(helper, name: name, forTab: self)
}
func getContentScript(name: String) -> TabContentScript? {
return contentScriptManager.getContentScript(name)
}
func hideContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = false
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = true
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(_ bar: SnackBar) {
if bars.count > 2 { return } // maximum 3 snackbars allowed on a tab
bars.append(bar)
tabDelegate?.tab(self, didAddSnackbar: bar)
}
func removeSnackbar(_ bar: SnackBar) {
if let index = bars.firstIndex(of: bar) {
bars.remove(at: index)
tabDelegate?.tab(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
bars.reversed().forEach { removeSnackbar($0) }
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
bars.reversed().filter({ !$0.shouldPersist(self) }).forEach({ removeSnackbar($0) })
}
func expireSnackbars(withClass snackbarClass: String) {
bars.reversed().filter({ $0.snackbarClassIdentifier == snackbarClass }).forEach({ removeSnackbar($0) })
}
func setScreenshot(_ screenshot: UIImage?, revUUID: Bool = true) {
self.screenshot = screenshot
if revUUID {
self.screenshotUUID = UUID()
}
}
func toggleChangeUserAgent() {
changedUserAgent = !changedUserAgent
if changedUserAgent, let url = url?.withoutMobilePrefix() {
let request = URLRequest(url: url)
webView?.load(request)
} else {
reload()
}
TabEvent.post(.didToggleDesktopMode, for: self)
}
func queueJavascriptAlertPrompt(_ alert: JSAlertInfo) {
alertQueue.append(alert)
}
func dequeueJavascriptAlertPrompt() -> JSAlertInfo? {
guard !alertQueue.isEmpty else {
return nil
}
return alertQueue.removeFirst()
}
func cancelQueuedAlerts() {
alertQueue.forEach { alert in
alert.cancel()
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let webView = object as? WKWebView, webView == self.webView,
let path = keyPath, path == KVOConstants.URL.rawValue else {
return assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
}
guard let url = self.webView?.url else {
return
}
self.urlDidChangeDelegate?.tab(self, urlDidChangeTo: url)
}
func isDescendentOf(_ ancestor: Tab) -> Bool {
return sequence(first: parent) { $0?.parent }.contains { $0 == ancestor }
}
func observeURLChanges(delegate: URLChangeDelegate) {
self.urlDidChangeDelegate = delegate
}
func removeURLChangeObserver(delegate: URLChangeDelegate) {
if let existing = self.urlDidChangeDelegate, existing === delegate {
self.urlDidChangeDelegate = nil
}
}
func applyTheme() {
UITextField.appearance().keyboardAppearance = isPrivate ? .dark : (ThemeManager.instance.currentName == .dark ? .dark : .light)
}
func getProviderForUrl() -> SearchEngine {
guard let url = self.webView?.url else {
return .none
}
for provider in SearchEngine.allCases {
if (url.absoluteString.contains(provider.rawValue)) {
return provider
}
}
return .none
}
func updateFaviconCache() {
guard let displayFavicon = displayFavicon?.url, let faviconUrl = URL(string: displayFavicon), let baseDomain = url?.baseDomain else {
return
}
if currentFaviconUrl == nil {
currentFaviconUrl = faviconUrl
} else if !faviconUrl.isEqual(currentFaviconUrl!) {
return
}
FaviconFetcher.downloadFaviconAndCache(imageURL: currentFaviconUrl, imageKey: baseDomain)
}
}
extension Tab: TabWebViewDelegate {
fileprivate func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) {
tabDelegate?.tab(self, didSelectFindInPageForSelection: selection)
}
fileprivate func tabWebViewSearchWithFirefox(_ tabWebViewSearchWithFirefox: TabWebView, didSelectSearchWithFirefoxForSelection selection: String) {
tabDelegate?.tab(self, didSelectSearchWithFirefoxForSelection: selection)
}
}
extension Tab: ContentBlockerTab {
func currentURL() -> URL? {
return url
}
func currentWebView() -> WKWebView? {
return webView
}
func imageContentBlockingEnabled() -> Bool {
return noImageMode
}
}
private class TabContentScriptManager: NSObject, WKScriptMessageHandler {
private var helpers = [String: TabContentScript]()
// Without calling this, the TabContentScriptManager will leak.
func uninstall(tab: Tab) {
helpers.forEach { helper in
if let name = helper.value.scriptMessageHandlerName() {
tab.webView?.configuration.userContentController.removeScriptMessageHandler(forName: name)
}
}
}
@objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName(), scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
func addContentScript(_ helper: TabContentScript, name: String, forTab tab: Tab) {
if let _ = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right TabHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
tab.webView?.configuration.userContentController.addInDefaultContentWorld(scriptMessageHandler: self, name: scriptMessageHandlerName)
}
}
func getContentScript(_ name: String) -> TabContentScript? {
return helpers[name]
}
}
private protocol TabWebViewDelegate: AnyObject {
func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String)
func tabWebViewSearchWithFirefox(_ tabWebViewSearchWithFirefox: TabWebView, didSelectSearchWithFirefoxForSelection selection: String)
}
class TabWebView: WKWebView, MenuHelperInterface {
fileprivate weak var delegate: TabWebViewDelegate?
// Updates the `background-color` of the webview to match
// the theme if the webview is showing "about:blank" (nil).
func applyTheme() {
if url == nil {
let backgroundColor = ThemeManager.instance.current.browser.background.hexString
evaluateJavascriptInDefaultContentWorld("document.documentElement.style.backgroundColor = '\(backgroundColor)';")
}
window?.backgroundColor = UIColor.theme.browser.background
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return super.canPerformAction(action, withSender: sender) || action == MenuHelper.SelectorFindInPage
}
@objc func menuHelperFindInPage() {
evaluateJavascriptInDefaultContentWorld("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
self.delegate?.tabWebView(self, didSelectFindInPageForSelection: selection)
}
}
@objc func menuHelperSearchWithFirefox() {
evaluateJavascriptInDefaultContentWorld("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
self.delegate?.tabWebViewSearchWithFirefox(self, didSelectSearchWithFirefoxForSelection: selection)
}
}
internal override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// The find-in-page selection menu only appears if the webview is the first responder.
becomeFirstResponder()
return super.hitTest(point, with: event)
}
/// Override evaluateJavascript - should not be called directly on TabWebViews any longer
// We should only be calling evaluateJavascriptInDefaultContentWorld in the future
@available(*, unavailable, message:"Do not call evaluateJavaScript directly on TabWebViews, should only be called on super class")
override func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((Any?, Error?) -> Void)? = nil) {
super.evaluateJavaScript(javaScriptString, completionHandler: completionHandler)
}
}
///
// Temporary fix for Bug 1390871 - NSInvalidArgumentException: -[WKContentView menuHelperFindInPage]: unrecognized selector
//
// This class only exists to contain the swizzledMenuHelperFindInPage. This class is actually never
// instantiated. It only serves as a placeholder for the method. When the method is called, self is
// actually pointing to a WKContentView. Which is not public, but that is fine, we only need to know
// that it is a UIView subclass to access its superview.
//
class TabWebViewMenuHelper: UIView {
@objc func swizzledMenuHelperFindInPage() {
if let tabWebView = superview?.superview as? TabWebView {
tabWebView.evaluateJavascriptInDefaultContentWorld("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
tabWebView.delegate?.tabWebView(tabWebView, didSelectFindInPageForSelection: selection)
}
}
}
}
extension URL {
/**
Returns a URL without a mobile prefix (`"m."` or `"mobile."`)
*/
func withoutMobilePrefix() -> URL {
let mPrefix = "m."
let mobilePrefix = "mobile."
let foundPrefix: String?
if host?.contains(mPrefix) == true {
foundPrefix = mPrefix
} else if host?.contains(mobilePrefix) == true {
foundPrefix = mobilePrefix
} else {
foundPrefix = nil
}
guard
let prefixToRemove = foundPrefix,
var components = URLComponents(url: self, resolvingAgainstBaseURL: true),
var host = components.host,
let range = host.range(of: prefixToRemove) else { return self }
host.removeSubrange(range)
components.host = host
return components.url ?? self
}
}
|
mpl-2.0
|
29f9c7cabf57b48f042dd86ab837ded9
| 34.229529 | 201 | 0.634372 | 5.248614 | false | false | false | false |
arrrnas/vinted-ab-ios
|
vinted-ab-ios/Extensions/VNTModel+Testable.swift
|
1
|
3177
|
import Foundation
private let NumberedJsonFileFormat = "%@[%@]"
extension VNTModel {
static func mappedObject(bundle: Bundle, index: String, dictChanges: [(key: String, value: AnyObject?)] = []) -> Self? {
guard let dict = jsonFileDictionary(forType: self,
bundle: bundle,
index: index) else { return nil }
var updatedDict = dict
for dictChange in dictChanges {
updatedDict = updateDictionary(dict: dict as [String : AnyObject], keyPath: dictChange.key, value: dictChange.value)
}
return self.init(dictionary: updatedDict)
}
static func loadSample(_ bundle: Bundle, index: String = "0", replace key: String? = nil, with value: AnyObject? = nil) -> Self? {
if let key = key {
return mappedObject(bundle: bundle, index: index, dictChanges: [(key: key, value: value)])
}
return mappedObject(bundle: bundle, index: index)
}
}
private func updateDictionary(dict: [String: AnyObject], keyPath: String, value: AnyObject?) -> [String: AnyObject] {
var dictToEdit: [String: AnyObject] = dict
let keys = keyPath.characters.split { $0 == "." }.map(String.init)
for (i, key) in keys.enumerated() {
if keys.count == 1 {
dictToEdit[key] = value
}
else if let dictToUpdate = dictToEdit[key] as? [String: AnyObject] {
var subset = keys
subset.remove(at: i)
dictToEdit[key] = updateDictionary(dict: dictToUpdate, keyPath: subset.joined(separator: "."), value: value) as AnyObject?
}
}
return dictToEdit
}
func jsonFileString(forType type: Any, bundle: Bundle, index: String) -> String? {
guard let data = jsonFileData(forType: type, bundle: bundle, index: index) else { return nil }
return String(data: data, encoding: String.Encoding.utf8)
}
func jsonFileDictionary(forType type: Any, bundle: Bundle, index: String) -> [String : Any]? {
guard let data = jsonFileData(forType: type, bundle: bundle, index: index) else { return nil }
var dict: [String : Any]?
do {
dict = try JSONSerialization.jsonObject(with: data,
options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : Any]
} catch {
return nil
}
return dict
}
private func jsonFileData(forType type: Any, bundle: Bundle, index: String) -> Data? {
guard let filePath = jsonFilePath(forType: type, bundle: bundle, index: index) else {
return nil
}
return (try? Data(contentsOf: URL(fileURLWithPath: filePath)))
}
private func jsonFilePath(forType type: Any, bundle: Bundle, index: String) -> String? {
guard let resourceName = jsonFileName(forType: type, index: index) else { return nil }
return bundle.path(forResource: resourceName, ofType: "json")
}
private func jsonFileName(forType type: Any, index: String) -> String? {
guard let lastComponent = "\(String(describing: type))".components(separatedBy: ".").first else { return nil }
return String(format: NumberedJsonFileFormat, lastComponent, index)
}
|
mit
|
90e181e8f96cc98ccbcd6b92cc5c5e7f
| 40.802632 | 134 | 0.639282 | 4.219124 | false | false | false | false |
asurinsaka/swift_examples_2.1
|
LocateMe/LocateMe/LocateViewController.swift
|
1
|
9228
|
//
// LocateViewController.swift
// LocateMe
//
// Created by doudou on 8/17/14.
// Copyright (c) 2014 larryhou. All rights reserved.
//
import Foundation
import CoreLocation
import UIKit
extension CLAuthorizationStatus
{
var description:String
{
var status:String
switch self
{
case .Authorized:status="Authorized"
case .AuthorizedWhenInUse:status="AuthorizedWhenInUse"
case .Denied:status="Denied"
case .NotDetermined:status="NotDetermined"
case .Restricted:status="Restriced"
}
return "CLAuthorizationStatus.\(status)"
}
}
class LocateViewController:UITableViewController, SetupSettingReceiver, CLLocationManagerDelegate
{
enum LocationUpdateStatus:String
{
case Updating = "Updating"
case Timeout = "Timeout"
case Acquired = "Acquired Location"
case Error = "Error"
case None = "None"
}
enum SectionType:Int
{
case LocateStatus = 0
case BestMeasurement = 1
case Measurements = 2
}
enum CellIdentifier:String
{
case Status = "StatusCell"
case Measurement = "MeasurementCell"
}
private var setting:LocateSettingInfo!
private var dateFormatter:NSDateFormatter!
private var leftFormatter:NSNumberFormatter!
private var bestMeasurement:CLLocation!
private var measurements:[CLLocation]!
private var locationManager:CLLocationManager!
private var timer:NSTimer!
private var remainTime:Float!
private var status:LocationUpdateStatus!
func setupSetting(setting: LocateSettingInfo)
{
self.setting = setting
}
override func viewDidLoad()
{
dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = localizeString("DateFormat")
leftFormatter = NSNumberFormatter()
leftFormatter.minimumIntegerDigits = 2
leftFormatter.maximumFractionDigits = 0
measurements = []
locationManager = CLLocationManager()
}
override func viewWillAppear(animated: Bool)
{
if bestMeasurement == nil
{
startUpdateLocation()
}
}
override func viewWillDisappear(animated: Bool)
{
stopUpdatingLocation(.None)
}
// MARK: 数据重置
@IBAction func refresh(sender: UIBarButtonItem)
{
startUpdateLocation()
}
// MARK: 定位相关
func startUpdateLocation()
{
if timer != nil
{
timer.invalidate()
timer = nil
}
locationManager.stopUpdatingLocation()
measurements.removeAll(keepCapacity: false)
bestMeasurement = nil
status = .Updating
tableView.reloadData()
print(setting)
remainTime = setting.sliderValue
timer = NSTimer.scheduledTimerWithTimeInterval(1.0,
target: self, selector: "timeTickUpdate",
userInfo: nil, repeats: true)
// FIXME: 无法使用带参数的selector,否则报错: [NSCFTimer copyWithZone:]: unrecognized selector sent to instance
// timer = NSTimer.scheduledTimerWithTimeInterval(delay,
// target: self, selector: "stopUpdatingLocation:",
// userInfo: nil, repeats: false)
if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse)
{
locationManager.requestWhenInUseAuthorization()
}
locationManager.desiredAccuracy = setting.accuracy
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
func stopUpdatingLocation(status:LocationUpdateStatus)
{
if status != .None
{
self.status = status
tableView.reloadData()
}
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
if timer != nil
{
timer.invalidate()
timer = nil
}
}
func timeTickUpdate()
{
remainTime!--
tableView.reloadData()
if remainTime <= 0
{
stopUpdatingLocation(.Timeout)
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
print("authorization:\(status.description)")
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
for data in locations
{
let location = data as CLLocation
measurements.append(location)
if bestMeasurement == nil || bestMeasurement.horizontalAccuracy > location.horizontalAccuracy
{
bestMeasurement = location
if location.horizontalAccuracy < locationManager.desiredAccuracy
{
stopUpdatingLocation(.Acquired)
}
}
}
tableView.reloadData()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
stopUpdatingLocation(.Error)
}
// MARK: 列表展示
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return bestMeasurement != nil ? 3 : 1
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
switch SectionType(rawValue: indexPath.section)!
{
case .LocateStatus:return 60.0 //FIXME: 自定义UITableViewCell需要手动指定高度
default:return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
if let type = SectionType(rawValue: section)
{
switch type
{
case .LocateStatus:
return localizeString("Status")
case .BestMeasurement:
return localizeString("Best Measurement")
case .Measurements:
return localizeString("All Measurements")
}
}
else
{
return nil
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if let type = SectionType(rawValue: section)
{
switch type
{
case .LocateStatus:return 1
case .BestMeasurement:return 1
case .Measurements:return measurements.count
}
}
else
{
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let type = SectionType(rawValue: indexPath.section)
{
switch type
{
case .LocateStatus:
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.Status.rawValue) as! StatusTableViewCell
cell.timeTicker.text = leftFormatter.stringFromNumber(remainTime)
cell.label.text = localizeString(status.rawValue)
if status == .Updating
{
cell.timeTicker.alpha = 1.0
if !cell.indicator.isAnimating()
{
cell.indicator.startAnimating()
}
}
else
{
cell.timeTicker.alpha = 0.0
if cell.indicator.isAnimating()
{
cell.indicator.stopAnimating()
}
}
return cell
case .BestMeasurement:
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.Measurement.rawValue)! as UITableViewCell
cell.textLabel!.text = bestMeasurement.getCoordinateString()
cell.detailTextLabel!.text = dateFormatter.stringFromDate(bestMeasurement.timestamp)
return cell
case .Measurements:
let location = measurements[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.Measurement.rawValue)! as UITableViewCell
cell.textLabel!.text = location.getCoordinateString()
cell.detailTextLabel!.text = dateFormatter.stringFromDate(location.timestamp)
return cell
}
}
else{
return UITableViewCell()
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
//MARK: segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
if segue.identifier == "LocationDetailSegue"
{
let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
let type:SectionType = SectionType(rawValue: indexPath!.section)!
let destinationCtrl = segue.destinationViewController as! LocationDetailViewController
switch type
{
case .BestMeasurement:
destinationCtrl.location = bestMeasurement
case .Measurements:
destinationCtrl.location = measurements[indexPath!.row]
default:break
}
}
}
}
|
mit
|
c65617aebbc3e8a5859a01f14c783aa4
| 25.923529 | 127 | 0.624317 | 5.26092 | false | false | false | false |
simonkim/AVCapture
|
AVCapture/AVEncoderVideoToolbox/NALUtil.swift
|
1
|
1667
|
//
// NALUtil.swift
// AVCapture
//
// Created by Simon Kim on 2016. 9. 11..
// Copyright © 2016 DZPub.com. All rights reserved.
//
import Foundation
import CoreMedia
enum NALUnitType: Int8 {
case IDR = 5
case SPS = 7
case PPS = 8
}
class NALUtil {
static func readNALUnitLength(at pointer: UnsafePointer<UInt8>, headerLength: Int) -> Int
{
var result: Int = 0
for i in 0...(headerLength - 1) {
result |= Int(pointer[i]) << (((headerLength - 1) - i) * 8)
}
return result
}
}
extension CMBlockBuffer {
/*
* List of NAL Units without NALUnitHeader
*/
public func NALUnits(headerLength: Int) -> [Data] {
var totalLength: Int = 0
var pointer:UnsafeMutablePointer<Int8>? = nil
var dataArray: [Data] = []
if noErr == CMBlockBufferGetDataPointer(self, 0, &totalLength, nil, &pointer) {
while totalLength > Int(headerLength) {
let unitLength = pointer!.withMemoryRebound(to: UInt8.self, capacity: totalLength) {
NALUtil.readNALUnitLength(at: $0, headerLength: Int(headerLength))
}
dataArray.append(Data(bytesNoCopy: pointer!.advanced(by: Int(headerLength)),
count: unitLength,
deallocator: .none))
let nextOffset = headerLength + unitLength
pointer = pointer!.advanced(by: nextOffset)
totalLength -= Int(nextOffset)
}
}
return dataArray
}
}
|
apache-2.0
|
115544c742e1edf4af601ee5a24d8354
| 27.237288 | 100 | 0.537815 | 4.384211 | false | false | false | false |
JohnSansoucie/MyProject2
|
BlueCap/Utils/BeaconStore.swift
|
1
|
1470
|
//
// BeaconStore.swift
// BlueCap
//
// Created by Troy Stribling on 9/16/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import Foundation
import BlueCapKit
class BeaconStore {
class func getBeacons() -> [String:NSUUID] {
if let storedBeacons = NSUserDefaults.standardUserDefaults().dictionaryForKey("beacons") {
var beacons = [String:NSUUID]()
for (name, uuid) in storedBeacons {
if let name = name as? String {
if let uuid = uuid as? String {
beacons[name] = NSUUID(UUIDString:uuid)
}
}
}
return beacons
} else {
return [:]
}
}
class func setBeacons(beacons:[String:NSUUID]) {
var storedBeacons = [String:String]()
for (name, uuid) in beacons {
storedBeacons[name] = uuid.UUIDString
}
NSUserDefaults.standardUserDefaults().setObject(storedBeacons, forKey:"beacons")
}
class func getBeaconNames() -> [String] {
return self.getBeacons().keys.array
}
class func addBeacon(name:String, uuid:NSUUID) {
var beacons = self.getBeacons()
beacons[name] = uuid
self.setBeacons(beacons)
}
class func removeBeacon(name:String) {
var beacons = self.getBeacons()
beacons.removeValueForKey(name)
self.setBeacons(beacons)
}
}
|
mit
|
ca8143fabfb668259c626d5755258f03
| 26.754717 | 98 | 0.566667 | 4.666667 | false | false | false | false |
darincon/MaskedLabel
|
Example/ViewController.swift
|
1
|
2351
|
//
// ViewController.swift
// MaskedLabel
//
// Created by Diego Rincon on 4/17/17.
// Copyright © 2017 Scire Studios. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var maskedLabel: MaskedLabel!
@IBOutlet weak var fillSegmentedControl: UISegmentedControl!
@IBOutlet weak var useSegmentedControl: UISegmentedControl!
let gradientColors = [UIColor(red:0.79, green:0.30, blue:0.64, alpha:1.00),
UIColor(red:0.08, green:0.33, blue:0.82, alpha:1.00)]
var labelText: String {
var text: String
if fillSegmentedControl.selectedSegmentIndex == 0 {
text = "BACKGROUND "
}
else {
text = "TEXT "
}
if useSegmentedControl.selectedSegmentIndex == 0 {
text += "COLOR"
}
else {
text += "GRADIENT"
}
return "\(text)\n\(text)\n\(text)\n\(text)"
}
// MARK: Life cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupMaskedLabel()
}
override func viewDidLayoutSubviews() {
setupGradientPoints()
}
// MARK: Setup
func setupMaskedLabel() {
maskedLabel.text = labelText
maskedLabel.fillColor = UIColor.red
maskedLabel.gradientColors = nil
maskedLabel.fillOption = .background
}
func setupGradientPoints() {
maskedLabel.startPoint = CGPoint(x: 0.0, y: 0.0)
maskedLabel.endPoint = CGPoint(x: maskedLabel.frame.width, y: maskedLabel.frame.height)
}
// MARK: Action methods
@IBAction func fillSegmentedControlDidChange(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
maskedLabel.fillOption = .background
}
else {
maskedLabel.fillOption = .text
}
maskedLabel.text = labelText
}
@IBAction func useSegmentedControlDidChange(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
maskedLabel.gradientColors = nil
}
else {
maskedLabel.gradientColors = gradientColors
}
maskedLabel.text = labelText
}
}
|
mit
|
c8fbe7590cc53fde060eecebf0f7c479
| 25.111111 | 95 | 0.581702 | 4.766734 | false | false | false | false |
jeanetienne/Bee
|
Bee/Modules/Spelling/CollapsiblePicker/CollapsiblePicker.swift
|
1
|
5883
|
//
// Bee
// Copyright © 2017 Jean-Étienne. All rights reserved.
//
import UIKit
protocol CollapsiblePickerDelegate {
func pickerDidSelectItem(withName name: String)
}
class CollapsiblePicker: UIView {
enum Height: CGFloat {
case collapsed = 38.0
case expanded = 205.0
}
var items: [String]?
var displayItems: [String]? {
return items?.filter { itemName -> Bool in
itemName != pickerButton.title(for: .normal)
}
}
var delegate: CollapsiblePickerDelegate?
// MARK: Outlets
@IBOutlet weak var pickerButton: UIButton!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var arrow: DisclosureArrow!
@IBOutlet weak var topGradient: GradientView!
@IBOutlet weak var bottomGradient: GradientView!
// MARK: Private properties
private var isExpanded: Bool {
return heightConstraint.constant == Height.expanded.rawValue
}
private let animationDuration: TimeInterval = 0.2
private var heightConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
let view = loadFromNib()
view.frame = bounds
addSubview(view)
heightConstraint = initialHeightConstraint()
addConstraint(heightConstraint)
pickerButton.setTitleColor(UIColor.faded, for: .normal)
// TableView
let cell = UINib(nibName: String(describing: CollapsiblePickerTableViewCell.self), bundle: Bundle.main)
tableView.register(cell, forCellOfClass: CollapsiblePickerTableViewCell.self)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = Height.collapsed.rawValue
var contentInset = tableView.contentInset
contentInset.top = 3
contentInset.bottom = 3
tableView.contentInset = contentInset
topGradient.alpha = 0
bottomGradient.alpha = 0
clipsToBounds = true
}
func selectItem(atIndex index: Int) {
if let name = items?[index] {
pickerButton.setTitle(name, for: .normal)
}
}
@IBAction private func pickerDidTouchUpInside(_ sender: Any, forEvent event: UIEvent) {
if isExpanded {
animate(toHeight: .collapsed)
} else {
animate(toHeight: .expanded)
}
}
fileprivate func selectItem(withName name: String) {
animate(toHeight: .collapsed)
pickerButton.setTitle(name, for: .normal)
delegate?.pickerDidSelectItem(withName: name)
}
// MARK: - Helpers
private func loadFromNib() -> UIView {
let bundle = Bundle(for: CollapsiblePicker.self)
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
return nib.instantiate(withOwner: self, options: nil)[0] as! UIView
}
private func initialHeightConstraint() -> NSLayoutConstraint {
return NSLayoutConstraint(item: self,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: Height.collapsed.rawValue)
}
private func animate(toHeight height: Height) {
pickerButton.isEnabled = false
let angle: CGFloat = (height == .collapsed) ? 0 : .pi
let gradientsAlpha: CGFloat = (height == .collapsed) ? 0 : 1
UIView.animate(withDuration: animationDuration,
delay: 0,
options: .curveEaseInOut,
animations: {
self.heightConstraint.constant = height.rawValue
self.arrow.transform = CGAffineTransform(rotationAngle: angle)
self.topGradient.alpha = gradientsAlpha
self.bottomGradient.alpha = gradientsAlpha
self.superview?.layoutIfNeeded()
}) { _ in
self.pickerButton.isEnabled = true
if height == .expanded {
self.tableView.flashScrollIndicators()
} else {
self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
}
}
}
}
extension CollapsiblePicker: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withClass: CollapsiblePickerTableViewCell.self,
for: indexPath) as! CollapsiblePickerTableViewCell
// Selection background
cell.selectionStyle = .default
let cellbackgroundView = UIView()
cellbackgroundView.backgroundColor = UIColor.secondary
cellbackgroundView.layer.cornerRadius = 2
cellbackgroundView.clipsToBounds = true
cell.selectedBackgroundView = cellbackgroundView
if let itemName = displayItems?[indexPath.row] {
cell.configure(withItemName: itemName)
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayItems?.count ?? 0
}
}
extension CollapsiblePicker: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let itemName = displayItems?[indexPath.row] {
selectItem(withName: itemName)
}
tableView.deselectRow(at: indexPath, animated: true)
tableView.reloadData()
}
}
|
mit
|
d1726abe245de2bad4cc16cc1cdff69b
| 31.672222 | 111 | 0.595307 | 5.475791 | false | false | false | false |
kstaring/swift
|
test/SILGen/objc_set_bridging.swift
|
2
|
5310
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import gizmo
@objc class Foo : NSObject {
// Bridging set parameters
// CHECK-LABEL: sil hidden [thunk] @_TToFC17objc_set_bridging3Foo16bridge_Set_param{{.*}} : $@convention(objc_method) (NSSet, Foo) -> ()
func bridge_Set_param(_ s: Set<Foo>) {
// CHECK: bb0([[NSSET:%[0-9]+]] : $NSSet, [[SELF:%[0-9]+]] : $Foo):
// CHECK: [[NSSET_COPY:%.*]] = copy_value [[NSSET]] : $NSSet
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Foo
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_TZFE10FoundationVs3Set36_unconditionallyBridgeFromObjectiveCfGSqCSo5NSSet_GS0_x_
// CHECK: [[OPT_NSSET:%[0-9]+]] = enum $Optional<NSSet>, #Optional.some!enumelt.1, [[NSSET_COPY]] : $NSSet
// CHECK: [[SET_META:%[0-9]+]] = metatype $@thin Set<Foo>.Type
// CHECK: [[SET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[OPT_NSSET]], [[SET_META]])
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_TFC17objc_set_bridging3Foo16bridge_Set_param{{.*}} : $@convention(method) (@owned Set<Foo>, @guaranteed Foo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[SET]], [[SELF_COPY]]) : $@convention(method) (@owned Set<Foo>, @guaranteed Foo) -> ()
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
}
// CHECK: // end sil function '_TToFC17objc_set_bridging3Foo16bridge_Set_param{{.*}}'
// Bridging set results
// CHECK-LABEL: sil hidden [thunk] @_TToFC17objc_set_bridging3Foo17bridge_Set_result{{.*}} : $@convention(objc_method) (Foo) -> @autoreleased NSSet {
func bridge_Set_result() -> Set<Foo> {
// CHECK: bb0([[SELF:%[0-9]+]] : $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Foo
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_TFC17objc_set_bridging3Foo17bridge_Set_result{{.*}} : $@convention(method) (@guaranteed Foo) -> @owned Set<Foo>
// CHECK: [[SET:%[0-9]+]] = apply [[SWIFT_FN]]([[SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Set<Foo>
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_TFE10FoundationVs3Set19_bridgeToObjectiveCfT_CSo5NSSet
// CHECK: [[NSSET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[SET]]) : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@guaranteed Set<τ_0_0>) -> @owned NSSet
// CHECK: destroy_value [[SET]]
// CHECK: return [[NSSET]] : $NSSet
}
// CHECK: } // end sil function '_TToFC17objc_set_bridging3Foo17bridge_Set_result{{.*}}'
var property: Set<Foo> = Set()
// Property getter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC17objc_set_bridging3Foog8property{{.*}} : $@convention(objc_method) (Foo) -> @autoreleased NSSet
// CHECK: bb0([[SELF:%[0-9]+]] : $Foo):
// CHECK: [[SELF_COPY]] = copy_value [[SELF]] : $Foo
// CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFC17objc_set_bridging3Foog8property{{.*}} : $@convention(method) (@guaranteed Foo) -> @owned Set<Foo>
// CHECK: [[SET:%[0-9]+]] = apply [[GETTER]]([[SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Set<Foo>
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_TFE10FoundationVs3Set19_bridgeToObjectiveCfT_CSo5NSSet
// CHECK: [[NSSET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[SET]]) : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@guaranteed Set<τ_0_0>) -> @owned NSSet
// CHECK: destroy_value [[SET]]
// CHECK: return [[NSSET]] : $NSSet
// CHECK: } // end sil function '_TToFC17objc_set_bridging3Foog8property{{.*}}'
// Property setter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC17objc_set_bridging3Foos8property{{.*}} : $@convention(objc_method) (NSSet, Foo) -> () {
// CHECK: bb0([[NSSET:%[0-9]+]] : $NSSet, [[SELF:%[0-9]+]] : $Foo):
// CHECK: [[NSSET_COPY:%.*]] = copy_value [[NSSET]] : $NSSet
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Foo
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_TZFE10FoundationVs3Set36_unconditionallyBridgeFromObjectiveCfGSqCSo5NSSet_GS0_x_
// CHECK: [[OPT_NSSET:%[0-9]+]] = enum $Optional<NSSet>, #Optional.some!enumelt.1, [[NSSET_COPY]] : $NSSet
// CHECK: [[SET_META:%[0-9]+]] = metatype $@thin Set<Foo>.Type
// CHECK: [[SET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[OPT_NSSET]], [[SET_META]])
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_TFC17objc_set_bridging3Foos8property{{.*}} : $@convention(method) (@owned Set<Foo>, @guaranteed Foo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[SETTER]]([[SET]], [[SELF_COPY]]) : $@convention(method) (@owned Set<Foo>, @guaranteed Foo) -> ()
// CHECK: destroy_value [[SELF_COPY]] : $Foo
// CHECK: return [[RESULT]] : $()
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC17objc_set_bridging3Foog19nonVerbatimProperty{{.*}} : $@convention(objc_method) (Foo) -> @autoreleased NSSet
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC17objc_set_bridging3Foos19nonVerbatimProperty{{.*}} : $@convention(objc_method) (NSSet, Foo) -> () {
@objc var nonVerbatimProperty: Set<String> = Set()
}
func ==(x: Foo, y: Foo) -> Bool { }
|
apache-2.0
|
fd9f2815758ca7597108b90d328ce67d
| 67 | 168 | 0.605392 | 3.199035 | false | false | false | false |
Polidea/RxBluetoothKit
|
ExampleApp/ExampleApp/Screens/CharacteristicRead/CharacteristicReadView.swift
|
2
|
883
|
import UIKit
class CharacteristicReadView: UIView {
init() {
super.init(frame: .zero)
backgroundColor = .systemBackground
setupLayout()
}
required init?(coder: NSCoder) { nil }
// MARK: - Subviews
let label: UILabel = {
let label = UILabel()
label.text = "Read value: --"
label.font = UIFont.systemFont(ofSize: 20.0)
label.textColor = .green
return label
}()
// MARK: - Private
private func setupLayout() {
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: centerXAnchor),
label.centerYAnchor.constraint(equalTo: centerYAnchor),
label.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -32)
])
}
}
|
apache-2.0
|
1f4ef59cdf10b2efbe0ddba42067aad2
| 23.527778 | 87 | 0.616082 | 4.988701 | false | false | false | false |
TheTekton/Malibu
|
MalibuTests/Specs/Response/WaveSpec.swift
|
1
|
946
|
@testable import Malibu
import When
import Quick
import Nimble
class WaveSpec: QuickSpec {
override func spec() {
describe("Wave") {
let URL = NSURL(string: "http://hyper.no")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/2.0", headerFields: nil)!
var request: NSURLRequest!
var data: NSData!
beforeEach {
request = NSURLRequest(URL: NSURL(string: "http://hyper.no")!)
data = try! NSJSONSerialization.dataWithJSONObject([["name": "Taylor"]],
options: NSJSONWritingOptions())
}
describe("#init") {
it("sets data, request and response parameters to instance vars") {
let result = Wave(data: data, request: request, response: response)
expect(result.data).to(equal(data))
expect(result.request).to(equal(request))
expect(result.response).to(equal(response))
}
}
}
}
}
|
mit
|
37a090abd49f489a431233b5ab59627b
| 28.5625 | 110 | 0.623679 | 4.280543 | false | false | false | false |
mikker/Disaster.app
|
Disaster/SearchViewController.swift
|
1
|
2402
|
//
// ViewController.swift
// Disaster
//
// Created by Mikkel Malmberg on 13/09/14.
// Copyright (c) 2014 BRNBW. All rights reserved.
//
import UIKit
class SearchViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
@IBOutlet var searchBar :UISearchBar?
var results : Array<JSONValue>?
override func viewDidLoad() {
super.viewDidLoad()
title = "DR TV"
self.searchBar!.becomeFirstResponder()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if sender is UITableViewCell {
let cell = sender as UITableViewCell!
var bundle = results![tableView.indexPathForCell(cell)!.row]
let dest = segue.destinationViewController as BundleViewController
dest.bundle = bundle
}
}
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results? == nil ? 0 : results!.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("TextCell") as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "TextCell")
}
let bundle = results![indexPath.row]
cell!.textLabel!.text = bundle["Title"].string!
return cell
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: UISearchDisplay
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchFor(searchBar.text)
}
// MARK: -
private func searchFor(title: String) {
println("Searching for '\(title)'")
var path = "/Bundle?Title=$like('\(title)')"
DRMU.sharedClient.GET(path, completionHandler: { (response, obj, error) -> Void in
var resultsCount = obj["TotalSize"].number
println("Returned \(resultsCount) results")
self.results = sorted(obj["Data"].array!) {
$0["Title"].string! < $1["Title"].string!
}
self.tableView.reloadData()
})
}
}
|
mit
|
14cc3644670a9bd5cb91082661f99d2d
| 26.930233 | 116 | 0.689009 | 4.892057 | false | false | false | false |
inamiy/ReactiveCocoaCatalog
|
ReactiveCocoaCatalog/Samples/IncrementalSearchViewController.swift
|
1
|
3033
|
//
// IncrementalSearchViewController.swift
// ReactiveCocoaCatalog
//
// Created by Yasuhiro Inami on 2015-09-16.
// Copyright © 2015 Yasuhiro Inami. All rights reserved.
//
import UIKit
import Result
import ReactiveSwift
import APIKit
import Argo
private let _cellIdentifier = "IncrementalSearchCellIdentifier"
class IncrementalSearchViewController: UITableViewController, UISearchBarDelegate, NibSceneProvider
{
var searchController: UISearchController?
var bingSearchResponse: BingSearchResponse?
override func viewDidLoad()
{
super.viewDidLoad()
let searchController = UISearchController(searchResultsController: nil)
searchController.dimsBackgroundDuringPresentation = false
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: _cellIdentifier)
self.tableView.tableHeaderView = searchController.searchBar
// workaround for iOS8
// http://useyourloaf.com/blog/2015/04/26/search-bar-not-showing-without-a-scope-bar.html
if !ProcessInfo().isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: 9, minorVersion: 0, patchVersion: 0))
{
searchController.searchBar.sizeToFit()
}
self.searchController = searchController
let producer = searchController.searchBar.reactive.continuousTextValues
.throttle(0.15, on: QueueScheduler.main)
.flatMap(.latest) { value -> SignalProducer<BingSearchResponse, NoError> in
if let str = value {
return BingAPI.searchProducer(query: str)
.ignoreCastError(NoError.self)
}
else {
return .empty
}
}
producer.observeValues { [weak self] response in
print("onNext = \(response)")
self?.bingSearchResponse = response
self?.tableView.reloadData()
}
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
// Workaround for UISearchController activated at wrong x-position
// inside UISplitViewController (in iOS 9.3).
// (Caveat: This is a hotfix and not perfect)
if !(self.searchController?.searchBar.superview is UITableView) {
self.searchController?.searchBar.superview?.frame.origin.x = 0
}
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.bingSearchResponse?.suggestions.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: _cellIdentifier, for: indexPath)
cell.textLabel?.text = self.bingSearchResponse?.suggestions[indexPath.row]
return cell
}
}
|
mit
|
10057dd8ded88db38246a7789026b076
| 31.602151 | 125 | 0.670515 | 5.423971 | false | false | false | false |
nanoxd/Bourne
|
Sources/Decodable/Mappable+JSON.swift
|
1
|
2525
|
import Foundation
public extension JSON {
/// Decodes any `Mappable` type into itself or a default value
///
/// - Parameters:
/// - key: JSON key path
/// - defaultValue: Value to default to when key is not present
/// - Returns: The `Mappable` type
/// - Throws: A DecodeError iff the key is empty and defaultValue is not defined
public func from<T: Mappable>(_ key: String, or defaultValue: T? = nil) throws -> T {
guard let json = self[key], let value = try? T.decode(json) else {
if let defaultValue = defaultValue {
return defaultValue
} else {
throw BourneError.emptyJSON(key)
}
}
return value
}
/// Decodes any `Mappable` type into an array of itself or a default value
///
/// - Parameters:
/// - key: JSON key path
/// - defaultValues: Value to default to when key is not present
/// - Returns: An array of `Mappable` types
/// - Throws: A DecodeError iff the key is empty and defaultValue is not defined
public func from<T: Mappable>(_ key: String, or defaultValues: [T]? = nil) throws -> [T] {
guard let array = self[key]?.array else {
if let defaultValues = defaultValues {
return defaultValues
} else {
throw BourneError.emptyJSON(key)
}
}
return try array.map { json in
guard let value = try? T.decode(json) else {
throw BourneError.emptyJSON(key)
}
return value
}
}
/// Decodes any `Decodable` type into an array of itself or a default value
///
/// - Parameters:
/// - key: JSON key path
/// - defaultValue: Value to default to when key is not present
/// - Returns: A dictionary of `String: Decodable` types
/// - Throws: A DecodeError iff the key is empty and defaultValue is not defined
public func from<Value: Mappable>(_ key: String, or defaultValue: [String: Value]? = nil) throws -> [String: Value] {
var dict = [String: Value]()
guard let value = self[key], let dictionary = value.dictionary else {
if let defaultValue = defaultValue {
return defaultValue
} else {
throw BourneError.emptyJSON(key)
}
}
for (key, value) in dictionary {
dict[key] = try? Value.decode(value)
}
return dict
}
}
|
mit
|
f654e011fc2314b8f6a524a80d381119
| 34.069444 | 121 | 0.564752 | 4.607664 | false | false | false | false |
jackcook/interface
|
Interface/ArticlesViewController.swift
|
1
|
2931
|
//
// ArticlesViewController.swift
// Interface
//
// Created by Jack Cook on 4/2/16.
// Copyright © 2016 Jack Cook. All rights reserved.
//
import UIKit
class ArticlesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
private var articles = [Article]()
private var articleToSend: Article!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBarHidden = false
Interface.sharedInstance.retrieveArticles { (articles) in
guard let articles = articles else {
return
}
self.articles = articles
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
tableView.dataSource = self
tableView.delegate = self
}
@IBAction func quizletButton(sender: UIBarButtonItem) {
if Quizlet.sharedInstance.accessToken == nil {
Quizlet.sharedInstance.beginAuthorization(self)
} else {
let setId = Quizlet.sharedInstance.setId
guard setId > 0 else {
return
}
let url = NSURL(string: "https://quizlet.com/\(setId)/")!
UIApplication.sharedApplication().openURL(url)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let avc = segue.destinationViewController as! ArticleViewController
avc.article = articleToSend
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return indexPath.row % 5 == 0 ? 312 : 136
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let article = articles[indexPath.row]
let cell = NSBundle.mainBundle().loadNibNamed(indexPath.row % 5 == 0 ? (article.imageUrl == nil ? "NoImageArticleCell" : "LargeArticleCell") : (article.imageUrl == nil ? "NoImageArticleCell" : "ArticleCell"), owner: self, options: nil)[0] as! ArticleCell
cell.configure(articles[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
articleToSend = articles[indexPath.row]
performSegueWithIdentifier("articleSegue", sender: nil)
}
}
|
mit
|
68b004d1e8ff8522c1083d35f346aa90
| 33.069767 | 262 | 0.631399 | 5.549242 | false | false | false | false |
dathtcheapgo/Jira-Demo
|
Driver/MVC/Core/View/CGNavigationBar/CGNavbar.swift
|
1
|
1731
|
//
// CGNavbar.swift
// rider
//
// Created by Đinh Anh Huy on 10/19/16.
// Copyright © 2016 Đinh Anh Huy. All rights reserved.
//
import UIKit
protocol CGNavbarDelegate {
func navbarDidClickBack(sender: CGNavbar)
}
class CGNavbar: HBorderView {
@IBOutlet var view: UIView!
@IBOutlet var lbTitle: UILabel!
@IBInspectable var useBackButton: Bool = true
@IBInspectable var title: String = "Countries"
@IBInspectable var useCustomButton: Bool = false
@IBAction func btBackDidClick(sender: UIButton) {
delegate?.navbarDidClickBack(sender: self)
}
var delegate: CGNavbarDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
initControl()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initControl()
}
func initControl() {
Bundle.main.loadNibNamed("CGNavbar", owner: self, options: nil)
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
_ = view.addConstraintFillInView(view: self, commenParrentView: self)
gradientLeftColor = UIColor()
gradientRightColor = UIColor()
}
override func layoutSubviews() {
super.layoutSubviews()
gradient.removeFromSuperlayer()
gradient.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
gradient.colors = [gradientLeftColor?.cgColor, gradientRightColor?.cgColor]
gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
gradient.endPoint = CGPoint(x: 1.0, y: 0.0)
view.layer.insertSublayer(gradient, at: 0)
lbTitle.text = title
}
}
|
mit
|
61cc144ebcd1c1de2df4acbbcddddca4
| 26.428571 | 95 | 0.637731 | 4.20438 | false | false | false | false |
carnivalmobile/carnival-stream-examples
|
iOS/CarnivalSwiftStreamExamples/CarnivalSwiftStreamExamples/ListStreamViewController.swift
|
1
|
7484
|
//
// ListStreamViewController.swift
// CarnivalSwiftStreamExamples
//
// Created by Sam Jarman on 11/09/15.
// Copyright (c) 2015 Carnival Mobile. All rights reserved.
//
import Foundation
import UIKit
class ListStreamViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIBarPositioningDelegate {
var messages: NSMutableArray = []
var refreshControl: UIRefreshControl?
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var emptyDataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.setUpRefreshControl()
if self.tableView.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
self.tableView.separatorInset = UIEdgeInsets.zero
}
self.navigationBar.topItem?.title = NSLocalizedString("Messages", comment: "")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.refreshTableView()
}
@IBAction func refreshTableView() {
self.tableView!.setContentOffset(CGPoint(x: 0, y: -self.refreshControl!.frame.size.height), animated: true)
self.refreshControl!.beginRefreshing()
self.fetchMessages()
}
//MARK: TableView Data Source Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.messages.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard self.messages.count > 0 else {
return nil;
}
//Define the header view
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 60))
headerView.backgroundColor = UIColor(red: 241.0 / 255.0, green: 241.0 / 255.0, blue: 245.0 / 255.0, alpha: 1)
//Define and configure the label
let messagesLabel = UILabel(frame: CGRect(x: 10, y: 6, width: tableView.frame.size.width, height: 30))
if self.messages.count == 0 {
messagesLabel.text = NSLocalizedString("1 MESSAGE", comment:"")
}
else {
messagesLabel.text = NSLocalizedString("\(self.messages.count) MESSAGES", comment:"")
}
messagesLabel.font = UIFont.systemFont(ofSize: 12)
messagesLabel.textColor = UIColor(red: 112.0 / 255.0, green: 107.0 / 255, blue: 107.0 / 255.0, alpha: 1)
//Add the label to the header view and return it
headerView.addSubview(messagesLabel)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return ScreenSizeHelper.isIphone5orLess() ? 90 : 110
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: BasicListStreamTableViewCell.cellIdentifier(), for: indexPath as IndexPath) as! BasicListStreamTableViewCell
return cell
}
//MARK: TableView Delegate Methods
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//Get the message
let message = self.messages.object(at: indexPath.row) as! CarnivalMessage
//Configure the message
let aCell = cell as! BasicListStreamTableViewCell
aCell.configureCell(message: message)
//Create a stream impression on the message
CarnivalMessageStream.registerImpression(with: CarnivalImpressionType.streamView, for: message)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Get the Carnival Message
let message = self.messages.object(at: indexPath.row) as! CarnivalMessage
//Present the full screen message
CarnivalMessageStream.presentMessageDetail(for: message)
//Mark the message as read
CarnivalMessageStream.markMessage(asRead: message, withResponse: nil)
//Deselect the row that is selected
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
}
func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCell.EditingStyle.delete) {
self.deleteMessage(tableView: tableView, forRowAtIndexPath: indexPath as NSIndexPath)
}
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let button = UITableViewRowAction(style: UITableViewRowAction.Style.default, title: NSLocalizedString("Delete", comment:"")) { (action, indexPath) -> Void in
self.deleteMessage(tableView: tableView, forRowAtIndexPath: indexPath as NSIndexPath)
}
button.backgroundColor = UIColor(red: 212.0 / 255.0, green: 84.0 / 255.0, blue: 140.0 / 255.0, alpha: 1)
return [button]
}
func deleteMessage(tableView: UITableView, forRowAtIndexPath indexPath: NSIndexPath) {
//Get the Carnival Message
let message = self.messages.object(at: indexPath.row) as! CarnivalMessage
//Register the message as deleted with Carnival
CarnivalMessageStream.remove(message, withResponse: nil)
//Remove it from the data source
self.messages.remove(message)
//Remove from Table View
tableView.deleteRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.fade)
}
//MARK: UI
func setUpRefreshControl() {
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(ListStreamViewController.fetchMessages), for: UIControl.Event.valueChanged)
self.tableView.addSubview(self.refreshControl!)
}
@IBAction func closeStream(sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
// MARK: Bar Position Delegate
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return UIBarPosition.topAttached
}
// MARK: Get Messages
@objc func fetchMessages() {
CarnivalMessageStream.messages { (theMessages, anError) -> Void in
self.refreshControl?.endRefreshing()
if let error = anError {
print(error, terminator: "")
self.tableView.isHidden = true
self.emptyDataLabel.text = NSLocalizedString("Failed to get messages", comment:"")
}
if let messages = theMessages {
self.messages = NSMutableArray(array:messages)
self.tableView.reloadData()
self.tableView.isHidden = self.messages.count == 0
self.emptyDataLabel.text = NSLocalizedString("You have no messages", comment:"")
}
}
}
}
|
apache-2.0
|
8b65eeaf65e5e381a2ea1eee50f6c8a9
| 37.57732 | 173 | 0.654596 | 5.060176 | false | false | false | false |
rechsteiner/Parchment
|
Parchment/Enums/PagingState.swift
|
1
|
2603
|
import Foundation
import UIKit
/// The current state of the menu items. Indicates whether an item
/// is currently selected or is scrolling to another item. Can be
/// used to get the distance and progress of any ongoing transition.
public enum PagingState: Equatable {
case empty
case selected(pagingItem: PagingItem)
case scrolling(
pagingItem: PagingItem,
upcomingPagingItem: PagingItem?,
progress: CGFloat,
initialContentOffset: CGPoint,
distance: CGFloat
)
}
public extension PagingState {
var currentPagingItem: PagingItem? {
switch self {
case .empty:
return nil
case let .scrolling(pagingItem, _, _, _, _):
return pagingItem
case let .selected(pagingItem):
return pagingItem
}
}
var upcomingPagingItem: PagingItem? {
switch self {
case .empty:
return nil
case let .scrolling(_, upcomingPagingItem, _, _, _):
return upcomingPagingItem
case .selected:
return nil
}
}
var progress: CGFloat {
switch self {
case let .scrolling(_, _, progress, _, _):
return progress
case .selected, .empty:
return 0
}
}
var distance: CGFloat {
switch self {
case let .scrolling(_, _, _, _, distance):
return distance
case .selected, .empty:
return 0
}
}
var visuallySelectedPagingItem: PagingItem? {
if abs(progress) > 0.5 {
return upcomingPagingItem ?? currentPagingItem
} else {
return currentPagingItem
}
}
}
public func == (lhs: PagingState, rhs: PagingState) -> Bool {
switch (lhs, rhs) {
case
(let .scrolling(lhsCurrent, lhsUpcoming, lhsProgress, lhsOffset, lhsDistance),
let .scrolling(rhsCurrent, rhsUpcoming, rhsProgress, rhsOffset, rhsDistance)):
if lhsCurrent.isEqual(to: rhsCurrent),
lhsProgress == rhsProgress,
lhsOffset == rhsOffset,
lhsDistance == rhsDistance {
if let lhsUpcoming = lhsUpcoming, let rhsUpcoming = rhsUpcoming, lhsUpcoming.isEqual(to: rhsUpcoming) {
return true
} else if lhsUpcoming == nil, rhsUpcoming == nil {
return true
}
}
return false
case let (.selected(a), .selected(b)) where a.isEqual(to: b):
return true
case (.empty, .empty):
return true
default:
return false
}
}
|
mit
|
e40de431268eed7f062e3bc366cb4260
| 27.293478 | 115 | 0.575106 | 4.82037 | false | false | false | false |
BeezleLabs/HackerTracker-iOS
|
hackertracker/Views/CountDownCell.swift
|
1
|
999
|
//
// CountDownCell.swift
// hackertracker
//
// Created by Seth W Law on 6/2/22.
// Copyright © 2022 Beezle Labs. All rights reserved.
//
import SwiftUI
import UIKit
class CountDownCell: UITableViewCell {
init(statDate: Date) {
super.init(style: .default, reuseIdentifier: "CountDownViewCell")
let cdv = UIHostingController(rootView: CountdownView(start: statDate))
contentView.addSubview(cdv.view)
cdv.view.translatesAutoresizingMaskIntoConstraints = false
cdv.view.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
cdv.view.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
cdv.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
cdv.view.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
cdv.view.backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
gpl-2.0
|
5d1698048556807d6f72d3d0db3db992
| 32.266667 | 91 | 0.714429 | 4.264957 | false | false | false | false |
mbogh/Schnell
|
Schnell/ViewModels/SectionsViewModel.swift
|
1
|
1047
|
//
// SectionsViewModel.swift
// Schnell
//
// Created by Morten Bøgh on 07/06/14.
// Copyright (c) 2014 Morten Bøgh. All rights reserved.
//
import Foundation
import SchnellKit
class SectionsViewModel {
var sections = [RoadSection]()
var isActivated = false
func activate() {
self.isActivated = true
let reponseData = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("sections", ofType: "json"))
if let response = NSJSONSerialization.JSONObjectWithData(reponseData, options: nil, error: nil) as? NSDictionary {
if let result = response["result"] as? NSDictionary {
if let records = result["records"] as? NSArray {
for (var i = 0; i < records.count; i++) {
let record = records[i] as NSDictionary
let roadSection = RoadSection(data:record)
sections.append(roadSection)
}
}
}
}
}
}
|
mit
|
7caf098ec4a8d3a6a52e5a6eeea136d9
| 30.69697 | 122 | 0.561722 | 4.75 | false | false | false | false |
chicio/Exploring-SceneKit
|
ExploringSceneKit/Model/Scenes/BlinnPhong/DynamicSphere.swift
|
1
|
718
|
//
// DynamicSphere.swift
// ExploringSceneKit
//
// Created by Fabrizio Duroni on 26.08.17.
//
import SceneKit
class DynamicSphere: Object {
let sphereGeometry: SCNSphere
init(material: BlinnPhongMaterial, physicsBodyFeature: PhysicsBodyFeatures, radius: CGFloat, position: SCNVector3, rotation: SCNVector4) {
sphereGeometry = SCNSphere(radius: radius)
super.init(geometry: sphereGeometry, position: position, rotation: rotation)
node.geometry?.firstMaterial = material.material
node.physicsBody = SCNPhysicsBody.dynamic()
node.physicsBody?.mass = physicsBodyFeature.mass
node.physicsBody?.rollingFriction = physicsBodyFeature.rollingFriction
}
}
|
mit
|
9412af3a8bfbe3446b381630575ffeac
| 33.190476 | 142 | 0.731198 | 4.459627 | false | false | false | false |
OscarSwanros/swift
|
stdlib/public/core/SentinelCollection.swift
|
2
|
5316
|
//===--- SentinelCollection.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public // @testable
protocol _Function {
associatedtype Input
associatedtype Output
func apply(_: Input) -> Output
}
protocol _Predicate : _Function where Output == Bool { }
@_fixed_layout // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal struct _SentinelIterator<
Base: IteratorProtocol,
IsSentinel : _Predicate
> : IteratorProtocol, Sequence
where IsSentinel.Input == Base.Element {
@_versioned // FIXME(sil-serialize-all)
internal var _base: Base
@_versioned // FIXME(sil-serialize-all)
internal var _isSentinel: IsSentinel
@_versioned // FIXME(sil-serialize-all)
internal var _expired: Bool = false
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_ base: Base, until condition: IsSentinel) {
_base = base
_isSentinel = condition
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal mutating func next() -> Base.Element? {
guard _fastPath(!_expired) else { return nil }
let x = _base.next()
// We don't need this check if it's a precondition that the sentinel will be
// found
// guard _fastPath(x != nil), let y = x else { return x }
guard _fastPath(!_isSentinel.apply(x!)) else { _expired = true; return nil }
return x
}
}
@_fixed_layout // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal struct _SentinelCollection<
Base: Collection,
IsSentinel : _Predicate
> : Collection
where IsSentinel.Input == Base.Iterator.Element {
@_versioned // FIXME(sil-serialize-all)
internal let _isSentinel: IsSentinel
@_versioned // FIXME(sil-serialize-all)
internal var _base : Base
internal typealias IndexDistance = Base.IndexDistance
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal func makeIterator() -> _SentinelIterator<Base.Iterator, IsSentinel> {
return _SentinelIterator(_base.makeIterator(), until: _isSentinel)
}
@_fixed_layout // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal struct Index : Comparable {
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(
_impl: (position: Base.Index, element: Base.Iterator.Element)?
) {
self._impl = _impl
}
@_versioned // FIXME(sil-serialize-all)
internal var _impl: (position: Base.Index, element: Base.Iterator.Element)?
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal static func == (lhs: Index, rhs: Index) -> Bool {
if rhs._impl == nil { return lhs._impl == nil }
return lhs._impl != nil && rhs._impl!.position == lhs._impl!.position
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal static func < (lhs: Index, rhs: Index) -> Bool {
if rhs._impl == nil { return lhs._impl != nil }
return lhs._impl != nil && rhs._impl!.position < lhs._impl!.position
}
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var startIndex : Index {
return _index(at: _base.startIndex)
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var endIndex : Index {
return Index(_impl: nil)
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal subscript(i: Index) -> Base.Iterator.Element {
return i._impl!.element
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal func index(after i: Index) -> Index {
return _index(at: _base.index(after: i._impl!.position))
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal func _index(at i: Base.Index) -> Index {
// We don't need this check if it's a precondition that the sentinel will be
// found
// guard _fastPath(i != _base.endIndex) else { return endIndex }
let e = _base[i]
guard _fastPath(!_isSentinel.apply(e)) else { return endIndex }
return Index(_impl: (position: i, element: e))
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_ base: Base, until condition: IsSentinel) {
_base = base
_isSentinel = condition
}
}
@_fixed_layout // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal struct _IsZero<T : BinaryInteger> : _Predicate {
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init() {}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal func apply(_ x: T) -> Bool {
return x == 0
}
}
|
apache-2.0
|
b0e3bf8a7f96ad8b78c29a6110596583
| 32.433962 | 80 | 0.656132 | 3.9117 | false | false | false | false |
HTWDD/htwcampus
|
HTWDD/Core/UI/Colors.swift
|
1
|
2357
|
//
// Colors.swift
// HTWDD
//
// Created by Benjamin Herzog on 19.10.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit.UIColor
extension UIColor {
convenience init(hex: UInt, alpha: CGFloat = 1.0) {
self.init(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hex & 0x0000FF) / 255.0,
alpha: alpha
)
}
func hex() -> UInt {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: nil)
let rh: UInt = UInt(r * 255)
let gh: UInt = UInt(g * 255)
let bh: UInt = UInt(b * 255)
return (rh << 16) + (gh << 8) + bh
}
}
extension HTWNamespace where Base: UIColor {
static var blue: UIColor {
return UIColor(hex: 0x003DA2)
}
static var orange: UIColor {
return UIColor(hex: 0xF1A13D)
}
static var green: UIColor {
return UIColor(hex: 0x2ECC5D)
}
static var red: UIColor {
return UIColor(hex: 0xC21717)
}
static var yellow: UIColor {
return UIColor(hex: 0xf1c40f)
}
static var textBody: UIColor {
return UIColor(hex: 0x7F7F7F)
}
static var textHeadline: UIColor {
return UIColor(hex: 0x000000)
}
static var lightBlue: UIColor {
return UIColor(hex: 0x5060F5)
}
static var martianRed: UIColor {
return UIColor(hex: 0xE35D50)
}
static var veryLightGrey: UIColor {
return UIColor(hex: 0xF7F7F7)
}
static var lightGrey: UIColor {
return UIColor(hex: 0xE7E7E7)
}
static var grey: UIColor {
return UIColor(hex: 0x8F8F8F)
}
static var mediumGrey: UIColor {
return UIColor(hex: 0x5A5A5A)
}
static var darkGrey: UIColor {
return UIColor(hex: 0x474747)
}
static var white: UIColor {
return UIColor.white
}
static var scheduleColors: [UIColor] {
let colors = [
UIColor(hex: 0xC21717),
UIColor(hex: 0xf39c12),
UIColor(hex: 0x8e44ad),
UIColor(hex: 0x27ae60),
UIColor(hex: 0xe74c3c),
UIColor(hex: 0xF0C987),
UIColor(hex: 0x3498db),
UIColor(hex: 0x2ecc71),
UIColor(hex: 0x9097C0),
UIColor(hex: 0xf1c40f),
UIColor(hex: 0x2c3e50),
UIColor(hex: 0xc0392b)
]
return colors
}
}
|
mit
|
d9c8f4f475ec26f976ddc1f7229e605b
| 19.310345 | 59 | 0.598048 | 2.989848 | false | false | false | false |
lyle-luan/firefox-ios
|
Client/Frontend/Reader/ReaderViewController.swift
|
3
|
2316
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class ReaderViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
var urlSpec: String!
private var docLoaded = false
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Loading reader content..."
let url = NSURL(string: urlSpec)!
let request = NSURLRequest(URL: url)
webView.delegate = self
webView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func close(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
func webViewDidFinishLoad(webView: UIWebView) {
if (docLoaded) {
// We've already handled the load event for this document.
return
}
let readyJS = "document.readyState == 'complete'"
let result = webView.stringByEvaluatingJavaScriptFromString(readyJS)
if (result == "false") {
// The load event was for a subframe. Ignore.
return
}
docLoaded = true
let readabilityJS = getReadabilityJS()
webView.stringByEvaluatingJavaScriptFromString(readabilityJS)
webView.stringByEvaluatingJavaScriptFromString("var reader = new Readability('', document); var readerResult = reader.parse();")
// TODO: Cache the article.
let title = webView.stringByEvaluatingJavaScriptFromString("readerResult.title")
let content = webView.stringByEvaluatingJavaScriptFromString("readerResult.content")
// Set the reader title and content in the WebView.
self.title = title
let aboutUrl = NSURL(string: "about:reader")
webView.loadHTMLString(content, baseURL: aboutUrl)
}
func getReadabilityJS() -> String {
let fileRoot = NSBundle.mainBundle().pathForResource("Readability", ofType: "js")
return NSString(contentsOfFile: fileRoot!, encoding: NSUTF8StringEncoding, error: nil)!
}
}
|
mpl-2.0
|
5a5faca77b92db05f31afae78917a631
| 33.058824 | 136 | 0.664076 | 5.101322 | false | false | false | false |
ztyjr888/WeChat
|
WeChat/Plugins/Chat/WeChatChatAVPlayView.swift
|
1
|
2877
|
//
// WeChatChatAVPlayView.swift
// WeChat
//
// Created by Smile on 16/3/29.
// Copyright © 2016年 smile.love.tao@gmail.com. All rights reserved.
//
import UIKit
import AVFoundation
@IBDesignable
class WeChatChatAVPlayView: UIView {
var playView: UIView!
var slider: UISlider!
var timerIndicator: UILabel!
// MARK: - lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
deinit {
NSLog("deinit")
}
func setup() {
backgroundColor = UIColor.blackColor()
playView = UIView()
slider = UISlider()
slider.setThumbImage(UIImage.imageWithColor(UIColor.redColor()), forState: .Normal)
timerIndicator = UILabel()
timerIndicator.font = UIFont.systemFontOfSize(12.0)
timerIndicator.textColor = UIColor.whiteColor()
addSubview(playView)
addSubview(slider)
addSubview(timerIndicator)
playView.translatesAutoresizingMaskIntoConstraints = false
slider.translatesAutoresizingMaskIntoConstraints = false
timerIndicator.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: playView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: playView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: playView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: playView, attribute: .Bottom, relatedBy: .Equal, toItem: slider, attribute: .Top, multiplier: 1, constant: -5))
addConstraint(NSLayoutConstraint(item: slider, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 10))
addConstraint(NSLayoutConstraint(item: slider, attribute: .Right, relatedBy: .Equal, toItem: timerIndicator, attribute: .Left, multiplier: 1, constant: -5))
addConstraint(NSLayoutConstraint(item: slider, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: -5))
addConstraint(NSLayoutConstraint(item: timerIndicator, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: -5))
addConstraint(NSLayoutConstraint(item: timerIndicator, attribute: .CenterY, relatedBy: .Equal, toItem: slider, attribute: .CenterY, multiplier: 1, constant: 0))
}
override class func layerClass() -> AnyClass {
return AVPlayerLayer.self
}
}
|
apache-2.0
|
4ea78e783c3f4d3163ae59b81a827e0f
| 40.057143 | 168 | 0.676757 | 4.703764 | false | false | false | false |
google/swift-jupyter
|
EnableIPythonDisplay.swift
|
1
|
3730
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Hooks IPython to the KernelCommunicator, so that it can send display
/// messages to Jupyter.
#if canImport(PythonKit)
import PythonKit
#else
import Python
#endif
enum IPythonDisplay {
static var socket: PythonObject = Python.None
static var shell: PythonObject = Python.None
// Tracks whether the Python version that we are interoperating with has a
// "real" bytes type that is an array of bytes, rather than Python2's "fake"
// bytes type that is just an alias of str.
private static var hasRealBytesType: Bool = false
}
extension IPythonDisplay {
private static func bytes(_ py: PythonObject) -> KernelCommunicator.BytesReference {
// TODO: Replace with a faster implementation that reads bytes directly
// from the python object's memory.
if hasRealBytesType {
let bytes = py.lazy.map { CChar(bitPattern: UInt8($0)!) }
return KernelCommunicator.BytesReference(bytes)
}
let bytes = py.lazy.map { CChar(bitPattern: UInt8(Python.ord($0))!) }
return KernelCommunicator.BytesReference(bytes)
}
private static func updateParentMessage(to parentMessage: KernelCommunicator.ParentMessage) {
let json = Python.import("json")
IPythonDisplay.shell.set_parent(json.loads(parentMessage.json))
}
private static func consumeDisplayMessages() -> [KernelCommunicator.JupyterDisplayMessage] {
let displayMessages = IPythonDisplay.socket.messages.map {
KernelCommunicator.JupyterDisplayMessage(parts: $0.map { bytes($0) })
}
IPythonDisplay.socket.messages = []
return displayMessages
}
static func enable() {
if IPythonDisplay.shell != Python.None {
print("Warning: IPython display already enabled.")
return
}
hasRealBytesType = Bool(Python.isinstance(PythonObject("t").encode("utf8")[0], Python.int))!
let swift_shell = Python.import("swift_shell")
let socketAndShell = swift_shell.create_shell(
username: JupyterKernel.communicator.jupyterSession.username,
session_id: JupyterKernel.communicator.jupyterSession.id,
key: PythonObject(JupyterKernel.communicator.jupyterSession.key).encode("utf8"))
IPythonDisplay.socket = socketAndShell[0]
IPythonDisplay.shell = socketAndShell[1]
JupyterKernel.communicator.handleParentMessage(updateParentMessage)
JupyterKernel.communicator.afterSuccessfulExecution(run: consumeDisplayMessages)
}
}
extension PythonObject {
func display() {
Python.import("IPython.display")[dynamicMember: "display"](pythonObject)
}
}
#if canImport(SwiftPlot)
import SwiftPlot
import AGGRenderer
var __agg_renderer = AGGRenderer()
extension Plot {
func display(size: Size = Size(width: 1000, height: 660)) {
drawGraph(size: size, renderer: __agg_renderer)
let image_b64 = __agg_renderer.base64Png()
let displayImage = Python.import("IPython.display")
let codecs = Python.import("codecs")
let imageData = codecs.decode(Python.bytes(image_b64, encoding: "utf8"),
encoding: "base64")
displayImage.Image(data: imageData, format: "png").display()
}
}
#endif
IPythonDisplay.enable()
|
apache-2.0
|
511a9d5b7343931f0e6eacaf996b45c2
| 34.865385 | 96 | 0.726005 | 3.913956 | false | false | false | false |
ddimitrov90/EverliveSDK
|
Tests/Pods/EverliveSDK/EverliveSDK/ValueCondition.swift
|
2
|
1046
|
//
// ValueCondition.swift
// EverliveSwift
//
// Created by Dimitar Dimitrov on 2/22/16.
// Copyright © 2016 ddimitrov. All rights reserved.
//
import Foundation
import SwiftyJSON
class ValueCondition : FilterCondition {
var value: AnyObject
init(key: String, value: AnyObject, operand:String){
self.value = value
super.init(key: key, operand: operand)
}
override func getJson() -> String {
let innerFilter = [ self.operand: self.value]
let fieldNameFilter = [ self.key: innerFilter]
let resultJsonFilter:JSON = JSON(fieldNameFilter)
return resultJsonFilter.rawString(NSUTF8StringEncoding, options: NSJSONWritingOptions(rawValue: 0))!
}
override func getJsonObj() -> JSON {
let innerFilter = [ self.operand: self.value]
let fieldNameFilter = [ self.key: innerFilter]
let resultJsonFilter:JSON = JSON(fieldNameFilter)
return resultJsonFilter
}
//let operandDefinitions: [String: String] = ["eq" : ""]
}
|
mit
|
805916e03c97d6195366d8f18b75622c
| 28.885714 | 108 | 0.657416 | 4.230769 | false | false | false | false |
rudkx/swift
|
test/decl/protocol/protocols.swift
|
1
|
19973
|
// RUN: %target-typecheck-verify-swift -enable-objc-interop
protocol EmptyProtocol { }
protocol DefinitionsInProtocols {
init() {} // expected-error {{protocol initializers must not have bodies}}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
// Protocol decl.
protocol Test {
func setTitle(_: String)
func erase() -> Bool
var creator: String { get }
var major : Int { get }
var minor : Int { get }
var subminor : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{21-21= { get <#set#> \}}}
static var staticProperty: Int // expected-error{{property in protocol must have explicit { get } or { get set } specifier}} {{33-33= { get <#set#> \}}}
let bugfix // expected-error {{type annotation missing in pattern}} expected-error {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}}
var comment // expected-error {{type annotation missing in pattern}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
}
protocol Test2 {
var property: Int { get }
var title: String = "The Art of War" { get } // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{20-20= { get <#set#> \}}}
static var title2: String = "The Art of War" // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{28-28= { get <#set#> \}}}
associatedtype mytype
associatedtype mybadtype = Int
associatedtype V : Test = // expected-error {{expected type in associated type declaration}} {{28-28= <#type#>}}
}
func test1() {
var v1: Test
var s: String
v1.setTitle(s)
v1.creator = "Me" // expected-error {{cannot assign to property: 'creator' is a get-only property}}
}
protocol Bogus : Int {}
// expected-error@-1{{inheritance from non-protocol, non-class type 'Int'}}
// expected-error@-2{{type 'Self' constrained to non-protocol, non-class type 'Int'}}
// Explicit conformance checks (successful).
protocol CustomStringConvertible { func print() } // expected-note{{protocol requires function 'print()' with type '() -> ()'}} expected-note{{protocol requires}} expected-note{{protocol requires}} expected-note{{protocol requires}}
struct TestFormat { }
protocol FormattedPrintable : CustomStringConvertible {
func print(format: TestFormat)
}
struct X0 : Any, CustomStringConvertible {
func print() {}
}
class X1 : Any, CustomStringConvertible {
func print() {}
}
enum X2 : Any { }
extension X2 : CustomStringConvertible {
func print() {}
}
// Explicit conformance checks (unsuccessful)
struct NotPrintableS : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableS' does not conform to protocol 'CustomStringConvertible'}}
class NotPrintableC : CustomStringConvertible, Any {} // expected-error{{type 'NotPrintableC' does not conform to protocol 'CustomStringConvertible'}}
enum NotPrintableO : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableO' does not conform to protocol 'CustomStringConvertible'}}
struct NotFormattedPrintable : FormattedPrintable { // expected-error{{type 'NotFormattedPrintable' does not conform to protocol 'CustomStringConvertible'}}
func print(format: TestFormat) {}
}
// Protocol compositions in inheritance clauses
protocol Left {
func l() // expected-note {{protocol requires function 'l()' with type '() -> ()'; do you want to add a stub?}}
}
protocol Right {
func r() // expected-note {{protocol requires function 'r()' with type '() -> ()'; do you want to add a stub?}}
}
typealias Both = Left & Right
protocol Up : Both {
func u()
}
struct DoesNotConform : Up {
// expected-error@-1 {{type 'DoesNotConform' does not conform to protocol 'Left'}}
// expected-error@-2 {{type 'DoesNotConform' does not conform to protocol 'Right'}}
func u() {}
}
// Circular protocols
protocol CircleMiddle : CircleStart { func circle_middle() } // expected-error {{protocol 'CircleMiddle' refines itself}}
// expected-note@-1 {{protocol 'CircleMiddle' declared here}}
protocol CircleStart : CircleEnd { func circle_start() } // expected-error {{protocol 'CircleStart' refines itself}}
// expected-note@-1 {{protocol 'CircleStart' declared here}}
protocol CircleEnd : CircleMiddle { func circle_end()} // expected-note 2 {{protocol 'CircleEnd' declared here}}
protocol CircleEntry : CircleTrivial { }
protocol CircleTrivial : CircleTrivial { } // expected-error {{protocol 'CircleTrivial' refines itself}}
struct Circle {
func circle_start() {}
func circle_middle() {}
func circle_end() {}
}
func testCircular(_ circle: Circle) {
// FIXME: It would be nice if this failure were suppressed because the protocols
// have circular definitions.
_ = circle as any CircleStart // expected-error{{cannot convert value of type 'Circle' to type 'any CircleStart' in coercion}}
}
// <rdar://problem/14750346>
protocol Q : C, H { }
protocol C : E { }
protocol H : E { }
protocol E { }
//===----------------------------------------------------------------------===//
// Associated types
//===----------------------------------------------------------------------===//
protocol SimpleAssoc {
associatedtype Associated // expected-note{{protocol requires nested type 'Associated'}}
}
struct IsSimpleAssoc : SimpleAssoc {
struct Associated {}
}
struct IsNotSimpleAssoc : SimpleAssoc {} // expected-error{{type 'IsNotSimpleAssoc' does not conform to protocol 'SimpleAssoc'}}
protocol StreamWithAssoc {
associatedtype Element
func get() -> Element // expected-note{{protocol requires function 'get()' with type '() -> NotAStreamType.Element'}}
}
struct AnRange<Int> : StreamWithAssoc {
typealias Element = Int
func get() -> Int {}
}
// Okay: Word is a typealias for Int
struct AWordStreamType : StreamWithAssoc {
typealias Element = Int
func get() -> Int {}
}
struct NotAStreamType : StreamWithAssoc { // expected-error{{type 'NotAStreamType' does not conform to protocol 'StreamWithAssoc'}}
typealias Element = Float
func get() -> Int {} // expected-note{{candidate has non-matching type '() -> Int'}}
}
// Okay: Infers Element == Int
struct StreamTypeWithInferredAssociatedTypes : StreamWithAssoc {
func get() -> Int {}
}
protocol SequenceViaStream {
associatedtype SequenceStreamTypeType : IteratorProtocol // expected-note{{protocol requires nested type 'SequenceStreamTypeType'}}
func makeIterator() -> SequenceStreamTypeType
}
struct IntIterator : IteratorProtocol /*, Sequence, ReplPrintable*/ {
typealias Element = Int
var min : Int
var max : Int
var stride : Int
mutating func next() -> Int? {
if min >= max { return .none }
let prev = min
min += stride
return prev
}
typealias Generator = IntIterator
func makeIterator() -> IntIterator {
return self
}
}
extension IntIterator : SequenceViaStream {
typealias SequenceStreamTypeType = IntIterator
}
struct NotSequence : SequenceViaStream { // expected-error{{type 'NotSequence' does not conform to protocol 'SequenceViaStream'}}
typealias SequenceStreamTypeType = Int // expected-note{{possibly intended match 'NotSequence.SequenceStreamTypeType' (aka 'Int') does not conform to 'IteratorProtocol'}}
func makeIterator() -> Int {}
}
protocol GetATuple {
associatedtype Tuple
func getATuple() -> Tuple
}
struct IntStringGetter : GetATuple {
typealias Tuple = (i: Int, s: String)
func getATuple() -> Tuple {}
}
protocol ClassConstrainedAssocType {
associatedtype T : class
// expected-error@-1 {{'class' constraint can only appear on protocol declarations}}
// expected-note@-2 {{did you mean to write an 'AnyObject' constraint?}}{{22-27=AnyObject}}
}
//===----------------------------------------------------------------------===//
// Default arguments
//===----------------------------------------------------------------------===//
// FIXME: Actually make use of default arguments, check substitutions, etc.
protocol ProtoWithDefaultArg {
func increment(_ value: Int = 1) // expected-error{{default argument not permitted in a protocol method}}
}
struct HasNoDefaultArg : ProtoWithDefaultArg {
func increment(_: Int) {}
}
//===----------------------------------------------------------------------===//
// Variadic function requirements
//===----------------------------------------------------------------------===//
protocol IntMaxable {
func intmax(first: Int, rest: Int...) -> Int // expected-note 2{{protocol requires function 'intmax(first:rest:)' with type '(Int, Int...) -> Int'}}
}
struct HasIntMax : IntMaxable {
func intmax(first: Int, rest: Int...) -> Int {}
}
struct NotIntMax1 : IntMaxable { // expected-error{{type 'NotIntMax1' does not conform to protocol 'IntMaxable'}}
func intmax(first: Int, rest: [Int]) -> Int {} // expected-note{{candidate has non-matching type '(Int, [Int]) -> Int'}}
}
struct NotIntMax2 : IntMaxable { // expected-error{{type 'NotIntMax2' does not conform to protocol 'IntMaxable'}}
func intmax(first: Int, rest: Int) -> Int {} // expected-note{{candidate has non-matching type '(Int, Int) -> Int'}}
}
//===----------------------------------------------------------------------===//
// 'Self' type
//===----------------------------------------------------------------------===//
protocol IsEqualComparable {
func isEqual(other: Self) -> Bool // expected-note{{protocol requires function 'isEqual(other:)' with type '(WrongIsEqual) -> Bool'}}
}
struct HasIsEqual : IsEqualComparable {
func isEqual(other: HasIsEqual) -> Bool {}
}
struct WrongIsEqual : IsEqualComparable { // expected-error{{type 'WrongIsEqual' does not conform to protocol 'IsEqualComparable'}}
func isEqual(other: Int) -> Bool {} // expected-note{{candidate has non-matching type '(Int) -> Bool'}}
}
//===----------------------------------------------------------------------===//
// Static methods
//===----------------------------------------------------------------------===//
protocol StaticP {
static func f()
}
protocol InstanceP {
func f() // expected-note{{protocol requires function 'f()' with type '() -> ()'}}
}
struct StaticS1 : StaticP {
static func f() {}
}
struct StaticS2 : InstanceP { // expected-error{{type 'StaticS2' does not conform to protocol 'InstanceP'}}
static func f() {} // expected-note{{candidate operates on a type, not an instance as required}}
}
struct StaticAndInstanceS : InstanceP {
static func f() {}
func f() {}
}
func StaticProtocolFunc() {
let a: StaticP = StaticS1()
a.f() // expected-error{{static member 'f' cannot be used on instance of type 'any StaticP'}}
}
func StaticProtocolGenericFunc<t : StaticP>(_: t) {
t.f()
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
protocol Eq {
static func ==(lhs: Self, rhs: Self) -> Bool
}
extension Int : Eq { }
// Matching prefix/postfix.
prefix operator <>
postfix operator <>
protocol IndexValue {
static prefix func <> (_ max: Self) -> Int
static postfix func <> (min: Self) -> Int
}
prefix func <> (max: Int) -> Int { return 0 }
postfix func <> (min: Int) -> Int { return 0 }
extension Int : IndexValue {}
//===----------------------------------------------------------------------===//
// Class protocols
//===----------------------------------------------------------------------===//
protocol IntrusiveListNode : class {
var next : Self { get }
}
final class ClassNode : IntrusiveListNode {
var next : ClassNode = ClassNode()
}
struct StructNode : IntrusiveListNode { // expected-error{{non-class type 'StructNode' cannot conform to class protocol 'IntrusiveListNode'}}
var next : StructNode // expected-error {{value type 'StructNode' cannot have a stored property that recursively contains it}}
}
final class ClassNodeByExtension { }
struct StructNodeByExtension { }
extension ClassNodeByExtension : IntrusiveListNode {
var next : ClassNodeByExtension {
get {
return self
}
set {}
}
}
extension StructNodeByExtension : IntrusiveListNode { // expected-error{{non-class type 'StructNodeByExtension' cannot conform to class protocol 'IntrusiveListNode'}}
var next : StructNodeByExtension {
get {
return self
}
set {}
}
}
final class GenericClassNode<T> : IntrusiveListNode {
var next : GenericClassNode<T> = GenericClassNode()
}
struct GenericStructNode<T> : IntrusiveListNode { // expected-error{{non-class type 'GenericStructNode<T>' cannot conform to class protocol 'IntrusiveListNode'}}
var next : GenericStructNode<T> // expected-error {{value type 'GenericStructNode<T>' cannot have a stored property that recursively contains it}}
}
// Refined protocols inherit class-ness
protocol IntrusiveDListNode : IntrusiveListNode {
var prev : Self { get }
}
final class ClassDNode : IntrusiveDListNode {
var prev : ClassDNode = ClassDNode()
var next : ClassDNode = ClassDNode()
}
struct StructDNode : IntrusiveDListNode { // expected-error{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveDListNode'}}
// expected-error@-1{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveListNode'}}
var prev : StructDNode // expected-error {{value type 'StructDNode' cannot have a stored property that recursively contains it}}
var next : StructDNode
}
@objc protocol ObjCProtocol {
func foo() // expected-note{{protocol requires function 'foo()' with type '() -> ()'}}
}
protocol NonObjCProtocol : class { //expected-note{{protocol 'NonObjCProtocol' declared here}}
func bar()
}
class DoesntConformToObjCProtocol : ObjCProtocol { // expected-error{{type 'DoesntConformToObjCProtocol' does not conform to protocol 'ObjCProtocol'}}
}
@objc protocol ObjCProtocolRefinement : ObjCProtocol { }
@objc protocol ObjCNonObjCProtocolRefinement : NonObjCProtocol { } //expected-error{{@objc protocol 'ObjCNonObjCProtocolRefinement' cannot refine non-@objc protocol 'NonObjCProtocol'}}
// <rdar://problem/16079878>
protocol P1 {
associatedtype Assoc // expected-note 2{{protocol requires nested type 'Assoc'}}
}
protocol P2 {
}
struct X3<T : P1> where T.Assoc : P2 {}
struct X4 : P1 { // expected-error{{type 'X4' does not conform to protocol 'P1'}}
func getX1() -> X3<X4> { return X3() }
}
protocol ShouldntCrash {
// rdar://16109996
let fullName: String { get } // expected-error {{'let' declarations cannot be computed properties}} {{3-6=var}}
// <rdar://problem/17200672> Let in protocol causes unclear errors and crashes
let fullName2: String // expected-error {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}} {{3-6=var}} {{24-24= { get \}}}
// <rdar://problem/16789886> Assert on protocol property requirement without a type
var propertyWithoutType { get } // expected-error {{type annotation missing in pattern}}
// expected-error@-1 {{computed property must have an explicit type}} {{26-26=: <# Type #>}}
}
// rdar://problem/18168866
protocol FirstProtocol {
// expected-warning@+1 {{'weak' cannot be applied to a property declaration in a protocol; this is an error in Swift 5}}
weak var delegate : SecondProtocol? { get } // expected-error{{'weak' must not be applied to non-class-bound 'any SecondProtocol'; consider adding a protocol conformance that has a class bound}}
}
protocol SecondProtocol {
func aMethod(_ object : FirstProtocol)
}
// <rdar://problem/19495341> Can't upcast to parent types of type constraints without forcing
class C1 : P2 {}
func f<T : C1>(_ x : T) {
_ = x as P2
}
class C2 {}
func g<T : C2>(_ x : T) {
x as P2 // expected-error{{cannot convert value of type 'T' to type 'any P2' in coercion}}
}
class C3 : P1 {} // expected-error{{type 'C3' does not conform to protocol 'P1'}}
func h<T : C3>(_ x : T) {
_ = x as any P1
}
func i<T : C3>(_ x : T?) -> Bool {
return x is any P1
// expected-warning@-1 {{checking a value with optional type 'T?' against type 'any P1' succeeds whenever the value is non-nil; did you mean to use '!= nil'?}}
}
func j(_ x : C1) -> Bool {
return x is P1 // expected-warning {{use of protocol 'P1' as a type must be written 'any P1'}}
}
func k(_ x : C1?) -> Bool {
return x is any P1
}
protocol P4 {
associatedtype T // expected-note {{protocol requires nested type 'T'}}
}
class C4 : P4 { // expected-error {{type 'C4' does not conform to protocol 'P4'}}
associatedtype T = Int // expected-error {{associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement}} {{3-17=typealias}}
}
// <rdar://problem/25185722> Crash with invalid 'let' property in protocol
protocol LetThereBeCrash {
let x: Int
// expected-error@-1 {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}} {{13-13= { get \}}}
// expected-note@-2 {{declared here}}
let xs: [Int]
// expected-error@-1 {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}} {{3-6=var}} {{16-16= { get \}}}
// expected-note@-2 {{declared here}}
}
extension LetThereBeCrash {
init() { x = 1; xs = [] }
// expected-error@-1 {{'let' property 'x' may not be initialized directly; use "self.init(...)" or "self = ..." instead}}
// expected-error@-2 {{'let' property 'xs' may not be initialized directly; use "self.init(...)" or "self = ..." instead}}
}
// SR-11412
// Offer fix-it to conform type of context to the missing protocols
protocol SR_11412_P1 {}
protocol SR_11412_P2 {}
protocol SR_11412_P3 {}
protocol SR_11412_P4: AnyObject {}
class SR_11412_C0 {
var foo1: SR_11412_P1?
var foo2: (SR_11412_P1 & SR_11412_P2)?
weak var foo3: SR_11412_P4?
}
// Context has no inherited types and does not conform to protocol //
class SR_11412_C1 {
let c0 = SR_11412_C0()
func conform() {
c0.foo1 = self // expected-error {{cannot assign value of type 'SR_11412_C1' to type '(any SR_11412_P1)?'}}
// expected-note@-1 {{add missing conformance to 'SR_11412_P1' to class 'SR_11412_C1'}}{{18-18=: SR_11412_P1}}
}
}
// Context has no inherited types and does not conform to protocol composition //
class SR_11412_C2 {
let c0 = SR_11412_C0()
func conform() {
c0.foo2 = self // expected-error {{cannot assign value of type 'SR_11412_C2' to type '(any SR_11412_P1 & SR_11412_P2)?'}}
// expected-note@-1 {{add missing conformance to 'SR_11412_P1 & SR_11412_P2' to class 'SR_11412_C2'}}{{18-18=: SR_11412_P1 & SR_11412_P2}}
}
}
// Context already has an inherited type, but does not conform to protocol //
class SR_11412_C3: SR_11412_P3 {
let c0 = SR_11412_C0()
func conform() {
c0.foo1 = self // expected-error {{cannot assign value of type 'SR_11412_C3' to type '(any SR_11412_P1)?'}}
// expected-note@-1 {{add missing conformance to 'SR_11412_P1' to class 'SR_11412_C3'}}{{31-31=, SR_11412_P1}}
}
}
// Context conforms to only one protocol in the protocol composition //
class SR_11412_C4: SR_11412_P1 {
let c0 = SR_11412_C0()
func conform() {
c0.foo2 = self // expected-error {{cannot assign value of type 'SR_11412_C4' to type '(any SR_11412_P1 & SR_11412_P2)?'}}
// expected-note@-1 {{add missing conformance to 'SR_11412_P1 & SR_11412_P2' to class 'SR_11412_C4'}}{{31-31=, SR_11412_P2}}
}
}
// Context is a value type, but protocol requires class //
struct SR_11412_S0 {
let c0 = SR_11412_C0()
func conform() {
c0.foo3 = self // expected-error {{cannot assign value of type 'SR_11412_S0' to type '(any SR_11412_P4)?'}}
}
}
|
apache-2.0
|
5a3e5df5ac384f76a3f5a18a8fc49ccc
| 35.580586 | 232 | 0.658589 | 4.066164 | false | false | false | false |
Diuit/DUMessagingUIKit-iOS
|
DUMessagingUIKit/DUMediaItem.swift
|
1
|
7131
|
//
// DUMediaItem.swift
// DUMessagingUIKit
//
// Created by Pofat Diuit on 2016/6/20.
// Copyright © 2016年 duolC. All rights reserved.
//
import Foundation
import UIKit
/**
* This structure contains all elements required by a media message for displaying.
*/
public struct DUMediaItem {
/**
Indicating the type of this media message
- image: An image message.
- video: A video message.
- file: A file message.
- audio: An audio message.
- location: A location message.
- URL: If your text message contains only URL, it will be transformed to an URL media message.
*/
public enum MediaType: String {
case Image
case Video
case File
case Audio
case Location
case URL
}
/// Return the size of media content
public var mediaDisplaySize: CGSize {
switch self.type {
case .Image, .Video, .Location:
return CGSize(width: 212, height: 158)
case .Audio, .File:
return CGSize(width: 212, height: 53)
case .URL:
return CGSize(width: 204, height: 109)
}
}
// MARK: Stored Properties
/// Type of the media message
public var type: MediaType
/// An UIView instance for placeholder.
public var placeholderView: UIView { return _cachedPlaceholderView }
/// Instance of media content, may be an UIImage
public var mediaContentData: AnyObject?
/// URL of media source. Used by file, URL, video and audio message.
public var mediaSourceURL: String? = nil
/// Display name of the file on media content view.
public var fileDisplayName: String? = nil
/// Detail description of file, default value is `nil`.
public var fileDescription: String? = nil
fileprivate var _cachedMediaContentView: UIView? = nil
fileprivate var _cachedPlaceholderView: DUMediaPlaceholderView
// MARK: Initialize
/**
Init an image mediaItem
- parameter image: Main image, could be `nil` if you have not retrieved the image yet.
- returns: An instance of `DUMediaItem` of image type
*/
public init(fromImage image: UIImage?) {
self.type = .Image
self.mediaContentData = image
_cachedPlaceholderView = DUMediaPlaceholderView.init(frame:CGRect.zero)
_cachedPlaceholderView.frame = CGRect(x: 0, y: 0, width: mediaDisplaySize.width, height: mediaDisplaySize.height)
}
/**
Init an image mediaItem from URL string
- parameter url: URL string of the image resource.
- returns: An instance of `DUMediaItem` of image type
*/
public init(fromImageURL url: String) {
self.type = .Image
self.mediaContentData = nil
self.mediaSourceURL = url
_cachedPlaceholderView = DUMediaPlaceholderView.init(frame:CGRect.zero)
_cachedPlaceholderView.frame = CGRect(x: 0, y: 0, width: mediaDisplaySize.width, height: mediaDisplaySize.height)
}
/**
Init a video mediaItem
- parameter url: URL string of video file path
- parameter image: Preive image of the video.
- returns: An instance of `DUMediaItem` of video type
- note: If you initialize with a preview image, `mediaContentData` will be used to save it.
*/
public init(fromVideoURL url: String, withPreviewImage image: UIImage?) {
self.type = .Video
self.mediaSourceURL = url
self.mediaContentData = image
_cachedPlaceholderView = DUMediaPlaceholderView.init(frame:CGRect.zero)
_cachedPlaceholderView.frame = CGRect(x: 0, y: 0, width: mediaDisplaySize.width, height: mediaDisplaySize.height)
}
/**
Init a file mediaItem
- parameter url: URL string of file path
- parameter fileName: File name string.
- parameter fileDescription: File information, such as file size. Default value is `nil`.
- returns: An instance of `DUMediaItem` of file type
- note: This file is neither playable video or playable audio
*/
public init(fromFileURL url: String, fileName: String, fileDescription: String?) {
self.type = .File
self.mediaSourceURL = url
self.fileDisplayName = fileName
self.fileDescription = fileDescription
_cachedPlaceholderView = DUMediaPlaceholderView.init(frame:CGRect.zero)
_cachedPlaceholderView.frame = CGRect(x: 0, y: 0, width: mediaDisplaySize.width, height: mediaDisplaySize.height)
}
/**
Init a URL preview mediaItem
- parameter url: URL string
- returns: An instance of `DUMediaItem` of URL type
- note: You can get a preview from web page's open graph (if they have)
*/
public init(fromURL url: String) {
self.type = .URL
self.mediaSourceURL = url
_cachedPlaceholderView = DUMediaPlaceholderView.init(frame:CGRect.zero)
_cachedPlaceholderView.frame = CGRect(x: 0, y: 0, width: mediaDisplaySize.width, height: mediaDisplaySize.height)
}
/**
Get media contnet view. Return `nil` if there is no media data
- returns: A media content view. May be UIImageView or composed UIView
*/
public mutating func getMediaContentView() -> UIView? {
if mediaContentData == nil && mediaSourceURL == nil {
return nil
}
if _cachedMediaContentView != nil {
return _cachedMediaContentView
}
switch type {
case .Image:
_cachedMediaContentView = DUMediaContentViewFactory.makeImageContentView(image: mediaContentData as? UIImage, frame:CGRect(x: 0, y: 0, width: mediaDisplaySize.width, height: mediaDisplaySize.height))
return _cachedMediaContentView
case .URL:
_cachedMediaContentView = DUMediaContentViewFactory.makeURLContentView(url: mediaSourceURL!, frame: CGRect(x: 0, y: 0, width: mediaDisplaySize.width, height: mediaDisplaySize.height))
return _cachedMediaContentView
case .File:
_cachedMediaContentView = DUMediaContentViewFactory.makeFileContentView(name: fileDisplayName ?? "File", description: fileDescription, frame: CGRect(x: 0, y: 0, width: mediaDisplaySize.width, height: mediaDisplaySize.height))
return _cachedMediaContentView
case .Video:
_cachedMediaContentView = DUMediaContentViewFactory.makeVideoContentView(previewImage: mediaContentData as? UIImage, frame: CGRect(x: 0, y: 0, width: mediaDisplaySize.width, height: mediaDisplaySize.height))
return _cachedMediaContentView
default:
return nil
}
}
/**
Set a media content view on your own. Rememer your customized view will be displayed with default size for each type of media message.
- parameter view: Your customized media content view.
*/
public mutating func set(mediaContentView view: UIView) {
_cachedMediaContentView = view
}
}
|
mit
|
061f2f59117ee62e1018aef5552fb66d
| 36.319372 | 237 | 0.651515 | 4.595745 | false | false | false | false |
lixiangzhou/ZZSwiftTool
|
ZZSwiftTool/ZZSwiftTool/ZZCustom/ZZButton.swift
|
1
|
3066
|
//
// ZZButton.swift
// ZZSwiftTool
//
// Created by lixiangzhou on 17/3/12.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
/// 可以调整图片位置的按钮
open class ZZImagePositionButton: UIButton {
enum ZZImagePosition {
case left, right
case none // 默认,不调整左中右的间距
}
private var leftPadding: CGFloat = 0
private var middlePadding: CGFloat = 0
private var rightPadding: CGFloat = 0
private var imgPosition: ZZImagePosition = .none
override open func layoutSubviews() {
super.layoutSubviews()
if imgPosition == .left {
self.imageView?.zz_x = leftPadding
self.titleLabel?.zz_x = (self.imageView?.zz_width ?? 0) + leftPadding + middlePadding
self.titleLabel?.zz_width = self.zz_width - (self.imageView?.zz_width ?? 0) - leftPadding - middlePadding - rightPadding
} else if imgPosition == .right {
self.titleLabel?.zz_x = leftPadding
let imgX = self.zz_width - (self.imageView?.zz_width ?? 0) - rightPadding
self.imageView?.zz_x = imgX
self.titleLabel?.zz_width = imgX - leftPadding - middlePadding
}
}
convenience init(title: String? = nil,
titleSize: CGFloat = 12,
titleColor: UIColor = UIColor.darkText,
imageName: String? = nil,
hilightedImageName: String? = nil,
selectedImageName: String? = nil,
backgroundImageName: String? = nil,
hilightedBackgroundImageName: String? = nil,
selectedBackgroundImageName: String? = nil,
backgroundColor: UIColor? = nil,
target: Any? = nil,
action: Selector? = nil,
imgPosition: ZZImagePosition = .none,
leftPadding: CGFloat = 0,
middlePadding: CGFloat = 0,
rightPadding: CGFloat = 0) {
self.init(title: title,
titleSize: titleSize,
titleColor: titleColor,
imageName: imageName,
hilightedImageName: hilightedImageName,
selectedImageName: selectedImageName,
backgroundImageName: backgroundImageName,
hilightedBackgroundImageName: hilightedBackgroundImageName,
selectedBackgroundImageName: selectedBackgroundImageName,
backgroundColor: backgroundColor,
target: target,
action: action)
self.imgPosition = imgPosition
self.leftPadding = leftPadding
self.rightPadding = rightPadding
self.middlePadding = middlePadding
if imgPosition != .none {
self.zz_width += leftPadding + rightPadding + middlePadding
}
}
}
|
mit
|
1f4f7111236f4a7ed46ede8f5c3378ad
| 35.349398 | 132 | 0.55121 | 5.201724 | false | false | false | false |
ScottLegrove/HoneyDueIOS
|
Honey Due/ShareListController.swift
|
1
|
2074
|
//
// AddTaskViewController.swift
// Honey Due
//
// Created by C412IT44 on 2016-04-13.
// Copyright © 2016 Scott Legrove. All rights reserved.
//
import UIKit
class ShareListViewController: UIViewController{
var currentList: Int?
var uPrefs: NSUserDefaults?
var uToken: String?
@IBOutlet weak var username: UITextField!
@IBAction func btnShare(sender: AnyObject) {
let shared = UserHelper.AddUser(currentList!, username: username!.text!, token: uToken!)
if shared {
let alertController = UIAlertController(title: "List shared successfully!", message: "List shared with the specified user!", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default){
(_) in
self.navigationController?.popViewControllerAnimated(true)
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true){}
}
else
{
let alertController = UIAlertController(title: "List could not be shared", message: "The specified user does not exist.", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default){
(_) in
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true){}
}
}
override func viewDidLoad() {
super.viewDidLoad()
uPrefs = NSUserDefaults.standardUserDefaults()
uToken = uPrefs!.stringForKey("userToken")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segueBackToTaskList"{
let destView = segue.destinationViewController as! TasksViewController
destView.listID = currentList
}
}
}
|
mit
|
57a1fc4d1c51ce0bb2d4f21ac2b7aec4
| 31.904762 | 160 | 0.611192 | 5.370466 | false | false | false | false |
iluuu1994/Pathfinder
|
Pathfinder/Coordinates.swift
|
1
|
2116
|
//
// Coordinates.swift
// Pathfinder
//
// Created by Ilija Tovilo on 16/08/14.
// Copyright (c) 2014 Ilija Tovilo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/// Coordinates stores coordinate of any type of coordinate system
open class Coordinates {
/// Wraps the coordinates in an array
open func toArray() -> [Int] {
assert(false, "`toArray` must be overridden in the Coordinates subclasses!")
return []
}
// ------------------
// MARK: - Hashable -
// ------------------
// TODO: "Error: Declarations in extensions cannot override yet".
// Move this to the extension once that feature is supported by Swift.
open var hashValue: Int {
return 0
}
}
// ------------------
// MARK: - Hashable -
// ------------------
extension Coordinates: Hashable {
}
// -------------------
// MARK: - Equatable -
// -------------------
extension Coordinates: Equatable {}
public func ==(lhs: Coordinates, rhs: Coordinates) -> Bool {
return lhs === rhs
}
|
mit
|
a53e4fa4ca936dbdc534317c9b1d031c
| 30.117647 | 84 | 0.655009 | 4.502128 | false | false | false | false |
lplotni/xconf_swift_example
|
test/test/AppDelegate.swift
|
1
|
1600
|
import Cocoa
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var skView: SKView!
func applicationDidFinishLaunching(aNotification: NSNotification?) {
/* Pick a size for the scene */
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
self.skView!.presentScene(scene)
/* Sprite Kit applies additional optimizations to improve rendering performance */
self.skView!.ignoresSiblingOrder = true
self.skView!.showsFPS = true
self.skView!.showsNodeCount = true
}
}
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
return true;
}
}
|
mit
|
bddfc0f87d5e0e5013d3b5a713e8a181
| 35.363636 | 110 | 0.635 | 5.882353 | false | false | false | false |
darkdong/DarkSwift
|
Source/Foundation/Layout.swift
|
1
|
6911
|
//
// Layout.swift
// DarkSwift
//
// Created by Dark Dong on 2017/4/2.
// Copyright © 2017年 Dark Dong. All rights reserved.
//
public protocol Layoutable {
var coordinateSystemOrigin: CoordinateSystemOrigin { get }
var size: CGSize { get }
var anchorPoint: CGPoint { get }
}
public extension Layoutable {
static func positions(forItems items: [Layoutable], alignment: Alignment, in rect: CGRect) -> [CGPoint] {
let cpoints: [CGPoint]
switch alignment {
case let .horizontal(verticalAlignment):
cpoints = horizontalCenterPoints(forItems: items, in: rect, verticalAlignment: verticalAlignment)
case let.vertical(horizontalAlignment):
cpoints = verticalCenterPoints(forItems: items, in: rect, horizontalAlignment: horizontalAlignment)
case let .tabular(numberOfRows, numberOfColumns, itemSize):
cpoints = tabularCenterPoints(forItemSize: itemSize, numberOfTableRows: numberOfRows, numberOfTableColumns: numberOfColumns, in: rect)
}
var points: [CGPoint] = []
for (cpoint, item) in zip(cpoints, items) {
let point = item.convertCenterPoint(cpoint)
points.append(point)
}
return points
}
static func horizontalCenterPoints(forItems items: [Layoutable], in rect: CGRect, verticalAlignment: UIControl.ContentVerticalAlignment = .center) -> [CGPoint] {
if items.isEmpty {
return []
} else if items.count == 1 {
let cpoint = items[0].centerPoint(in: rect, verticalAlignment: verticalAlignment)
return [cpoint]
} else {
var cpoints: [CGPoint] = []
let sumOfWidths = sum(ofItems: items) { $0.size.width }
let numberOfSpacings = items.count - 1
let spacing = (rect.width - sumOfWidths) / CGFloat(numberOfSpacings)
let spacings = [0] + [CGFloat](repeating: spacing, count: numberOfSpacings)
var lastItemX = rect.minX
for (spacing, item) in zip(spacings, items) {
let cx = lastItemX + spacing + item.size.width/2
let cy = item.centerY(in: rect, verticalAlignment: verticalAlignment)
let cpoint = CGPoint(x: cx, y: cy)
cpoints.append(cpoint)
lastItemX = cx + item.size.width/2
}
return cpoints
}
}
static func verticalCenterPoints(forItems items: [Layoutable], in rect: CGRect, horizontalAlignment: UIControl.ContentHorizontalAlignment = .center) -> [CGPoint] {
if items.isEmpty {
return []
} else if items.count == 1 {
let cpoint = items[0].centerPoint(in: rect, horizontalAlignment: horizontalAlignment)
return [cpoint]
} else {
var cpoints: [CGPoint] = []
let sumOfHeights = sum(ofItems: items) { $0.size.height }
let numberOfSpacings = items.count - 1
let spacing = (rect.height - sumOfHeights) / CGFloat(numberOfSpacings)
let spacings = [0] + [CGFloat](repeating: spacing, count: numberOfSpacings)
var lastItemY = rect.minY
for (spacing, item) in zip(spacings, items) {
let cx = item.centerX(in: rect, horizontalAlignment: horizontalAlignment)
let cy = lastItemY + spacing + item.size.height/2
let cpoint = CGPoint(x: cx, y: cy)
cpoints.append(cpoint)
lastItemY = cy + item.size.height/2
}
return cpoints
}
}
static func tabularCenterPoints(forItemSize itemSize: CGSize, numberOfTableRows: Int, numberOfTableColumns: Int, in rect: CGRect) -> [CGPoint] {
var cpoints: [CGPoint] = []
let rowRectSize = CGSize(width: rect.width, height: rect.height / CGFloat(numberOfTableRows))
var rowRects: [CGRect] = []
for row in 0..<numberOfTableRows {
let origin = CGPoint(x: rect.minX, y: rect.minY + CGFloat(row) * rowRectSize.height)
let rowRect = CGRect(origin: origin, size: rowRectSize)
rowRects.append(rowRect)
}
let item = LayoutableItem(size: itemSize)
let items = [LayoutableItem](repeating: item, count: numberOfTableColumns)
for rect in rowRects {
let rowCenterPoints = horizontalCenterPoints(forItems: items, in: rect)
cpoints.append(contentsOf: rowCenterPoints)
}
return cpoints
}
static func sum(ofItems items: [Layoutable], on attributeValue: (Layoutable) -> CGFloat) -> CGFloat {
return items.reduce(0) { (accumulatedValue, item) -> CGFloat in
return accumulatedValue + attributeValue(item)
}
}
func centerX(in rect: CGRect, horizontalAlignment: UIControl.ContentHorizontalAlignment = .center) -> CGFloat {
switch horizontalAlignment {
case .left:
return rect.minX + size.width/2
case .right:
return rect.maxX - size.width/2
default:
return rect.midX
}
}
func centerY(in rect: CGRect, verticalAlignment: UIControl.ContentVerticalAlignment = .center) -> CGFloat {
switch verticalAlignment {
case .top:
return coordinateSystemOrigin == .upperLeft ? rect.minY + size.height/2 : rect.maxY - size.height/2
case .bottom:
return coordinateSystemOrigin == .upperLeft ? rect.maxY - size.height/2 : rect.minY + size.height/2
default:
return rect.midY
}
}
func centerPoint(in rect: CGRect, horizontalAlignment: UIControl.ContentHorizontalAlignment = .center, verticalAlignment: UIControl.ContentVerticalAlignment = .center) -> CGPoint {
let cx = centerX(in: rect, horizontalAlignment: horizontalAlignment)
let cy = centerY(in: rect, verticalAlignment: verticalAlignment)
return CGPoint(x: cx, y: cy)
}
func convertCenterPoint(_ centerPoint: CGPoint) -> CGPoint {
let dx = (anchorPoint.x - 0.5) * size.width
let dy = (anchorPoint.y - 0.5) * size.height
return CGPoint(x: centerPoint.x + dx, y: centerPoint.y + dy)
}
}
struct LayoutableItem: Layoutable {
var size: CGSize
var anchorPoint: CGPoint
var coordinateSystemOrigin: CoordinateSystemOrigin
init(size: CGSize = CGSize.zero, anchorPoint: CGPoint = CGPoint.zero, coordinateSystemOrigin: CoordinateSystemOrigin = .upperLeft) {
self.size = size
self.anchorPoint = anchorPoint
self.coordinateSystemOrigin = coordinateSystemOrigin
}
}
public enum CoordinateSystemOrigin {
case upperLeft, lowerLeft
}
public enum Alignment {
case horizontal(UIControl.ContentVerticalAlignment)
case vertical(UIControl.ContentHorizontalAlignment)
case tabular(Int, Int, CGSize)
}
|
mit
|
1871204c32bb7dba0c9153bc5195261c
| 41.641975 | 181 | 0.631587 | 4.512084 | false | false | false | false |
DianQK/RxExample
|
RxZhihuDaily/Theme/ThemeViewController.swift
|
1
|
3096
|
//
// ThemeViewController.swift
// RxExample
//
// Created by 宋宋 on 16/2/16.
// Copyright © 2016年 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import SWRevealViewController
import Kingfisher
class ThemeViewController: UITableViewController {
var id: Int!
let disposeBag = DisposeBag()
let sections = Variable([NewsModel]())
let imageURL = Variable(NSURL())
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = nil
tableView.delegate = nil
let revealController = self.revealViewController()
view.addGestureRecognizer(revealController.tapGestureRecognizer())
view.addGestureRecognizer(revealController.panGestureRecognizer())
navigationController?.navigationBar.lt_backgroundColor = UIColor.clearColor()
navigationController?.navigationBar.shadowImage = UIImage()
let navImageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, 64))
navImageView.contentMode = UIViewContentMode.ScaleAspectFill
navImageView.clipsToBounds = true
let headerView = ParallaxHeaderView.parallaxThemeHeaderViewWithSubView(navImageView, size: CGSizeMake(self.view.frame.width, 64), image: navImageView.image)
tableView.tableHeaderView = headerView
ZhihuDailyProvider.request(.Theme(id: id))
.mapObject(ThemeNewsListModel)
.subscribeNext { [unowned self] in
self.sections.value = $0.stories
self.imageURL.value = NSURL(string: $0.image)!
}.addDisposableTo(disposeBag)
sections.asObservable().bindTo(tableView.rx_itemsWithCellIdentifier("\(ThemeNewCell.self)", cellType: ThemeNewCell.self)) { (row, element, cell) in
cell.nameLabel.text = element.title
if let imageStr = element.images?.first {
cell.contentImageView.kf_setImageWithURL(NSURL(string: imageStr)!)
cell.trailingLayoutConstraint.priority = 700
} else {
cell.trailingLayoutConstraint.priority = 900
}
}.addDisposableTo(disposeBag)
// TODO: UPDATE CODE
imageURL.asObservable().subscribeNext {
navImageView.kf_setImageWithURL($0, placeholderImage: nil, optionsInfo: nil, completionHandler: { (image, error, cacheType, imageURL) -> () in
headerView.blurViewImage = image
headerView.refreshBlurViewForNewsImage()
})
}.addDisposableTo(disposeBag)
tableView.rx_contentOffset.subscribeNext { [unowned self] in
headerView.layoutThemeHeaderViewForScrollViewOffset($0)
if self.tableView.contentOffset.y < -80 {
self.tableView.contentOffset.y = -80
}
}.addDisposableTo(disposeBag)
}
//设置StatusBar为白色
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
|
mit
|
1145e8279be3ea5a760e3e17bbe3a014
| 36.54878 | 164 | 0.654108 | 5.392294 | false | false | false | false |
sabyapradhan/IBM-Ready-App-for-Banking
|
HatchReadyApp/apps/Hatch/iphone/native/Hatch/Extensions/DoubleExtension.swift
|
1
|
645
|
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import Foundation
extension Double{
var toCGFloat:CGFloat {return CGFloat(self)}
func roundToDecimalDigits(decimals:Int) -> Double
{
let a : Double = self
var format : NSNumberFormatter = NSNumberFormatter()
format.numberStyle = NSNumberFormatterStyle.DecimalStyle
format.roundingMode = NSNumberFormatterRoundingMode.RoundHalfUp
format.maximumFractionDigits = 2
var string: NSString = format.stringFromNumber(NSNumber(double: a))!
return string.doubleValue
}
}
|
epl-1.0
|
4edf04837732bfb8b4de45318d36e2f9
| 28.318182 | 76 | 0.703416 | 5.322314 | false | false | false | false |
quangvu1994/Exchange
|
Exchange/View/CollectionTableViewCell.swift
|
1
|
3947
|
//
// CollectionTableViewCell.swift
// Exchange
//
// Created by Quang Vu on 7/20/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
import FirebaseDatabase
class CollectionTableViewCell: UITableViewCell {
var status: String?
var itemList = [String: Any]() {
didSet {
collectionView.reloadData()
}
}
var cashAmount: String?
var controller: DisplayItemDetailHandler?
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
collectionView.delegate = self
collectionView.dataSource = self
}
}
extension CollectionTableViewCell: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numOfItems = itemList.count
if let _ = cashAmount {
numOfItems += 1
}
if numOfItems == 0 {
let emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height))
emptyLabel.textAlignment = .center
emptyLabel.font = UIFont(name: "Futura", size: 14)
emptyLabel.textColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
emptyLabel.numberOfLines = 2
emptyLabel.text = "No items offered "
collectionView.backgroundView = emptyLabel
}
return numOfItems
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Item Cell", for: indexPath) as! MyItemPostImageCell
// If there is cash
if let cashAmount = cashAmount {
// if this is the last cell
if indexPath.row == itemList.count {
cell.imageLabel.text = cashAmount
cell.imageLabel.isHidden = false
return cell
}
}
if let controller = controller {
cell.delegate = controller
cell.gestureDisplayingItemDetailWithInfo()
}
let key = Array(itemList.keys)[indexPath.row]
if let itemDataDict = itemList[key] as? [String : Any],
let url = itemDataDict["image_url"] as? String,
let itemTitle = itemDataDict["post_title"] as? String,
let itemDescription = itemDataDict["post_description"] as? String {
let imageURL = URL(string: url)
cell.postImage.kf.setImage(with: imageURL)
cell.itemImageURL = url
cell.itemTitle = itemTitle
cell.itemDescription = itemDescription
}
// Observe the availability of the item
let itemRef = Database.database().reference().child("allItems/\(key)/availability")
itemRef.observe(.value, with: { (snapshot) in
guard let availability = snapshot.value as? Bool else {
return
}
if !availability && self.status != "Confirmed"{
cell.soldLabel.isHidden = false
} else {
cell.soldLabel.isHidden = true
}
})
return cell
}
}
extension CollectionTableViewCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.height, height: collectionView.bounds.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
}
|
mit
|
b3d3d91efc2797323051def4040d29cf
| 35.537037 | 170 | 0.622402 | 5.318059 | false | false | false | false |
gobetti/Swift
|
CheckConnectivity/CheckConnectivity/ViewController.swift
|
1
|
1410
|
//
// ViewController.swift
// CheckConnectivity
//
// Created by Mukesh Thawani on 09/12/15.
// Copyright © 2015 Mukesh Thawani. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var checkingLabel: UILabel!
override func viewDidAppear(animated: Bool) {
checkConnectivity()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func checkConnectivity() {
print(Reachability.isConnectedToNetwork(), terminator: "")
if Reachability.isConnectedToNetwork() == false {
let alert = UIAlertController(title: "Alert", message: "Internet is not working", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: false, completion: nil)
let okAction = UIAlertAction(title: "Retry", style: UIAlertActionStyle.Default) {
UIAlertAction in
alert.dismissViewControllerAnimated(false, completion: nil)
self.checkConnectivity()
}
alert.addAction(okAction)
checkingLabel.text = ""
}
else {
checkingLabel.text = "Connected"
}
}
}
|
mit
|
0f8acc6fdbe684aaaf85a03017a2e130
| 27.18 | 139 | 0.618879 | 5.357414 | false | false | false | false |
Alchemistxxd/AXStylishNavigationBar
|
cartooldt/CarReader.swift
|
1
|
1898
|
//
// Reader.swift
// CartoolKit
//
// Created by Xudong Xu on 1/7/21.
//
import CoreUI
public class Reader<T> where T: Rendition {
public typealias CompletionHandler = (Result<[T], Error>) -> Void
let car: Car
private let catalog: CUICatalog
public init(_ car: Car) throws {
self.car = car
self.catalog = try CUICatalog(url: car.url)
}
@discardableResult
public func read(_ completion: CompletionHandler?) -> Self {
DispatchQueue.global(qos: .default).async {
do {
try completion?(.success(self.read()))
} catch {
completion?(.failure(error))
}
}
return self
}
public func read() throws -> [T] {
guard
try !isPro(self.car),
let count = catalog.allImageNames()?.count,
count != 0
else {
return []
}
return readTheme(catalog)
}
private func isPro(_ car: Car) throws -> Bool {
let chars: [CChar] = [0x50, 0x72, 0x6F, 0x54, 0x68, 0x65, 0x6D, 0x65, 0x44, 0x65, 0x66, 0x69, 0x6E, 0x69, 0x74, 0x69, 0x6F, 0x6E]
let data: Data = try .init(contentsOf: car.url, options: [.uncachedRead, .alwaysMapped])
let token = String(cString: chars).data(using: .utf8)!
return data.range(of: token, options: .anchored, in: data.startIndex..<data.endIndex) != nil
}
private func readTheme(_ catalog: CUICatalog) -> [T] {
let result: [T] = catalog.allAssetKeys.compactMap { key in
guard let rendition = catalog._themeStore()?.rendition(withKey: key.keyList()) else {
return nil
}
let name = catalog._themeStore()?.renditionName(forKeyList: key.keyList())
return T(rendition, name ?? "")
}
return result
}
}
|
mit
|
1d145900532df5a30fc2d27f2406325d
| 28.65625 | 137 | 0.551106 | 3.788423 | false | false | false | false |
artsy/eigen
|
ios/Artsy/View_Controllers/Live_Auctions/LiveAuctionStateManager.swift
|
1
|
7915
|
import Foundation
import Interstellar
import SwiftyJSON
/*
Independent of sockets:
- time elapsed
Based on socket events:
- lot state (bidding not yet, bidding open, bidding closed)
- reserve status
- # of bids
- # of watchers
- next bid amount $
- bid history
- bid request (command) success/failure
*/
class LiveAuctionStateManager: NSObject {
typealias SocketCommunicatorCreator = (_ host: String, _ causalitySaleID: String, _ jwt: JWT) -> LiveAuctionSocketCommunicatorType
typealias StateReconcilerCreator = (_ saleArtworks: [LiveAuctionLotViewModel]) -> LiveAuctionStateReconcilerType
let sale: LiveSale
let bidderCredentials: BiddingCredentials
let operatorConnectedSignal = Observable<Bool>()
let saleOnHoldSignal = Observable<(isOnHold: Bool, message: String?)>()
let initialStateLoadedSignal = Observable<Void>(options: .Once)
fileprivate let socketCommunicator: LiveAuctionSocketCommunicatorType
fileprivate let stateReconciler: LiveAuctionStateReconcilerType
fileprivate var biddingStates = [String: LiveAuctionBiddingViewModelType]()
var socketConnectionSignal: Observable<Bool> {
return socketCommunicator.socketConnectionSignal
}
init(host: String,
sale: LiveSale,
saleArtworks: [LiveAuctionLotViewModel],
jwt: JWT,
bidderCredentials: BiddingCredentials,
socketCommunicatorCreator: SocketCommunicatorCreator = LiveAuctionStateManager.defaultSocketCommunicatorCreator(),
stateReconcilerCreator: StateReconcilerCreator = LiveAuctionStateManager.defaultStateReconcilerCreator()) {
self.sale = sale
self.bidderCredentials = bidderCredentials
self.socketCommunicator = socketCommunicatorCreator(host, sale.causalitySaleID, jwt)
self.stateReconciler = stateReconcilerCreator(saleArtworks)
super.init()
socketCommunicator.updatedAuctionState.subscribe { [weak self] state in
self?.stateReconciler.updateState(state)
self?.handleOperatorConnectedState(state)
self?.handleSaleOnHoldInitialState(state)
self?.initialStateLoadedSignal.update(())
}
socketCommunicator.lotUpdateBroadcasts.subscribe { [weak self] broadcast in
self?.stateReconciler.processLotEventBroadcast(broadcast)
}
socketCommunicator.currentLotUpdate.subscribe { [weak self] update in
self?.stateReconciler.processCurrentLotUpdate(update)
}
socketCommunicator.postEventResponses.subscribe { [weak self] response in
let json = JSON(response)
let bidUUID = json["key"].stringValue
let biddingViewModel = self?.biddingStates.removeValue(forKey: bidUUID)
// So far this event isn't needed anywhere, but keeping for prosperities sake
// let eventJSON = json["event"].dictionaryObject
// let liveEvent = LiveEvent(JSON: eventJSON)
let confirmed: LiveAuctionBiddingProgressState
let responseType = json["type"].stringValue
if responseType != "CommandFailed" {
confirmed = LiveAuctionBiddingProgressState.bidAcknowledged
} else {
let reason = json["reason"]["type"].string
let userFacingError = reason != nil ? reason! : "An unknown error occurred"
confirmed = LiveAuctionBiddingProgressState.bidFailed(reason: userFacingError)
}
biddingViewModel?.bidPendingSignal.update(confirmed)
}
socketCommunicator.saleOnHoldSignal.subscribe { [weak self] response in
self?.handleSaleOnHoldState(response)
}
socketCommunicator.operatorConnectedSignal.subscribe { [weak self] state in
self?.handleOperatorConnectedState(state)
}
}
}
private typealias PublicFunctions = LiveAuctionStateManager
extension PublicFunctions {
func bidOnLot(_ lotID: String, amountCents: UInt64, biddingViewModel: LiveAuctionBiddingViewModelType) {
if !bidderCredentials.canBid {
return print("Tried to bid without a bidder ID on account")
}
biddingViewModel.bidPendingSignal.update(.biddingInProgress)
let bidID = UUID().uuidString
biddingStates[bidID] = biddingViewModel
socketCommunicator.bidOnLot(lotID, amountCents: amountCents, bidderCredentials: bidderCredentials, bidUUID: bidID)
}
func leaveMaxBidOnLot(_ lotID: String, amountCents: UInt64, biddingViewModel: LiveAuctionBiddingViewModelType) {
if !bidderCredentials.canBid {
return print("Tried to leave a max bid without a bidder ID on account")
}
biddingViewModel.bidPendingSignal.update(.biddingInProgress)
let bidID = UUID().uuidString
biddingStates[bidID] = biddingViewModel
socketCommunicator.leaveMaxBidOnLot(lotID, amountCents: amountCents, bidderCredentials: bidderCredentials, bidUUID: bidID)
}
var debugAllEventsSignal: Observable<LotEventJSON> {
return stateReconciler.debugAllEventsSignal
}
}
private typealias ComputedProperties = LiveAuctionStateManager
extension ComputedProperties {
var currentLotSignal: Observable<LiveAuctionLotViewModelType?> {
return stateReconciler.currentLotSignal
}
}
private typealias PrivateFunctions = LiveAuctionStateManager
private extension PrivateFunctions {
func handleOperatorConnectedState(_ state: AnyObject) {
let json = JSON(state)
let operatorConnected = json["operatorConnected"].bool ?? true // Defaulting to true in case the value isn't specified, we don't want to obstruct the user.
self.operatorConnectedSignal.update(operatorConnected)
}
func handleSaleOnHoldState(_ state: AnyObject) {
let json = JSON(state)
let saleOnHold = json["isOnHold"].boolValue
let message = json["userMessage"].string
saleOnHoldSignal.update((isOnHold: saleOnHold, message: message))
}
func handleSaleOnHoldInitialState(_ state: AnyObject) {
let json = JSON(state)
let saleOnHold = json["saleOnHold"].boolValue
let message = json["saleOnHoldMessage"].string
saleOnHoldSignal.update((isOnHold: saleOnHold, message: message))
}
}
private typealias DefaultCreators = LiveAuctionStateManager
extension DefaultCreators {
class func defaultSocketCommunicatorCreator() -> SocketCommunicatorCreator {
return { host, causalitySaleID, jwt in
return LiveAuctionSocketCommunicator(host: host, causalitySaleID: causalitySaleID, jwt: jwt)
}
}
class func stubbedSocketCommunicatorCreator() -> SocketCommunicatorCreator {
return { host, causalitySaleID, jwt in
return Stubbed_SocketCommunicator(state: loadJSON("live_auctions_socket"))
}
}
class func defaultStateReconcilerCreator() -> StateReconcilerCreator {
return { saleArtworks in
return LiveAuctionStateReconciler(saleArtworks: saleArtworks)
}
}
}
private class Stubbed_SocketCommunicator: LiveAuctionSocketCommunicatorType {
let updatedAuctionState: Observable<AnyObject>
let lotUpdateBroadcasts = Observable<AnyObject>()
let currentLotUpdate = Observable<AnyObject>()
let postEventResponses = Observable<AnyObject>()
let socketConnectionSignal = Observable<Bool>(true) // We're conencted by default.
let operatorConnectedSignal = Observable<AnyObject>()
let saleOnHoldSignal = Observable<AnyObject>()
init (state: AnyObject) {
updatedAuctionState = Observable(state)
}
func bidOnLot(_ lotID: String, amountCents: UInt64, bidderCredentials: BiddingCredentials, bidUUID: String) {
}
func leaveMaxBidOnLot(_ lotID: String, amountCents: UInt64, bidderCredentials: BiddingCredentials, bidUUID: String) {
}
}
|
mit
|
791f7df4417fa8e0df29e299c976daab
| 37.990148 | 163 | 0.714845 | 4.956168 | false | false | false | false |
qxuewei/XWSwiftWB
|
XWSwiftWB/XWSwiftWB/Classes/Compose/ComposeVC.swift
|
1
|
7721
|
//
// ComposeVC.swift
// XWSwiftWB
//
// Created by 邱学伟 on 2016/11/9.
// Copyright © 2016年 邱学伟. All rights reserved.
//
import UIKit
//import SVProgressHUD
import MBProgressHUD
class ComposeVC: UIViewController {
//MARK: - 类内属性
fileprivate lazy var titleView : ComposeTitleView = ComposeTitleView()
fileprivate lazy var picPickerS : [UIImage] = [UIImage]()
//表情键盘控制器
fileprivate lazy var emojiKeyboardController : XWEmojiController = XWEmojiController { [weak self](emoji) in
self!.composeTextView.insertEmoji(emoji: emoji)
//手动触发代理方法
self?.textViewDidChange((self?.composeTextView)!)
}
@IBOutlet weak var composeTextView: ComposeTextView!
@IBOutlet weak var picPickerCollection: PicPickerCollection!
@IBOutlet weak var toolBar: UIToolbar!
@IBOutlet weak var picPickerBtnCLick: UIButton!
//创建照片控制器
fileprivate let ipc : UIImagePickerController = UIImagePickerController()
//约束属性
@IBOutlet weak var textViewBottomCons: NSLayoutConstraint!
@IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
@IBOutlet weak var collectionViewHeightCons: NSLayoutConstraint!
//MARK: - 回调函数
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
composeLogic()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
composeTextView.becomeFirstResponder()
}
//选择照片
@IBAction func picPickerBtnClick(_ sender: UIButton) {
self.collectionViewHeightCons.constant = UIScreen.main.bounds.height*0.65
self.composeTextView.resignFirstResponder()
UIView.animate(withDuration: 0.45){() -> Void in
self.view.layoutIfNeeded()
}
}
//选择表情
@IBAction func chooseEmojiClick(_ sender: UIButton) {
//取消键盘
composeTextView.resignFirstResponder()
//弹出表情键盘
composeTextView.inputView = composeTextView.inputView == nil ? emojiKeyboardController.view : nil
composeTextView.becomeFirstResponder()
}
//移除通知
deinit {
NotificationCenter.default.removeObserver(self)
}
}
//MARK: - UI
extension ComposeVC {
fileprivate func setupNavigationBar() {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(ComposeVC.cancelMethod))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(ComposeVC.publishMethod))
navigationItem.rightBarButtonItem?.isEnabled = false
titleView.frame = CGRect(x: 0, y: 0, width: 84, height: 44)
navigationItem.titleView = titleView
}
}
//MARK: - 逻辑
extension ComposeVC {
fileprivate func composeLogic() {
composeTextView.delegate = self
composeTextView.dataDetectorTypes = UIDataDetectorTypes.link //只有网址加链接
//监听键盘弹出
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillChangeFrame(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
//监听发布界面选择照片
NotificationCenter.default.addObserver(self, selector: #selector(picPickerAddPhotoMethod), name: NSNotification.Name(rawValue: picPickerAddPhotoNoti), object: nil)
//监听删除照片
NotificationCenter.default.addObserver(self, selector: #selector(picPickerDelegatePhotoMethod(noti:)), name: NSNotification.Name(picPickerDelegateNoti), object: nil)
}
}
//MARK: - selector
extension ComposeVC {
@objc fileprivate func cancelMethod() {
dismiss(animated: true, completion: nil)
}
@objc fileprivate func publishMethod() {
composeTextView.resignFirstResponder()
XWLog("发布:\(composeTextView.getEmojiText())")
let status : String = composeTextView.getEmojiText()
let isSuccesssBlock = {(isSuccess : Bool) in
if isSuccess == true {
MBProgressHUD.hide(for: self.view, animated: true)
NSObject_Tool.showHUD(self.view, isSuccess: true)
self.dismiss(animated: true, completion: nil)
}else{
MBProgressHUD.hide(for: self.view, animated: true)
NSObject_Tool.showHUD(self.view, isSuccess: false)
}
}
MBProgressHUD.showAdded(to: self.view, animated: true)
guard picPickerS.count == 0 else {
guard let firstImage = picPickerS.first else {
return
}
NetworkingToolS.shareInstance.publishStatusAndImage(status: status, image: firstImage, isSuccess: isSuccesssBlock)
return
}
NetworkingToolS.shareInstance.publishStatus(status: status, isSuccess: isSuccesssBlock)
}
@objc fileprivate func textViewChange() {
XWLog("textView文字改变 :\(composeTextView.text)")
}
//键盘改变
@objc fileprivate func KeyboardWillChangeFrame(noti : NSNotification) {
guard let userInfoDict = noti.userInfo else {
return
}
//获取动画执行时间 UIKeyboardAnimationDurationUserInfoKey : 0.25
let duration : TimeInterval = userInfoDict["UIKeyboardAnimationDurationUserInfoKey"] as! TimeInterval
//键盘变化后RECT UIKeyboardFrameEndUserInfoKey
let keyboardFrame : CGRect = userInfoDict["UIKeyboardFrameEndUserInfoKey"] as! CGRect
UIView.animate(withDuration: duration){() -> Void in
self.toolBarBottomCons.constant = (UIScreen.main.bounds.height - keyboardFrame.origin.y)
}
}
//选择照片
@objc fileprivate func picPickerAddPhotoMethod() {
//判断照片源是否可用
let sourceType : UIImagePickerControllerSourceType = .photoLibrary
guard UIImagePickerController.isSourceTypeAvailable(sourceType) == true else {
XWLog("照片源不可用!")
return
}
//设置照片源
ipc.sourceType = sourceType
ipc.delegate = self
present(ipc, animated: true, completion: nil)
}
//删除照片
@objc fileprivate func picPickerDelegatePhotoMethod(noti : NSNotification) {
XWLog("删除照片! \(noti.object)")
//要删除的照片
guard let deleteImage : UIImage = noti.object as? UIImage else {
return
}
guard let deleteImageIndex : Int = picPickerS.index(of: deleteImage) else {
return
}
picPickerS.remove(at: deleteImageIndex)
picPickerCollection.picPickerS = picPickerS
}
}
//MARK: - TEXTVIEW DELEGATE
extension ComposeVC : UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
composeTextView.placeholderLB.isHidden = textView.hasText
navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
composeTextView.resignFirstResponder()
}
}
extension ComposeVC : UIImagePickerControllerDelegate,UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
XWLog("info\(info)")
let selectedImage : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
picPickerS.append(selectedImage)
//在collection中展示照片数组
picPickerCollection.picPickerS = picPickerS
ipc.dismiss(animated: true, completion: nil)
}
}
|
apache-2.0
|
abd5d0da3828801fdebbf66dc3cdc55b
| 37.670157 | 173 | 0.677092 | 4.953722 | false | false | false | false |
colemancda/MySQLSwift
|
Sources/MySQL/ConvertString.swift
|
4
|
1033
|
//
// ConvertString.swift
// MySQL
//
// Created by Alsey Coleman Miller on 12/4/15.
// Copyright © 2015 ColemanCDA. All rights reserved.
//
// returns an allocated buffer holding the string's contents and the full size in bytes which was allocated
// An empty (but not nil) string would have a count of 1
func convertString(s: String?) -> (UnsafeMutablePointer<Int8>, Int) {
var ret: (UnsafeMutablePointer<Int8>, Int) = (UnsafeMutablePointer<Int8>(), 0)
guard let notNilString = s else {
return ret
}
notNilString.withCString { p in
var c = 0
while p[c] != 0 {
c += 1
}
c += 1
let alloced = UnsafeMutablePointer<Int8>.alloc(c)
alloced.initialize(0)
for i in 0..<c {
alloced[i] = p[i]
}
alloced[c-1] = 0
ret = (alloced, c)
}
return ret
}
func cleanConvertedString(pair: (UnsafeMutablePointer<Int8>, Int)) {
if pair.1 > 0 {
pair.0.destroy()
pair.0.dealloc(pair.1)
}
}
|
mit
|
5ee1e926f99fc19beafb11ff619d22b7
| 26.184211 | 107 | 0.589147 | 3.646643 | false | false | false | false |
kenwilcox/Scriv
|
Swift/Pods/SwiftyDropbox/Source/Auth.swift
|
3
|
13493
|
import UIKit
import WebKit
import Security
import Foundation
public class DropboxAccessToken : Printable {
var accessToken: String
var uid: String
init(accessToken: String, uid: String) {
self.accessToken = accessToken
self.uid = uid
}
public var description : String {
return self.accessToken
}
}
/// A failed authorization.
/// See RFC6749 4.2.2.1
///
/// - `UnauthorizedClient` - The client is not authorized to request an access token using this method.
/// - `AccessDenied` - The resource owner or authorization server denied the request.
/// - `UnsupportedResponseType` - The authorization server does not support obtaining an access token using this method.
/// - `InvalidScope` - The requested scope is invalid, unknown, or malformed.
/// - `ServerError` - The authorization server encountered an unexpected condition that prevented it from fulfilling the request.
/// - `TemporarilyUnavailable` - The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
/// - `Unknown` - Some other error (outside of the OAuth2 specification)
public enum OAuth2Error {
case UnauthorizedClient
case AccessDenied
case UnsupportedResponseType
case InvalidScope
case ServerError
case TemporarilyUnavailable
case Unknown
init(errorCode: String) {
switch errorCode {
case "unauthorized_client": self = .UnauthorizedClient
case "access_denied": self = .AccessDenied
case "unsupported_response_type": self = .UnsupportedResponseType
case "invalid_scope": self = .InvalidScope
case "server_error": self = .ServerError
case "temporarily_unavailable": self = .TemporarilyUnavailable
default: self = .Unknown
}
}
}
/// The result of an authorization attempt.
///
/// - `Success` - The authorization succeeded. Includes a `DropboxAccessToken`.
/// - `Error` - The authorization failed. Includes an `OAuth2Error` and a descriptive message.
public enum DropboxAuthResult {
case Success(DropboxAccessToken)
case Error(OAuth2Error, String)
}
private class Keychain {
class func set(#key: String, value: String) -> Bool {
if let data = value.dataUsingEncoding(NSUTF8StringEncoding) {
return set(key: key, value: data)
} else {
return false
}
}
class func set(#key: String, value: NSData) -> Bool {
let query : CFDictionaryRef = [
( kSecClass as! String): kSecClassGenericPassword,
(kSecAttrAccount as! String): key,
( kSecValueData as! String): value
]
SecItemDelete(query)
return SecItemAdd(query, nil) == noErr
}
class func getAsData(key: String) -> NSData? {
let query : CFDictionaryRef = [
( kSecClass as! String): kSecClassGenericPassword,
(kSecAttrAccount as! String): key,
( kSecReturnData as! String): kCFBooleanTrue,
( kSecMatchLimit as! String): kSecMatchLimitOne
]
var dataTypeRef : Unmanaged<AnyObject>?
let status = SecItemCopyMatching(query, &dataTypeRef)
if status == noErr {
return dataTypeRef?.takeRetainedValue() as? NSData
}
return nil
}
class func getAll() -> [String] {
let query : CFDictionaryRef = [
( kSecClass as! String): kSecClassGenericPassword,
( kSecReturnAttributes as! String): kCFBooleanTrue,
( kSecMatchLimit as! String): kSecMatchLimitAll
]
var dataTypeRef : Unmanaged<AnyObject>?
let status = SecItemCopyMatching(query, &dataTypeRef)
if status == noErr {
let results = dataTypeRef?.takeRetainedValue() as! [[String : AnyObject]]
return results.map { d in d["acct"] as! String }
}
return []
}
class func get(key: String) -> String? {
if let data = getAsData(key) {
return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
} else {
return nil
}
}
class func delete(key: String) -> Bool {
let query : CFDictionaryRef = [
(kSecClass as! String) : kSecClassGenericPassword,
(kSecAttrAccount as! String): key
]
return SecItemDelete(query) == noErr
}
class func clear() -> Bool {
let query : CFDictionaryRef = [
(kSecClass as! String) : kSecClassGenericPassword,
]
return SecItemDelete(query) == noErr
}
}
/// Manages access token storage and authentication
///
/// Use the `DropboxAuthManager` to authenticate users through OAuth2, save access tokens, and retrieve access tokens.
public class DropboxAuthManager {
let appKey : String
let redirectURL: NSURL
let host: String
public static var sharedAuthManager : DropboxAuthManager!
public init(appKey: String, host: String) {
self.appKey = appKey
self.host = host
self.redirectURL = NSURL(string: "db-\(self.appKey)://2/token")!
}
convenience public init(appKey: String) {
self.init(appKey: appKey, host: "www.dropbox.com")
}
private func authURL() -> NSURL {
let components = NSURLComponents()
components.scheme = "https"
components.host = self.host
components.path = "/1/oauth2/authorize"
components.queryItems = [
NSURLQueryItem(name: "response_type", value: "token"),
NSURLQueryItem(name: "client_id", value: self.appKey),
NSURLQueryItem(name: "redirect_uri", value: self.redirectURL.URLString)
]
return components.URL!
}
private func canHandleURL(url: NSURL) -> Bool {
return (url.scheme == self.redirectURL.scheme
&& url.host == self.redirectURL.host
&& url.path == self.redirectURL.path)
}
/// Present the OAuth2 authorization request page by presenting a web view controller modally
///
/// :param: controller
/// The controller to present from
public func authorizeFromController(controller: UIViewController) {
let web = DropboxConnectController(
URL: self.authURL(),
tryIntercept: { url in
if self.canHandleURL(url) {
UIApplication.sharedApplication().openURL(url)
return true
} else {
return false
}
}
)
let navigationController = UINavigationController(rootViewController: web)
controller.presentViewController(navigationController, animated: true, completion: nil)
}
/// Try to handle a redirect back into the application
///
/// :param: url
/// The URL to attempt to handle
/// :returns: `nil` if SwiftyDropbox cannot handle the redirect URL, otherwise returns the `DropboxAuthResult`.
public func handleRedirectURL(url: NSURL) -> DropboxAuthResult? {
if !self.canHandleURL(url) {
return nil
}
var results = [String: String]()
let pairs = url.fragment?.componentsSeparatedByString("&") ?? []
for pair in pairs {
let kv = pair.componentsSeparatedByString("=")
results.updateValue(kv[1], forKey: kv[0])
}
if let error = results["error"] {
let desc = results["error_description"]?.stringByReplacingOccurrencesOfString("+", withString: " ").stringByReplacingPercentEscapesUsingEncoding(NSASCIIStringEncoding)
return .Error(OAuth2Error(errorCode: error), desc ?? "")
} else {
let accessToken = results["access_token"]!
let uid = results["uid"]!
Keychain.set(key: uid, value: accessToken)
return .Success(DropboxAccessToken(accessToken: accessToken, uid: uid))
}
}
/// Retrieve all stored access tokens
///
/// :returns: a dictionary mapping users to their access tokens
public func getAllAccessTokens() -> [String : DropboxAccessToken] {
let users = Keychain.getAll()
var ret = [String : DropboxAccessToken]()
for user in users {
if let accessToken = Keychain.get(user) {
ret[user] = DropboxAccessToken(accessToken: accessToken, uid: user)
}
}
return ret
}
/// Check if there are any stored access tokens
///
/// :returns: Whether there are stored access tokens
public func hasStoredAccessTokens() -> Bool {
return self.getAllAccessTokens().count != 0
}
/// Retrieve the access token for a particular user
///
/// :param: user
/// The user whose token to retrieve
/// :returns: An access token if present, otherwise `nil`.
public func getAccessToken(#user: String) -> DropboxAccessToken? {
if let accessToken = Keychain.get(user) {
return DropboxAccessToken(accessToken: accessToken, uid: user)
} else {
return nil
}
}
/// Delete a specific access token
///
/// :param: token
/// The access token to delete
/// :returns: whether the operation succeeded
public func clearStoredAccessToken(token: DropboxAccessToken) -> Bool {
return Keychain.delete(token.uid)
}
/// Delete all stored access tokens
///
/// :returns: whether the operation succeeded
public func clearStoredAccessTokens() -> Bool {
return Keychain.clear()
}
/// Save an access token
///
/// :param: token
/// The access token to save
/// :returns: whether the operation succeeded
public func storeAccessToken(token: DropboxAccessToken) -> Bool {
return Keychain.set(key: token.uid, value: token.accessToken)
}
/// Utility function to return an arbitrary access token
///
/// :returns: the "first" access token found, if any (otherwise `nil`)
public func getFirstAccessToken() -> DropboxAccessToken? {
return self.getAllAccessTokens().values.first
}
}
public class DropboxConnectController : UIViewController, WKNavigationDelegate {
var webView : WKWebView!
var onWillDismiss: ((didCancel: Bool) -> Void)?
var tryIntercept: ((url: NSURL) -> Bool)?
var cancelButton: UIBarButtonItem?
public init() {
super.init(nibName: nil, bundle: nil)
}
public init(URL: NSURL, tryIntercept: ((url: NSURL) -> Bool)) {
super.init(nibName: nil, bundle: nil)
self.startURL = URL
self.tryIntercept = tryIntercept
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func viewDidLoad() {
super.viewDidLoad()
self.title = "Link to Dropbox"
self.webView = WKWebView(frame: self.view.bounds)
self.view.addSubview(self.webView)
self.webView.navigationDelegate = self
self.view.backgroundColor = UIColor.whiteColor()
self.cancelButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancel:")
self.navigationItem.rightBarButtonItem = self.cancelButton
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !webView.canGoBack {
if nil != startURL {
loadURL(startURL!)
}
else {
webView.loadHTMLString("There is no `startURL`", baseURL: nil)
}
}
}
public func webView(webView: WKWebView,
decidePolicyForNavigationAction navigationAction: WKNavigationAction,
decisionHandler: (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.URL, callback = self.tryIntercept {
if callback(url: url) {
self.dismiss(animated: true)
return decisionHandler(.Cancel)
}
}
return decisionHandler(.Allow)
}
public var startURL: NSURL? {
didSet(oldURL) {
if nil != startURL && nil == oldURL && isViewLoaded() {
loadURL(startURL!)
}
}
}
public func loadURL(url: NSURL) {
webView.loadRequest(NSURLRequest(URL: url))
}
func showHideBackButton(show: Bool) {
navigationItem.leftBarButtonItem = show ? UIBarButtonItem(barButtonSystemItem: .Rewind, target: self, action: "goBack:") : nil
}
func goBack(sender: AnyObject?) {
webView.goBack()
}
func cancel(sender: AnyObject?) {
dismiss(asCancel: true, animated: (sender != nil))
}
func dismiss(#animated: Bool) {
dismiss(asCancel: false, animated: animated)
}
func dismiss(#asCancel: Bool, animated: Bool) {
webView.stopLoading()
self.onWillDismiss?(didCancel: asCancel)
presentingViewController?.dismissViewControllerAnimated(animated, completion: nil)
}
}
|
mit
|
c200e346a862f7eb386b9d9fbb2a1367
| 32.154791 | 179 | 0.604906 | 5.07065 | false | false | false | false |
asalom/Cocoa-Design-Patterns-in-Swift
|
DesignPatterns/DesignPatterns/Basic/Enumerators/LinkedList.swift
|
1
|
1412
|
//
// LinkedList.swift
// DesignPatterns
//
// Created by Alex Salom on 06/11/15.
// Copyright © 2015 Alex Salom © alexsalom.es. All rights reserved.
//
import Foundation
class LinkedList<T> {
var first: Node<T>?
var last: Node<T>?
var count: Int = 0
func push(element: T) {
if let lLast = self.last {
lLast.next = Node(value: element, previous: lLast)
self.last = lLast.next
}
else {
self.first = Node(value: element)
self.last = self.first
}
count++
}
func pop() {
if let lLast = self.last {
if let lPrevious = lLast.previous {
self.last = lPrevious
}
else {
self.last = nil
self.first = nil
}
count--
}
}
}
extension LinkedList: SequenceType {
func generate() -> LinkedListGenerator<T> {
return LinkedListGenerator(value: self)
}
}
struct LinkedListGenerator<T>: GeneratorType {
let value: LinkedList<T>
var actual: Node<T>?
init(value: LinkedList<T>) {
self.value = value
self.actual = self.value.first
}
mutating func next() -> Node<T>? {
if let lActual = self.actual {
self.actual = lActual.next
return lActual
}
return nil
}
}
|
mit
|
2444e7ebc00b117ce2cee205eff5f97c
| 20.707692 | 68 | 0.516312 | 4.017094 | false | false | false | false |
laiskailves/Mazzzy
|
Mazzzy/UI/MenuOverlay.swift
|
1
|
3945
|
//
// MenuOverlay.swift
// Mazzzy
//
// Created by Anna Afanasyeva on 21/10/2016.
// Copyright © 2016 Anna Afanasyeva. All rights reserved.
//
import SpriteKit
public class MenuOverlay: SKSpriteNode {
public init(size: CGSize) {
super.init(texture: nil, color: SKColor.black.withAlphaComponent(0.5), size: size)
setupTitle()
setupSplitter()
setupCurrentLevelLabel()
setupCheckpointsLabel()
setupCrashesLabel()
setupTapToPlayLabel()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupTitle() {
let title = SKLabelNode(fontNamed: "Arial")
title.text = "MAZZZY"
title.fontSize = UIParameters().titleFontSize
title.position = CGPoint(x: frame.midX, y: frame.maxY - UIParameters().titlePositionOffsetY)
addChild(title)
}
private func setupSplitter() {
let point1 = CGPoint(x: frame.minX + UIParameters().splitterOffsetX, y: frame.midY + UIParameters().splitterOffsetY)
let point2 = CGPoint(x: frame.maxX - UIParameters().splitterOffsetX, y: frame.midY + UIParameters().splitterOffsetY)
let path = CGMutablePath()
let shape: SKShapeNode = SKShapeNode(path:path)
path.move(to: point1)
path.addLine(to: point2)
shape.path = path
shape.strokeColor = SKColor.white.withAlphaComponent(0.8)
shape.lineWidth = UIParameters().splitterLineWidth
addChild(shape)
}
private func setupCurrentLevelLabel() {
let currentLevel = SharedStorage.sharedInstance.level()
let currentLevelLabel = SKLabelNode(fontNamed: "Arial")
currentLevelLabel.text = "CURRENT LEVEL: \(currentLevel)"
currentLevelLabel.fontSize = UIParameters().statisticsItemFontSize
currentLevelLabel.fontColor = UIColor.white.withAlphaComponent(0.8)
currentLevelLabel.position = CGPoint(x: frame.midX, y: frame.midY + UIParameters().currentLevelOffsetY)
addChild(currentLevelLabel)
}
private func setupCheckpointsLabel() {
let checkpoints = SharedStorage.sharedInstance.checkpoints()
let checkpointsLabel = SKLabelNode(fontNamed: "Arial")
checkpointsLabel.text = "CHECKPOINTS: \(checkpoints)"
checkpointsLabel.fontSize = UIParameters().statisticsItemFontSize
checkpointsLabel.fontColor = UIColor.white.withAlphaComponent(0.8)
checkpointsLabel.position = CGPoint(x: frame.midX, y: frame.midY + UIParameters().checkpointsOffsetY)
addChild(checkpointsLabel)
}
private func setupCrashesLabel() {
let crashes = SharedStorage.sharedInstance.crashes()
let crashesLabel = SKLabelNode(fontNamed: "Arial")
crashesLabel.text = "CRASHES: \(crashes)"
crashesLabel.fontSize = UIParameters().statisticsItemFontSize
crashesLabel.fontColor = UIColor.white.withAlphaComponent(0.8)
crashesLabel.position = CGPoint(x: frame.midX, y: frame.midY + UIParameters().crashesOffsetY)
addChild(crashesLabel)
}
private func setupTapToPlayLabel() {
let tapToStartLabel = SKLabelNode(fontNamed: "Arial")
tapToStartLabel.text = "TAP TO PLAY"
tapToStartLabel.fontSize = UIParameters().tapToPlayFontSize
tapToStartLabel.position = CGPoint(x: frame.midX, y: frame.minY + UIParameters().tapToPlayOffsetY)
addChild(tapToStartLabel)
let oneScaleDown = SKAction.scale(to: 1.0, duration: 0.8)
let oneScaleUp = SKAction.scale(to: 1.1, duration: 0.4)
let wait = SKAction.wait(forDuration: 3.0)
let scale = SKAction.repeatForever(SKAction.sequence([wait, oneScaleUp, oneScaleDown]))
tapToStartLabel.run(scale)
}
}
|
mit
|
3f08a3edba1efea71257cc2ce54720a3
| 37.291262 | 124 | 0.661004 | 4.406704 | false | false | false | false |
Bouke/HAP
|
Sources/HAP/Base/Predefined/Characteristics/Characteristic.LabelNamespace.swift
|
1
|
2015
|
import Foundation
public extension AnyCharacteristic {
static func labelNamespace(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read],
description: String? = "Label Namespace",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 4,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.labelNamespace(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func labelNamespace(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read],
description: String? = "Label Namespace",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 4,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<UInt8> {
GenericCharacteristic<UInt8>(
type: .labelNamespace,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
|
mit
|
2bda945db025573cbc5800c83448f26b
| 32.032787 | 66 | 0.57469 | 5.387701 | false | false | false | false |
hiroraba/KYShutterButton
|
Classes/KYShutterButton.swift
|
1
|
11601
|
/*
The MIT License (MIT)
Copyright (c) 2015 Kyohei Yamaguchi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
@IBDesignable
public class KYShutterButton: UIButton {
public enum ShutterType: Int {
case Normal, SlowMotion, TimeLapse
}
public enum ButtonState: Int {
case Normal, Recording
}
private let _kstartAnimateDuration: CFTimeInterval = 0.5
/**************************************************************************/
// MARK: - Properties
/**************************************************************************/
@IBInspectable var typeRaw: Int = 0 {
didSet {
if let type = ShutterType(rawValue: typeRaw) {
self.shutterType = type
} else {
self.shutterType = .Normal
}
}
}
@IBInspectable public var buttonColor: UIColor = UIColor.redColor() {
didSet {
_circleLayer.backgroundColor = buttonColor.CGColor
}
}
@IBInspectable public var arcColor: UIColor = UIColor.whiteColor() {
didSet {
_arcLayer.strokeColor = arcColor.CGColor
}
}
@IBInspectable public var progressColor: UIColor = UIColor.whiteColor() {
didSet {
_progressLayer.strokeColor = progressColor.CGColor
_rotateLayer.strokeColor = progressColor.CGColor
}
}
public var buttonState: ButtonState = .Normal {
didSet {
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = _circleLayer.path
animation.duration = 0.15
switch buttonState {
case .Normal:
if shutterType == .TimeLapse {
_progressLayer.removeAllAnimations()
_rotateLayer.removeAllAnimations()
}
animation.toValue = _circlePath.CGPath
_circleLayer.addAnimation(animation, forKey: "path-anim")
_circleLayer.path = _circlePath.CGPath
case .Recording:
animation.toValue = _roundRectPath.CGPath
_circleLayer.addAnimation(animation, forKey: "path-anim")
_circleLayer.path = _roundRectPath.CGPath
if shutterType == .TimeLapse {
_progressLayer.addAnimation(_startProgressAnimation, forKey: "start-anim")
_rotateLayer.addAnimation(_startRotateAnimation, forKey: "rotate-anim")
_progressLayer.addAnimation(_recordingAnimation, forKey: "recording-anim")
_rotateLayer.addAnimation(_recordingRotateAnimation, forKey: "recordingRotate-anim")
_progressLayer.path = p_arcPathWithProgress(1.0).CGPath
}
}
}
}
public var shutterType: ShutterType = .Normal {
didSet {
switch shutterType {
case .Normal:
_arcLayer.lineDashPattern = nil
_progressLayer.hidden = true
case .SlowMotion:
_arcLayer.lineDashPattern = [1, 1]
_progressLayer.hidden = true
case .TimeLapse:
let diameter = 2*CGFloat(M_PI)*(self.bounds.width/2 - self._arcWidth/2)
_arcLayer.lineDashPattern = [1, diameter/10 - 1]
_progressLayer.hidden = false
}
}
}
private var _arcWidth: CGFloat {
return bounds.width * 0.09090
}
private var _arcMargin: CGFloat {
return bounds.width * 0.03030
}
lazy private var _circleLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.path = self._circlePath.CGPath
layer.fillColor = self.buttonColor.CGColor
return layer
}()
lazy private var _arcLayer: CAShapeLayer = {
let layer = CAShapeLayer()
let path = UIBezierPath(
arcCenter: CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)),
radius: self.bounds.width/2 - self._arcWidth/2,
startAngle: -CGFloat(M_PI_2),
endAngle: CGFloat(M_PI*2.0) - CGFloat(M_PI_2),
clockwise: true
)
layer.path = path.CGPath
layer.fillColor = UIColor.clearColor().CGColor
layer.strokeColor = self.arcColor.CGColor
layer.lineWidth = self._arcWidth
return layer
}()
lazy private var _progressLayer: CAShapeLayer = {
let layer = CAShapeLayer()
let path = self.p_arcPathWithProgress(1.0, clockwise: true)
let diameter = 2*CGFloat(M_PI)*(self.bounds.width/2 - self._arcWidth/3)
layer.lineDashPattern = [1, diameter/60 - 1]
layer.path = path.CGPath
layer.fillColor = UIColor.clearColor().CGColor
layer.strokeColor = self.progressColor.CGColor
layer.lineWidth = self._arcWidth/1.5
return layer
}()
lazy private var _rotateLayer: CAShapeLayer = {
let layer = CAShapeLayer()
let subPath = UIBezierPath()
subPath.moveToPoint(CGPointMake(self.bounds.width/2, 0))
subPath.addLineToPoint(CGPointMake(self.bounds.width/2, self._arcWidth))
layer.strokeColor = self.progressColor.CGColor
layer.lineWidth = 1
layer.path = subPath.CGPath
layer.frame = self.bounds
return layer
}()
private var _circlePath: UIBezierPath {
let side = self.bounds.width - self._arcWidth*2 - self._arcMargin*2
return UIBezierPath(
roundedRect: CGRectMake(bounds.width/2 - side/2, bounds.width/2 - side/2, side, side),
cornerRadius: side/2
)
}
private var _roundRectPath: UIBezierPath {
let side = bounds.width * 0.4242
return UIBezierPath(
roundedRect: CGRectMake(bounds.width/2 - side/2, bounds.width/2 - side/2, side, side),
cornerRadius: side * 0.107
)
}
private var _startProgressAnimation: CAKeyframeAnimation {
let frameCount = 60
var paths = [CGPath]()
var times = [CGFloat]()
for i in 1...frameCount {
let animationProgress = 1/CGFloat(frameCount) * CGFloat(i) - 0.01
paths.append(self.p_arcPathWithProgress(animationProgress, clockwise: false).CGPath)
times.append(CGFloat(i)*0.1)
}
let animation = CAKeyframeAnimation(keyPath: "path")
animation.duration = _kstartAnimateDuration
animation.values = paths
return animation
}
private var _startRotateAnimation: CABasicAnimation {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = 0
animation.toValue = CGFloat(M_PI*2.0)
animation.duration = _kstartAnimateDuration
return animation
}
private var _recordingAnimation: CAKeyframeAnimation {
let frameCount = 60
var paths = [CGPath]()
for i in 1...frameCount {
let animationProgress = 1/CGFloat(frameCount) * CGFloat(i)
paths.append(self.p_arcPathWithProgress(animationProgress).CGPath)
}
for i in 1...frameCount {
let animationProgress = 1/CGFloat(frameCount) * CGFloat(i) - 0.01
paths.append(self.p_arcPathWithProgress(animationProgress, clockwise: false).CGPath)
}
let animation = CAKeyframeAnimation(keyPath: "path")
animation.duration = 10
animation.values = paths
animation.beginTime = CACurrentMediaTime() + _kstartAnimateDuration
animation.repeatCount = Float.infinity
animation.calculationMode = kCAAnimationDiscrete
return animation
}
private var _recordingRotateAnimation: CABasicAnimation {
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.fromValue = 0
animation.toValue = CGFloat(M_PI*2.0)
animation.duration = 5
animation.repeatCount = Float.infinity
animation.beginTime = CACurrentMediaTime() + _kstartAnimateDuration
return animation
}
/**************************************************************************/
// MARK: - initialize
/**************************************************************************/
public convenience init(frame: CGRect, shutterType: ShutterType, buttonColor: UIColor) {
self.init(frame: frame)
self.shutterType = shutterType
self.buttonColor = buttonColor
}
/**************************************************************************/
// MARK: - Override
/**************************************************************************/
override public var highlighted: Bool {
didSet {
_circleLayer.opacity = highlighted ? 0.5 : 1.0
}
}
public override func layoutSubviews() {
super.layoutSubviews()
if _arcLayer.superlayer != layer {
layer.addSublayer(_arcLayer)
}
if _progressLayer.superlayer != layer {
layer.addSublayer(_progressLayer)
}
if _rotateLayer.superlayer != layer {
layer.insertSublayer(_rotateLayer, atIndex: 0)
}
if _circleLayer.superlayer != layer {
layer.addSublayer(_circleLayer)
}
}
/**************************************************************************/
// MARK: - Method
/**************************************************************************/
private func p_arcPathWithProgress(progress: CGFloat, clockwise: Bool = true) -> UIBezierPath {
let diameter = 2*CGFloat(M_PI)*(self.bounds.width/2 - self._arcWidth/3)
let startAngle = clockwise ?
-CGFloat(M_PI_2) :
-CGFloat(M_PI_2) + CGFloat(M_PI)*(540/diameter)/180
let endAngle = clockwise ?
CGFloat(M_PI*2.0)*progress - CGFloat(M_PI_2) :
CGFloat(M_PI*2.0)*progress - CGFloat(M_PI_2) + CGFloat(M_PI)*(540/diameter)/180
let path = UIBezierPath(
arcCenter: CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)),
radius: self.bounds.width/2 - self._arcWidth/3,
startAngle: startAngle,
endAngle: endAngle,
clockwise: clockwise
)
return path
}
}
|
mit
|
fd8b693d79f7e9606cec32fb8b074e37
| 37.287129 | 104 | 0.571244 | 5.144568 | false | false | false | false |
lennet/bugreporter
|
Bugreporter/Extensions/NSViewExtension.swift
|
1
|
923
|
//
// NSViewExtension.swift
// Bugreporter
//
// Created by Leo Thomas on 16/12/2016.
// Copyright © 2016 Leonard Thomas. All rights reserved.
//
import Cocoa
extension NSView {
var width: CGFloat {
set {
bounds.size.width = newValue
}
get {
return bounds.size.width
}
}
var height: CGFloat {
set {
bounds.size.height = newValue
}
get {
return bounds.size.height
}
}
var backgroundColor: NSColor? {
set {
wantsLayer = true
layer?.backgroundColor = newValue?.cgColor
}
get {
if let color = layer?.backgroundColor {
return NSColor(cgColor: color)
}
return nil
}
}
}
|
mit
|
4e5fce725092cde114f99596f05cbf50
| 15.464286 | 57 | 0.439262 | 5.179775 | false | false | false | false |
AlexLittlejohn/Weight
|
Weight/Views/Weight Capture/WeightCaptureViewController.swift
|
1
|
3034
|
//
// WeightCaptureViewController.swift
// Weight
//
// Created by Alex Littlejohn on 2016/02/20.
// Copyright © 2016 Alex Littlejohn. All rights reserved.
//
import UIKit
import ReSwift
class WeightCaptureViewController: UIViewController, StoreSubscriber {
@IBOutlet weak var weightPicker: WeightCaptureView!
@IBOutlet weak var gradientView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let gradient = CAGradientLayer()
gradient.frame = gradientView.bounds
gradient.colors = [UIColor.black.cgColor, UIColor.black.cgColor, UIColor.clear.cgColor]
gradient.locations = [0.0, 0.65, 1.0]
gradientView.layer.mask = gradient
titleLabel.font = Typography.NavigationBar.title.font
titleLabel.textColor = Colors.NavigationBar.title.color
dateLabel.font = Typography.DateButton.title.font
dateLabel.textColor = Colors.DateButton.title.color
view.sendSubview(toBack: weightPicker)
}
@IBAction func changeDate(_ sender: AnyObject) {
}
@IBAction func confirm(_ sender: AnyObject) {
guard let pickerValue = weightPicker.getValue() else {
return
}
let date = mainStore.state?.captureDate ?? Date()
let mode = mainStore.state?.captureMode ?? .weight
let addAction = action(mode, weight: pickerValue.weight, unit: pickerValue.unit, date: date)
mainStore.dispatch(addAction)
}
@IBAction func cancel(_ sender: AnyObject) {
}
override func viewWillAppear(_ animated: Bool) {
mainStore.subscribe(self)
}
override func viewWillDisappear(_ animated: Bool) {
mainStore.unsubscribe(self)
}
func newState(state: AppState) {
configureTitle(state.captureMode, goal: state.goal != nil)
configureDate(state.captureDate as Date)
}
func action(_ mode: CaptureMode, weight: Double, unit: Unit, date: Date) -> Action {
if mode == .goal {
let goal = Goal(weight: weight, unit: unit)
return Actions.addGoal(goal)
} else {
let w = Weight(weight: weight, date: date, unit: unit)
return Actions.addWeight(w)
}
}
func configureTitle(_ mode: CaptureMode, goal: Bool) {
let title: String
switch mode {
case .weight:
title = localizedString("addWeightTitle")
case .goal:
if goal {
title = localizedString("changeGoalTitle")
} else {
title = localizedString("addGoalTitle")
}
}
titleLabel.text = title
}
func configureDate(_ date: Date) {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM"
dateLabel.text = formatter.string(from: date)
}
}
|
mit
|
2e4106ce347920fcbfcb934b7bb31cc5
| 28.735294 | 100 | 0.607649 | 4.716952 | false | false | false | false |
hstdt/GodEye
|
GodEye/Classes/ORM/CrashRecordModel+ORM.swift
|
1
|
2257
|
//
// CrashRecordModel+ORM.swift
// Pods
//
// Created by zixun on 17/1/9.
//
//
import Foundation
import SQLite
import CrashEye
extension CrashRecordModel: RecordORMProtocol {
static var type: RecordType {
return RecordType.crash
}
func mappingToRelation() -> [Setter] {
return [CrashRecordModel.col.type <- self.type.rawValue,
CrashRecordModel.col.name <- self.name,
CrashRecordModel.col.reason <- self.reason,
CrashRecordModel.col.appinfo <- self.appinfo,
CrashRecordModel.col.callStack <- self.callStack]
}
static func mappingToObject(with row: Row) -> CrashRecordModel {
let type = CrashModelType(rawValue:row[CrashRecordModel.col.type])!
let name = row[CrashRecordModel.col.name]
let reason = row[CrashRecordModel.col.reason]
let appinfo = row[CrashRecordModel.col.appinfo]
let callStack = row[CrashRecordModel.col.callStack]
return CrashRecordModel(type: type, name: name, reason: reason, appinfo: appinfo, callStack: callStack)
}
static func configure(tableBuilder:TableBuilder) {
tableBuilder.column(CrashRecordModel.col.type)
tableBuilder.column(CrashRecordModel.col.name)
tableBuilder.column(CrashRecordModel.col.reason)
tableBuilder.column(CrashRecordModel.col.appinfo)
tableBuilder.column(CrashRecordModel.col.callStack)
}
static func configure(select table:Table) -> Table {
return table.select(CrashRecordModel.col.type,
CrashRecordModel.col.name,
CrashRecordModel.col.reason,
CrashRecordModel.col.appinfo,
CrashRecordModel.col.callStack)
}
func attributeString() -> NSAttributedString {
return CrashRecordViewModel(self).attributeString()
}
class col: NSObject {
static let type = Expression<Int>("type")
static let name = Expression<String>("name")
static let reason = Expression<String>("reason")
static let appinfo = Expression<String>("appinfo")
static let callStack = Expression<String>("callStack")
}
}
|
mit
|
8ddd376776a6003602840b5df8f67ed9
| 34.825397 | 111 | 0.643332 | 4.672878 | false | false | false | false |
mattwelborn/HSTracker
|
HSTracker/Hearthstats/HearthstatsAPI.swift
|
1
|
19855
|
//
// HearthstatsAPI.swift
// HSTracker
//
// Created by Benjamin Michotte on 21/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import Alamofire
import CleanroomLogger
extension Deck {
func merge(deck: Deck) {
self.name = deck.name
self.playerClass = deck.playerClass
self.version = deck.version
self.creationDate = deck.creationDate
self.hearthstatsId = deck.hearthstatsId
self.hearthstatsVersionId = deck.hearthstatsVersionId
self.isActive = deck.isActive
self.isArena = deck.isArena
self.removeAllCards()
for card in deck.sortedCards {
for _ in 0...card.count {
self.addCard(card)
}
}
self.statistics = deck.statistics
}
static func fromHearthstatsDict(json: [String: AnyObject]) -> Deck? {
if let name = json["deck"]?["name"] as? String,
klassId = json["deck"]?["klass_id"] as? Int,
playerClass = HearthstatsAPI.heroes[klassId],
version = json["current_version"] as? String,
creationDate = json["deck"]?["created_at"] as? String,
hearthstatsId = json["deck"]?["id"] as? Int,
archived = json["deck"]?["archived"] as? Int,
isArchived = archived.boolValue {
var currentVersion: [String : AnyObject]?
(json["versions"] as? [[String: AnyObject]])?
.forEach { (_version: [String : AnyObject]) in
if _version["version"] as? String == version {
currentVersion = _version
}
}
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let currentVersion = currentVersion,
hearthstatsVersionId = currentVersion["deck_version_id"] as? Int,
date = formatter.dateFromString(creationDate) {
var cards = [Card]()
(json["cards"] as? [[String: String]])?
.forEach({ (_card: [String: String]) in
if let card = Cards.byId(_card["id"]),
_count = _card["count"],
count = Int(_count) {
card.count = count
cards.append(card)
}
})
let deck = Deck(playerClass: playerClass, name: name)
deck.creationDate = date
deck.hearthstatsId = hearthstatsId
deck.hearthstatsVersionId = hearthstatsVersionId
deck.isActive = !isArchived
deck.version = version
cards.forEach({ deck.addCard($0) })
if deck.isValid() {
return deck
}
}
}
return nil
}
}
extension Decks {
func byHearthstatsId(id: Int) -> Deck? {
return decks().filter({ $0.hearthstatsId == id }).first
}
func addOrUpdateMatches(dict: [String: AnyObject]) {
if let existing = decks()
.filter({ $0.hearthstatsId == (dict["deck_id"] as? Int)
&& $0.hearthstatsVersionId == (dict["deck_version_id"] as? Int) }).first {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let resultId = dict["match"]?["result_id"] as? Int,
result = HearthstatsAPI.gameResults[resultId],
coin = dict["match"]?["coin"] as? Bool,
classId = dict["match"]?["oppclass_id"] as? Int,
opponentClass = HearthstatsAPI.heroes[classId],
opponentName = dict["match"]?["oppname"] as? String,
playerRank = dict["ranklvl"] as? Int,
mode = dict["match"]?["mode_id"] as? Int,
playerMode = HearthstatsAPI.gameModes[mode],
date = dict["match"]?["created_at"] as? String,
creationDate = formatter.dateFromString(date) {
let stat = Statistic()
stat.gameResult = result
stat.hasCoin = coin
stat.opponentClass = opponentClass
stat.opponentName = opponentName
stat.playerRank = playerRank
stat.playerMode = playerMode
stat.date = creationDate
existing.addStatistic(stat)
update(existing)
}
}
}
}
enum HearthstatsError: ErrorType {
case NotLogged,
DeckNotSaved
}
struct HearthstatsAPI {
static let gameResults: [Int: GameResult] = [
1: .Win,
2: .Loss,
3: .Draw
]
static let gameModes: [Int: GameMode] = [
1: .Arena,
2: .Casual,
3: .Ranked,
4: .None,
5: .Friendly
]
static let heroes: [Int: CardClass] = [
1: .DRUID,
2: .HUNTER,
3: .MAGE,
4: .PALADIN,
5: .PRIEST,
6: .ROGUE,
7: .SHAMAN,
8: .WARLOCK,
9: .WARRIOR
]
private static let baseUrl = "http://api.hearthstats.net/api/v3"
// MARK: - Authentication
static func login(email: String, password: String,
callback: (success: Bool, message: String) -> ()) {
Alamofire.request(.POST, "\(baseUrl)/users/sign_in",
parameters: ["user_login": ["email": email, "password": password ]], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
if let success = json["success"] as? Bool where success {
let settings = Settings.instance
settings.hearthstatsLogin = json["email"] as? String
settings.hearthstatsToken = json["auth_token"] as? String
callback(success: true, message: "")
} else {
callback(success: false,
message: json["message"] as? String ?? "Unknown error")
}
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false,
message: NSLocalizedString("server error", comment: ""))
}
}
static func logout() {
let settings = Settings.instance
settings.hearthstatsLogin = nil
settings.hearthstatsToken = nil
}
static func isLogged() -> Bool {
let settings = Settings.instance
return settings.hearthstatsLogin != nil && settings.hearthstatsToken != nil
}
static func loadDecks(force: Bool = false,
callback: (success: Bool, added: Int) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
if force {
settings.hearthstatsLastDecksSync = NSDate.distantPast().timeIntervalSince1970
}
try getDecks(settings.hearthstatsLastDecksSync, callback: callback)
}
// MARK: - decks
private static func getDecks(unixTime: Double,
callback: (success: Bool, added: Int) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST,
"\(baseUrl)/decks/after_date?auth_token=\(settings.hearthstatsToken!)",
parameters: ["date": "\(unixTime)"], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value,
status = json["status"] as? Int where status == 200 {
var newDecks = 0
(json["data"] as? [[String: AnyObject]])?.forEach({
newDecks += 1
if let deck = Deck.fromHearthstatsDict($0),
hearthstatsId = deck.hearthstatsId {
if let existing = Decks.instance.byHearthstatsId(hearthstatsId) {
existing.merge(deck)
Decks.instance.update(existing)
} else {
Decks.instance.add(deck)
}
}
})
Settings.instance.hearthstatsLastDecksSync = NSDate().timeIntervalSince1970
callback(success: true, added: newDecks)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false, added: 0)
}
}
static func postDeck(deck: Deck, callback: (success: Bool) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST, "\(baseUrl)/decks?auth_token=\(settings.hearthstatsToken!)",
parameters: [
"name": deck.name ?? "",
"tags": [],
"notes": "",
"cards": deck.sortedCards.map {["id": $0.id, "count": $0.count]},
"class": deck.playerClass.rawValue.capitalizedString,
"version": deck.version
], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value,
data = json["data"] as? [String:AnyObject],
jsonDeck = data["deck"] as? [String:AnyObject],
hearthstatsId = jsonDeck["id"] as? Int,
deckVersions = data["deck_versions"] as? [[String:AnyObject]],
hearthstatsVersionId = deckVersions.first?["id"] as? Int {
deck.hearthstatsId = hearthstatsId
deck.hearthstatsVersionId = hearthstatsVersionId
callback(success: true)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false)
}
}
static func updateDeck(deck: Deck, callback: (success: Bool) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST, "\(baseUrl)/decks/edit?auth_token=\(settings.hearthstatsToken!)",
parameters: [
"deck_id": deck.hearthstatsId!,
"name": deck.name ?? "",
"tags": [],
"notes": "",
"cards": deck.sortedCards.map {["id": $0.id, "count": $0.count]},
"class": deck.playerClass.rawValue.capitalizedString
], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("update deck : \(json)")
callback(success: true)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false)
}
}
static func postDeckVersion(deck: Deck, callback: (success: Bool) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST,
"\(baseUrl)/decks/create_version?auth_token=\(settings.hearthstatsToken!)",
parameters: [
"deck_id": deck.hearthstatsId!,
"cards": deck.sortedCards.map {["id": $0.id, "count": $0.count]},
"version": deck.version
], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value,
data = json["data"] as? [String:AnyObject],
hearthstatsVersionId = data["id"] as? Int {
Log.debug?.message("post deck version : \(json)")
deck.hearthstatsVersionId = hearthstatsVersionId
callback(success: true)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false)
}
}
static func deleteDeck(deck: Deck) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST, "\(baseUrl)/decks/delete?auth_token=\(settings.hearthstatsToken!)",
parameters: ["deck_id": "[\(deck.hearthstatsId)]"], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("delete deck : \(json)")
return
}
}
}
}
// MARK: - matches
static func getGames(unixTime: Double, callback: (success: Bool) -> ()) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
Alamofire.request(.POST,
"\(baseUrl)/matches/after_date?auth_token=\(settings.hearthstatsToken!)",
parameters: ["date": "\(unixTime)"], encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("get games : \(json)")
(json["data"] as? [[String: AnyObject]])?.forEach({
Decks.instance.addOrUpdateMatches($0)
})
// swiftlint:disable line_length
Settings.instance.hearthstatsLastMatchesSync = NSDate().timeIntervalSince1970
// swiftlint:enable line_length
callback(success: true)
return
}
}
Log.error?.message("\(response.result.error)")
callback(success: false)
}
}
static func postMatch(game: Game, deck: Deck, stat: Statistic) throws {
let settings = Settings.instance
guard let _ = settings.hearthstatsToken else { throw HearthstatsError.NotLogged }
guard let _ = deck.hearthstatsId else { throw HearthstatsError.DeckNotSaved }
guard let _ = deck.hearthstatsVersionId else { throw HearthstatsError.DeckNotSaved }
let startTime: NSDate
if let gameStartDate = game.gameStartDate {
startTime = gameStartDate
} else {
startTime = NSDate()
}
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(name: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
let startAt = formatter.stringFromDate(startTime)
let parameters: [String: AnyObject] = [
"class": deck.playerClass.rawValue.capitalizedString,
"mode": "\(game.currentGameMode)",
"result": "\(game.gameResult)",
"coin": "\(stat.hasCoin)",
"numturns": stat.numTurns,
"duration": stat.duration,
"deck_id": deck.hearthstatsId!,
"deck_version_id": deck.hearthstatsVersionId!,
"oppclass": stat.opponentClass.rawValue.capitalizedString,
"oppname": stat.opponentName,
"notes": stat.note ?? "",
"ranklvl": stat.playerRank,
"oppcards": stat.cards,
"created_at": startAt
]
Log.info?.message("Posting match to Hearthstats \(parameters)")
Alamofire.request(.POST, "\(baseUrl)/matches?auth_token=\(settings.hearthstatsToken!)",
parameters: parameters, encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("post match : \(json)")
return
}
}
}
}
// MARK: - Arena
static func postArenaMatch(game: Game, deck: Deck, stat: Statistic) throws {
guard let _ = Settings.instance.hearthstatsToken else { throw HearthstatsError.NotLogged }
guard let _ = deck.hearthStatsArenaId else {
createArenaRun(game, deck: deck, stat: stat)
return
}
_postArenaMatch(game, deck: deck, stat: stat)
}
private static func _postArenaMatch(game: Game, deck: Deck, stat: Statistic) {
let parameters: [String: AnyObject] = [
"class": deck.playerClass.rawValue.capitalizedString,
"mode": "\(game.currentGameMode)",
"result": "\(game.gameResult)",
"coin": "\(stat.hasCoin)",
"numturns": stat.numTurns,
"duration": stat.duration,
"arena_run_id": deck.hearthStatsArenaId!,
"oppclass": stat.opponentClass.rawValue.capitalizedString,
"oppname": stat.opponentName,
]
Log.info?.message("Posting arena match to Hearthstats \(parameters)")
let url = "\(baseUrl)/matches?auth_token=\(Settings.instance.hearthstatsToken!)"
Alamofire.request(.POST, url,
parameters: parameters, encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value {
Log.debug?.message("post arena match : \(json)")
return
}
}
}
}
static func createArenaRun(game: Game, deck: Deck, stat: Statistic) {
Log.info?.message("Creating new arena deck")
let parameters: [String: AnyObject] = [
"class": deck.playerClass.rawValue.capitalizedString,
"cards": deck.sortedCards.map {["id": $0.id, "count": $0.count]}
]
let url = "\(baseUrl)/arena_runs/new?auth_token=\(Settings.instance.hearthstatsToken!)"
Alamofire.request(.POST, url,
parameters: parameters, encoding: .JSON)
.responseJSON { response in
if response.result.isSuccess {
if let json = response.result.value,
data = json["data"] as? [String:AnyObject],
hearthStatsArenaId = data["id"] as? Int {
deck.hearthStatsArenaId = hearthStatsArenaId
Log.debug?.message("Arena run : \(hearthStatsArenaId)")
_postArenaMatch(game, deck: deck, stat: stat)
return
}
}
}
}
}
|
mit
|
661e4d8156c51fe1997b439cf9b5c91b
| 40.190871 | 101 | 0.508663 | 4.848352 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/ViewRelated/Post/PrepublishingViewController.swift
|
1
|
18715
|
import UIKit
import WordPressAuthenticator
import Combine
private struct PrepublishingOption {
let id: PrepublishingIdentifier
let title: String
let type: PrepublishingCellType
}
private enum PrepublishingCellType {
case value
case textField
var cellType: UITableViewCell.Type {
switch self {
case .value:
return WPTableViewCell.self
case .textField:
return WPTextFieldTableViewCell.self
}
}
}
enum PrepublishingIdentifier {
case title
case schedule
case visibility
case tags
case categories
}
class PrepublishingViewController: UITableViewController {
let post: Post
private lazy var publishSettingsViewModel: PublishSettingsViewModel = {
return PublishSettingsViewModel(post: post)
}()
private lazy var presentedVC: DrawerPresentationController? = {
return (navigationController as? PrepublishingNavigationController)?.presentedVC
}()
enum CompletionResult {
case completed(AbstractPost)
case dismissed
}
private let completion: (CompletionResult) -> ()
private let options: [PrepublishingOption]
private var didTapPublish = false
let publishButton: NUXButton = {
let nuxButton = NUXButton()
nuxButton.isPrimary = true
return nuxButton
}()
private weak var titleField: UITextField?
/// Determines whether the text has been first responder already. If it has, don't force it back on the user unless it's been selected by them.
private var hasSelectedText: Bool = false
init(post: Post, identifiers: [PrepublishingIdentifier], completion: @escaping (CompletionResult) -> ()) {
self.post = post
self.options = identifiers.map { identifier in
return PrepublishingOption(identifier: identifier)
}
self.completion = completion
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var cancellables = Set<AnyCancellable>()
@Published private var keyboardShown: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
title = ""
let nib = UINib(nibName: "PrepublishingHeaderView", bundle: nil)
tableView.register(nib, forHeaderFooterViewReuseIdentifier: Constants.headerReuseIdentifier)
setupPublishButton()
setupFooterSeparator()
updatePublishButtonLabel()
announcePublishButton()
configureKeyboardToggle()
}
/// Toggles `keyboardShown` as the keyboard notifications come in
private func configureKeyboardToggle() {
NotificationCenter.default.publisher(for: UIResponder.keyboardDidShowNotification)
.map { _ in return true }
.assign(to: \.keyboardShown, on: self)
.store(in: &cancellables)
NotificationCenter.default.publisher(for: UIResponder.keyboardDidHideNotification)
.map { _ in return false }
.assign(to: \.keyboardShown, on: self)
.store(in: &cancellables)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
preferredContentSize = tableView.contentSize
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
// Setting titleField first resonder alongside our transition to avoid layout issues.
transitionCoordinator?.animateAlongsideTransition(in: nil, animation: { [weak self] _ in
if self?.hasSelectedText == false {
self?.titleField?.becomeFirstResponder()
self?.hasSelectedText = true
}
})
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
let isPresentingAViewController = navigationController?.viewControllers.count ?? 0 > 1
if isPresentingAViewController {
navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Forced unwrap copied from this guide by Apple:
// https://developer.apple.com/documentation/uikit/views_and_controls/table_views/adding_headers_and_footers_to_table_sections
//
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: Constants.headerReuseIdentifier) as! PrepublishingHeaderView
header.delegate = self
header.configure(post.blog)
return header
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let option = options[indexPath.row]
let cell = dequeueCell(for: option.type, indexPath: indexPath)
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = .zero
cell.layoutMargins = Constants.cellMargins
switch option.type {
case .textField:
if let cell = cell as? WPTextFieldTableViewCell {
setupTextFieldCell(cell)
}
case .value:
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = option.title
}
switch option.id {
case .title:
if let cell = cell as? WPTextFieldTableViewCell {
configureTitleCell(cell)
}
case .tags:
configureTagCell(cell)
case .visibility:
configureVisibilityCell(cell)
case .schedule:
configureScheduleCell(cell)
case .categories:
configureCategoriesCell(cell)
}
return cell
}
private func dequeueCell(for type: PrepublishingCellType, indexPath: IndexPath) -> WPTableViewCell {
switch type {
case .textField:
guard let cell = tableView.dequeueReusableCell(withIdentifier: Constants.textFieldReuseIdentifier) as? WPTextFieldTableViewCell else {
return WPTextFieldTableViewCell.init(style: .default, reuseIdentifier: Constants.textFieldReuseIdentifier)
}
return cell
case .value:
guard let cell = tableView.dequeueReusableCell(withIdentifier: Constants.reuseIdentifier) as? WPTableViewCell else {
return WPTableViewCell.init(style: .value1, reuseIdentifier: Constants.reuseIdentifier)
}
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch options[indexPath.row].id {
case .title:
break
case .tags:
didTapTagCell()
case .visibility:
didTapVisibilityCell()
case .schedule:
didTapSchedule(indexPath)
case .categories:
didTapCategoriesCell()
}
}
private func reloadData() {
tableView.reloadData()
}
private func setupTextFieldCell(_ cell: WPTextFieldTableViewCell) {
WPStyleGuide.configureTableViewTextCell(cell)
cell.delegate = self
}
// MARK: - Title
private func configureTitleCell(_ cell: WPTextFieldTableViewCell) {
cell.textField.text = post.postTitle
cell.textField.adjustsFontForContentSizeCategory = true
cell.textField.font = .preferredFont(forTextStyle: .body)
cell.textField.textColor = .text
cell.textField.placeholder = Constants.titlePlaceholder
cell.textField.heightAnchor.constraint(equalToConstant: 40).isActive = true
cell.textField.autocorrectionType = .yes
cell.textField.autocapitalizationType = .sentences
titleField = cell.textField
}
// MARK: - Tags
private func configureTagCell(_ cell: WPTableViewCell) {
cell.detailTextLabel?.text = post.tags
}
private func didTapTagCell() {
let tagPickerViewController = PostTagPickerViewController(tags: post.tags ?? "", blog: post.blog)
tagPickerViewController.onValueChanged = { [weak self] tags in
WPAnalytics.track(.editorPostTagsChanged, properties: Constants.analyticsDefaultProperty)
self?.post.tags = tags
self?.reloadData()
}
tagPickerViewController.onContentViewHeightDetermined = { [weak self] in
self?.presentedVC?.containerViewWillLayoutSubviews()
}
navigationController?.pushViewController(tagPickerViewController, animated: true)
}
private func configureCategoriesCell(_ cell: WPTableViewCell) {
cell.detailTextLabel?.text = post.categories?.array.map { $0.categoryName }.joined(separator: ",")
}
private func didTapCategoriesCell() {
let categoriesViewController = PostCategoriesViewController(blog: post.blog, currentSelection: post.categories?.array, selectionMode: .post)
categoriesViewController.delegate = self
categoriesViewController.onCategoriesChanged = { [weak self] in
self?.presentedVC?.containerViewWillLayoutSubviews()
self?.tableView.reloadData()
}
categoriesViewController.onTableViewHeightDetermined = { [weak self] in
self?.presentedVC?.containerViewWillLayoutSubviews()
}
navigationController?.pushViewController(categoriesViewController, animated: true)
}
// MARK: - Visibility
private func configureVisibilityCell(_ cell: WPTableViewCell) {
cell.detailTextLabel?.text = post.titleForVisibility
}
private func didTapVisibilityCell() {
let visbilitySelectorViewController = PostVisibilitySelectorViewController(post)
visbilitySelectorViewController.completion = { [weak self] option in
self?.reloadData()
self?.updatePublishButtonLabel()
WPAnalytics.track(.editorPostVisibilityChanged, properties: Constants.analyticsDefaultProperty)
// If tue user selects password protected, prompt for a password
if option == AbstractPost.passwordProtectedLabel {
self?.showPasswordAlert()
} else {
self?.navigationController?.popViewController(animated: true)
}
}
navigationController?.pushViewController(visbilitySelectorViewController, animated: true)
}
// MARK: - Schedule
func configureScheduleCell(_ cell: WPTableViewCell) {
cell.textLabel?.text = post.shouldPublishImmediately() ? Constants.publishDateLabel : Constants.scheduledLabel
cell.detailTextLabel?.text = publishSettingsViewModel.detailString
post.status == .publishPrivate ? cell.disable() : cell.enable()
}
func didTapSchedule(_ indexPath: IndexPath) {
transitionIfVoiceOverDisabled(to: .hidden)
let viewController = PresentableSchedulingViewControllerProvider.viewController(
sourceView: tableView.cellForRow(at: indexPath)?.contentView,
sourceRect: nil,
viewModel: publishSettingsViewModel,
transitioningDelegate: nil,
updated: { [weak self] date in
WPAnalytics.track(.editorPostScheduledChanged, properties: Constants.analyticsDefaultProperty)
self?.publishSettingsViewModel.setDate(date)
self?.reloadData()
self?.updatePublishButtonLabel()
},
onDismiss: { [weak self] in
self?.reloadData()
self?.transitionIfVoiceOverDisabled(to: .collapsed)
}
)
present(viewController, animated: true)
}
// MARK: - Publish Button
private func setupPublishButton() {
let footer = UIView(frame: Constants.footerFrame)
footer.addSubview(publishButton)
footer.pinSubviewToSafeArea(publishButton, insets: Constants.nuxButtonInsets)
publishButton.translatesAutoresizingMaskIntoConstraints = false
tableView.tableFooterView = footer
publishButton.addTarget(self, action: #selector(publish(_:)), for: .touchUpInside)
updatePublishButtonLabel()
}
private func setupFooterSeparator() {
guard let footer = tableView.tableFooterView else {
return
}
let separator = UIView()
separator.translatesAutoresizingMaskIntoConstraints = false
footer.addSubview(separator)
NSLayoutConstraint.activate([
separator.topAnchor.constraint(equalTo: footer.topAnchor),
separator.leftAnchor.constraint(equalTo: footer.leftAnchor),
separator.rightAnchor.constraint(equalTo: footer.rightAnchor),
separator.heightAnchor.constraint(equalToConstant: 1)
])
WPStyleGuide.applyBorderStyle(separator)
}
private func updatePublishButtonLabel() {
publishButton.setTitle(post.isScheduled() ? Constants.scheduleNow : Constants.publishNow, for: .normal)
}
@objc func publish(_ sender: UIButton) {
didTapPublish = true
navigationController?.dismiss(animated: true) {
WPAnalytics.track(.editorPostPublishNowTapped)
self.completion(.completed(self.post))
}
}
// MARK: - Password Prompt
private func showPasswordAlert() {
let passwordAlertController = PasswordAlertController(onSubmit: { [weak self] password in
guard let password = password, !password.isEmpty else {
self?.cancelPasswordProtectedPost()
return
}
self?.post.password = password
self?.navigationController?.popViewController(animated: true)
}, onCancel: { [weak self] in
self?.cancelPasswordProtectedPost()
})
passwordAlertController.show(from: self)
}
private func cancelPasswordProtectedPost() {
post.status = .publish
post.password = nil
reloadData()
}
// MARK: - Accessibility
private func announcePublishButton() {
DispatchQueue.main.asyncAfter(deadline: .now()) {
UIAccessibility.post(notification: .screenChanged, argument: self.publishButton)
}
}
/// Only perform a transition if Voice Over is disabled
/// This avoids some unresponsiveness
private func transitionIfVoiceOverDisabled(to position: DrawerPosition) {
guard !UIAccessibility.isVoiceOverRunning else {
return
}
presentedVC?.transition(to: position)
}
fileprivate enum Constants {
static let reuseIdentifier = "wpTableViewCell"
static let headerReuseIdentifier = "wpTableViewHeader"
static let textFieldReuseIdentifier = "wpTextFieldCell"
static let nuxButtonInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
static let cellMargins = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
static let footerFrame = CGRect(x: 0, y: 0, width: 100, height: 80)
static let publishNow = NSLocalizedString("Publish Now", comment: "Label for a button that publishes the post")
static let scheduleNow = NSLocalizedString("Schedule Now", comment: "Label for the button that schedules the post")
static let publishDateLabel = NSLocalizedString("Publish Date", comment: "Label for Publish date")
static let scheduledLabel = NSLocalizedString("Scheduled for", comment: "Scheduled for [date]")
static let titlePlaceholder = NSLocalizedString("Title", comment: "Placeholder for title")
static let analyticsDefaultProperty = ["via": "prepublishing_nudges"]
}
}
extension PrepublishingViewController: PrepublishingHeaderViewDelegate {
func closeButtonTapped() {
dismiss(animated: true)
}
}
extension PrepublishingViewController: PrepublishingDismissible {
func handleDismiss() {
defer { completion(.dismissed) }
guard
!didTapPublish,
post.status == .publishPrivate,
let originalStatus = post.original?.status else {
return
}
post.status = originalStatus
}
}
extension PrepublishingViewController: WPTextFieldTableViewCellDelegate {
func cellWants(toSelectNextField cell: WPTextFieldTableViewCell!) {
}
func cellTextDidChange(_ cell: WPTextFieldTableViewCell!) {
WPAnalytics.track(.editorPostTitleChanged, properties: Constants.analyticsDefaultProperty)
post.postTitle = cell.textField.text
}
}
extension PrepublishingViewController: PostCategoriesViewControllerDelegate {
func postCategoriesViewController(_ controller: PostCategoriesViewController, didUpdateSelectedCategories categories: NSSet) {
WPAnalytics.track(.editorPostCategoryChanged, properties: ["via": "prepublishing_nudges"])
// Save changes.
guard let categories = categories as? Set<PostCategory> else {
return
}
post.categories = categories
post.save()
}
}
extension Set {
var array: [Element] {
return Array(self)
}
}
// MARK: - DrawerPresentable
extension PrepublishingViewController: DrawerPresentable {
var allowsUserTransition: Bool {
return keyboardShown == false
}
var collapsedHeight: DrawerHeight {
return .intrinsicHeight
}
}
private extension PrepublishingOption {
init(identifier: PrepublishingIdentifier) {
switch identifier {
case .title:
self.init(id: .title, title: PrepublishingViewController.Constants.titlePlaceholder, type: .textField)
case .schedule:
self.init(id: .schedule, title: PrepublishingViewController.Constants.publishDateLabel, type: .value)
case .categories:
self.init(id: .categories, title: NSLocalizedString("Categories", comment: "Label for Categories"), type: .value)
case .visibility:
self.init(id: .visibility, title: NSLocalizedString("Visibility", comment: "Label for Visibility"), type: .value)
case .tags:
self.init(id: .tags, title: NSLocalizedString("Tags", comment: "Label for Tags"), type: .value)
}
}
}
|
gpl-2.0
|
38e4ad4f72b4bcf9209c62f79df3c3b6
| 34.445076 | 148 | 0.669036 | 5.427784 | false | false | false | false |
oisinlavery/HackingWithSwift
|
project5-oisin/project5-oisin/AppDelegate.swift
|
1
|
3241
|
//
// AppDelegate.swift
// project5-oisin
//
// Created by Oisín Lavery on 10/3/15.
// Copyright © 2015 Oisín Lavery. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
|
unlicense
|
708e188896ab72a4a987b95136231929
| 52.081967 | 281 | 0.788141 | 5.985213 | false | false | false | false |
zixun/GodEye
|
Core/AppBaseKit/Classes/Extension/UIKit/UIColor+AppBaseKit.swift
|
1
|
3293
|
//
// UIColor+AppBaseKit.swift
// Pods
//
// Created by zixun on 16/9/25.
//
//
import Foundation
import UIKit
extension UIColor {
public class func niceBlack() -> UIColor {
return UIColor(red: 30.0/255.0, green: 32.0/255.0, blue: 40.0/255.0, alpha: 1)
}
public class func niceDuckBlack() -> UIColor {
return UIColor(red: 20.0/255.0, green: 21.0/255.0, blue: 27.0/255.0, alpha: 1)
}
public class func niceRed() -> UIColor {
return UIColor(red: 237.0/255.0, green: 66.0/255.0, blue: 82.0/255.0, alpha: 1)
}
public class func niceJHSRed() -> UIColor {
return UIColor(red: 235.0/255.0, green: 0.0/255.0, blue: 18.0/255.0, alpha: 1)
}
}
// MARK: - RGB
extension UIColor {
public convenience init(hex:Int, alpha:CGFloat = 1.0) {
let red: CGFloat = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let green: CGFloat = CGFloat((hex & 0x00FF00) >> 8) / 255.0
let blue: CGFloat = CGFloat((hex & 0x0000FF)) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
public convenience init?(hexString:String,alpha:CGFloat = 1.0) {
let formatted = hexString.replacingOccurrences(of: "0x", with: "")
.replacingOccurrences(of:"#", with: "")
if let hex = Int(formatted, radix: 16) {
self.init(hex: hex, alpha: alpha)
}
return nil
}
public func hexString(prefix:String = "") -> String {
let rgbFloat = self.rgba()
let result = self.string(of: rgbFloat.r) + self.string(of: rgbFloat.g) + self.string(of: rgbFloat.b)
return prefix + result.uppercased()
}
private func string(of component:Int) -> String {
var result = String(format: "%x", component)
let count = result.count
if count == 0 {
return "00"
}else if count == 1 {
return "0" + result
}else {
return result
}
}
public func hex() -> Int? {
return Int(self.hexString(), radix: 16)
}
public func rgba() -> (r:Int,g:Int,b:Int,a:CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
r = r * 255
g = g * 255
b = b * 255
return (Int(r),Int(g),Int(b),a)
}
}
// MARK: - Gradient
extension UIColor {
public class func gradient(startColor:UIColor,endColor:UIColor,fraction:CGFloat) -> UIColor {
var startR: CGFloat = 0, startG: CGFloat = 0, startB: CGFloat = 0, startA: CGFloat = 0
startColor.getRed(&startR, green: &startG, blue: &startB, alpha: &startA)
var endR: CGFloat = 0, endG: CGFloat = 0, endB: CGFloat = 0, endA: CGFloat = 0
endColor.getRed(&endR, green: &endG, blue: &endB, alpha: &endA)
let resultA = startA + (endA - startA) * fraction
let resultR = startR + (endR - startR) * fraction
let resultG = startG + (endG - startG) * fraction
let resultB = startB + (endB - startB) * fraction
return UIColor(red: resultR, green: resultG, blue: resultB, alpha: resultA)
}
}
|
mit
|
002264d080bbe7c6d3d8f9e0d3d1f02b
| 30.361905 | 108 | 0.553902 | 3.466316 | false | false | false | false |
poulpix/PXGoogleDirections
|
Sources/PXGoogleDirections/PXGoogleDirectionsRoute.swift
|
2
|
6132
|
//
// PXGoogleDirectionsRoute.swift
// PXGoogleDirections
//
// Created by Romain on 04/03/2015.
// Copyright (c) 2015 RLT. All rights reserved.
//
import Foundation
import GoogleMaps
/// A route computed by the Google Directions API, following a directions request. A route consists of nested legs and steps.
public class PXGoogleDirectionsRoute: NSObject {
/// Short textual description for the route, suitable for naming and disambiguating the route from alternatives
public var summary: String?
/// Array which contains information about a leg of the route, between two locations within the given route (a separate leg will be present for each waypoint or destination specified: a route with no waypoints will contain exactly one leg within the legs array) ; each leg consists of a series of steps
public var legs: [PXGoogleDirectionsRouteLeg] = [PXGoogleDirectionsRouteLeg]()
/// Array indicating the order of any waypoints in the calculated route (waypoints may be reordered if the request was passed optimize:true within its waypoints parameter)
public var waypointsOrder: [Int] = [Int]()
/// Holds an encoded polyline representation of the route (this polyline is an approximate/smoothed path of the resulting directions)
public var overviewPolyline: String?
/// Viewport bounding box of the `overviewPolyline`
public var bounds: GMSCoordinateBounds?
/// Copyrights text to be displayed for this route
public var copyrights: String?
/// Array of warnings to be displayed when showing these directions
public var warnings: [String] = [String]()
/// Contains the total fare (that is, the total ticket costs) on this route (only valid for transit requests and routes where fare information is available for all transit legs)
public var fare: PXGoogleDirectionsRouteFare?
/// Returns the corresponding `GMSPath` object associated with this route
public var path: GMSPath? {
if let op = overviewPolyline {
return GMSPath(fromEncodedPath: op)
} else {
return nil
}
}
/// Returns a detailed `GMSPath` object built from the legs and steps composing the route
public var detailedPath: GMSPath? {
let dp = GMSMutablePath()
for l in legs {
for s in l.steps {
if let sl = s.startLocation {
dp.add(sl)
}
if let spl = s.polyline, let subpath = GMSPath(fromEncodedPath: spl) {
for i in 0 ..< subpath.count() {
dp.add(subpath.coordinate(at: i))
}
}
if let el = s.endLocation {
dp.add(el)
}
}
}
return (dp.count() > 0 ? dp : path)
}
/// Returns the route's total duration, in seconds
public var totalDuration: TimeInterval {
get {
var td = 0 as TimeInterval
for l in legs {
guard let ld = l.duration, let d = ld.duration else {
break
}
td += d
}
return td
}
}
/// Returns the route's total distance, in meters
public var totalDistance: CLLocationDistance {
get {
var td = 0 as CLLocationDistance
for l in legs {
guard let ld = l.distance, let d = ld.distance else {
break
}
td += d
}
return td
}
}
/**
Draws the route on the specified Google Maps map view.
- parameter map: A `GMSMapView` object on which the route should be drawn
- parameter approximate: `true` if the route should be drawn using rough directions, `false` otherwise ; `false` by default but has a performance impact
- parameter strokeColor: The optional route stroke color
- parameter strokeWidth: The optional route stroke width
- returns: The resulting `GMSPolyline` object that was drawn to the map
*/
@discardableResult public func drawOnMap(_ map: GMSMapView, approximate: Bool = false, strokeColor: UIColor = UIColor.red, strokeWidth: Float = 2.0) -> GMSPolyline {
let polyline = GMSPolyline(path: (approximate ? path : detailedPath))
polyline.strokeColor = strokeColor
polyline.strokeWidth = CGFloat(strokeWidth)
polyline.map = map
return polyline
}
/**
Draws a marker representing the origin of the route on the specified Google Maps map view.
- parameter map: A `GMSMapView` object on which the marker should be drawn
- parameter title: An optional marker title
- parameter color: An optional marker color
- parameter opacity: An optional marker specific opacity
- parameter flat: An optional indicator to flatten the marker
- returns: The resulting `GMSMarker` object that was drawn to the map
*/
@discardableResult public func drawOriginMarkerOnMap(_ map: GMSMapView, title: String = "", color: UIColor = UIColor.red, opacity: Float = 1.0, flat: Bool = false) -> GMSMarker? {
var marker: GMSMarker?
if let p = path {
if p.count() > 1 {
marker = drawMarkerWithCoordinates(p.coordinate(at: 0), onMap: map, title: title, color: color, opacity: opacity, flat: flat)
}
}
return marker
}
/**
Draws a marker representing the destination of the route on the specified Google Maps map view.
- parameter map: A `GMSMapView` object on which the marker should be drawn
- parameter title: An optional marker title
- parameter color: An optional marker color
- parameter opacity: An optional marker specific opacity
- parameter flat: An optional indicator to flatten the marker
- returns: The resulting `GMSMarker` object that was drawn to the map
*/
@discardableResult public func drawDestinationMarkerOnMap(_ map: GMSMapView, title: String = "", color: UIColor = UIColor.red, opacity: Float = 1.0, flat: Bool = false) -> GMSMarker? {
var marker: GMSMarker?
if let p = path {
if p.count() > 1 {
marker = drawMarkerWithCoordinates(p.coordinate(at: p.count() - 1), onMap: map, title: title, color: color, opacity: opacity, flat: flat)
}
}
return marker
}
// MARK: Private functions
fileprivate func drawMarkerWithCoordinates(_ coordinates: CLLocationCoordinate2D, onMap map: GMSMapView, title: String = "", color: UIColor = UIColor.red, opacity: Float = 1.0, flat: Bool = false) -> GMSMarker {
let marker = GMSMarker(position: coordinates)
marker.title = title
marker.icon = GMSMarker.markerImage(with: color)
marker.opacity = opacity
marker.isFlat = flat
marker.map = map
return marker
}
}
|
bsd-3-clause
|
bb24c5f31b8d144ccd7a938f1a15d163
| 39.078431 | 303 | 0.723418 | 3.885932 | false | false | false | false |
OneBestWay/EasyCode
|
BPNetwork/Pods/PromiseKit/Categories/UIKit/UIViewController+Promise.swift
|
1
|
5939
|
import Foundation.NSError
import UIKit
#if !COCOAPODS
import PromiseKit
#endif
/**
To import this `UIViewController` category:
use_frameworks!
pod "PromiseKit/UIKit"
Or `UIKit` is one of the categories imported by the umbrella pod:
use_frameworks!
pod "PromiseKit"
And then in your sources:
import PromiseKit
*/
extension UIViewController {
public enum PMKError: ErrorType {
case NavigationControllerEmpty
case NoImageFound
case NotPromisable
case NotGenericallyPromisable
case NilPromisable
}
public enum FulfillmentType {
case OnceDisappeared
case BeforeDismissal
}
@available(*, deprecated=3.4, renamed="promiseViewController(_:animate:fulfills:completion:)")
public func promiseViewController<T>(vc: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<T> {
return promiseViewController(vc, animate: [.Appear, .Disappear], completion: completion)
}
public func promiseViewController<T>(vc: UIViewController, animate animationOptions: PMKAnimationOptions = [.Appear, .Disappear], fulfills fulfillmentType: FulfillmentType = .OnceDisappeared, completion: (() -> Void)? = nil) -> Promise<T> {
let pvc: UIViewController
switch vc {
case let nc as UINavigationController:
guard let vc = nc.viewControllers.first else { return Promise(error: PMKError.NavigationControllerEmpty) }
pvc = vc
default:
pvc = vc
}
let promise: Promise<T>
if !pvc.conformsToProtocol(Promisable) {
promise = Promise(error: PMKError.NotPromisable)
} else if let p = pvc.valueForKeyPath("promise") as? Promise<T> {
promise = p
} else if let _: AnyObject = pvc.valueForKeyPath("promise") {
promise = Promise(error: PMKError.NotGenericallyPromisable)
} else {
promise = Promise(error: PMKError.NilPromisable)
}
if !promise.pending {
return promise
}
presentViewController(vc, animated: animationOptions.contains(.Appear), completion: completion)
let (wrappingPromise, fulfill, reject) = Promise<T>.pendingPromise()
switch fulfillmentType {
case .OnceDisappeared:
promise.then { result in
vc.presentingViewController?.dismissViewControllerAnimated(animationOptions.contains(.Disappear), completion: { fulfill(result) })
}
.error(policy: .AllErrors) { error in
vc.presentingViewController?.dismissViewControllerAnimated(animationOptions.contains(.Disappear), completion: { reject(error) })
}
case .BeforeDismissal:
promise.then { result -> Void in
fulfill(result)
vc.presentingViewController?.dismissViewControllerAnimated(animationOptions.contains(.Disappear), completion: nil)
}
.error(policy: .AllErrors) { error in
reject(error)
vc.presentingViewController?.dismissViewControllerAnimated(animationOptions.contains(.Disappear), completion: nil)
}
}
return wrappingPromise
}
public func promiseViewController(vc: UIImagePickerController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<UIImage> {
let proxy = UIImagePickerControllerProxy()
vc.delegate = proxy
vc.mediaTypes = ["public.image"] // this promise can only resolve with a UIImage
presentViewController(vc, animated: animated, completion: completion)
return proxy.promise.then(on: zalgo) { info -> UIImage in
if let img = info[UIImagePickerControllerEditedImage] as? UIImage {
return img
}
if let img = info[UIImagePickerControllerOriginalImage] as? UIImage {
return img
}
throw PMKError.NoImageFound
}.always {
vc.presentingViewController?.dismissViewControllerAnimated(animated, completion: nil)
}
}
public func promiseViewController(vc: UIImagePickerController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<[String: AnyObject]> {
let proxy = UIImagePickerControllerProxy()
vc.delegate = proxy
presentViewController(vc, animated: animated, completion: completion)
return proxy.promise.always {
vc.presentingViewController?.dismissViewControllerAnimated(animated, completion: nil)
}
}
}
@objc(Promisable) public protocol Promisable {
/**
Provide a promise for promiseViewController here.
The resulting property must be annotated with @objc.
Obviously return a Promise<T>. There is an issue with generics and Swift and
protocols currently so we couldn't specify that.
*/
var promise: AnyObject! { get }
}
// internal scope because used by ALAssetsLibrary extension
@objc class UIImagePickerControllerProxy: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let (promise, fulfill, reject) = Promise<[String : AnyObject]>.pendingPromise()
var retainCycle: AnyObject?
required override init() {
super.init()
retainCycle = self
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
fulfill(info)
retainCycle = nil
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
reject(UIImagePickerController.Error.Cancelled)
retainCycle = nil
}
}
extension UIImagePickerController {
public enum Error: CancellableErrorType {
case Cancelled
public var cancelled: Bool {
switch self {
case .Cancelled: return true
}
}
}
}
|
mit
|
d9712e9f659fac7d87e2fb7c763ea7a1
| 34.142012 | 244 | 0.657855 | 5.340827 | false | false | false | false |
wackosix/WSNetEaseNews
|
NetEaseNews/Classes/External/PhotoBrowser/Frameworks/CFSnapKit/Source/View+SnapKit.swift
|
1
|
8559
|
//
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
public typealias View = UIView
#else
import AppKit
public typealias View = NSView
#endif
/**
Used to expose public API on views
*/
public extension View {
/// left edge
public var snp_left: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Left) }
/// top edge
public var snp_top: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Top) }
/// right edge
public var snp_right: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Right) }
/// bottom edge
public var snp_bottom: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Bottom) }
/// leading edge
public var snp_leading: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Leading) }
/// trailing edge
public var snp_trailing: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Trailing) }
/// width dimension
public var snp_width: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Width) }
/// height dimension
public var snp_height: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Height) }
/// centerX position
public var snp_centerX: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterX) }
/// centerY position
public var snp_centerY: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterY) }
/// baseline position
public var snp_baseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Baseline) }
/// first baseline position
@available(iOS 8.0, *)
public var snp_firstBaseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.FirstBaseline) }
/// left margin
@available(iOS 8.0, *)
public var snp_leftMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeftMargin) }
/// right margin
@available(iOS 8.0, *)
public var snp_rightMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.RightMargin) }
/// top margin
@available(iOS 8.0, *)
public var snp_topMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TopMargin) }
/// bottom margin
@available(iOS 8.0, *)
public var snp_bottomMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.BottomMargin) }
/// leading margin
@available(iOS 8.0, *)
public var snp_leadingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeadingMargin) }
/// trailing margin
@available(iOS 8.0, *)
public var snp_trailingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TrailingMargin) }
/// centerX within margins
@available(iOS 8.0, *)
public var snp_centerXWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterXWithinMargins) }
/// centerY within margins
@available(iOS 8.0, *)
public var snp_centerYWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterYWithinMargins) }
// top + left + bottom + right edges
public var snp_edges: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Edges) }
// width + height dimensions
public var snp_size: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Size) }
// centerX + centerY positions
public var snp_center: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Center) }
// top + left + bottom + right margins
@available(iOS 8.0, *)
public var snp_margins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Margins) }
// centerX + centerY within margins
@available(iOS 8.0, *)
public var snp_centerWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterWithinMargins) }
/**
Prepares constraints with a `ConstraintMaker` and returns the made constraints but does not install them.
:param: closure that will be passed the `ConstraintMaker` to make the constraints with
:returns: the constraints made
*/
public func snp_prepareConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> [Constraint] {
return ConstraintMaker.prepareConstraints(view: self, location: SourceLocation(file: file, line: line), closure: closure)
}
/**
Makes constraints with a `ConstraintMaker` and installs them along side any previous made constraints.
:param: closure that will be passed the `ConstraintMaker` to make the constraints with
*/
public func snp_makeConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.makeConstraints(view: self, location: SourceLocation(file: file, line: line), closure: closure)
}
/**
Updates constraints with a `ConstraintMaker` that will replace existing constraints that match and install new ones.
For constraints to match only the constant can be updated.
:param: closure that will be passed the `ConstraintMaker` to update the constraints with
*/
public func snp_updateConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.updateConstraints(view: self, location: SourceLocation(file: file, line: line), closure: closure)
}
/**
Remakes constraints with a `ConstraintMaker` that will first remove all previously made constraints and make and install new ones.
:param: closure that will be passed the `ConstraintMaker` to remake the constraints with
*/
public func snp_remakeConstraints(file: String = #file, line: UInt = #line, @noescape closure: (make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.remakeConstraints(view: self, location: SourceLocation(file: file, line: line), closure: closure)
}
/**
Removes all previously made constraints.
*/
public func snp_removeConstraints() {
ConstraintMaker.removeConstraints(view: self)
}
internal var snp_installedLayoutConstraints: [LayoutConstraint] {
get {
if let constraints = objc_getAssociatedObject(self, &installedLayoutConstraintsKey) as? [LayoutConstraint] {
return constraints
}
return []
}
set {
objc_setAssociatedObject(self, &installedLayoutConstraintsKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private var installedLayoutConstraintsKey = ""
|
mit
|
1669d3880ccb7f87fd967c436ee33967
| 45.770492 | 150 | 0.713868 | 5.037669 | false | false | false | false |
tristanchu/FlavorFinder
|
FlavorFinder/Pods/DOFavoriteButton/DOFavoriteButton/DOFavoriteButton.swift
|
1
|
15582
|
//
// DOFavoriteButton.swift
// DOFavoriteButton
//
// Created by Daiki Okumura on 2015/07/09.
// Copyright (c) 2015 Daiki Okumura. All rights reserved.
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
import UIKit
@IBDesignable
public class DOFavoriteButton: UIButton {
private var imageShape: CAShapeLayer!
@IBInspectable public var image: UIImage! {
didSet {
createLayers(image)
}
}
@IBInspectable public var imageColorOn: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
if (selected) {
imageShape.fillColor = imageColorOn.CGColor
}
}
}
@IBInspectable public var imageColorOff: UIColor! = UIColor(red: 136/255, green: 153/255, blue: 166/255, alpha: 1.0) {
didSet {
if (!selected) {
imageShape.fillColor = imageColorOff.CGColor
}
}
}
private var circleShape: CAShapeLayer!
private var circleMask: CAShapeLayer!
@IBInspectable public var circleColor: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
circleShape.fillColor = circleColor.CGColor
}
}
private var lines: [CAShapeLayer]!
@IBInspectable public var lineColor: UIColor! = UIColor(red: 250/255, green: 120/255, blue: 68/255, alpha: 1.0) {
didSet {
for line in lines {
line.strokeColor = lineColor.CGColor
}
}
}
private let circleTransform = CAKeyframeAnimation(keyPath: "transform")
private let circleMaskTransform = CAKeyframeAnimation(keyPath: "transform")
private let lineStrokeStart = CAKeyframeAnimation(keyPath: "strokeStart")
private let lineStrokeEnd = CAKeyframeAnimation(keyPath: "strokeEnd")
private let lineOpacity = CAKeyframeAnimation(keyPath: "opacity")
private let imageTransform = CAKeyframeAnimation(keyPath: "transform")
@IBInspectable public var duration: Double = 1.0 {
didSet {
circleTransform.duration = 0.333 * duration // 0.0333 * 10
circleMaskTransform.duration = 0.333 * duration // 0.0333 * 10
lineStrokeStart.duration = 0.6 * duration //0.0333 * 18
lineStrokeEnd.duration = 0.6 * duration //0.0333 * 18
lineOpacity.duration = 1.0 * duration //0.0333 * 30
imageTransform.duration = 1.0 * duration //0.0333 * 30
}
}
override public var selected : Bool {
didSet {
if (selected != oldValue) {
if selected {
imageShape.fillColor = imageColorOn.CGColor
} else {
deselect()
}
}
}
}
public convenience init() {
self.init(frame: CGRectZero)
}
public override convenience init(frame: CGRect) {
self.init(frame: frame, image: UIImage())
}
public init(frame: CGRect, image: UIImage!) {
super.init(frame: frame)
self.image = image
createLayers(image)
addTargets()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createLayers(UIImage())
addTargets()
}
private func createLayers(image: UIImage!) {
self.layer.sublayers = nil
let imageFrame = CGRectMake(frame.size.width / 2 - frame.size.width / 4, frame.size.height / 2 - frame.size.height / 4, frame.size.width / 2, frame.size.height / 2)
let imgCenterPoint = CGPointMake(CGRectGetMidX(imageFrame), CGRectGetMidY(imageFrame))
let lineFrame = CGRectMake(imageFrame.origin.x - imageFrame.width / 4, imageFrame.origin.y - imageFrame.height / 4 , imageFrame.width * 1.5, imageFrame.height * 1.5)
//===============
// circle layer
//===============
circleShape = CAShapeLayer()
circleShape.bounds = imageFrame
circleShape.position = imgCenterPoint
circleShape.path = UIBezierPath(ovalInRect: imageFrame).CGPath
circleShape.fillColor = circleColor.CGColor
circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 1.0)
self.layer.addSublayer(circleShape)
circleMask = CAShapeLayer()
circleMask.bounds = imageFrame
circleMask.position = imgCenterPoint
circleMask.fillRule = kCAFillRuleEvenOdd
circleShape.mask = circleMask
let maskPath = UIBezierPath(rect: imageFrame)
maskPath.addArcWithCenter(imgCenterPoint, radius: 0.1, startAngle: CGFloat(0.0), endAngle: CGFloat(M_PI * 2), clockwise: true)
circleMask.path = maskPath.CGPath
//===============
// line layer
//===============
lines = []
for i in 0 ..< 5 {
let line = CAShapeLayer()
line.bounds = lineFrame
line.position = imgCenterPoint
line.masksToBounds = true
line.actions = ["strokeStart": NSNull(), "strokeEnd": NSNull()]
line.strokeColor = lineColor.CGColor
line.lineWidth = 1.25
line.miterLimit = 1.25
line.path = {
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, CGRectGetMidX(lineFrame), CGRectGetMidY(lineFrame))
CGPathAddLineToPoint(path, nil, lineFrame.origin.x + lineFrame.width / 2, lineFrame.origin.y)
return path
}()
line.lineCap = kCALineCapRound
line.lineJoin = kCALineJoinRound
line.strokeStart = 0.0
line.strokeEnd = 0.0
line.opacity = 0.0
line.transform = CATransform3DMakeRotation(CGFloat(M_PI) / 5 * (CGFloat(i) * 2 + 1), 0.0, 0.0, 1.0)
self.layer.addSublayer(line)
lines.append(line)
}
//===============
// image layer
//===============
imageShape = CAShapeLayer()
imageShape.bounds = imageFrame
imageShape.position = imgCenterPoint
imageShape.path = UIBezierPath(rect: imageFrame).CGPath
imageShape.fillColor = imageColorOff.CGColor
imageShape.actions = ["fillColor": NSNull()]
self.layer.addSublayer(imageShape)
imageShape.mask = CALayer()
imageShape.mask!.contents = image.CGImage
imageShape.mask!.bounds = imageFrame
imageShape.mask!.position = imgCenterPoint
//==============================
// circle transform animation
//==============================
circleTransform.duration = 0.333 // 0.0333 * 10
circleTransform.values = [
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/10
NSValue(CATransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)), // 1/10
NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), // 2/10
NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 3/10
NSValue(CATransform3D: CATransform3DMakeScale(1.3, 1.3, 1.0)), // 4/10
NSValue(CATransform3D: CATransform3DMakeScale(1.37, 1.37, 1.0)), // 5/10
NSValue(CATransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)), // 6/10
NSValue(CATransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)) // 10/10
]
circleTransform.keyTimes = [
0.0, // 0/10
0.1, // 1/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
1.0 // 10/10
]
circleMaskTransform.duration = 0.333 // 0.0333 * 10
circleMaskTransform.values = [
NSValue(CATransform3D: CATransform3DIdentity), // 0/10
NSValue(CATransform3D: CATransform3DIdentity), // 2/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 1.25, imageFrame.height * 1.25, 1.0)), // 3/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 2.688, imageFrame.height * 2.688, 1.0)), // 4/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 3.923, imageFrame.height * 3.923, 1.0)), // 5/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 4.375, imageFrame.height * 4.375, 1.0)), // 6/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 4.731, imageFrame.height * 4.731, 1.0)), // 7/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)), // 9/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)) // 10/10
]
circleMaskTransform.keyTimes = [
0.0, // 0/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
0.7, // 7/10
0.9, // 9/10
1.0 // 10/10
]
//==============================
// line stroke animation
//==============================
lineStrokeStart.duration = 0.6 //0.0333 * 18
lineStrokeStart.values = [
0.0, // 0/18
0.0, // 1/18
0.18, // 2/18
0.2, // 3/18
0.26, // 4/18
0.32, // 5/18
0.4, // 6/18
0.6, // 7/18
0.71, // 8/18
0.89, // 17/18
0.92 // 18/18
]
lineStrokeStart.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.333, // 6/18
0.389, // 7/18
0.444, // 8/18
0.944, // 17/18
1.0, // 18/18
]
lineStrokeEnd.duration = 0.6 //0.0333 * 18
lineStrokeEnd.values = [
0.0, // 0/18
0.0, // 1/18
0.32, // 2/18
0.48, // 3/18
0.64, // 4/18
0.68, // 5/18
0.92, // 17/18
0.92 // 18/18
]
lineStrokeEnd.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.944, // 17/18
1.0, // 18/18
]
lineOpacity.duration = 1.0 //0.0333 * 30
lineOpacity.values = [
1.0, // 0/30
1.0, // 12/30
0.0 // 17/30
]
lineOpacity.keyTimes = [
0.0, // 0/30
0.4, // 12/30
0.567 // 17/30
]
//==============================
// image transform animation
//==============================
imageTransform.duration = 1.0 //0.0333 * 30
imageTransform.values = [
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/30
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 3/30
NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 9/30
NSValue(CATransform3D: CATransform3DMakeScale(1.25, 1.25, 1.0)), // 10/30
NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 11/30
NSValue(CATransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 14/30
NSValue(CATransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 15/30
NSValue(CATransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 16/30
NSValue(CATransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 17/30
NSValue(CATransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 20/30
NSValue(CATransform3D: CATransform3DMakeScale(1.025, 1.025, 1.0)), // 21/30
NSValue(CATransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 22/30
NSValue(CATransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 25/30
NSValue(CATransform3D: CATransform3DMakeScale(0.95, 0.95, 1.0)), // 26/30
NSValue(CATransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 27/30
NSValue(CATransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)), // 29/30
NSValue(CATransform3D: CATransform3DIdentity) // 30/30
]
imageTransform.keyTimes = [
0.0, // 0/30
0.1, // 3/30
0.3, // 9/30
0.333, // 10/30
0.367, // 11/30
0.467, // 14/30
0.5, // 15/30
0.533, // 16/30
0.567, // 17/30
0.667, // 20/30
0.7, // 21/30
0.733, // 22/30
0.833, // 25/30
0.867, // 26/30
0.9, // 27/30
0.967, // 29/30
1.0 // 30/30
]
}
private func addTargets() {
//===============
// add target
//===============
self.addTarget(self, action: "touchDown:", forControlEvents: UIControlEvents.TouchDown)
self.addTarget(self, action: "touchUpInside:", forControlEvents: UIControlEvents.TouchUpInside)
self.addTarget(self, action: "touchDragExit:", forControlEvents: UIControlEvents.TouchDragExit)
self.addTarget(self, action: "touchDragEnter:", forControlEvents: UIControlEvents.TouchDragEnter)
self.addTarget(self, action: "touchCancel:", forControlEvents: UIControlEvents.TouchCancel)
}
func touchDown(sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchUpInside(sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragExit(sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragEnter(sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchCancel(sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
public func select() {
selected = true
imageShape.fillColor = imageColorOn.CGColor
CATransaction.begin()
circleShape.addAnimation(circleTransform, forKey: "transform")
circleMask.addAnimation(circleMaskTransform, forKey: "transform")
imageShape.addAnimation(imageTransform, forKey: "transform")
for i in 0 ..< 5 {
lines[i].addAnimation(lineStrokeStart, forKey: "strokeStart")
lines[i].addAnimation(lineStrokeEnd, forKey: "strokeEnd")
lines[i].addAnimation(lineOpacity, forKey: "opacity")
}
CATransaction.commit()
}
public func deselect() {
selected = false
imageShape.fillColor = imageColorOff.CGColor
// remove all animations
circleShape.removeAllAnimations()
circleMask.removeAllAnimations()
imageShape.removeAllAnimations()
lines[0].removeAllAnimations()
lines[1].removeAllAnimations()
lines[2].removeAllAnimations()
lines[3].removeAllAnimations()
lines[4].removeAllAnimations()
}
}
|
mit
|
7f63624237faba4ee14ec6806c099364
| 38.24937 | 173 | 0.534014 | 3.92 | false | false | false | false |
iAugux/iBBS-Swift
|
iBBS/Additions/DEBUGLog.swift
|
1
|
1022
|
//
// DEBUGLog.swift
//
// Created by Augus on 2/21/16.
// Copyright © 2016 iAugus. All rights reserved.
//
import Foundation
#if DEBUG
func DEBUGLog(message: String?, filename: NSString = #file, function: String = #function, line: Int = #line) {
NSLog("[\(filename.lastPathComponent):\(line)] \(function) - \(message.debugDescription)")
}
func DEBUGLog(message: AnyObject?, filename: NSString = #file, function: String = #function, line: Int = #line) {
NSLog("[\(filename.lastPathComponent):\(line)] \(function) - \(message.debugDescription)")
}
func DEBUGPrint(message: Any?) {
guard message != nil else { return }
print(message)
}
#else
func DEBUGLog(message: String?, filename: String = #file, function: String = #function, line: Int = #line) { }
func DEBUGLog(message: AnyObject?, filename: NSString = #file, function: String = #function, line: Int = #line) { }
func DEBUGPrint(message: Any?) { }
#endif
|
mit
|
dd8337741c11e773e8003e7867456ad5
| 29.969697 | 119 | 0.61998 | 3.972763 | false | false | false | false |
nessBautista/iOSBackup
|
iOSNotebook/Pods/Outlaw/Sources/Outlaw/Extractable+Value.swift
|
1
|
13475
|
//
// Extractable+Value.swift
// Outlaw
//
// Created by Brian Mullen on 11/5/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
// MARK: -
// MARK: Value
public extension Extractable {
public func value<V: Value>(for key: Key) throws -> V {
let any = try self.any(for: key)
do {
guard let result = try V.value(from: any) as? V else {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: V.self, actual: any)
}
return result
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value>(for key: Key) -> V? {
return try? self.value(for: key)
}
public func value<V: Value>(for key: Key, or value: V) -> V {
guard let result: V = self.value(for: key) else { return value }
return result
}
}
// MARK: -
// MARK: Transform Value
public extension Extractable {
public func value<V: Value, T>(for key: Key, with transform:(V) throws -> T) throws -> T {
let rawValue: V = try self.value(for: key)
return try transform(rawValue)
}
public func value<V: Value, T>(for key: Key, with transform:(V?) throws -> T) throws -> T {
let rawValue: V? = self.value(for: key)
return try transform(rawValue)
}
public func value<V: Value, T>(for key: Key, with transform:(V) -> T?) -> T? {
guard let rawValue: V = try? self.value(for: key) else { return nil }
return transform(rawValue)
}
public func value<V: Value, T>(for key: Key, with transform:(V?) -> T?) -> T? {
let rawValue: V? = self.value(for: key)
return transform(rawValue)
}
}
// MARK: -
// MARK: Array of Value's
public extension Extractable {
public func value<V: Value>(for key: Key) throws -> [V] {
let any = try self.any(for: key)
do {
return try Array<V>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value>(for key: Key) -> [V]? {
return try? self.value(for: key)
}
public func value<V: Value>(for key: Key, or value: [V]) -> [V] {
guard let result: [V] = self.value(for: key) else { return value }
return result
}
}
// MARK: -
// MARK: Array of Transformed Value's
public extension Extractable {
public func value<V: Value, T>(for key: Key, with transform:(V) throws -> T) throws -> [T] {
let any = try self.any(for: key)
do {
return try Array<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value, T>(for key: Key, with transform:(V) throws -> T) -> [T]? {
return try? self.value(for: key, with: transform)
}
public func value<V: Value, T>(for key: Key, with transform:(V?) throws -> T) throws -> [T] {
let any = try self.any(for: key)
do {
return try Array<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value, T>(for key: Key, with transform:(V?) throws -> T) -> [T]? {
return try? self.value(for: key, with: transform)
}
}
// MARK: -
// MARK: Array of Optional Value's
public extension Extractable {
public func value<V: Value>(for key: Key) throws -> [V?] {
let any = try self.any(for: key)
do {
return try Array<V?>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value>(for key: Key) -> [V?]? {
return try? self.value(for: key)
}
public func value<V: Value>(for key: Key, or value: [V?]) -> [V?] {
guard let result: [V?] = self.value(for: key) else { return value }
return result
}
}
// MARK: -
// MARK: Array of Transformed Optional Value's
public extension Extractable {
public func value<V: Value, T>(for key: Key, with transform:(V) -> T?) throws -> [T?] {
let any = try self.any(for: key)
do {
return try Array<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value, T>(for key: Key, with transform:(V) -> T?) -> [T?]? {
return try? self.value(for: key, with: transform)
}
public func value<V: Value, T>(for key: Key, with transform:(V?) -> T?) throws -> [T?] {
let any = try self.any(for: key)
do {
return try Array<V?>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value, T>(for key: Key, with transform:(V?) -> T?) -> [T?]? {
return try? self.value(for: key, with: transform)
}
}
// MARK: -
// MARK: Dictionary of Value's
public extension Extractable {
public func value<K, V: Value>(for key: Key) throws -> [K: V] {
let any = try self.any(for: key)
do {
return try Dictionary<K, V>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<K, V: Value>(for key: Key) -> [K: V]? {
return try? self.value(for: key)
}
public func value<K, V: Value>(for key: Key, or value: [K: V]) -> [K: V] {
guard let result: [K: V] = self.value(for: key) else { return value }
return result
}
}
// MARK: -
// MARK: Dictionary of Transformed Value's
public extension Extractable {
public func value<K, V: Value, T>(for key: Key, with transform:(V) throws -> T) throws -> [K: T] {
let any = try self.any(for: key)
do {
return try Dictionary<K, V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<K, V: Value, T>(for key: Key, with transform:(V) throws -> T) -> [K: T]? {
return try? self.value(for: key, with: transform)
}
public func value<K, V: Value, T>(for key: Key, with transform:(V?) throws -> T) throws -> [K: T] {
let any = try self.any(for: key)
do {
return try Dictionary<K, V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<K, V: Value, T>(for key: Key, with transform:(V?) throws -> T) -> [K: T]? {
return try? self.value(for: key, with: transform)
}
}
// MARK: -
// MARK: Dictionary of Optional Value's
public extension Extractable {
public func value<K, V: Value>(for key: Key) throws -> [K: V?] {
let any = try self.any(for: key)
do {
return try Dictionary<K, V?>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<K, V: Value>(for key: Key) -> [K: V?]? {
return try? self.value(for: key)
}
public func value<K, V: Value>(for key: Key, or value: [K: V?]) -> [K: V?] {
guard let result: [K: V?] = self.value(for: key) else { return value }
return result
}
}
// MARK: -
// MARK: Dictionary of Transformed Optional Value's
public extension Extractable {
public func value<K, V: Value, T>(for key: Key, with transform:(V) -> T?) throws -> [K: T?] {
let any = try self.any(for: key)
do {
return try Dictionary<K, V?>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<K, V: Value, T>(for key: Key, with transform:(V) -> T?) -> [K: T?]? {
return try? self.value(for: key, with: transform)
}
public func value<K, V: Value, T>(for key: Key, with transform:(V?) -> T?) throws -> [K: T?] {
let any = try self.any(for: key)
do {
return try Dictionary<K, V?>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<K, V: Value, T>(for key: Key, with transform:(V?) -> T?) -> [K: T?]? {
return try? self.value(for: key, with: transform)
}
}
// MARK: -
// MARK: Set of Value's
public extension Extractable {
public func value<V: Value>(for key: Key) throws -> Set<V> {
let any = try self.any(for: key)
do {
return try Set<V>.mappedValue(from: any)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value>(for key: Key) -> Set<V>? {
return try? self.value(for: key)
}
public func value<V: Value>(for key: Key, or value: Set<V>) -> Set<V> {
guard let result: Set<V> = self.value(for: key) else { return value }
return result
}
}
// MARK: -
// MARK: Set of Transformed Value's
public extension Extractable {
public func value<V: Value & Hashable, T>(for key: Key, with transform:(V) throws -> T) throws -> Set<T> {
let any = try self.any(for: key)
do {
return try Set<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value & Hashable, T>(for key: Key, with transform:(V) throws -> T) -> Set<T>? {
return try? self.value(for: key, with: transform)
}
public func value<V: Value & Hashable, T>(for key: Key, with transform:(V?) throws -> T) throws -> Set<T> {
let any = try self.any(for: key)
do {
return try Set<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value & Hashable, T>(for key: Key, with transform:(V?) throws -> T) -> Set<T>? {
return try? self.value(for: key, with: transform)
}
public func value<V: Value & Hashable, T>(for key: Key, with transform:(V) -> T?) throws -> Set<T> {
let any = try self.any(for: key)
do {
return try Set<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value & Hashable, T>(for key: Key, with transform:(V) -> T?) -> Set<T>? {
return try? self.value(for: key, with: transform)
}
public func value<V: Value & Hashable, T>(for key: Key, with transform:(V?) -> T?) throws -> Set<T> {
let any = try self.any(for: key)
do {
return try Set<V>.mappedValue(from: any, with: transform)
}
catch let OutlawError.typeMismatch(expected: expected, actual: actual) {
throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual)
}
}
public func value<V: Value & Hashable, T>(for key: Key, with transform:(V?) -> T?) -> Set<T>? {
return try? self.value(for: key, with: transform)
}
}
|
cc0-1.0
|
a5e9650183e9b6140fb2aa871a1efd0e
| 34.930667 | 111 | 0.590174 | 3.712869 | false | false | false | false |
colemancda/Seam
|
SeamDemo/SeamDemo/ViewController.swift
|
1
|
2576
|
//
// ViewController.swift
// SeamDemo
//
// Created by Nofel Mahmood on 12/08/2015.
// Copyright © 2015 CloudKitSpace. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// do
// {
// try moc.save()
// }
// catch
// {
// print("Error thrown baby", appendNewline: true)
// }
// let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: "Task")
// do
// {
// let results = try moc.executeFetchRequest(fetchRequest)
// for result in results as! [Task]
// {
// result.name = "\(result.name!) ClientChange"
// }
// try moc.save()
// }
// catch
// {
//
// }
// let moc = CoreDataStack.defaultStack.managedObjectContext
// let task: Task = NSEntityDescription.insertNewObjectForEntityForName("Task", inManagedObjectContext: moc) as! Task
// task.name = "HElaLuia"
//
// let cycling: Task = NSEntityDescription.insertNewObjectForEntityForName("Task", inManagedObjectContext: moc) as! Task
// cycling.name = "Foolish"
//
// let biking: Task = NSEntityDescription.insertNewObjectForEntityForName("Task", inManagedObjectContext: moc) as! Task
// biking.name = "Acting"
//
// let outdoorTasksTag = NSEntityDescription.insertNewObjectForEntityForName("Tag", inManagedObjectContext: moc) as! Tag
// outdoorTasksTag.name = "AnotherTag"
//
// let newTasksTag = NSEntityDescription.insertNewObjectForEntityForName("Tag", inManagedObjectContext: moc) as! Tag
// newTasksTag.name = "Just Another Tag"
// newTasksTag.task = biking
//
// outdoorTasksTag.task = cycling
// if moc.hasChanges
// {
// do
// {
// try moc.save()
// }
// catch let error as NSError?
// {
// print("Error Occured \(error!)", appendNewline: true)
// }
// }
// CoreDataStack.defaultStack.seamStore!.triggerSync()
// CoreDataStack.defaultStack.seamStore!.tri
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
f31ed6cbb82b9fed344b6add910f6161
| 29.294118 | 127 | 0.565437 | 4.493892 | false | false | false | false |
TonnyTao/HowSwift
|
Funny Swift.playground/Pages/#selector.xcplaygroundpage/Contents.swift
|
1
|
1265
|
/*:
# Selector
Selector is Objective-C term, Using selector in pure swift, we need @objc attibution to expose Swift api to Objective-C
*/
import UIKit
import Foundation
class Dog {
@objc func say() {
}
@objc func say(text: String) {
print("hi")
}
}
let sel1 = #selector(Dog.say as (Dog) -> () -> Void)
let sel2 = #selector(Dog.say(text:) as (Dog) -> (String) -> Void)
//: Using selector in Swift to access Objective-C property's getter and setter
class Cat : NSObject {
@objc var name: String?
}
let getName = #selector(getter: Cat.name)
let setName = #selector(setter: Cat.name)
let cat = Cat()
cat.perform(setName, with: "Kitty")
let unmanagedObject = cat.perform(getName)
let name = unmanagedObject?.takeUnretainedValue() as? String //Kitty
//: Using extra extension to make your code more native, and save your fingers.
class ViewController: UIViewController {
let btn = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
btn.addTarget(self, action: .btnTapped, for: .touchUpInside)
}
@objc func btnTapped(btn: UIButton) {
}
}
fileprivate extension Selector {
static let btnTapped = #selector(ViewController.btnTapped(btn:))
}
|
mit
|
322e1afb988bf953c93cc77d04d85f4c
| 21.589286 | 119 | 0.658498 | 3.844985 | false | false | false | false |
samodom/TestableMapKit
|
TestableMapKit/MKAnnotationView/MKAnnotationViewCalls.swift
|
1
|
2216
|
//
// MKAnnotationViewCalls.swift
// TestableMapKit
//
// Created by Sam Odom on 12/25/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import MapKit
public extension MKAnnotationView {
public override func setSelected(selected: Bool, animated: Bool) {
setSelectedCalled = true
setSelectedSelected = selected
setSelectedAnimated = animated
if shouldForwardMethodCallWithSelector("setSelected:animated:") {
super.setSelected(selected, animated: animated)
}
}
public override func setDragState(newDragState: MKAnnotationViewDragState, animated: Bool) {
setDragStateCalled = true
setDragStateState = newDragState
setDragStateAnimated = animated
if shouldForwardMethodCallWithSelector("setDragState:animated:") {
super.setDragState(newDragState, animated: animated)
}
}
}
extension MKAnnotationView: ShimMethodForwarding {
/*!
The MKAnnotationView shim should not forward spied messages by default.
*/
public var shouldForwardByDefault: Bool { return forwardingList.shouldForwardByDefault }
/*!
This method indicates whether or not the spy for the provided selector forwards the method call to the superclass implementation.
:param: selector Selector of spy method to check for forwarding status.
:returns: Boolean value indicating whether or not the spy currently forwards calls to the specified method.
*/
public func shouldForwardMethodCallWithSelector(selector: Selector) -> Bool {
return forwardingList.shouldForwardMethodCallWithSelector(selector)
}
/*!
Calls to this method control whether or not the spy for the provided selector forwards the method call to the superclass implementation.
:param: selector Selector of spy method of which to change the forwarding status.
:param: Boolean value indicating whether or not the method calls should be forwarded.
*/
public func setShouldForwardMethodCallWithSelector(selector: Selector, _ shouldForward: Bool) {
forwardingList.setShouldForwardMethodCallWithSelector(selector, shouldForward)
}
}
|
mit
|
0608271fd21ad69fab9db374fd1ef3c5
| 34.741935 | 144 | 0.723827 | 5.153488 | false | false | false | false |
tad-iizuka/swift-sdk
|
Source/DiscoveryV1/Models/Entity.swift
|
2
|
2222
|
/**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** A named entity (a person, company, organization, etc) extracted from a document. */
public struct Entity: JSONDecodable {
/// How often this entity is seen.
public let count: Int?
/// Disambiguation information for the detected entity (sent only if disambiguation occurred).
public let disambiguated: DisambiguatedLinks?
/// See **KnowledgeGraph**.
public let knowledgeGraph: KnowledgeGraph?
/// Relevance to content.
public let relevance: Double?
/// Sentiment concerning keyword.
public let sentiment: Sentiment?
/// Surrounding text of the entity.
public let text: String?
/// Classification of the entity.
public let type: String?
/// The raw JSON object used to construct this model.
public let json: [String: Any]
/// Used internally to initialize an `Entity` object from JSON.
public init(json: JSON) throws {
count = try? json.getInt(at: "count")
disambiguated = try? json.decode(at: "disambiguated", type: DisambiguatedLinks.self)
knowledgeGraph = try? json.decode(at: "knowledgeGraph", type: KnowledgeGraph.self)
relevance = try? json.getDouble(at: "relevance")
sentiment = try? json.decode(at: "sentiment", type: Sentiment.self)
text = try? json.getString(at: "text")
type = try? json.getString(at: "type")
self.json = try json.getDictionaryObject()
}
/// Used internally to serialize an 'Entity' model to JSON.
public func toJSONObject() -> Any {
return json
}
}
|
apache-2.0
|
10544a88ace3ce3199043c13966255bc
| 33.71875 | 98 | 0.676868 | 4.40873 | false | false | false | false |
mumbler/PReVo-iOS
|
ReVoModeloj/ReVoModelojTests/ModulTestoj/VortoTestoj.swift
|
1
|
1406
|
//
// VortoTestoj.swift
// PoshReVoUnuopTestoj
//
// Created by Robin Hill on 5/4/20.
// Copyright © 2020 Robin Hill. All rights reserved.
//
import Foundation
import XCTest
@testable import ReVoModeloj
final class VortoTestoj: XCTestCase {
func testKreiVorton() {
let ofertiTeksto = "tr \n\n[EKON] <a href=\"propon.0i\">Proponi</a> al iu varon aŭ servon aĉetotan: <i>Vobis unua kuraĝis, ekde ĉi marto, oferti komputilojn kun la nova Superdisk-aparato anstataŭ la diskingo por tradiciaj disketoj</i>"
let oferti = Vorto(titolo: "ofert/i", teksto: ofertiTeksto, marko: "ofert.0i", ofc: "8")
XCTAssertEqual(oferti.titolo, "ofert/i")
XCTAssertEqual(oferti.teksto, ofertiTeksto)
XCTAssertEqual(oferti.marko, "ofert.0i")
XCTAssertEqual(oferti.ofc, "8")
let kveriTeksto = "ntr \n\n1. (pri turtoj kaj kolomboj) <a href=\"blek.0o\">Bleki</a> per milda murmuro. ➞ <a href=\"kurre.0.ZOO\">kurre</a>\n\n2. (figure) Ame interparoli: <i>... kaj kverantaj voĉoj de ridetantaj junulinoj... Junaj voĉoj kveradas kaj flustradas,....</i>"
let kveri = Vorto(titolo: "kver/i", teksto: kveriTeksto, marko: "kver.0i", ofc: nil)
XCTAssertEqual(kveri.titolo, "kver/i")
XCTAssertEqual(kveri.teksto, kveriTeksto)
XCTAssertEqual(kveri.marko, "kver.0i")
XCTAssertEqual(kveri.ofc, nil)
}
}
|
mit
|
060fd78d1e099712d785cb5bc9cfdc65
| 41.30303 | 280 | 0.665473 | 2.629002 | false | true | false | false |
piscoTech/GymTracker
|
Gym Tracker watchOS Extension/ExecuteWorkoutIC.swift
|
1
|
5698
|
//
// ExecuteWorkoutInterfaceController.swift
// Gym Tracker
//
// Created by Marco Boschi on 24/03/2017.
// Copyright © 2017 Marco Boschi. All rights reserved.
//
import WatchKit
import HealthKit
import Foundation
import AVFoundation
import GymTrackerCore
class ExecuteWorkoutInterfaceController: WKInterfaceController, ExecuteWorkoutControllerDelegate {
@IBOutlet weak var timerLbl: WKInterfaceTimer!
@IBOutlet weak var bpmLbl: WKInterfaceLabel!
@IBOutlet weak var currentExerciseGrp: WKInterfaceGroup!
@IBOutlet weak var exerciseNameLbl: WKInterfaceLabel!
@IBOutlet weak var setRepWeightLbl: WKInterfaceLabel!
@IBOutlet weak var otherSetsLbl: WKInterfaceLabel!
@IBOutlet weak var doneSetBtn: WKInterfaceButton!
@IBOutlet weak var restGrp: WKInterfaceGroup!
@IBOutlet weak var restLbl: WKInterfaceTimer!
@IBOutlet weak var restEndBtn: WKInterfaceButton!
@IBOutlet weak var nextUpLbl: WKInterfaceLabel!
@IBOutlet weak var workoutDoneGrp: WKInterfaceGroup!
@IBOutlet weak var workoutDoneLbl: WKInterfaceLabel!
@IBOutlet weak var workoutDoneBtn: WKInterfaceButton!
private var workoutController: ExecuteWorkoutController!
private var restTimer: Timer? {
didSet {
DispatchQueue.main.async {
oldValue?.invalidate()
}
}
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
guard let data = context as? ExecuteWorkoutData else {
appDelegate.restoreDefaultState()
return
}
appDelegate.executeWorkout = self
addMenuItem(with: .decline, title: GTLocalizedString("CANCEL", comment: "cancel"), action: #selector(cancelWorkout))
addMenuItem(with: .accept, title: GTLocalizedString("WORKOUT_END_BUTTON", comment: "End"), action: #selector(endWorkout))
self.workoutController = ExecuteWorkoutController(data: data, viewController: self, source: .watch)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
// MARK: - ExecuteWorkoutViewController
func askForChoices(_ choices: [GTChoice]) {
presentController(withName: "choice", context: AskChoiceData(choices: choices, n: 0, otherChoices: [:], delegate: self))
}
func reportChoices(_ choices: [GTChoice: Int32]) {
workoutController.reportChoices(choices)
appDelegate.executeWorkoutDetail?.reloadData(choices: choices)
}
func cancelStartup() {
workoutController.cancelStartup()
}
func setWorkoutTitle(_ text: String) {
self.setTitle(text)
}
func setBPM(_ text: String) {
bpmLbl.setText(text)
}
func startTimer(at date: Date) {
timerLbl.setDate(date)
timerLbl.start()
}
func stopTimer() {
timerLbl.stop()
}
func setCurrentExerciseViewHidden(_ hidden: Bool) {
currentExerciseGrp.setHidden(hidden)
}
func setExerciseName(_ name: String) {
exerciseNameLbl.setText(name)
}
func setCurrentSetViewHidden(_ hidden: Bool) {
setRepWeightLbl.setHidden(hidden)
}
func setCurrentSetText(_ text: NSAttributedString) {
setRepWeightLbl.setAttributedText(text)
}
func setOtherSetsViewHidden(_ hidden: Bool) {
otherSetsLbl.setHidden(hidden)
}
func setOtherSetsText(_ text: NSAttributedString) {
otherSetsLbl.setAttributedText(text)
}
func setSetDoneButtonHidden(_ hidden: Bool) {
doneSetBtn.setHidden(hidden)
}
func startRestTimer(to date: Date) {
restLbl.setDate(date)
restLbl.start()
}
func stopRestTimer() {
restLbl.stop()
}
func setRestViewHidden(_ hidden: Bool) {
restGrp.setHidden(hidden)
}
func setRestEndButtonHidden(_ hidden: Bool) {
restEndBtn.setHidden(hidden)
}
func setWorkoutDoneViewHidden(_ hidden: Bool) {
workoutDoneGrp.setHidden(hidden)
}
func setWorkoutDoneText(_ text: String) {
workoutDoneLbl.setText(text)
}
func setWorkoutDoneButtonEnabled(_ enabled: Bool) {
workoutDoneBtn.setEnabled(enabled)
}
func disableGlobalActions() {
DispatchQueue.main.async {
self.clearAllMenuItems()
}
}
func setNextUpTextHidden(_ hidden: Bool) {
nextUpLbl.setHidden(hidden)
}
func setNextUpText(_ text: NSAttributedString) {
nextUpLbl.setAttributedText(text)
}
func notifyEndRest() {
let sound = WKHapticType.stop
DispatchQueue.main.async {
try? AVAudioSession.sharedInstance().setActive(true)
WKInterfaceDevice.current().play(sound)
self.restTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { _ in
WKInterfaceDevice.current().play(sound)
}
RunLoop.main.add(self.restTimer!, forMode: .common)
}
}
func endNotifyEndRest() {
DispatchQueue.main.async {
RunLoop.main.add(Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
try? AVAudioSession.sharedInstance().setActive(false)
}, forMode: .common)
self.restTimer = nil
}
}
func notifyExerciseChange(isRest: Bool) {
WKInterfaceDevice.current().play(.click)
}
func askUpdateSecondaryInfo(with data: UpdateSecondaryInfoData) {
presentController(withName: "updateSecondaryInfo", context: data)
}
@IBAction func endRest() {
workoutController.endRest()
}
@IBAction func endSet() {
workoutController.endSet()
}
@objc func endWorkout() {
workoutController.endWorkout()
}
@objc func cancelWorkout() {
workoutController.cancelWorkout()
}
func workoutHasStarted() {}
@IBAction func exitWorkoutTracking() {
appDelegate.restoreDefaultState()
}
func globallyUpdateSecondaryInfoChange() {
appDelegate.executeWorkoutDetail?.reloadDetails(from: workoutController)
}
}
|
mit
|
dc8891ce1ee18fa3206deb38a0ad2375
| 23.877729 | 123 | 0.739512 | 3.728403 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
piwigo/Album/Extensions/AlbumViewController+Share.swift
|
1
|
9001
|
//
// AlbumViewController+Share.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 29/05/2022.
// Copyright © 2022 Piwigo.org. All rights reserved.
//
import Foundation
import Photos
// MARK: Share Images
extension AlbumViewController
{
@objc func shareSelection() {
initSelection(beforeAction: .share)
}
func checkPhotoLibraryAccessBeforeShare() {
// Check autorisation to access Photo Library (camera roll)
if #available(iOS 14, *) {
PhotosFetch.shared.checkPhotoLibraryAuthorizationStatus(
for: PHAccessLevel.addOnly, for: self,
onAccess: { [self] in
// User allowed to save image in camera roll
presentShareImageViewController(withCameraRollAccess: true)
},
onDeniedAccess: { [self] in
// User not allowed to save image in camera roll
DispatchQueue.main.async { [self] in
presentShareImageViewController(withCameraRollAccess: false)
}
})
} else {
// Fallback on earlier versions
PhotosFetch.shared.checkPhotoLibraryAccessForViewController(nil) { [self] in
// User allowed to save image in camera roll
presentShareImageViewController(withCameraRollAccess: true)
} onDeniedAccess: { [self] in
// User not allowed to save image in camera roll
if Thread.isMainThread {
self.presentShareImageViewController(withCameraRollAccess: false)
} else {
DispatchQueue.main.async(execute: { [self] in
presentShareImageViewController(withCameraRollAccess: false)
})
}
}
}
}
func presentShareImageViewController(withCameraRollAccess hasCameraRollAccess: Bool) {
// To exclude some activity types
var excludedActivityTypes = [UIActivity.ActivityType]()
// Create new activity provider items to pass to the activity view controller
totalNumberOfImages = selectedImageData.count
var itemsToShare: [UIActivityItemProvider] = []
for imageData in selectedImageData {
if imageData.isVideo {
// Case of a video
let videoItemProvider = ShareVideoActivityItemProvider(placeholderImage: imageData)
// Use delegation to monitor the progress of the item method
videoItemProvider.delegate = self
// Add to list of items to share
itemsToShare.append(videoItemProvider)
// Exclude "assign to contact" activity
excludedActivityTypes.append(.assignToContact)
} else {
// Case of an image
let imageItemProvider = ShareImageActivityItemProvider(placeholderImage: imageData)
// Use delegation to monitor the progress of the item method
imageItemProvider.delegate = self
// Add to list of items to share
itemsToShare.append(imageItemProvider)
}
}
// Create an activity view controller with the activity provider item.
// ShareImageActivityItemProvider's superclass conforms to the UIActivityItemSource protocol
let activityViewController = UIActivityViewController(activityItems: itemsToShare, applicationActivities: nil)
// Exclude camera roll activity if needed
if !hasCameraRollAccess {
// Exclude "camera roll" activity when the Photo Library is not accessible
excludedActivityTypes.append(.saveToCameraRoll)
}
activityViewController.excludedActivityTypes = Array(excludedActivityTypes)
// Delete image/video files and remove observers after dismissing activity view controller
activityViewController.completionWithItemsHandler = { [self] activityType, completed, returnedItems, activityError in
// NSLog(@"Activity Type selected: %@", activityType);
if completed {
// NSLog(@"Selected activity was performed and returned error:%ld", (long)activityError.code);
// Delete shared files & remove observers
NotificationCenter.default.post(name: .pwgDidShare, object: nil)
// Close HUD with success
updatePiwigoHUDwithSuccess() { [self] in
hidePiwigoHUD(afterDelay: kDelayPiwigoHUD) { [self] in
// Deselect images
cancelSelect()
// Close ActivityView
presentedViewController?.dismiss(animated: true)
}
}
} else {
if activityType == nil {
// NSLog(@"User dismissed the view controller without making a selection.");
updateButtonsInSelectionMode()
} else {
// Check what to do with selection
if selectedImageIds.isEmpty {
cancelSelect()
} else {
setEnableStateOfButtons(true)
}
// Cancel download task
NotificationCenter.default.post(name: .pwgCancelDownload, object: nil)
// Delete shared file & remove observers
NotificationCenter.default.post(name: .pwgDidShare, object: nil)
// Close ActivityView
presentedViewController?.dismiss(animated: true)
}
}
}
// Present share image activity view controller
activityViewController.popoverPresentationController?.barButtonItem = shareBarButton
present(activityViewController, animated: true)
}
@objc func cancelShareImages() {
// Cancel image file download and remaining activity shares if any
NotificationCenter.default.post(name: .pwgCancelDownload, object: nil)
}
}
// MARK: - ShareImageActivityItemProviderDelegate Methods
extension AlbumViewController: ShareImageActivityItemProviderDelegate
{
func imageActivityItemProviderPreprocessingDidBegin(_ imageActivityItemProvider: UIActivityItemProvider?,
withTitle title: String) {
// Show HUD to let the user know the image is being downloaded in the background.
let detail = String(format: "%d / %d", totalNumberOfImages - selectedImageIds.count + 1, totalNumberOfImages)
presentedViewController?.showPiwigoHUD(withTitle: title, detail: detail,
buttonTitle: NSLocalizedString("alertCancelButton", comment: "Cancel"),
buttonTarget: self, buttonSelector: #selector(cancelShareImages),
inMode: .annularDeterminate)
}
func imageActivityItemProvider(_ imageActivityItemProvider: UIActivityItemProvider?,
preprocessingProgressDidUpdate progress: Float) {
// Update HUD
presentedViewController?.updatePiwigoHUD(withProgress: progress)
}
func imageActivityItemProviderPreprocessingDidEnd(_ imageActivityItemProvider: UIActivityItemProvider?,
withImageId imageId: Int) {
// Check activity item provider
guard let imageActivityItemProvider = imageActivityItemProvider else { return }
// Close HUD
let imageIdObject = NSNumber(value: imageId)
if imageActivityItemProvider.isCancelled {
presentedViewController?.hidePiwigoHUD { }
} else if selectedImageIds.contains(imageIdObject) {
// Remove image from selection
selectedImageIds.removeAll(where: {$0 == imageIdObject})
updateButtonsInSelectionMode()
// Close HUD if last image
if selectedImageIds.count == 0 {
presentedViewController?.updatePiwigoHUDwithSuccess {
self.presentedViewController?.hidePiwigoHUD(afterDelay: kDelayPiwigoHUD) { }
}
}
}
}
func showError(withTitle title: String, andMessage message: String?) {
// Cancel remaining shares
cancelShareImages()
// Close HUD if needed
presentedViewController?.hidePiwigoHUD { }
// Display error alert after trying to share image
presentedViewController?.dismissPiwigoError(withTitle: title, message: message ?? "") {
// Close ActivityView
self.presentedViewController?.dismiss(animated: true)
}
}
}
|
mit
|
6b981d2ce285c2e56543b44cc949cb0c
| 42.897561 | 125 | 0.598622 | 6.310659 | false | false | false | false |
zapdroid/RXWeather
|
Pods/Alamofire/Source/Validation.swift
|
1
|
11530
|
//
// Validation.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Request {
// MARK: Helper Types
fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason
/// Used to represent whether validation was successful or encountered an error resulting in a failure.
///
/// - success: The validation was successful.
/// - failure: The validation failed encountering the provided error.
public enum ValidationResult {
case success
case failure(Error)
}
fileprivate struct MIMEType {
let type: String
let subtype: String
var isWildcard: Bool { return type == "*" && subtype == "*" }
init?(_ string: String) {
let components: [String] = {
let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines)
let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)
return split.components(separatedBy: "/")
}()
if let type = components.first, let subtype = components.last {
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(_ mime: MIMEType) -> Bool {
switch (type, subtype) {
case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
return true
default:
return false
}
}
}
// MARK: Properties
fileprivate var acceptableStatusCodes: [Int] { return Array(200 ..< 300) }
fileprivate var acceptableContentTypes: [String] {
if let accept = request?.value(forHTTPHeaderField: "Accept") {
return accept.components(separatedBy: ",")
}
return ["*/*"]
}
// MARK: Status Code
fileprivate func validate<S: Sequence>(
statusCode acceptableStatusCodes: S,
response: HTTPURLResponse)
-> ValidationResult
where S.Iterator.Element == Int {
if acceptableStatusCodes.contains(response.statusCode) {
return .success
} else {
let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
return .failure(AFError.responseValidationFailed(reason: reason))
}
}
// MARK: Content Type
fileprivate func validate<S: Sequence>(
contentType acceptableContentTypes: S,
response: HTTPURLResponse,
data: Data?)
-> ValidationResult
where S.Iterator.Element == String {
guard let data = data, data.count > 0 else { return .success }
guard
let responseContentType = response.mimeType,
let responseMIMEType = MIMEType(responseContentType)
else {
for contentType in acceptableContentTypes {
if let mimeType = MIMEType(contentType), mimeType.isWildcard {
return .success
}
}
let error: AFError = {
let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes))
return AFError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
return .success
}
}
let error: AFError = {
let reason: ErrorReason = .unacceptableContentType(
acceptableContentTypes: Array(acceptableContentTypes),
responseContentType: responseContentType
)
return AFError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
}
// MARK: -
extension DataRequest {
/// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
/// request was valid.
public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
/// Validates the request, using the specified closure.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter validation: A closure to validate the request.
///
/// - returns: The request.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validationExecution: () -> Void = { [unowned self] in
if
let response = self.response,
self.delegate.error == nil,
case let .failure(error) = validation(self.request, response, self.delegate.data) {
self.delegate.error = error
}
}
validations.append(validationExecution)
return self
}
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter range: The range of acceptable status codes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
return validate { [unowned self] _, response, _ in
self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
return validate { [unowned self] _, response, data in
self.validate(contentType: acceptableContentTypes, response: response, data: data)
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - returns: The request.
@discardableResult
public func validate() -> Self {
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
// MARK: -
extension DownloadRequest {
/// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
/// destination URL, and returns whether the request was valid.
public typealias Validation = (
_ request: URLRequest?,
_ response: HTTPURLResponse,
_ temporaryURL: URL?,
_ destinationURL: URL?)
-> ValidationResult
/// Validates the request, using the specified closure.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter validation: A closure to validate the request.
///
/// - returns: The request.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validationExecution: () -> Void = { [unowned self] in
let request = self.request
let temporaryURL = self.downloadDelegate.temporaryURL
let destinationURL = self.downloadDelegate.destinationURL
if
let response = self.response,
self.delegate.error == nil,
case let .failure(error) = validation(request, response, temporaryURL, destinationURL) {
self.delegate.error = error
}
}
validations.append(validationExecution)
return self
}
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter range: The range of acceptable status codes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
return validate { [unowned self] _, response, _, _ in
self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
return validate { [unowned self] _, response, _, _ in
let fileURL = self.downloadDelegate.fileURL
guard let validFileURL = fileURL else {
return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
}
do {
let data = try Data(contentsOf: validFileURL)
return self.validate(contentType: acceptableContentTypes, response: response, data: data)
} catch {
return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL)))
}
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - returns: The request.
@discardableResult
public func validate() -> Self {
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
|
mit
|
358ca77e9a5d383e94b7c42507bed7ec
| 36.803279 | 121 | 0.637641 | 5.291418 | false | false | false | false |
mikengyn/SideMenuController
|
Source/SideMenuController+CustomTypes.swift
|
1
|
2524
|
//
// SideMenuController+CustomTypes.swift
// SideMenuController
//
// Created by Teodor Patras on 15/07/16.
// Copyright © 2016 teodorpatras. All rights reserved.
//
// MARK: - Extension for implementing the custom nested types
public extension SideMenuController {
public enum SidePanelPosition {
case underCenterPanelLeft
case underCenterPanelRight
case overCenterPanelLeft
case overCenterPanelRight
var isPositionedUnder: Bool {
return self == SidePanelPosition.underCenterPanelLeft || self == SidePanelPosition.underCenterPanelRight
}
var isPositionedLeft: Bool {
return self == SidePanelPosition.underCenterPanelLeft || self == SidePanelPosition.overCenterPanelLeft
}
}
public enum StatusBarBehaviour {
case slideAnimation
case fadeAnimation
case horizontalPan
case showUnderlay
var statusBarAnimation: UIStatusBarAnimation {
switch self {
case .fadeAnimation:
return .fade
case .slideAnimation:
return .slide
default:
return .none
}
}
}
public struct Preferences {
public struct Drawing {
public var menuButtonImage: UIImage?
public var sidePanelPosition = SidePanelPosition.underCenterPanelLeft
public var sidePanelWidth: CGFloat = 300
public var centerPanelOverlayColor = UIColor(hue:0.15, saturation:0.21, brightness:0.17, alpha:0.6)
public var centerPanelShadow = false
public var centerPanelOverlay = true
}
public struct Animating {
public var statusBarBehaviour = StatusBarBehaviour.slideAnimation
public var reavealDuration = 0.3
public var hideDuration = 0.2
public var transitionAnimator: TransitionAnimatable.Type? = FadeAnimator.self
}
public struct Interaction {
public var panningEnabled = true
public var swipingEnabled = true
public var menuButtonAccessibilityIdentifier: String?
public var closeOnViewDisappear = true
public var enableCenterViewInteraction = false
}
public var drawing = Drawing()
public var animating = Animating()
public var interaction = Interaction()
public init() {}
}
}
|
mit
|
0d884d2c9075e147cf9d105e3db8cdf2
| 32.64 | 116 | 0.620293 | 5.619154 | false | false | false | false |
safx/EJDB-Swift
|
Source/Collection.swift
|
1
|
1532
|
//
// Collection.swift
// EJDB-Swift
//
// Created by Safx Developer on 2015/07/28.
// Copyright © 2015年 Safx Developers. All rights reserved.
//
import Foundation
public final class Collection {
public typealias QueryResult = OpaqueList<BSONIterator>
private let coll: COpaquePointer
public init(name: String, database: Database) { // FIXME: EJCOLLOPTS to args
assert(name.characters.count < Int(JBMAXCOLNAMELEN))
coll = name.withCString { str in
return ejdbcreatecoll(database.jb, str, nil)
}
assert(coll != nil)
}
internal init(coll: COpaquePointer) {
self.coll = coll
}
public func save(bson: BSON, oid: OID = OID()) {
ejdbsavebson(coll, &bson.bs, &oid.oid)
}
public func remove(oid: OID) -> Bool {
return ejdbrmbson(coll, &oid.oid)
}
public func load(oid: OID) -> BSON {
let b = ejdbloadbson(coll, &oid.oid)
assert(b != nil)
return BSON(b: b.memory)
}
public func query(query: Query) -> QueryResult {
var count: UInt32 = 0
let result = ejdbqryexecute(coll, query.q, &count, 0, nil) // FIXME: fixed param
return OpaqueList(list: result)
}
public func sync() -> Bool {
return ejdbsyncoll(coll)
}
public func transaction(@noescape closure: Collection -> Bool) {
ejdbtranbegin(coll)
if closure(self) {
ejdbtrancommit(coll)
} else {
ejdbtranabort(coll)
}
}
}
|
mit
|
5b95bfd69a765913c53f5a6b659cc024
| 23.269841 | 88 | 0.59843 | 3.597647 | false | false | false | false |
jhurray/SelectableTextView
|
Source/TextSelectionValidator/LinkValidators.swift
|
1
|
2739
|
//
// LinkValidators.swift
// SelectableTextView
//
// Created by Jeff Hurray on 2/10/17.
// Copyright © 2017 jhurray. All rights reserved.
//
import Foundation
public protocol LinkValidatorAttributes: TextSelectionValidator {
var tintColor: UIColor? {get}
var underlined: Bool {get}
}
public extension LinkValidatorAttributes {
public var tintColor: UIColor? {
return nil
}
public var underlined: Bool {
return true
}
public var selectionAttributes: [NSAttributedStringKey : Any]? {
var attributes: [NSAttributedStringKey: Any] = [:]
if let tintColor = tintColor {
attributes[NSAttributedStringKey.foregroundColor] = tintColor
}
if underlined {
attributes[NSAttributedStringKey.underlineStyle] = NSUnderlineStyle.styleSingle.rawValue
}
return attributes
}
}
public struct LinkValidator: ContainerTextSelectionValidator, LinkValidatorAttributes {
public init() {}
private(set) public var validator: TextSelectionValidator = ContainsTextValidator(text: "://")
}
// Works for HTTP and HTTPS Links
public struct HTTPLinkValidator: CompositeTextSelectionValidator, LinkValidatorAttributes{
public init() {}
private(set) public var validators: [TextSelectionValidator] = [
PrefixValidator(prefix: "http"),
ContainsTextValidator(text: "://")
]
}
public struct UnsafeLinkValidator: ContainerTextSelectionValidator, LinkValidatorAttributes{
public init() {}
private(set) public var validator: TextSelectionValidator = PrefixValidator(prefix: "http://")
private(set) public var selectionAttributes: [NSAttributedStringKey: Any]? = [NSAttributedStringKey.foregroundColor: UIColor.red]
}
public struct HTTPSLinkValidator: ContainerTextSelectionValidator, LinkValidatorAttributes {
public init() {}
private(set) public var validator: TextSelectionValidator = PrefixValidator(prefix: "https://")
}
public struct CustomLinkValidator: ContainerTextSelectionValidator, LinkValidatorAttributes {
private(set) public var replacementText: String?
private(set) public var url: URL
private(set) public var validator: TextSelectionValidator
public init(urlString: String!, replacementText: String? = nil) {
self.url = URL(string: urlString)!
self.replacementText = replacementText
self.validator = MatchesTextValidator(text: urlString)
}
public init(url: URL!, replacementText: String? = nil) {
self.url = url
self.replacementText = replacementText
self.validator = MatchesTextValidator(text: url.absoluteString)
}
}
|
mit
|
1789567c84fb13c2310df13447eb6018
| 29.087912 | 133 | 0.701242 | 4.898032 | false | false | false | false |
ijung5399/Ex001
|
SuperCool/ViewController.swift
|
1
|
1075
|
//
// ViewController.swift
// SuperCool
//
// Created by Il Mo Jung on 1/14/16.
// Copyright © 2016 Il Mo Jung. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var CoolLogo: UIImageView!
@IBOutlet weak var CoolBg: UIImageView!
@IBOutlet weak var UnCoolBt: UIButton!
@IBOutlet weak var ResetButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func makeMeNotSoUnCool(sender: AnyObject) {
CoolLogo.hidden = false
CoolBg.hidden = false
UnCoolBt.hidden = true
ResetButton.hidden = false
}
@IBAction func ResetView(sender: AnyObject) {
CoolLogo.hidden = true
CoolBg.hidden = true
UnCoolBt.hidden = false
ResetButton.hidden = true
}
}
|
apache-2.0
|
7b00ded79d355d00e6454df5f66b4e79
| 23.976744 | 80 | 0.646182 | 4.383673 | false | false | false | false |
glassonion1/R9HTTPRequest
|
R9HTTPRequest/HttpJsonClient.swift
|
1
|
1114
|
//
// HttpJsonClient.swift
// R9HTTPRequest
//
// Created by taisuke fujita on 2017/10/03.
// Copyright © 2017年 Revolution9. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
public class HttpJsonClient<T: Codable>: HttpClient {
public typealias ResponseType = T
public init() {
}
public func action(method: HttpClientMethodType, url: URL, requestBody: Data?, headers: HTTPHeaders?) -> Observable<T> {
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData)
request.httpMethod = method.rawValue
request.allHTTPHeaderFields = headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = requestBody
let scheduler = ConcurrentDispatchQueueScheduler(qos: .background)
return URLSession.shared.rx.data(request: request).timeout(30, scheduler: scheduler).map { data -> T in
let jsonDecoder = JSONDecoder()
let response = try! jsonDecoder.decode(T.self, from: data)
return response
}
}
}
|
mit
|
dae25f150a49729a555e0cac63f70f89
| 31.676471 | 124 | 0.674167 | 4.648536 | false | false | false | false |
chrisjmendez/swift-exercises
|
GUI/Cards/Carthage/Checkouts/Async/AsyncPodsExample/AsyncExample iOS/ViewController.swift
|
8
|
3563
|
//
// ViewController.swift
// AsyncExample iOS
//
// Created by Tobias DM on 15/07/14.
// Copyright (c) 2014 Tobias Due Munk. All rights reserved.
//
import UIKit
import Async
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Async syntactic sugar
Async.background {
print("A: This is run on the \(qos_class_self().description) (expected \(QOS_CLASS_BACKGROUND.description))")
}.main {
print("B: This is run on the \(qos_class_self().description) (expected \(qos_class_main().description)), after the previous block")
}
// Regular GCD
/*
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
print("REGULAR GCD: This is run on the background queue")
dispatch_async(dispatch_get_main_queue(), 0), {
print("REGULAR GCD: This is run on the main queue")
})
})
*/
/*
// Chaining with Async
var id = 0
Async.main {
print("This is run on the \(qos_class_self().description) (expected \(qos_class_main().description)) count: \(++id) (expected 1) ")
// Prints: "This is run on the Main (expected Main) count: 1 (expected 1)"
}.userInteractive {
print("This is run on the \(qos_class_self().description) (expected \(QOS_CLASS_USER_INTERACTIVE.description)) count: \(++id) (expected 2) ")
// Prints: "This is run on the Main (expected Main) count: 2 (expected 2)"
}.userInitiated {
print("This is run on the \(qos_class_self().description) (expected \(QOS_CLASS_USER_INITIATED.description)) count: \(++id) (expected 3) ")
// Prints: "This is run on the User Initiated (expected User Initiated) count: 3 (expected 3)"
}.utility {
print("This is run on the \(qos_class_self().description) (expected \(QOS_CLASS_UTILITY.description)) count: \(++id) (expected 4) ")
// Prints: "This is run on the Utility (expected Utility) count: 4 (expected 4)"
}.background {
print("This is run on the \(qos_class_self().description) (expected \(QOS_CLASS_BACKGROUND.description)) count: \(++id) (expected 5) ")
// Prints: "This is run on the User Interactive (expected User Interactive) count: 5 (expected 5)"
}
*/
/*
// Keep reference for block for later chaining
let backgroundBlock = Async.background {
print("This is run on the \(qos_class_self().description) (expected \(QOS_CLASS_BACKGROUND.description))")
}
// Run other code here...
backgroundBlock.main {
print("This is run on the \(qos_class_self().description) (expected \(qos_class_main().description)), after the previous block")
}
*/
/*
// Custom queues
let customQueue = dispatch_queue_create("CustomQueueLabel", DISPATCH_QUEUE_CONCURRENT)
let otherCustomQueue = dispatch_queue_create("OtherCustomQueueLabel", DISPATCH_QUEUE_CONCURRENT)
Async.customQueue(customQueue) {
print("Custom queue")
}.customQueue(otherCustomQueue) {
print("Other custom queue")
}
*/
/*
// After
let seconds = 0.5
Async.main(after: seconds) {
print("Is called after 0.5 seconds")
}.background(after: 0.4) {
print("At least 0.4 seconds after previous block, and 0.9 after Async code is called")
}
*/
/*
// Cancel blocks not yet dispatched
let block1 = Async.background {
// Heavy work
for i in 0...1000 {
print("A \(i)")
}
}
let block2 = block1.background {
print("B – shouldn't be reached, since cancelled")
}
Async.main {
block1.cancel() // First block is _not_ cancelled
block2.cancel() // Second block _is_ cancelled
}
*/
}
}
|
mit
|
927f764e14213f943d8e21d8524bfb92
| 32.59434 | 144 | 0.662735 | 3.460641 | false | false | false | false |
chrisjmendez/swift-exercises
|
Games/Quiz/Quiz/Quiz.swift
|
1
|
478
|
//
// Quiz.swift
// Quiz
//
// Created by tommy trojan on 5/26/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import Foundation
class Quiz{
var question:String
var ①:String
var ②:String
var ③:String
var 👌:Int
init(question:String, ①:String, ②:String, ③:String, 👌:Int){
self.question = question
self.① = ①
self.② = ②
self.③ = ③
self.👌 = 👌
}
}
|
mit
|
24da70f1490738da4427b36ffea3c66f
| 16.038462 | 63 | 0.552036 | 2.695122 | false | false | false | false |
wangCanHui/weiboSwift
|
weiboSwift/Classes/Module/Compose/Controller/CZComposeViewController.swift
|
1
|
15217
|
//
// CZComposeViewController.swift
// weiboSwift
//
// Created by 王灿辉 on 15/11/4.
// Copyright © 2015年 王灿辉. All rights reserved.
//
import UIKit
import SVProgressHUD
let CZComposeViewControllerSendStatusSuccessNotification = "CZComposeViewControllerSendStatusSuccessNotification"
class CZComposeViewController: UIViewController {
// MARK: - 属性
/// toolBar底部约束
private var toolBarBottomCons: NSLayoutConstraint?
/// 照片选择器控制器view的底部约束
private var photoSelectorViewBottomCons: NSLayoutConstraint?
/// 微博内容的最大长度
private let statusMaxLength = 20
override func viewDidLoad() {
super.viewDidLoad()
// 需要设置背景颜色,不然弹出时动画有问题
view.backgroundColor = UIColor.whiteColor()
prepareUI()
// 添加键盘frame改变的通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/*
notification:NSConcreteNotification 0x7f8fea5a4e20 {name = UIKeyboardDidChangeFrameNotification; userInfo = {
UIKeyboardAnimationCurveUserInfoKey = 7;
UIKeyboardAnimationDurationUserInfoKey = "0.25"; // 动画时间
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}"; // 键盘最终的位置
UIKeyboardIsLocalUserInfoKey = 1;
}}
*/
/// 键盘frame改变
func willChangeFrame(notification:NSNotification) {
// print("notification:\(notification)")
// 获取键盘最终位置
let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
// 动画时间
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
toolBarBottomCons?.constant = -(UIScreen.height() - endFrame.origin.y) // 相对于view的底部约束的,监听键盘的弹出和隐藏
UIView.animateWithDuration(duration) { () -> Void in
self.view.layoutIfNeeded()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// let view = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 258)) // 键盘的高度是258
// view.backgroundColor = UIColor.redColor()
// 自定义键盘其实就是给 textView.inputView 赋值
// textView.inputView = view
// 图片现在器隐藏的时候才需要显示键盘,要不让每次选择一张图片返回发微博界面,都会调用此方法叫出键盘
if photoSelectorViewBottomCons?.constant != 0 {
textView.becomeFirstResponder()
}
}
// MARK: - 准备UI
private func prepareUI() {
// 添加子控件,(顺序不能错,以免需要显示在上面的被遮挡)
view.addSubview(textView)
view.addSubview(photoSelectorVC.view)
view.addSubview(toolBar)
view.addSubview(lengthTipLabel)
// 设置导航栏
setupNavigationBar()
// 设置输入框textView
setupTextView()
// 设置图片选择器
preparePhotoSelectorView()
// 设置toolBar
setupToolBar()
// 设置可输入长度提示按钮
setupLengthTipLabel()
}
/// 设置导航栏
private func setupNavigationBar() {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
navigationItem.rightBarButtonItem?.enabled = false //禁用
setupTitleView()
}
/// 设置导航栏标题
private func setupTitleView() {
let prefix = "发微博"
// 获取用户的名称
if let name = CZUserAccount.loadAccount()?.name {
let titleLabel = UILabel()
// 设置文本属性
titleLabel.numberOfLines = 0
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.font = UIFont.systemFontOfSize(14)
// 有用户名
let text = prefix + "\n" + name
let attrText = NSMutableAttributedString(string: text)
// 设置属性文本的属性
let range = (text as NSString).rangeOfString(name)
attrText.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(12),NSForegroundColorAttributeName:UIColor.lightGrayColor()], range: range)
// 顺序不要搞错
titleLabel.attributedText = attrText
titleLabel.sizeToFit()
navigationItem.titleView = titleLabel
}else {
// 没有用户名
navigationItem.title = prefix
}
}
/// 设置toolBar
private func setupToolBar() {
// 添加约束
let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width(), height: 44))
// 获取底部约束
toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
// 创建toolBar item
var items = [UIBarButtonItem]()
// 每个item对应的图片名称
let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
["imageName": "compose_trendbutton_background", "action": "trend"],
["imageName": "compose_mentionbutton_background", "action": "mention"],
["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
["imageName": "compose_addbutton_background", "action": "add"]]
// var index = 0
for dict in itemSettings {
// 获取图片的名称
let imageName = dict["imageName"]!
// 获取图片对应点点击方法名称
let action = dict["action"]!
let item = UIBarButtonItem(imageName: imageName)
// 获取item里面的按钮
let button = item.customView as! UIButton
button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
items.append(item)
// 添加弹簧
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
// index ++
}
// 移除最后一个弹簧
items.removeLast()
toolBar.items = items
}
/// 设置textView
private func setupTextView() {
/*
前提: (UITextView继承自UIScrollView)
1.scrollView所在的控制器属于某个导航控制器
2.scrollView控制器的view或者控制器的view的第一个子view
*/
// scrollView会自动设置Insets, 比如scrollView所在的控制器属于某个导航控制器contentInset.top = 64
// automaticallyAdjustsScrollViewInsets = true // Defaults to YES
// 设置约束
// 相对控制器的view的内部左上角
textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
// 相对toolBar顶部右上角
textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
}
/// 准备 显示微博剩余长度 label
private func setupLengthTipLabel() {
// 设置约束
lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
}
/// 准备 照片选择器
private func preparePhotoSelectorView() {
// 照片选择器控制器的view
let photoSelectorView = photoSelectorVC.view
// 设置约束
photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
let views = ["psv": photoSelectorView]
// 水平
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
// 高度
view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.6, constant: 0))
// 底部重合,偏移photoSelectorView的高度,使初始位置隐藏
photoSelectorViewBottomCons = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.bounds.size.height * 0.6)
view.addConstraint(photoSelectorViewBottomCons!)
}
// MARK: - 按钮点击事件
/// 关闭控制器
@objc private func close() {
// 关闭sv提示
SVProgressHUD.dismiss()
// 关闭键盘
textView.resignFirstResponder()
dismissViewControllerAnimated(true, completion: nil)
}
/// 发微博
func sendStatus() {
// 获取textView的文本内容发送给服务器
let text = textView.emoticonText()
// 判断微博内容的长度是否超出, 超出不发送
let statusLength = text.characters.count
if statusMaxLength - statusLength < 0 {
// 微博内容超出,提示用户
SVProgressHUD.showErrorWithStatus("微博长度超出", maskType: SVProgressHUDMaskType.Black)
return
}
// 获取图片选择器中的图片
let image = photoSelectorVC.photos.first
// 显示正在发送
SVProgressHUD.showWithStatus("正在发布微博...", maskType: SVProgressHUDMaskType.Black)
// 发送微博
CZNetworkTools.sharedInstance.sendStatus(image, status: text) { (result, error) -> Void in
if error != nil {
print("error:\(error)")
SVProgressHUD.showErrorWithStatus("发布微博失败...", maskType: SVProgressHUDMaskType.Black)
return
}
// 发送成功, 直接关闭正在发送界面
self.close()
// 刷新微博(下拉刷新)
NSNotificationCenter.defaultCenter().postNotificationName(CZComposeViewControllerSendStatusSuccessNotification, object: self)
}
}
func picture() {
// 让照片选择器的view移动上来
photoSelectorViewBottomCons?.constant = 0
// 退下键盘
textView.resignFirstResponder()
// 动画效果
UIView.animateWithDuration(0.25) { () -> Void in
self.view.layoutIfNeeded()
}
}
func trend() {
print("#")
}
func mention() {
print("@")
}
func emoticon() {
print("切换前表情键盘:\(textView.inputView)")
// 先让键盘退回去
textView.resignFirstResponder()
// 延时0.25
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
// 如果inputView == nil 使用的是系统的键盘,切换到自定的键盘
// 如果inputView != nil 使用的是自定义键盘,切换到系统的键盘
self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
// 弹出键盘
self.textView.becomeFirstResponder()
print("切换后表情键盘:\(self.textView.inputView)")
}
}
func add() {
print("加号")
}
// MARK: - 懒加载
/// toolBar
private lazy var toolBar: UIToolbar = {
let toolBar = UIToolbar()
toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
return toolBar
}()
/*
iOS中可以让用户输入的控件:
1.UITextField:
1.只能显示一行
2.可以有占位符
3.不能滚动
2.UITextView:
1.可以显示多行
2.没有占位符
3.继承UIScrollView,可以滚动
*/
/// textView
private lazy var textView: CZPlaceholderTextView = {
let textView = CZPlaceholderTextView()
// 当textView被拖动的时候就会将键盘退回,textView能拖动
textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
textView.bounces = true // 默认是ture,只有此属性是true,alwaysBounceVertical设置为true才有效
textView.alwaysBounceVertical = true
textView.font = UIFont.systemFontOfSize(18)
textView.backgroundColor = UIColor.whiteColor()
textView.textColor = UIColor.blackColor()
// 设置占位文本
textView.placeholder = "分享新鲜事..."
// 设置顶部的偏移
// textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
// 设置控制器作为textView的代理来监听textView文本的改变
textView.delegate = self
return textView
}()
/// 表情键盘控制器
private lazy var emoticonVC: CZEmoticonViewController = {
let emoticonVC = CZEmoticonViewController()
// 设置textView
emoticonVC.textView = self.textView
return emoticonVC
}()
/// 显示微博剩余长度
private lazy var lengthTipLabel: UILabel = {
let label = UILabel(fontSize: 12, textColor: UIColor.lightGrayColor())
label.text = String(self.statusMaxLength)
return label
}()
/// 照片选择器的控制器
private lazy var photoSelectorVC: CZPhotoSelectorViewController = {
let photoSelectorVC = CZPhotoSelectorViewController()
// 让照片选择控制器被被人管理
self.addChildViewController(photoSelectorVC)
return photoSelectorVC
}()
}
extension CZComposeViewController: UITextViewDelegate {
/// textView文本改变的时候调用
func textViewDidChange(textView: UITextView) {
// 当textView 有文本的时候,发送按钮可用,
// 当textView 没有文本的时候,发送按钮不可用
navigationItem.rightBarButtonItem?.enabled = textView.hasText()
// 计算剩余微博的长度
let length = statusMaxLength - textView.emoticonText().characters.count // 注意此处使用emotionText,这样才能包含表情图片占的字符
lengthTipLabel.text = String(length)
// 判断 length 大于等于0显示灰色, 小于0显示红色
lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
}
}
|
apache-2.0
|
430ea882d48c3d325c894e78bc0b2b9f
| 35.048649 | 260 | 0.626856 | 4.787509 | false | false | false | false |
weikz/Mr-Ride-iOS
|
Mr-Ride-iOS/HomeViewController.swift
|
1
|
2448
|
//
// ViewController.swift
// Mr-Ride-iOS
//
// Created by 張瑋康 on 2016/5/23.
// Copyright © 2016年 Appworks School Weikz. All rights reserved.
//
import UIKit
import SideMenu
import Amplitude_iOS
class HomeViewController: UIViewController {
var conuter = 0
@IBOutlet weak var totalDistanceCount: UILabel!
@IBOutlet weak var totalCountsCount: UILabel!
@IBOutlet weak var averageSpeedCount: UILabel!
@IBOutlet weak var letsRideButton: UIButton!
@IBAction func letsRideButton(sender: UIButton) {
let newRecordViewController = self.storyboard?.instantiateViewControllerWithIdentifier("NewRecordViewController") as! NewRecordViewController
let navigationControllerForRootView = UINavigationController(rootViewController: newRecordViewController)
self.presentViewController(navigationControllerForRootView, animated: true, completion: nil)
Amplitude.instance().logEvent("select_ride_in_home")
}
@IBAction func sideMenuButton(sender: UIBarButtonItem) {
Amplitude.instance().logEvent("select_menu_in_home")
}
@IBOutlet weak var sideMenuButton: UIBarButtonItem!
}
// MARK: - View Life Cycle
extension HomeViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupLogo()
setupSideMenu()
setupLetsRideButton()
Amplitude.instance().logEvent("view_in_home")
}
func thumbsUpButtonPressed() {
print("thumbs up button pressed")
}
}
// MARK: - Setup
extension HomeViewController {
func setupLogo() {
let logo = UIImageView(image: UIImage(named: "logo-bike.png"))
logo.image = logo.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
logo.tintColor = .whiteColor()
self.navigationItem.titleView = logo
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
}
func setupSideMenu() {
if self.revealViewController() != nil {
sideMenuButton.target = self.revealViewController()
sideMenuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
func setupLetsRideButton() {
letsRideButton.layer.cornerRadius = 30
}
}
|
mit
|
d7ce02790343f1deb4b2bf36a5803a3e
| 31.52 | 149 | 0.695367 | 5.039256 | false | false | false | false |
mspvirajpatel/SwiftyBase
|
SwiftyBase/Classes/Model/Country.swift
|
1
|
1905
|
//
// Country.swift
// SwiftyBase
//
// Created by MacMini-2 on 08/09/17.
//
import Foundation
/// Class to define a country
open class Country: NSObject {
open var countryCode: String
open var phoneExtension: String
open var isMain: Bool
public static var emptyCountry: Country { return Country(countryCode: "", phoneExtension: "", isMain: true) }
public static var currentCountry: Country {
let localIdentifier = Locale.current.identifier //returns identifier of your telephones country/region settings
let locale = NSLocale(localeIdentifier: localIdentifier)
if let countryCode = locale.object(forKey: .countryCode) as? String {
return Countries.countryFromCountryCode(countryCode.uppercased())
}
return Country.emptyCountry
}
/// Constructor to initialize a country
///
/// - Parameters:
/// - countryCode: the country code
/// - phoneExtension: phone extension
/// - isMain: Bool
public init(countryCode: String, phoneExtension: String, isMain: Bool) {
self.countryCode = countryCode
self.phoneExtension = phoneExtension
self.isMain = isMain
}
/// Obatin the country name based on current locale
@objc open var name: String {
let localIdentifier = Locale.current.identifier //returns identifier of your telephones country/region settings
let locale = NSLocale(localeIdentifier: localIdentifier)
if let country: String = locale.displayName(forKey: .countryCode, value: countryCode.uppercased()) {
return country
} else {
return "Invalid country code"
}
}
}
/// compare to country
///
/// - Parameters:
/// - lhs: Country
/// - rhs: Country
/// - Returns: Bool
public func == (lhs: Country, rhs: Country) -> Bool {
return lhs.countryCode == rhs.countryCode
}
|
mit
|
bf4d1431b7bb43764ff3ab722a7764a7
| 26.214286 | 119 | 0.659318 | 4.786432 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.