repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Features/About/Legal/PrivacyPolicy/PrivacyPolicyViewController.swift | 1 | 3745 | //
// PrivacyPolicyViewController.swift
// EclipseSoundscapes
//
// Created by Arlindo Goncalves on 8/15/17.
// Copyright © 2017 Arlindo Goncalves. All rights reserved.
//
import UIKit
import Eureka
import WebKit
class PrivacyPolicyViewController: BaseViewController, TypedRowControllerType, WKNavigationDelegate {
var row: RowOf<String>!
var onDismissCallback: ((UIViewController) -> Void)?
private let viewModel = PrivacyPolicyViewModel()
private var headerView : ShrinkableHeaderView = {
let view = ShrinkableHeaderView(title: localizedString(key: "Privacy Policy"), titleColor: .black)
view.backgroundColor = SoundscapesColor.NavBarColor
view.maxHeaderHeight = 60
view.isShrinkable = false
return view
}()
private lazy var backBtn : UIButton = {
var btn = UIButton(type: .system)
btn.addSqueeze()
btn.setImage(#imageLiteral(resourceName: "left-small").withRenderingMode(.alwaysTemplate), for: .normal)
btn.tintColor = .black
btn.addTarget(self, action: #selector(close), for: .touchUpInside)
btn.accessibilityLabel = localizedString(key: "Back")
return btn
}()
private lazy var webView: WKWebView = {
let webView = WKWebView()
webView.navigationDelegate = self
return webView
}()
private let activityIndicator = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
private func setup() {
setupViews()
setupPrivacyPolicy()
}
private func setupViews() {
view.backgroundColor = headerView.backgroundColor
view.addSubviews(headerView, webView, activityIndicator)
headerView.headerHeightConstraint = headerView.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: headerView.maxHeaderHeight).last
headerView.addSubviews(backBtn)
backBtn.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
backBtn.leftAnchor.constraint(equalTo: headerView.leftAnchor, constant: 10).isActive = true
webView.anchorToTop(headerView.bottomAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor)
activityIndicator.center(in: view)
}
private func setupPrivacyPolicy() {
guard let privacyPolicyUrl = viewModel.privacyPolicyUrl else { return }
let request = URLRequest(url: privacyPolicyUrl)
activityIndicator.startAnimating()
webView.load(request)
}
@objc private func close() {
self.dismiss(animated: true, completion: nil)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
guard let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
if components?.scheme == "http" || components?.scheme == "https" {
LinkManager.shared.openUrl(url)
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
} else {
decisionHandler(.allow)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicator.stopAnimating()
}
}
| gpl-3.0 | 56c195684436e62d6917a713eda4b152 | 35 | 295 | 0.663194 | 5.363897 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/Business/Data Model/Extensions/Habit+Check.swift | 1 | 1061 | //
// Habit+Check.swift
// YourGoals
//
// Created by André Claaßen on 06.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
enum HabitCheckedState {
case checked
case notChecked
}
extension Habit {
func allHabitChecks() -> [HabitCheck] {
guard let checks = self.checks?.allObjects as? [HabitCheck] else {
return []
}
return checks
}
/// very inperformant way to get check states
///
/// - Returns: all check states as a hash
func allChecks() -> [Date:Bool] {
let checks = self.allHabitChecks()
var hash = [Date:Bool]()
for habitCheck in checks {
if let date = habitCheck.check {
hash[date] = true
}
}
return hash
}
/// true, if habit is checked for date
///
/// - Parameter date: the date
func isChecked(forDate date: Date) -> Bool {
return self.allChecks()[date.day()] ?? false
}
}
| lgpl-3.0 | 72b1463b821074a7e6c04206aee9ae3c | 20.12 | 74 | 0.539773 | 4.275304 | false | false | false | false |
wireapp/wire-ios-data-model | Tests/Source/Helper/MockActionHandler.swift | 1 | 1262 | //
// Wire
// Copyright (C) 2021 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
class MockActionHandler<T: EntityAction>: EntityActionHandler {
typealias Action = T
typealias Result = Swift.Result<Action.Result, Action.Failure>
var result: Result
var token: Any?
var didPerformAction: Bool = false
init(result: Result, context: NotificationContext) {
self.result = result
token = Action.registerHandler(self, context: context)
}
func performAction(_ action: Action) {
var action = action
action.notifyResult(result)
didPerformAction = true
}
}
| gpl-3.0 | 014166a63379123b6d5692b07b8ed96c | 29.780488 | 71 | 0.711569 | 4.397213 | false | false | false | false |
apple/swift-experimental-string-processing | Sources/_StringProcessing/Algorithms/Consumers/CollectionConsumer.swift | 1 | 1746 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
protocol CollectionConsumer {
associatedtype Consumed: Collection
func consuming(
_ consumed: Consumed,
in range: Range<Consumed.Index>
) -> Consumed.Index?
}
extension CollectionConsumer {
func consuming(_ consumed: Consumed) -> Consumed.Index? {
consuming(consumed, in: consumed.startIndex..<consumed.endIndex)
}
// TODO: `@discardableResult`?
/// Returns `true` if the consume was successful.
func consume(_ consumed: inout Consumed) -> Bool
where Consumed.SubSequence == Consumed
{
guard let index = consuming(consumed) else { return false }
consumed = consumed[index...]
return true
}
}
// MARK: Consuming from the back
protocol BidirectionalCollectionConsumer: CollectionConsumer
where Consumed: BidirectionalCollection
{
func consumingBack(
_ consumed: Consumed,
in range: Range<Consumed.Index>
) -> Consumed.Index?
}
extension BidirectionalCollectionConsumer {
func consumingBack(_ consumed: Consumed) -> Consumed.Index? {
consumingBack(consumed, in: consumed.startIndex..<consumed.endIndex)
}
func consumeBack(_ consumed: inout Consumed) -> Bool
where Consumed.SubSequence == Consumed
{
guard let index = consumingBack(consumed) else { return false }
consumed = consumed[..<index]
return true
}
}
| apache-2.0 | d71f1d39d34aebaa7cce97b1148ade77 | 28.59322 | 80 | 0.650057 | 4.85 | false | false | false | false |
caynan/Horus | Tests/BinarySpec.swift | 1 | 38161 | //
// BinarySpec.swift
// Horus
//
// Created by Caynan Sousa on 5/27/17.
// Copyright © 2017 Caynan. All rights reserved.
//
import Quick
import Nimble
@testable import Horus
class BinarySpec: QuickSpec {
override func spec() {
describe("BinarySpec") {
// MARK: - Initialization
context("Initializations") {
it("initializes with array literal.") {
let binary: Binary? = [0x63, 0x61, 0x79, 0x6E, 0x61, 0x6E, 0x00]
expect(binary).toNot(beNil())
}
it("initializes with Data object.") {
let data: Data = Data()
let binary: Binary? = Binary(with: data)
expect(binary).toNot(beNil())
}
it("initializes with array of bytes (aka UInt8).") {
let dataArray: [UInt8] = [0x63, 0x61, 0x79]
let binary = Binary(with: dataArray)
// Correct Size
expect(binary.count).to(equal(3))
// Correct Values
expect(binary[0]).to(equal(0x63))
expect(binary[1]).to(equal(0x61))
expect(binary[2]).to(equal(0x79))
}
it("Initializes with an Integer") {
func testSize<T: Integer>(_ number: T) {
let binary = Binary(with: number)
expect(binary.count).to(equal(MemoryLayout.size(ofValue: number)))
}
// for UInts
testSize(UInt.max)
testSize(UInt32.max)
testSize(UInt16.max)
testSize(UInt8.max)
// for Ints
testSize(Int.max)
testSize(Int32.max)
testSize(Int16.max)
testSize(Int8.max)
// Test values
func testValue<T: Integer>(_ testCase: (number: T, expected: [UInt8]) ) {
let binary = Binary(with: testCase.number)
for i in 0..<testCase.expected.count {
expect(binary[i]).to(equal(testCase.expected[i]))
}
}
// UInts
testValue( (number: UInt8.min, expected: [0x00]) )
testValue( (number: UInt16.min, expected: [0x00, 0x00]) )
testValue( (number: UInt32.min, expected: [0x00, 0x00, 0x00, 0x00]) )
testValue( (number: UInt64.min, expected: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) )
testValue( (number: UInt8.max, expected: [0xFF]) )
testValue( (number: UInt16.max, expected: [0xFF, 0xFF]) )
testValue( (number: UInt32.max, expected: [0xFF, 0xFF, 0xFF, 0xFF]) )
testValue( (number: UInt64.max, expected: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) )
testValue((number: UInt(0x1234567890), expected: [0x00, 0x00, 0x00, 0x12, 0x34, 0x56, 0x78, 0x90]))
// Ints
testValue( (number: Int8.min, expected: [0x80]) )
testValue( (number: Int16.min, expected: [0x80, 0x00]) )
testValue( (number: Int32.min, expected: [0x80, 0x00, 0x00, 0x00]) )
testValue( (number: Int64.min, expected: [0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) )
testValue( (number: Int8.max, expected: [0x7F]) )
testValue( (number: Int16.max, expected: [0x7F, 0xFF]) )
testValue( (number: Int32.max, expected: [0x7F, 0xFF, 0xFF, 0xFF]) )
testValue( (number: Int64.max, expected: [0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) )
testValue((number: Int(0x1234567890), expected: [0x00, 0x00, 0x00, 0x12, 0x34, 0x56, 0x78, 0x90]))
// 2-complement bin: 1111 1111 1111 1111 1111 1111 1110 1101 1100 1011 1010 1001 1000 0111 0111 0000
testValue((number: -Int(0x1234567890), expected: [0xFF, 0xFF, 0xFF, 0xED, 0xCB, 0xA9, 0x87, 0x70]))
}
it("Initializes with a hex string.") {
let hexString = "00FF"
guard let binary = Binary(with: hexString) else {
fail("Failed to initialize with \(hexString)")
return
}
expect(binary.count).to(equal(2))
expect(binary[0]).to(equal(0x00))
expect(binary[1]).to(equal(0xFF))
let wrongBin = Binary(with: "XX")
expect(wrongBin).to(beNil())
}
}
// MARK: - MutableCollection
context("MutableCollection") {
it("Should access single element") {
let binary: Binary = [0x00, 0x01, 0x02]
expect(binary[0]).to(equal(0x00))
expect(binary[1]).to(equal(0x01))
expect(binary[2]).to(equal(0x02))
}
it("Should change single element") {
var binary: Binary = [0x00, 0x01, 0x02]
expect(binary[0]).to(equal(0x00)) // Check old value
binary[0] = 0x42 // Change value
expect(binary[0]).to(equal(0x42)) // Check that it changed
}
it("Should access a range of elements") {
let binary: Binary = [0x00, 0x01, 0x02]
let openSlice = binary[0..<binary.count]
expect(openSlice).to(equal(binary))
let closedSlice = binary[0...2]
expect(closedSlice).to(equal(binary))
}
it("Should change a range of elements") {
var binary: Binary = [0x00, 0x01, 0x02]
binary[0...2] = [0x42, 0x43, 0x44]
expect(binary[0]).to(equal(0x42))
expect(binary[1]).to(equal(0x43))
expect(binary[2]).to(equal(0x44))
}
it("Should change a range of elements adding elements") {
var binary: Binary = [0x00, 0x01, 0x02]
binary[0..<2] = [0x42, 0x43, 0x44]
expect(binary[0]).to(equal(0x42))
expect(binary[1]).to(equal(0x43))
expect(binary[2]).to(equal(0x44))
expect(binary[3]).to(equal(0x02))
}
}
// MARK: - RangeReplaceableCollection
context("RangeReplaceableCollection") {
it("Should initialize with empty Data") {
let binary = Binary()
expect(binary.count).to(equal(0))
}
it("Should replace subrange using a collection") {
var binary: Binary = [0x01, 0x02, 0x03]
binary.replaceSubrange(0..<2, with: [0xFF, 0x00])
print(binary.toByteArray())
expect(binary[0]).to(equal(0xFF))
expect(binary[1]).to(equal(0x00))
expect(binary[2]).to(equal(0x03))
}
it("Should replace subrange using a collection bigger than the range") {
var binary: Binary = [0x01, 0x02, 0x03]
binary.replaceSubrange(0..<2, with: [30, 09, 19, 92])
print(binary.toByteArray())
expect(binary[0]).to(equal(30))
expect(binary[1]).to(equal(09))
expect(binary[2]).to(equal(19))
expect(binary[3]).to(equal(92))
expect(binary[4]).to(equal(0x03))
}
}
// MARK: - Little Endian Tests
context("Bit access - Little Endian") {
it("Get the correct bits for 0000001") {
do {
let binary: Binary = [0b0000001]
let bit0 = try binary.bit(0)
let bit1 = try binary.bit(1)
let bit2 = try binary.bit(2)
let bit3 = try binary.bit(3)
let bit4 = try binary.bit(4)
let bit5 = try binary.bit(5)
let bit6 = try binary.bit(6)
let bit7 = try binary.bit(7)
// Asserts
expect(bit0).to(equal(1))
expect(bit1).to(equal(0))
expect(bit2).to(equal(0))
expect(bit3).to(equal(0))
expect(bit4).to(equal(0))
expect(bit5).to(equal(0))
expect(bit6).to(equal(0))
expect(bit7).to(equal(0))
} catch {
fail("It should get the correct bit values")
}
}
it("Get the correct bits for 11111110") {
do {
let binary: Binary = [0b11111110]
let bit0 = try binary.bit(0)
let bit1 = try binary.bit(1)
let bit2 = try binary.bit(2)
let bit3 = try binary.bit(3)
let bit4 = try binary.bit(4)
let bit5 = try binary.bit(5)
let bit6 = try binary.bit(6)
let bit7 = try binary.bit(7)
// Asserts
expect(bit0).to(equal(0))
expect(bit1).to(equal(1))
expect(bit2).to(equal(1))
expect(bit3).to(equal(1))
expect(bit4).to(equal(1))
expect(bit5).to(equal(1))
expect(bit6).to(equal(1))
expect(bit7).to(equal(1))
} catch {
fail("It should get the correct bit values")
}
}
it("Get the correct bits for 11110000111") {
do {
let binary: Binary = [0b00000101, 0b10000111]
let bit0 = try binary.bit(0)
let bit1 = try binary.bit(1)
let bit2 = try binary.bit(2)
let bit3 = try binary.bit(3)
let bit4 = try binary.bit(4)
let bit5 = try binary.bit(5)
let bit6 = try binary.bit(6)
let bit7 = try binary.bit(7)
let bit8 = try binary.bit(8)
let bit9 = try binary.bit(9)
let bit10 = try binary.bit(10)
let bit11 = try binary.bit(11)
let bit12 = try binary.bit(12)
let bit13 = try binary.bit(13)
let bit14 = try binary.bit(14)
let bit15 = try binary.bit(15)
// Asserts
expect(bit0).to(equal(1))
expect(bit1).to(equal(1))
expect(bit2).to(equal(1))
expect(bit3).to(equal(0))
expect(bit4).to(equal(0))
expect(bit5).to(equal(0))
expect(bit6).to(equal(0))
expect(bit7).to(equal(1))
expect(bit8).to(equal(1))
expect(bit9).to(equal(0))
expect(bit10).to(equal(1))
expect(bit11).to(equal(0))
expect(bit12).to(equal(0))
expect(bit13).to(equal(0))
expect(bit14).to(equal(0))
expect(bit15).to(equal(0))
} catch {
fail("It should get the correct bit values")
}
}
it("Get the correct bits for 00010110000111") {
do {
let binary: Binary = [0b000101, 0b10000111]
let bit0 = try binary.bit(0)
let bit1 = try binary.bit(1)
let bit2 = try binary.bit(2)
let bit3 = try binary.bit(3)
let bit4 = try binary.bit(4)
let bit5 = try binary.bit(5)
let bit6 = try binary.bit(6)
let bit7 = try binary.bit(7)
let bit8 = try binary.bit(8)
let bit9 = try binary.bit(9)
let bit10 = try binary.bit(10)
let bit11 = try binary.bit(11)
let bit12 = try binary.bit(12)
let bit13 = try binary.bit(13)
let bit14 = try binary.bit(14)
let bit15 = try binary.bit(15)
// Asserts
expect(bit0).to(equal(1))
expect(bit1).to(equal(1))
expect(bit2).to(equal(1))
expect(bit3).to(equal(0))
expect(bit4).to(equal(0))
expect(bit5).to(equal(0))
expect(bit6).to(equal(0))
expect(bit7).to(equal(1))
expect(bit8).to(equal(1))
expect(bit9).to(equal(0))
expect(bit10).to(equal(1))
expect(bit11).to(equal(0))
expect(bit12).to(equal(0))
expect(bit13).to(equal(0))
expect(bit14).to(equal(0))
expect(bit15).to(equal(0))
} catch {
fail("It should get the correct bit values")
}
}
it("Get the correct bits for 00000101 00000011") {
do {
let binary: Binary = [0b101, 0b11]
let bit0 = try binary.bit(0)
let bit1 = try binary.bit(1)
let bit2 = try binary.bit(2)
let bit3 = try binary.bit(3)
let bit4 = try binary.bit(4)
let bit5 = try binary.bit(5)
let bit6 = try binary.bit(6)
let bit7 = try binary.bit(7)
let bit8 = try binary.bit(8)
let bit9 = try binary.bit(9)
let bit10 = try binary.bit(10)
let bit11 = try binary.bit(11)
let bit12 = try binary.bit(12)
let bit13 = try binary.bit(13)
let bit14 = try binary.bit(14)
let bit15 = try binary.bit(15)
// Asserts
expect(bit0).to(equal(1))
expect(bit1).to(equal(1))
expect(bit2).to(equal(0))
expect(bit3).to(equal(0))
expect(bit4).to(equal(0))
expect(bit5).to(equal(0))
expect(bit6).to(equal(0))
expect(bit7).to(equal(0))
expect(bit8).to(equal(1))
expect(bit9).to(equal(0))
expect(bit10).to(equal(1))
expect(bit11).to(equal(0))
expect(bit12).to(equal(0))
expect(bit13).to(equal(0))
expect(bit14).to(equal(0))
expect(bit15).to(equal(0))
} catch {
fail("It should get the correct bit values")
}
}
// MARK: - Big Endian tests
context("Bit access - Big Endian") {
it("Get the correct bits for 0000001") {
do {
let binary: Binary = [0b0000001]
let bit0 = try binary.bit(0, isLittleEndian: false)
let bit1 = try binary.bit(1, isLittleEndian: false)
let bit2 = try binary.bit(2, isLittleEndian: false)
let bit3 = try binary.bit(3, isLittleEndian: false)
let bit4 = try binary.bit(4, isLittleEndian: false)
let bit5 = try binary.bit(5, isLittleEndian: false)
let bit6 = try binary.bit(6, isLittleEndian: false)
let bit7 = try binary.bit(7, isLittleEndian: false)
// Asserts
expect(bit0).to(equal(0))
expect(bit1).to(equal(0))
expect(bit2).to(equal(0))
expect(bit3).to(equal(0))
expect(bit4).to(equal(0))
expect(bit5).to(equal(0))
expect(bit6).to(equal(0))
expect(bit7).to(equal(1))
} catch {
fail("It should get the correct bit values")
}
}
it("Get the correct bits for 11111110") {
do {
let binary: Binary = [0b11111110]
let bit0 = try binary.bit(0, isLittleEndian: false)
let bit1 = try binary.bit(1, isLittleEndian: false)
let bit2 = try binary.bit(2, isLittleEndian: false)
let bit3 = try binary.bit(3, isLittleEndian: false)
let bit4 = try binary.bit(4, isLittleEndian: false)
let bit5 = try binary.bit(5, isLittleEndian: false)
let bit6 = try binary.bit(6, isLittleEndian: false)
let bit7 = try binary.bit(7, isLittleEndian: false)
// Asserts
expect(bit0).to(equal(1))
expect(bit1).to(equal(1))
expect(bit2).to(equal(1))
expect(bit3).to(equal(1))
expect(bit4).to(equal(1))
expect(bit5).to(equal(1))
expect(bit6).to(equal(1))
expect(bit7).to(equal(0))
} catch {
fail("It should get the correct bit values")
}
}
it("Get the correct bits for 11110000111") {
do {
let binary: Binary = [0b00000101, 0b10000111]
let bit0 = try binary.bit(0, isLittleEndian: false)
let bit1 = try binary.bit(1, isLittleEndian: false)
let bit2 = try binary.bit(2, isLittleEndian: false)
let bit3 = try binary.bit(3, isLittleEndian: false)
let bit4 = try binary.bit(4, isLittleEndian: false)
let bit5 = try binary.bit(5, isLittleEndian: false)
let bit6 = try binary.bit(6, isLittleEndian: false)
let bit7 = try binary.bit(7, isLittleEndian: false)
let bit8 = try binary.bit(8, isLittleEndian: false)
let bit9 = try binary.bit(9, isLittleEndian: false)
let bit10 = try binary.bit(10, isLittleEndian: false)
let bit11 = try binary.bit(11, isLittleEndian: false)
let bit12 = try binary.bit(12, isLittleEndian: false)
let bit13 = try binary.bit(13, isLittleEndian: false)
let bit14 = try binary.bit(14, isLittleEndian: false)
let bit15 = try binary.bit(15, isLittleEndian: false)
// Asserts
expect(bit0).to(equal(0))
expect(bit1).to(equal(0))
expect(bit2).to(equal(0))
expect(bit3).to(equal(0))
expect(bit4).to(equal(0))
expect(bit5).to(equal(1))
expect(bit6).to(equal(0))
expect(bit7).to(equal(1))
expect(bit8).to(equal(1))
expect(bit9).to(equal(0))
expect(bit10).to(equal(0))
expect(bit11).to(equal(0))
expect(bit12).to(equal(0))
expect(bit13).to(equal(1))
expect(bit14).to(equal(1))
expect(bit15).to(equal(1))
} catch {
fail("It should get the correct bit values")
}
}
it("Get the correct bits for 00010110000111") {
do {
let binary: Binary = [0b000101, 0b10000111]
let bit0 = try binary.bit(0, isLittleEndian: false)
let bit1 = try binary.bit(1, isLittleEndian: false)
let bit2 = try binary.bit(2, isLittleEndian: false)
let bit3 = try binary.bit(3, isLittleEndian: false)
let bit4 = try binary.bit(4, isLittleEndian: false)
let bit5 = try binary.bit(5, isLittleEndian: false)
let bit6 = try binary.bit(6, isLittleEndian: false)
let bit7 = try binary.bit(7, isLittleEndian: false)
let bit8 = try binary.bit(8, isLittleEndian: false)
let bit9 = try binary.bit(9, isLittleEndian: false)
let bit10 = try binary.bit(10, isLittleEndian: false)
let bit11 = try binary.bit(11, isLittleEndian: false)
let bit12 = try binary.bit(12, isLittleEndian: false)
let bit13 = try binary.bit(13, isLittleEndian: false)
let bit14 = try binary.bit(14, isLittleEndian: false)
let bit15 = try binary.bit(15, isLittleEndian: false)
// Asserts
expect(bit0).to(equal(0))
expect(bit1).to(equal(0))
expect(bit2).to(equal(0))
expect(bit3).to(equal(0))
expect(bit4).to(equal(0))
expect(bit5).to(equal(1))
expect(bit6).to(equal(0))
expect(bit7).to(equal(1))
expect(bit8).to(equal(1))
expect(bit9).to(equal(0))
expect(bit10).to(equal(0))
expect(bit11).to(equal(0))
expect(bit12).to(equal(0))
expect(bit13).to(equal(1))
expect(bit14).to(equal(1))
expect(bit15).to(equal(1))
} catch {
fail("It should get the correct bit values")
}
}
it("Get the correct bits for 0b101 0b11") {
do {
let binary: Binary = [0b101, 0b11]
let bit0 = try binary.bit(0, isLittleEndian: false)
let bit1 = try binary.bit(1, isLittleEndian: false)
let bit2 = try binary.bit(2, isLittleEndian: false)
let bit3 = try binary.bit(3, isLittleEndian: false)
let bit4 = try binary.bit(4, isLittleEndian: false)
let bit5 = try binary.bit(5, isLittleEndian: false)
let bit6 = try binary.bit(6, isLittleEndian: false)
let bit7 = try binary.bit(7, isLittleEndian: false)
let bit8 = try binary.bit(8, isLittleEndian: false)
let bit9 = try binary.bit(9, isLittleEndian: false)
let bit10 = try binary.bit(10, isLittleEndian: false)
let bit11 = try binary.bit(11, isLittleEndian: false)
let bit12 = try binary.bit(12, isLittleEndian: false)
let bit13 = try binary.bit(13, isLittleEndian: false)
let bit14 = try binary.bit(14, isLittleEndian: false)
let bit15 = try binary.bit(15, isLittleEndian: false)
// Asserts
expect(bit0).to(equal(0))
expect(bit1).to(equal(0))
expect(bit2).to(equal(0))
expect(bit3).to(equal(0))
expect(bit4).to(equal(0))
expect(bit5).to(equal(1))
expect(bit6).to(equal(0))
expect(bit7).to(equal(1))
expect(bit8).to(equal(0))
expect(bit9).to(equal(0))
expect(bit10).to(equal(0))
expect(bit11).to(equal(0))
expect(bit12).to(equal(0))
expect(bit13).to(equal(0))
expect(bit14).to(equal(1))
expect(bit15).to(equal(1))
} catch {
fail("It should get the correct bit values")
}
}
}
}
// MARK: - Nibble parsing
context("Nibble parsing") {
it("Should get the correct nibbles for 0x0F") {
let binary: Binary = [0x0F]
do {
let nibble0 = try binary.nibble(0)
let nibble1 = try binary.nibble(1)
expect(nibble0).to(equal(0))
expect(nibble1).to(equal(15))
} catch {
fail("It failed to get nibbles.")
}
}
it("Should get the correct nibbles for 0xF0CA") {
guard let binary = Binary(with: "F0CA") else {
fail("Failed to initialize binary with F0CA")
return
}
do {
let nibble0 = try binary.nibble(0)
let nibble1 = try binary.nibble(1)
let nibble2 = try binary.nibble(2)
let nibble3 = try binary.nibble(3)
expect(nibble0).to(equal(15))
expect(nibble1).to(equal(0))
expect(nibble2).to(equal(12))
expect(nibble3).to(equal(10))
} catch {
fail("It failed to get the nibbles of 0xF0CA")
}
}
it("Should get the correct value for [0x0, 0xCA]") {
let binary: Binary = [0x0, 0xCA]
do {
let nibble0 = try binary.nibble(0)
let nibble1 = try binary.nibble(1)
let nibble2 = try binary.nibble(2)
let nibble3 = try binary.nibble(3)
expect(nibble0).to(equal(0))
expect(nibble1).to(equal(0))
expect(nibble2).to(equal(12))
expect(nibble3).to(equal(10))
} catch {
fail("it failed to get the nibbles from [0x0, 0xCA]")
}
}
it("Should get the correct value for 0x0CA") {
guard let binary = Binary(with: "0CA") else {
fail("Failed to initialize binary with '0CA'")
return
}
do {
let nibble0 = try binary.nibble(0)
let nibble1 = try binary.nibble(1)
let nibble2 = try binary.nibble(2)
let nibble3 = try binary.nibble(3)
expect(nibble0).to(equal(0))
expect(nibble1).to(equal(0))
expect(nibble2).to(equal(12))
expect(nibble3).to(equal(10))
} catch {
fail("it failed to get the nibbles from '0CA'")
}
}
it("Should get the correct value for [0xA, 0xB]") {
let binary: Binary = [0xA, 0xB]
do {
let nibble0 = try binary.nibble(0)
let nibble1 = try binary.nibble(1)
let nibble2 = try binary.nibble(2)
let nibble3 = try binary.nibble(3)
expect(nibble0).to(equal(0))
expect(nibble1).to(equal(10))
expect(nibble2).to(equal(0))
expect(nibble3).to(equal(11))
} catch {
fail("it failed to get the nibbles from [0xA, 0xB]")
}
}
}
// MARK: - Integer parsing
context("Integer Parsing") {
// MARK: Unsigned Integers
it("Should parse UInt8 with length") {
do {
let binary: Binary = [0xFF]
let parsedInt: UInt8 = try binary.scanValue(start: 0, length: 1)
expect(parsedInt).to(equal(UInt8.max)) // UInt8.max => 255
} catch {
fail("It should have parsed UInt8, but it failed.")
}
}
it("Should parse UInt8") {
let binary: Binary = [0xFF]
do {
let parsedInt: UInt8 = try binary.get(at: 0)
expect(parsedInt).to(equal(UInt8.max)) // UInt8.max => 255
} catch {
fail("It should have parsed UInt8, but it failed.")
}
}
it("Should parse UInt16 with length") {
let binary: Binary = [0xFF, 0xFF]
do {
let parsedInt: UInt16 = try binary.scanValue(start: 0, length: 2)
expect(parsedInt).to(equal(UInt16.max)) // UInt16.max => 65535
} catch {
fail("It should have parsed UInt16, but it failed.")
}
}
it("Should parse UInt16") {
let binary: Binary = [0xFF, 0xFF]
do {
let parsedInt: UInt16 = try binary.get(at: 0)
expect(parsedInt).to(equal(UInt16.max)) // UInt16.max => 65535
} catch {
fail("It should have parsed UInt16, but it failed.")
}
}
it("Should parse UInt32 with length") {
let binary: Binary = [0xFF, 0xFF, 0xFF, 0xFF]
do {
let parsedInt: UInt32 = try binary.scanValue(start: 0, length: 4)
expect(parsedInt).to(equal(UInt32.max)) // UInt32.max => 4294967295
} catch {
fail("It should have parsed UInt32, but it failed.")
}
}
it("Should parse UInt32") {
let binary: Binary = [0xFF, 0xFF, 0xFF, 0xFF]
do {
let parsedInt: UInt32 = try binary.get(at: 0)
expect(parsedInt).to(equal(UInt32.max)) // UInt32.max => 4294967295
} catch {
fail("It should have parsed UInt32, but it failed.")
}
}
it("Should parse UInt64 with length") {
let binary: Binary = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
do {
let parsedInt: UInt32 = try binary.scanValue(start: 0, length: 8)
expect(parsedInt).to(equal(UInt32.max)) // UInt64.max => 18446744073709551615
} catch {
fail("It should have parsed UInt64, but it failed.")
}
}
it("Should parse UInt64") {
let binary: Binary = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
do {
let parsedInt: UInt64 = try binary.get(at: 0)
expect(parsedInt).to(equal(UInt64.max)) // UInt64.max => 18446744073709551615
} catch {
fail("It should have parsed UInt64, but it failed.")
}
}
// MARK: Signed Integers
// TODO: Add test for remaining Integer types.
it("Should parse Int") {
}
}
// MARK: FloatingPoint numbers
context("FloatingPoint Numbers Parsing") {
it("Should parse Double with length") {
let doubleBin: Binary = [0x71, 0x3d, 0x0a, 0xd7, 0xa3, 0x10, 0x45, 0x40] // => 42.13
do {
let parsedDouble: Double = try doubleBin.scanValue(start: 0, length: 8)
expect(parsedDouble).to(equal(42.13))
} catch {
fail("It should have parsed Double, but it failed.")
}
}
it("Should parse Double") {
let doubleBin: Binary = [0x71, 0x3d, 0x0a, 0xd7, 0xa3, 0x10, 0x45, 0x40] // => 42.13
do {
let parsedDouble: Double = try doubleBin.get(at: 0)
expect(parsedDouble).to(equal(42.13))
} catch {
fail("It should have parsed Double, but it failed.")
}
}
it("Should parse Float with length") {
let floatBin: Binary = [0x1F, 0x85, 0x28, 0x42] // => 42.13
do {
let parsedDouble: Float = try floatBin.scanValue(start: 0, length: 4)
expect(parsedDouble).to(equal(42.13))
} catch {
fail("It should have parsed Float, but it failed.")
}
}
it("Should parse Float") {
let floatBin: Binary = [0x1F, 0x85, 0x28, 0x42] // => 42.13
do {
let parsedDouble: Float = try floatBin.get(at: 0)
expect(parsedDouble).to(equal(42.13))
} catch {
fail("It should have parsed Float, but it failed.")
}
}
}
// MARK: - Strings
context("String Parsing") {
let binString1: Binary = [0x43, 0x61, 0x79, 0x6E, 0x61, 0x6E, 0x00] // => "Caynan"
let binString2: Binary = [0x48, 0x6F, 0x72, 0x75, 0x73] // => "Horus"
it("Should parse string with given length") {
do {
let parsedString = try binString2.get(offset: 0, length: 5)
expect(parsedString).to(equal("Horus"))
} catch {
fail("It should have parsed String with offset, but it failed")
}
}
it("Should parse Nul terminated string") {
do {
let parsedString = try binString1.get(offset: 0)
expect(parsedString).to(equal("Caynan"))
} catch {
fail("It should have parsed nul terminated string, but it failed")
}
}
}
// MARK: - CustomStringConvertible
context("CustomStringConvertible Implementation") {
let bin: Binary = [0, 1, 127, 128, 255]
it("Should return hex represenation of `bin`") {
expect(String(describing: bin)).to(equal("00017f80ff"))
}
}
}
}
}
| mit | 08bf5b0814d06f8772783eaa52263294 | 45.086957 | 120 | 0.410666 | 4.683933 | false | false | false | false |
IvanVorobei/RequestPermission | Example/SPPermission/SPPermission/Frameworks/SparrowKit/Device/SPDevice.swift | 1 | 2166 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// 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
struct SPDevice {
static var iphone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
static var ipad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
struct Orientation {
static var isPortrait: Bool {
var isPortraitOrientation = true
if UIDevice.current.orientation.isValidInterfaceOrientation {
if UIDevice.current.orientation.isPortrait {
isPortraitOrientation = true
} else {
isPortraitOrientation = false
}
} else {
if UIScreen.main.bounds.width < UIScreen.main.bounds.height {
isPortraitOrientation = true
} else {
isPortraitOrientation = false
}
}
return isPortraitOrientation
}
private init() {}
}
private init() {}
}
| mit | a071ac8367fe2945860a8453c8b1859c | 35.694915 | 81 | 0.648499 | 5.332512 | false | false | false | false |
RedMadRobot/input-mask-ios | Source/InputMask/InputMask/Classes/Helper/String.swift | 1 | 2448 | //
// Project «InputMask»
// Created by Jeorge Taflanidi
//
import Foundation
/**
Utility extension for commonly used ```Mask``` operations upon strings.
*/
public extension String {
/**
A shortcut for ```String(str.reversed())```.
*/
var reversed: String {
return String(self.reversed())
}
/**
Make a string by cutting the first character of current.
- returns: Current string without first character.
- throws: EXC_BAD_INSTRUCTION for empty strings.
*/
func truncateFirst() -> String {
return String(self[self.index(after: self.startIndex)...])
}
/**
Find common prefix.
*/
func prefixIntersection(with string: String) -> Substring {
var lhsIndex = startIndex
var rhsIndex = string.startIndex
while lhsIndex != endIndex && rhsIndex != string.endIndex {
if self[lhsIndex] == string[rhsIndex] {
lhsIndex = index(after: lhsIndex)
rhsIndex = string.index(after: rhsIndex)
} else {
return self[..<lhsIndex]
}
}
return self[..<lhsIndex]
}
/**
Reverse format string preserving `[...]` and `{...}` symbol groups.
*/
func reversedFormat() -> String {
return String(
String(self.reversed())
.replacingOccurrences(of: "[\\", with: "\\]")
.replacingOccurrences(of: "]\\", with: "\\[")
.replacingOccurrences(of: "{\\", with: "\\}")
.replacingOccurrences(of: "}\\", with: "\\{")
.map { (c: Character) -> Character in
switch c {
case "[": return "]"
case "]": return "["
case "{": return "}"
case "}": return "{"
default: return c
}
}
)
}
/**
A shortcut for ```str.distance(from: str.startIndex, to: index)```.
*/
func distanceFromStartIndex(to index: String.Index) -> Int {
return self.distance(from: self.startIndex, to: index)
}
/**
A shortcut for ```str.index(str.startIndex, offsetBy: offset)```.
*/
func startIndex(offsetBy offset: Int) -> String.Index {
return self.index(self.startIndex, offsetBy: offset)
}
}
| mit | ef66fd325fe2eccaf7a92d382869ba90 | 26.795455 | 72 | 0.503271 | 4.96146 | false | false | false | false |
jhihguan/JSON2Realm | JSON2RealmTests/ArgoRealm.swift | 1 | 1171 | //
// ArgoRealm.swift
// JSON2Realm
//
// Created by Wane Wang on 2016/1/3.
// Copyright © 2016年 Wane Wang. All rights reserved.
//
import Foundation
import Argo
import Curry
import RealmSwift
class ArgoClass: BasicClass {
convenience required init(name: String, birthday: String, age: Int) {
self.init()
self.name = name
self.birthday = birthday
self.age = age
}
}
extension ArgoClass: Decodable {
static func decode(json: JSON) -> Decoded<ArgoClass> {
return curry(ArgoClass.init)
<^> json <| "name"
<*> json <| "birthday"
<*> json <| "age"
}
}
class ArgoOptionalClass: BasicOptionalClass {
convenience required init(distance: Int?, note: String?, value: Int) {
self.init()
self.distance.value = distance
self.note = note
self.value = value
}
}
extension ArgoOptionalClass: Decodable {
static func decode(json: JSON) -> Decoded<ArgoOptionalClass> {
return curry(ArgoOptionalClass.init)
<^> json <|? "distance"
<*> json <|? "note"
<*> json <| "value"
}
} | mit | 3c059895bae3c40d348b71610fa77a84 | 21.480769 | 74 | 0.583048 | 4.112676 | false | false | false | false |
vhart/SwiftHSVColorPicker | Source/SwiftHSVColorPicker.swift | 1 | 2986 | //
// SwiftHSVColorPicker.swift
// SwiftHSVColorPicker
//
// Created by johankasperi on 2015-08-20.
//
import UIKit
public class SwiftHSVColorPicker: UIView {
var colorWheel: ColorWheel!
var brightnessView: BrightnessView!
var selectedColorView: SelectedColorView!
public var color: UIColor!
var hue: CGFloat = 1.0
var saturation: CGFloat = 1.0
var brightness: CGFloat = 1.0
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clearColor()
}
override public init(frame: CGRect) {
super.init(frame: frame)
}
public func setViewColor(color: UIColor) {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
if (!ok) {
print("SwiftHSVColorPicker: exception <The color provided to SwiftHSVColorPicker is not convertible to HSV>")
}
self.hue = hue
self.saturation = saturation
self.brightness = brightness
self.color = color
setup()
}
func setup() {
// Remove all subviews
let views = self.subviews
for view in views {
view.removeFromSuperview()
}
let width = self.bounds.width
let height = self.bounds.height
// Init SelectedColorView subview
selectedColorView = SelectedColorView(frame: CGRect(x: 0, y:0, width: width, height: 44), color: self.color)
// Add selectedColorView as a subview of this view
self.addSubview(selectedColorView)
// Init new ColorWheel subview
colorWheel = ColorWheel(frame: CGRect(x: 0, y: 44, width: width, height: width), color: self.color)
colorWheel.delegate = self
// Add colorWheel as a subview of this view
self.addSubview(colorWheel)
// Init new BrightnessView subview
brightnessView = BrightnessView(frame: CGRect(x: 0, y: width+44, width: width, height: 26), color: self.color)
brightnessView.delegate = self
// Add brightnessView as a subview of this view
self.addSubview(brightnessView)
}
func hueAndSaturationSelected(hue: CGFloat, saturation: CGFloat) {
self.hue = hue
self.saturation = saturation
self.color = UIColor(hue: self.hue, saturation: self.saturation, brightness: self.brightness, alpha: 1.0)
brightnessView.setViewColor(self.color)
selectedColorView.setViewColor(self.color)
}
func brightnessSelected(brightness: CGFloat) {
self.brightness = brightness
self.color = UIColor(hue: self.hue, saturation: self.saturation, brightness: self.brightness, alpha: 1.0)
colorWheel.setViewBrightness(brightness)
selectedColorView.setViewColor(self.color)
}
}
| mit | 9de2a6aa0c27b8a1393e0690c34c7a3e | 34.547619 | 121 | 0.646015 | 4.490226 | false | false | false | false |
erikmartens/NearbyWeather | NearbyWeather/Daemons/WeatherInformationUpdateDaemon.swift | 1 | 5180 | //
// WeatherInformationUpdateDaemon.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 13.01.21.
// Copyright © 2021 Erik Maximilian Martens. All rights reserved.
//
import RxSwift
import RxCocoa
import RxOptional
// MARK: - Dependencies
extension WeatherInformationUpdateDaemon {
struct Dependencies { // TODO: create protocols for all
var apiKeyService: ApiKeyService
var preferencesService: PreferencesService
var userLocationService: UserLocationService
var weatherStationService: WeatherStationService
var weatherInformationService: WeatherInformationService
}
}
// MARK: - Class Definition
final class WeatherInformationUpdateDaemon: NSObject, Daemon {
// MARK: - Assets
private var disposeBag = DisposeBag()
// MARK: - Properties
private let dependencies: Dependencies
// MARK: - Observables
private let appDidBecomeActiveRelay = PublishRelay<Void>()
// MARK: - Initialization
init(dependencies: Dependencies) {
self.dependencies = dependencies
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(notifyAppDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
printDebugMessage(
domain: String(describing: self),
message: "was deinitialized",
type: .info
)
}
// MARK: - Functions
func startObservations() {
observeBookmarkedStationsChanges()
observeAmountOfNearbyResultsPreferenceChanges()
observeAppDidBecomeActive()
}
func stopObservations() {
disposeBag = DisposeBag()
}
}
// MARK: - Observations
private extension WeatherInformationUpdateDaemon {
func observeBookmarkedStationsChanges() {
Observable
.combineLatest(
dependencies.weatherInformationService.createGetBookmarkedWeatherInformationListObservable().map { $0.map { $0.identity.identifier } },
dependencies.weatherStationService.createGetBookmarkedStationsObservable().map { $0.compactMap { $0.identifier} }.map { $0.map { String($0) } },
resultSelector: { existingWeatherInformationIdentifiers, bookmarkedWeatherInformationIdentifiers -> ([String], [String]) in
var toBeDeletedWeatherInformationIdentifiers: [String] = []
var toBeAddedWeatherInformationIdentifiers: [String] = []
existingWeatherInformationIdentifiers.forEach { exisitingIdentifier in
if !bookmarkedWeatherInformationIdentifiers.contains(exisitingIdentifier) {
toBeDeletedWeatherInformationIdentifiers.append(exisitingIdentifier)
}
}
bookmarkedWeatherInformationIdentifiers.forEach { bookmarkedIdentifier in
if !existingWeatherInformationIdentifiers.contains(bookmarkedIdentifier) {
toBeAddedWeatherInformationIdentifiers.append(bookmarkedIdentifier)
}
}
return (toBeDeletedWeatherInformationIdentifiers, toBeAddedWeatherInformationIdentifiers)
}
)
.flatMapLatest { [unowned self] result in
Completable
.zip(
result.0.map { dependencies.weatherInformationService.createRemoveBookmarkedWeatherInformationItemCompletable(for: $0) }
+ result.1.map { dependencies.weatherInformationService.createUpdateBookmarkedWeatherInformationCompletable(forStationWith: Int($0)) }
)
.asObservable()
.materialize()
}
.skip(until: appDidBecomeActiveRelay.asObservable())
.subscribe()
.disposed(by: disposeBag)
}
func observeAmountOfNearbyResultsPreferenceChanges() {
dependencies.preferencesService
.createGetAmountOfNearbyResultsOptionObservable()
.skip(until: appDidBecomeActiveRelay.asObservable())
.flatMapLatest { [unowned self] _ in
dependencies.weatherInformationService
.createUpdateNearbyWeatherInformationCompletable()
.asObservable()
.materialize()
}
.subscribe()
.disposed(by: disposeBag)
}
func observeAppDidBecomeActive() {
appDidBecomeActiveRelay
.asObservable()
.flatMapLatest { [unowned self] _ in
dependencies.preferencesService
.createGetRefreshOnAppStartOptionObservable()
.take(1)
.asSingle()
.flatMapCompletable { [unowned self] refreshOnAppStartOption -> Completable in
guard refreshOnAppStartOption.value == .yes else {
return Completable.emptyCompletable
}
return Completable.zip([
dependencies.weatherInformationService.createUpdateBookmarkedWeatherInformationCompletable(),
dependencies.weatherInformationService.createUpdateNearbyWeatherInformationCompletable()
])
}
.asObservable()
.materialize()
}
.subscribe()
.disposed(by: disposeBag)
}
}
// MARK: - Helpers
fileprivate extension WeatherInformationUpdateDaemon {
@objc func notifyAppDidBecomeActive() {
appDidBecomeActiveRelay.accept(())
}
}
| mit | 8c8809adcc5cd64149ab8600967f1f3f | 31.36875 | 157 | 0.699556 | 5.691209 | false | false | false | false |
OneBusAway/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Source/Infra/EKBackgroundView.swift | 3 | 2097 | //
// EKBackgroundView.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 4/20/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
class EKBackgroundView: EKStyleView {
// MARK: Props
private let visualEffectView: UIVisualEffectView
private let imageView: UIImageView
private let gradientView: GradientView
// MARK: Setup
init() {
imageView = UIImageView()
visualEffectView = UIVisualEffectView(effect: nil)
gradientView = GradientView()
super.init(frame: UIScreen.main.bounds)
addSubview(imageView)
imageView.contentMode = .scaleAspectFill
imageView.fillSuperview()
addSubview(visualEffectView)
visualEffectView.fillSuperview()
addSubview(gradientView)
gradientView.fillSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Background setter
var background: EKAttributes.BackgroundStyle! {
didSet {
guard let background = background else {
return
}
var gradient: EKAttributes.BackgroundStyle.Gradient?
var backgroundEffect: UIBlurEffect?
var backgroundColor: UIColor = .clear
var backgroundImage: UIImage?
switch background {
case .color(color: let color):
backgroundColor = color
case .gradient(gradient: let value):
gradient = value
case .image(image: let image):
backgroundImage = image
case .visualEffect(style: let style):
backgroundEffect = UIBlurEffect(style: style)
case .clear:
break
}
gradientView.gradient = gradient
visualEffectView.effect = backgroundEffect
layer.backgroundColor = backgroundColor.cgColor
imageView.image = backgroundImage
}
}
}
| apache-2.0 | faaa70043fb531672e30f3e4a9079ce7 | 28.535211 | 64 | 0.590844 | 5.890449 | false | false | false | false |
nissivm/DemoShop | Demo Shop/View Controllers/Products_VC.swift | 1 | 13349 | //
// Products_VC.swift
// Demo Shop
//
// Created by Nissi Vieira Miranda on 1/14/16.
// Copyright © 2016 Nissi Vieira Miranda. All rights reserved.
//
import UIKit
class Products_VC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate, ItemForSaleCellDelegate, ShoppingCart_VC_Delegate
{
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var shoppingCartButton: UIButton!
@IBOutlet weak var authenticationContainerView: UIView!
@IBOutlet weak var shopLogo: UIImageView!
@IBOutlet weak var shopName: UILabel!
@IBOutlet weak var headerHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var signOutButton: UIButton!
@IBOutlet weak var buttonsStackViewHeightConstraint: NSLayoutConstraint!
var itemsForSale = [ItemForSale]()
var shoppingCartItems = [ShoppingCartItem]()
let backend = Backend()
var multiplier: CGFloat = 1
override func viewDidLoad()
{
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willEnterForeground",
name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionStarted",
name: "SessionStarted", object: nil)
if Device.IS_IPHONE_6
{
multiplier = Constants.multiplier6
adjustForBiggerScreen()
}
else if Device.IS_IPHONE_6_PLUS
{
multiplier = Constants.multiplier6plus
adjustForBiggerScreen()
}
if Auxiliar.sessionIsValid()
{
dispatch_async(dispatch_get_main_queue())
{
self.authenticationContainerView.hidden = true
self.backend.offset = 1
self.retrieveProducts()
}
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle
{
return UIStatusBarStyle.LightContent
}
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//-------------------------------------------------------------------------//
// MARK: Notifications
//-------------------------------------------------------------------------//
func willEnterForeground()
{
if Auxiliar.sessionIsValid() == false
{
authenticationContainerView.hidden = false
}
}
func sessionStarted()
{
dispatch_async(dispatch_get_main_queue())
{
self.authenticationContainerView.hidden = true
if self.itemsForSale.count == 0
{
self.backend.offset = 1
self.retrieveProducts()
}
}
}
//-------------------------------------------------------------------------//
// MARK: IBActions
//-------------------------------------------------------------------------//
@IBAction func shoppingCartButtonTapped(sender: UIButton)
{
if shoppingCartButton.enabled
{
performSegueWithIdentifier("ToShoppingCart", sender: self)
}
}
@IBAction func signOutButtonTapped(sender: UIButton)
{
let defaults = NSUserDefaults.standardUserDefaults()
var currentUser = defaults.dictionaryForKey("currentUser")!
currentUser["sessionStatus"] = "invalid"
defaults.setObject(currentUser, forKey: "currentUser")
defaults.synchronize()
authenticationContainerView.hidden = false
}
//-------------------------------------------------------------------------//
// MARK: Retrieve products
//-------------------------------------------------------------------------//
func retrieveProducts()
{
Auxiliar.showLoadingHUDWithText("Retrieving products...", forView: self.view)
guard Reachability.connectedToNetwork() else
{
Auxiliar.hideLoadingHUDInView(self.view)
return
}
backend.fetchItemsForSale({
[unowned self](status, returnData) -> Void in
if let returnData = returnData
{
var items = [ItemForSale]()
for dic in returnData
{
let id = dic["id"] as! Int
let itemName = dic["item_name"] as! String
let itemPriceStr = dic["item_price"] as! String
let itemPriceNumber = NSNumberFormatter().numberFromString(itemPriceStr)!
let itemPrice = CGFloat(itemPriceNumber)
let imageAddr = dic["image_addr"] as! String
let imageURL : NSURL = NSURL(string: imageAddr)!
let item = ItemForSale()
item.id = "\(id)"
item.itemName = itemName
item.itemPrice = itemPrice
item.itemImage = UIImage(data: NSData(contentsOfURL: imageURL)!)
items.append(item)
}
dispatch_async(dispatch_get_main_queue())
{
self.incorporateNewSearchItems(items)
}
}
else if status == "No results"
{
Auxiliar.hideLoadingHUDInView(self.view)
self.searchingMore = false
self.hasMoreToShow = false
}
})
}
//-------------------------------------------------------------------------//
// MARK: UIScrollViewDelegate
//-------------------------------------------------------------------------//
var searchingMore = false
var hasMoreToShow = true
func scrollViewDidScroll(scrollView: UIScrollView)
{
if collectionView.contentOffset.y >= (collectionView.contentSize.height - collectionView.bounds.size.height)
{
if (searchingMore == false) && hasMoreToShow
{
searchingMore = true
backend.offset += 6
retrieveProducts()
}
}
}
//-------------------------------------------------------------------------//
// MARK: Incorporate new search items
//-------------------------------------------------------------------------//
func incorporateNewSearchItems(items : [ItemForSale])
{
var indexPath : NSIndexPath = NSIndexPath(forItem: 0, inSection: 0)
var counter = collectionView.numberOfItemsInSection(0)
var newItems = [NSIndexPath]()
for item in items
{
indexPath = NSIndexPath(forItem: counter, inSection: 0)
newItems.append(indexPath)
itemsForSale.append(item)
counter++
}
collectionView.performBatchUpdates({
[unowned self]() -> Void in
self.collectionView.insertItemsAtIndexPaths(newItems)
}){
completed in
Auxiliar.hideLoadingHUDInView(self.view)
self.searchingMore = false
}
}
//-------------------------------------------------------------------------//
// MARK: UICollectionViewDataSource
//-------------------------------------------------------------------------//
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return itemsForSale.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ItemForSaleCell",
forIndexPath: indexPath) as! ItemForSaleCell
cell.index = indexPath.item
cell.delegate = self
cell.setupCellWithItem(itemsForSale[indexPath.item])
return cell
}
//-------------------------------------------------------------------------//
// MARK: UICollectionViewDelegateFlowLayout
//-------------------------------------------------------------------------//
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
let cellWidth = self.view.frame.size.width/2
return CGSizeMake(cellWidth, 190 * multiplier)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat
{
return 0
}
//-------------------------------------------------------------------------//
// MARK: ItemForSaleCellDelegate
//-------------------------------------------------------------------------//
func addThisItemToShoppingCart(clickedItemIndex: Int)
{
let item = itemsForSale[clickedItemIndex]
var found = false
var message = "\(item.itemName) was added to shopping cart."
if shoppingCartItems.count > 0
{
for (index, cartItem) in shoppingCartItems.enumerate()
{
if cartItem.itemForSale.id == item.id
{
found = true
cartItem.amount++
shoppingCartItems[index] = cartItem
let lastLetterIdx = item.itemName.characters.count - 1
let lastLetter = NSString(string: item.itemName).substringFromIndex(lastLetterIdx)
if lastLetter != "s"
{
message = "You have \(cartItem.amount) \(item.itemName)s in your shopping cart."
}
else
{
message = "You have \(cartItem.amount) \(item.itemName) in your shopping cart."
}
break
}
}
}
else
{
shoppingCartButton.enabled = true
}
if found == false
{
let cartItem = ShoppingCartItem()
cartItem.itemForSale = item
shoppingCartItems.append(cartItem)
}
Auxiliar.presentAlertControllerWithTitle("Item added!",
andMessage: message, forViewController: self)
}
//-------------------------------------------------------------------------//
// MARK: ShoppingCart_VC_Delegate
//-------------------------------------------------------------------------//
func shoppingCartItemsListChanged(cartItems: [ShoppingCartItem])
{
shoppingCartItems = cartItems
if shoppingCartItems.count == 0
{
shoppingCartButton.enabled = false
}
}
//-------------------------------------------------------------------------//
// MARK: Ajust for bigger screen
//-------------------------------------------------------------------------//
func adjustForBiggerScreen()
{
for constraint in shopLogo.constraints
{
constraint.constant *= multiplier
}
for constraint in shopName.constraints
{
constraint.constant *= multiplier
}
headerHeightConstraint.constant *= multiplier
buttonsStackViewHeightConstraint.constant *= multiplier
var fontSize = 25.0 * multiplier
shopName.font = UIFont(name: "HelveticaNeue", size: fontSize)
fontSize = 17.0 * multiplier
signOutButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: fontSize)
shoppingCartButton.imageEdgeInsets = UIEdgeInsetsMake(10 * multiplier, 64 * multiplier,
10 * multiplier, 64 * multiplier)
}
//-------------------------------------------------------------------------//
// MARK: Navigation
//-------------------------------------------------------------------------//
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if (segue.identifier != nil) && (segue.identifier == "ToShoppingCart")
{
let vc = segue.destinationViewController as! ShoppingCart_VC
vc.shoppingCartItems = shoppingCartItems
vc.delegate = self
}
}
//-------------------------------------------------------------------------//
// MARK: Memory Warning
//-------------------------------------------------------------------------//
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 5a431abe48530528c3a7e7fcad1db086 | 33.760417 | 172 | 0.477675 | 6.859198 | false | false | false | false |
gguuss/gplus-ios-swift | share/swiftshare/ViewController.swift | 1 | 3904 | //
// ViewController.swift
// swiftshare
//
// Created by Gus Class on 12/12/14.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class ViewController: UIViewController, GPPSignInDelegate {
var kClientId = "REPLACE_CLIENT_ID"; // Get this from https://console.developers.google.com
var kShareURL = "https://gusclass.com/";
@IBOutlet weak var toggleFetchEmail: UISwitch!
@IBOutlet weak var toggleFetchUserID: UISwitch!
@IBOutlet weak var signinButton: UIButton!
@IBOutlet weak var signOutButton: UIButton!
@IBOutlet weak var disconnectButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var emailDataField: UITextView!
@IBOutlet weak var userData: UITextView!
override func viewDidLoad() {
super.viewDidLoad();
// Configure the sign in object.
var signIn = GPPSignIn.sharedInstance();
signIn.shouldFetchGooglePlusUser = true;
signIn.clientID = kClientId;
signIn.shouldFetchGoogleUserEmail = toggleFetchEmail.on;
signIn.shouldFetchGoogleUserID = toggleFetchUserID.on;
signIn.scopes = [kGTLAuthScopePlusLogin];
signIn.trySilentAuthentication();
signIn.delegate = self;
// Update the buttons and text.
updateUI();
}
@IBAction func signInClicked(sender: AnyObject) {
var signIn = GPPSignIn.sharedInstance();
signIn.authenticate();
}
@IBAction func shareClicked(sender: AnyObject) {
var shareDialog = GPPShare.sharedInstance().nativeShareDialog();
// This line will fill out the title, description, and thumbnail from
// the URL that you are sharing and includes a link to that URL.
shareDialog.setURLToShare(NSURL(fileURLWithPath: kShareURL));
shareDialog.open();
}
func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) {
updateUI();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func toggleFetchEmailClick(sender: AnyObject) {
GPPSignIn.sharedInstance().shouldFetchGoogleUserEmail = toggleFetchEmail.on;
}
@IBAction func toggleUserId(sender: AnyObject) {
GPPSignIn.sharedInstance().shouldFetchGoogleUserID = toggleFetchUserID.on;
}
@IBAction func disconnect(sender: AnyObject) {
GPPSignIn.sharedInstance().disconnect();
updateUI();
}
@IBAction func signOut(sender: AnyObject) {
GPPSignIn.sharedInstance().signOut();
updateUI();
}
func updateUI() {
// TODO: Toggle buttons here.
if (GPPSignIn.sharedInstance().userID != nil){
// Signed in?
var user = GPPSignIn.sharedInstance().googlePlusUser;
userData.text = user.name.JSONString();
if (user.emails != nil){
emailDataField.text = user.emails.first?.JSONString() ?? "no email";
} else {
emailDataField.text = "no email";
}
signOutButton.enabled = true;
disconnectButton.enabled = true;
signinButton.enabled = true;
} else {
userData.text = "Signed out.";
emailDataField.text = "Signed out.";
signOutButton.enabled = false;
disconnectButton.enabled = false;
signinButton.enabled = true;
}
}
}
| apache-2.0 | a69cc2ed20fdbb5a18854929e02a62a8 | 29.5 | 95 | 0.671875 | 4.681055 | false | false | false | false |
kristenmills/scrabbli-swift | scrabbli-swift/Trie.swift | 1 | 953 | //
// Trie.swift
// scrabbli-swift
//
// Created by Kristen Mills on 7/29/14.
// Copyright (c) 2014 Kristen Mills. All rights reserved.
//
import Foundation
class Trie {
var root: TrieNode
init() {
self.root = TrieNode(value: nil)
}
func add(#word: String) {
var node = root
for char in word {
if let temp = node.walk(char) {
node = temp
} else {
node.children[char] = TrieNode(value: char)
node = node.walk(char)!
}
}
node.terminal = true
}
func delete(#word: String) {
var node = root
for char in word {
if let temp = node.walk(char) {
node = temp
} else {
return
}
}
node.terminal = false
}
func isWord(word: String) -> Bool {
var node = root
for char in word {
if let temp = node.walk(char) {
node = temp
} else {
return false
}
}
return node.terminal
}
} | mit | 2742805a4b07da4b655086c01e604327 | 15.448276 | 58 | 0.535152 | 3.52963 | false | false | false | false |
liuchuo/Swift-practice | 20150727-2.playground/Contents.swift | 1 | 1121 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//只读计算属性
class Employee {
var no : Int = 0
var firstName : String = "chen"
var lastName : String = "xin"
var job : String?
var salary : Double = 0
lazy var dept : Department = Department()
var fullName : String {
return firstName + "." + lastName
}
}
struct Department {
let no : Int = 0
var name : String = ""
}
var emp = Employee()
println(emp.fullName)
////只读计算属性不仅不用写setter访问器 而且get{}代码也可以省略
//结构体和枚举中的计算属性
struct Department {
let no : Int = 0
var name : String = "SALES"
var fullName : String {
return "Swift." + name + ".D"
}
}
var dept = Department()
println(dept.fullName)
enum WeekDays : String {
case Monday = "1"
case Tuesday = "2"
case Wednsday = "3"
case Thursday = "4"
case Friday = "5"
var message : String {
return "Today is" + self.rawValue
}
}
var day = WeekDays.Monday
println(day.message)
| gpl-2.0 | 42a22825775bf565553a43c160347e62 | 16.913793 | 52 | 0.59769 | 3.522034 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/Collection.swift | 1 | 7645 | //
// Collection.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-06-27.
//
// ---------------------------------------------------------------------------
//
// © 2016-2022 1024jp
//
// 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
//
// https://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.
//
extension RangeReplaceableCollection where Element: Equatable {
/// Remove first collection element that is equal to the given `element`.
///
/// - Parameter element: The element to be removed.
/// - Returns: The index of the removed element, or `nil` if not contains.
@discardableResult
mutating func removeFirst(_ element: Element) -> Index? {
guard let index = self.firstIndex(of: element) else { return nil }
self.remove(at: index)
return index
}
/// Add a new element to the end of the collection by keeping all the collection's elements unique.
///
/// - Parameters:
/// - element: The element to append.
/// - maximum: The muximum number of the elements to keep in the collection. The overflowed elements will be removed.
mutating func appendUnique(_ element: Element, maximum: Int) {
self.removeAll { $0 == element }
self.append(element)
if self.count > maximum {
self.removeFirst(self.count - maximum)
}
}
}
extension Collection {
/// Return the element at the specified index only if it is within bounds, otherwise nil.
///
/// - Parameter index: The position of the element to obtain.
subscript(safe index: Index) -> Element? {
return self.indices.contains(index) ? self[index] : nil
}
/// Split receiver into buffer sized chunks.
///
/// - Parameter length: The buffer size to split.
/// - Returns: Split subsequences.
func components(length: Int) -> [SubSequence] {
return stride(from: 0, to: self.count, by: length).map {
let start = self.index(self.startIndex, offsetBy: $0)
let end = self.index(start, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
return self[start..<end]
}
}
}
extension Sequence where Element: Equatable {
/// An array consists of unique elements of receiver keeping ordering.
var unique: [Element] {
self.reduce(into: []) { (unique, element) in
guard !unique.contains(element) else { return }
unique.append(element)
}
}
}
extension Dictionary {
/// Return a new dictionary containing the keys transformed by the given closure with the values of this dictionary.
///
/// - Parameter transform: A closure that transforms a key. Every transformed key must be unique.
/// - Returns: A dictionary containing transformed keys and the values of this dictionary.
func mapKeys<T>(transform: (Key) throws -> T) rethrows -> [T: Value] {
return try self.reduce(into: [:]) { $0[try transform($1.key)] = $1.value }
}
/// Return a new dictionary containing the keys transformed by the given keyPath with the values of this dictionary.
///
/// - Parameter keyPath: The keyPath to the value to transform key. Every transformed key must be unique.
/// - Returns: A dictionary containing transformed keys and the values of this dictionary.
func mapKeys<T>(_ keyPath: KeyPath<Key, T>) -> [T: Value] {
return self.mapKeys { $0[keyPath: keyPath] }
}
/// Syntax suger to use RawRepresentable keys in dictionaries whose key is the actual raw value.
///
/// - Parameter key: The raw representable whose raw value is the one of the receiver's key.
/// - Returns: The value corresponding to the given key.
subscript<K>(_ key: K) -> Value? where K: RawRepresentable, K.RawValue == Key {
get { self[key.rawValue] }
set { self[key.rawValue] = newValue }
}
}
// MARK: - Sort
extension Sequence {
/// Return the elements of the sequence, sorted using the value that the given key path refers as the comparison between elements.
///
/// - Parameter keyPath: The key path to the value to compare.
/// - Returns: A sorted array of the sequence’s elements.
func sorted<Value: Comparable>(_ keyPath: KeyPath<Element, Value>) -> [Element] {
return self.sorted { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
}
}
extension MutableCollection where Self: RandomAccessCollection {
/// Sort the collection in place, using the value that the given key path refers as the comparison between elements.
///
/// - Parameter keyPath: The key path to the value to compare.
mutating func sort<Value: Comparable>(_ keyPath: KeyPath<Element, Value>) {
self.sort { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
}
}
// MARK: - Count
enum QuantityComparisonResult {
case less, equal, greater
}
extension Sequence {
/// Count up elements that satisfy the given predicate.
///
/// - Parameters:
/// - predicate: A closure that takes an element of the sequence as its argument
/// and returns a Boolean value indicating whether the element should be counted.
/// - Returns: The number of elements that satisfies the given predicate.
func count(where predicate: (Element) throws -> Bool) rethrows -> Int {
return try self.filter(predicate).count
}
/// Count up elements by enumerating collection until encountering the element that doesn't satisfy the given predicate.
///
/// - Parameters:
/// - predicate: A closure that takes an element of the sequence as its argument
/// and returns a Boolean value indicating whether the element should be counted.
/// - Returns: The number of elements that satisfies the given predicate and are sequentially from the first index.
func countPrefix(while predicate: (Element) throws -> Bool) rethrows -> Int {
return try self.lazy.prefix(while: predicate).count
}
/// Performance efficient way to compare the number of elements with the given number.
///
/// - Note: This method takes advantage especially when counting elements is heavy (such as String count) and the number to compare is small.
///
/// - Parameter number: The number of elements to test.
/// - Returns: The result whether the number of the elements in the receiver is less than, equal, or more than the given number.
func compareCount(with number: Int) -> QuantityComparisonResult {
assert(number >= 0, "The count number to compare should be a natural number.")
guard number >= 0 else { return .greater }
var count = 0
for _ in self {
count += 1
if count > number { return .greater }
}
return (count == number) ? .equal : .less
}
}
| apache-2.0 | c9b3896c90d1a3908a3d038048a7033f | 32.517544 | 145 | 0.62392 | 4.64277 | false | false | false | false |
baquiax/SimpleTwitterClient | SimpleTwitterClient/SimpleTwitterClient/HashtagViewController.swift | 1 | 3693 | //
// HashtagViewController.swift
// SimpleTwitterClient
//
// Created by Alexander Baquiax on 4/8/16.
// Copyright © 2016 Alexander Baquiax. All rights reserved.
//
import Foundation
import UIKit
class HashtagViewController : LastTweetsViewController , UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
var textToSearch = ""
var timer : NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
}
override func loadData() {
self.loader.hidden = false
self.loader.startAnimating()
if let _ = NSUserDefaults.standardUserDefaults().objectForKey("user") {
if (self.textToSearch.isEqual("")) {
self.data = NSArray()
self.tableView.reloadData()
self.loader.stopAnimating()
return
}
TwitterClient.getTwitterClient().client.get("https://api.twitter.com/1.1/search/tweets.json", parameters: ["count" : 100, "q" : self.textToSearch], headers: nil, success: { data, response in
do {
let result = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSDictionary
self.data = result.objectForKey("statuses") as! NSArray
} catch {
self.data = NSArray()
}
self.tableView.reloadData()
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
self.loader.stopAnimating()
}, failure: { (error) -> Void in
})
} else {
self.loader.stopAnimating()
}
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
self.textToSearch = searchText
print(searchText)
if (self.timer != nil) {
self.timer?.invalidate()
}
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "loadData", userInfo: nil, repeats: false)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TwitterPostHashtag", forIndexPath: indexPath) as! TwitterPostCell
let item = self.data.objectAtIndex(indexPath.row) as! NSDictionary
if let user = item.objectForKey("user") as? NSDictionary {
if let name = user.objectForKey("name") as? String {
cell.name.text = name
}
if let screenName = user.objectForKey("screen_name") as? String {
cell.username.text = screenName
}
if let imageStringURL = user.objectForKey("profile_image_url") as? String {
let imageURL = NSURL(string: imageStringURL)
let request = NSURLRequest(URL: imageURL!)
cell.dataTask = self.urlSession.dataTaskWithRequest(request) { (data, response, error) -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
if error == nil && data != nil {
let image = UIImage(data: data!)
cell.profileImage.image = image
}
})
}
cell.dataTask?.resume()
}
}
if let text = item.objectForKey("text") as? String {
cell.tweet.text = text
}
return cell
}
} | mit | 4265fcf70e34366f212d8f17923af0a4 | 39.582418 | 202 | 0.575298 | 5.236879 | false | false | false | false |
practicalswift/swift | test/attr/hasInitialValue.swift | 9 | 767 | // RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -swift-version 4 -enable-source-import -I %S/Inputs | %FileCheck %s
// CHECK-LABEL: {{^}}class C {
class C {
// CHECK: {{^}} var without: Int
var without: Int
// CHECK: {{^}} @_hasInitialValue var with: Int
var with: Int = 0
// CHECK: {{^}} @_hasInitialValue var option: Int
var option: Int?
// CHECK: {{^}} @_implicitly_unwrapped_optional @_hasInitialValue var iuo: Int!
var iuo: Int!
// CHECK: {{^}} lazy var lazyIsntARealInit: Int
lazy var lazyIsntARealInit: Int = 0
init() {
without = 0
}
}
| apache-2.0 | 40bd697945186bf23fc5b17fe99fe69d | 35.52381 | 274 | 0.636245 | 3.567442 | false | false | false | false |
YQqiang/Nunchakus | Pods/BMPlayer/BMPlayer/Classes/BMPlayerProtocols.swift | 1 | 836 | //
// BMPlayerProtocols.swift
// Pods
//
// Created by BrikerMan on 16/4/30.
//
//
import UIKit
extension BMPlayerControlView {
public enum ButtonType: Int {
case play = 101
case pause = 102
case back = 103
case fullscreen = 105
case replay = 106
}
}
extension BMPlayer {
static func formatSecondsToString(_ secounds: TimeInterval) -> String {
let Min = Int(secounds / 60)
let Sec = Int(secounds.truncatingRemainder(dividingBy: 60))
return String(format: "%02d:%02d", Min, Sec)
}
// static func imageResourcePath(_ fileName: String) -> UIImage? {
// let bundle = Bundle(for: self.classForCoder)
// let image = UIImage(named: fileName, in: bundle, compatibleWith: nil)
// return image
// }
}
| mit | 71c80313ea68cf9f3a1d6b8612807f77 | 23.588235 | 80 | 0.592105 | 3.852535 | false | false | false | false |
biohazardlover/ROer | Pods/NSObject+Rx/NSObject+Rx.swift | 1 | 1175 | import Foundation
import RxSwift
import ObjectiveC
public extension NSObject {
fileprivate struct AssociatedKeys {
static var DisposeBag = "rx_disposeBag"
}
fileprivate func doLocked(_ closure: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
closure()
}
var rx_disposeBag: DisposeBag {
get {
var disposeBag: DisposeBag!
doLocked {
let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag
if let lookup = lookup {
disposeBag = lookup
} else {
let newDisposeBag = DisposeBag()
self.rx_disposeBag = newDisposeBag
disposeBag = newDisposeBag
}
}
return disposeBag
}
set {
doLocked {
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
extension Reactive where Base: NSObject {
var disposeBag: DisposeBag {
return base.rx_disposeBag
}
}
| mit | 3a04786c7e83d0e7501cba8268ae96f5 | 26.325581 | 120 | 0.553191 | 5.542453 | false | false | false | false |
mleiv/IBStyler | Initial Code Files/IBStyles/IBStyledThings.swift | 2 | 7683 | //
// IBStyledThings.swift
//
// Created by Emily Ivie on 2/25/15.
//
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import UIKit
@IBDesignable
open class IBStyledView: UIView, IBStylable {
@IBInspectable
open var identifier: String? {
didSet{
if didLayout && oldValue != identifier {
_ = styler?.didApplyStyles = false
_ = styler?.applyStyles()
}
}
}
open var defaultIdentifier: String { return "View" }
open lazy var styler: IBStyler? = { return IBStyler(element: self) }()
open var didLayout = false
public convenience init(identifier: String) {
self.init()
self.identifier = identifier
}
override open func layoutSubviews() {
_ = styler?.applyStyles()
super.layoutSubviews()
didLayout = true
}
}
@IBDesignable
open class IBStyledLabel: UILabel, IBStylable {
@IBInspectable
open var identifier: String? {
didSet{
if didLayout && oldValue != identifier {
styler?.didApplyStyles = false
_ = styler?.applyStyles()
}
}
}
open var defaultIdentifier: String { return "Label" }
open lazy var styler: IBStyler? = { return IBStyler(element: self) }()
open var didLayout = false
public convenience init(identifier: String) {
self.init()
self.identifier = identifier
}
override open func layoutSubviews() {
_ = styler?.applyStyles()
super.layoutSubviews()
didLayout = true
}
}
@IBDesignable
open class IBStyledTextField: UITextField, IBStylable {
@IBInspectable
open var identifier: String? {
didSet{
if didLayout && oldValue != identifier {
styler?.didApplyStyles = false
_ = styler?.applyStyles()
}
}
}
open var defaultIdentifier: String { return "TextField" }
open lazy var styler: IBStyler? = { return IBStyler(element: self) }()
var didLayout = false
public convenience init(identifier: String) {
self.init()
self.identifier = identifier
}
override open func layoutSubviews() {
contentVerticalAlignment = .center
_ = styler?.applyStyles()
super.layoutSubviews()
didLayout = true
}
}
@IBDesignable
open class IBStyledTextView: UITextView, IBStylable {
@IBInspectable
open var identifier: String? {
didSet{
if didLayout && oldValue != identifier {
styler?.didApplyStyles = false
_ = styler?.applyStyles()
}
}
}
open var defaultIdentifier: String { return "TextView" }
open lazy var styler: IBStyler? = { return IBStyler(element: self) }()
open var didLayout = false
open var heightConstraint: NSLayoutConstraint?
public convenience init(identifier: String) {
self.init()
self.identifier = identifier
}
override open func layoutSubviews() {
_ = styler?.applyStyles()
textContainer.lineFragmentPadding = 0
if !isScrollEnabled && heightConstraint == nil {
isScrollEnabled = true // iOS bug http://stackoverflow.com/a/33503522/5244752
heightConstraint = heightAnchor.constraint(equalToConstant: contentSize.height)
heightConstraint?.isActive = true
}
heightConstraint?.constant = contentSize.height
super.layoutSubviews()
didLayout = true
}
}
@IBDesignable
open class IBStyledImageView: UIImageView, IBStylable {
@IBInspectable
open var identifier: String? {
didSet{
if didLayout && oldValue != identifier {
styler?.didApplyStyles = false
_ = styler?.applyStyles()
}
}
}
open var defaultIdentifier: String { return "ImageView" }
open lazy var styler: IBStyler? = { return IBStyler(element: self) }()
open var didLayout = false
public convenience init(identifier: String) {
self.init()
self.identifier = identifier
}
override open func layoutSubviews() {
_ = styler?.applyStyles()
super.layoutSubviews()
didLayout = true
}
}
@IBDesignable
open class IBStyledButton: UIButton, IBStylable {
@IBInspectable
open var identifier: String? {
didSet{
if didLayout && oldValue != identifier {
styler?.didApplyStyles = false
_ = styler?.applyStyles()
}
}
}
open var defaultIdentifier: String { return "Button" }
@IBInspectable
open var tempDisabled: Bool = false
@IBInspectable
open var tempPressed: Bool = false
open lazy var styler: IBStyler? = { return IBStyler(element: self) }()
open var didLayout = false
open var lastState: UIControl.State?
public convenience init(identifier: String) {
self.init()
self.identifier = identifier
}
override open func layoutSubviews() {
_ = styler?.applyStyles()
let state = getState()
if lastState != state {
lastState = state
styler?.applyState(state)
}
super.layoutSubviews()
didLayout = true
}
override open func prepareForInterfaceBuilder() {
if tempDisabled {
isEnabled = false
}
if tempPressed {
isHighlighted = true
}
let state = getState()
lastState = state
styler?.applyState(state)
}
/// A subset of states which IBStyles can actually handle currently. :/
func getState() -> UIControl.State {
if !isEnabled {
return .disabled
}
if isHighlighted {
return .highlighted
}
if isSelected {
return .selected
}
return .normal
}
//button-specific:
override open var isEnabled: Bool {
didSet {
if didLayout && isEnabled != oldValue {
let state = getState()
styler?.applyState(state)
lastState = state
}
}
}
override open var isSelected: Bool {
didSet {
if didLayout && isSelected != oldValue {
let state = getState()
styler?.applyState(state)
lastState = state
}
}
}
override open var isHighlighted: Bool {
didSet {
if didLayout && isHighlighted != oldValue {
let state = getState()
styler?.applyState(state)
lastState = state
}
}
}
}
@IBDesignable
open class IBStyledSegmentedControl: UISegmentedControl, IBStylable {
@IBInspectable
open var identifier: String? {
didSet{
if didLayout && oldValue != identifier {
styler?.didApplyStyles = false
_ = styler?.applyStyles()
}
}
}
open var defaultIdentifier: String { return "SegmentedControl" }
open lazy var styler: IBStyler? = { return IBStyler(element: self) }()
open var didLayout = false
public convenience init(identifier: String) {
self.init()
self.identifier = identifier
}
override open func layoutSubviews() {
_ = styler?.applyStyles()
super.layoutSubviews()
didLayout = true
}
}
| mit | 30b72f17e23f7f91334814b6576c0831 | 27.142857 | 93 | 0.57881 | 5.342837 | false | false | false | false |
Performador/Pickery | Pickery/PhotoLibrary.swift | 1 | 3298 | //
// PhotoLibraryAsset.swift
// Pickery
//
// Created by Okan Arikan on 6/20/16.
//
//
import Foundation
import Photos
import ReactiveSwift
import MobileCoreServices
import ImageIO
import Result
/// Abstracts the photos library on the device
class PhotoLibrary : NSObject, PHPhotoLibraryChangeObserver {
/// Da constants
struct Constants {
// The minimum refresh interval
static let kRefreshInterval = TimeInterval(1)
}
/// The singleton
static let sharedInstance = PhotoLibrary()
/// The caching image manager for the photo library
let cachingImageManager = PHCachingImageManager()
/// This is where we keep the photo assets
let assets = MutableProperty< [ PhotosAsset ]>([])
/// We emit this to request a refresh
let refreshRequest = SignalSource<(),NoError>()
/// The disposibles we are listenning
let disposibles = ScopedDisposable(CompositeDisposable())
/// Ctor
override init() {
super.init()
// We are interested in changes
PHPhotoLibrary.shared().register(self)
// Handle the refresh
disposibles += refreshRequest
.signal
.throttle(Constants.kRefreshInterval, on: QueueScheduler())
.observeValues { [ unowned self ] value in
// We better be off the main queue
assert(isMainQueue() == false)
// Let's see if we can read the gallery data
let results = PHAsset.fetchAssets(with: nil)
var photosAssets = [ PhotosAsset ]()
// Create an asset record for each of the local assets
for assetIndex in 0..<results.count {
// Add the asset
photosAssets.append(PhotosAsset(phAsset: results[assetIndex]))
}
// Set the value
self.assets.value = photosAssets
}
// We need refresh
setNeedsRefresh()
}
/// We want to refresh the library
/// Thread safe
func setNeedsRefresh() {
refreshRequest.observer.send(value: ())
}
/// Remove the assets from photo library
///
/// - parameter assets: The assets we want gone
/// - returns: A signal producer for the request
func deleteAssets(assets : [ PHAsset ]) -> SignalProducer<String,NSError> {
assertMainQueue()
return SignalProducer<String, NSError> { sink, disposible in
// Delete da assets
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.deleteAssets(assets as NSArray)
}, completionHandler: { (done: Bool, error: Swift.Error?) in
// Got an error?
if let error = error {
sink.send(error: error as NSError)
} else {
sink.sendCompleted()
}
})
}
}
/// Handle changes
func photoLibraryDidChange(_ changeInstance: PHChange) {
setNeedsRefresh()
}
}
| mit | eff28abdd8ab3ceb9af7b766c0201987 | 28.711712 | 82 | 0.546998 | 5.589831 | false | false | false | false |
BBBInc/AlzPrevent-ios | researchline/SexTableViewController.swift | 1 | 3869 | //
// SexTableViewController.swift
// researchline
//
// Created by jknam on 2015. 11. 26..
// Copyright © 2015년 bbb. All rights reserved.
//
import UIKit
class SexTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 2
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
debugPrint("this indexPath is \(indexPath.row)")
if(indexPath.row == 0){
Constants.userDefaults.setObject("Male", forKey:"sex")
}else{
Constants.userDefaults.setObject("Female", forKey:"sex")
}
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .None
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| bsd-3-clause | 203eee4b81998566743dce6e32de2f3a | 34.46789 | 157 | 0.68598 | 5.61103 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Flat Frequency Response Reverb Operation.xcplaygroundpage/Contents.swift | 5 | 796 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Flat Frequency Response Reverb Operation
//:
import XCPlayground
import AudioKit
//: Music Example
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("drumloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
let duration = AKOperation.sineWave(frequency: 0.2).scale(minimum: 0, maximum: 5)
let reverb = AKOperation.input.reverberateWithFlatFrequencyResponse(reverbDuration: duration, loopDuration: 0.1)
let effect = AKOperationEffect(player, operation: reverb)
AudioKit.output = effect
AudioKit.start()
player.play()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| apache-2.0 | 25b7eb625a0cc06b9d7e841418e5a931 | 28.481481 | 112 | 0.742462 | 3.901961 | false | false | false | false |
fmpinheiro/taiga-ios | taiga-ios/MainController.swift | 1 | 2308 | //
// MainController.swift
// taiga-ios
//
// Created by Rhonan Carneiro on 21/10/15.
// Copyright © 2015 Taiga. All rights reserved.
//
import UIKit
import Alamofire
class MainController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let LIST_PROJECTS_URL = "https://api.taiga.io/api/v1/projects"
@IBOutlet weak var tableView: UITableView!
var user: User!
var projects = [Project]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
print("Listing projects using this auth token: \(user.authToken!) 😎")
let headers = ["Authorization": "Bearer \(user.authToken!)"]
Alamofire.request(.GET, LIST_PROJECTS_URL + "?member=\(user.id!)", headers: headers, encoding: .JSON).responseCollection { (response: Response<[Project], NSError>) in
let projects: [Project] = response.result.value! as [Project]
if !projects.isEmpty {
print("There are some projects to show")
self.projects.appendContentsOf(projects)
self.tableView.reloadData()
} else {
print("No projects to show")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setUser(user: User){
self.user = user
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return projects.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("projectCell", forIndexPath: indexPath)
cell.textLabel!.text = projects[indexPath.row].name
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Project name: " + projects[indexPath.row].name!)
print("Project description: " + projects[indexPath.row].description!)
}
}
| apache-2.0 | 6c42f3e99494cb1362d972e27d4acc26 | 32.897059 | 174 | 0.644097 | 4.944206 | false | false | false | false |
hustlzp/Observable-Swift-Example | Observable-Swift-Example/HorizonalTagListView.swift | 1 | 3384 | //
// HorizonalTagListView.swift
// Face
//
// Created by hustlzp on 16/1/21.
// Copyright © 2016年 hustlzp. All rights reserved.
//
import UIKit
class HorizonalTagListView: UIView {
var cornerRadius: CGFloat = 13.0
var textColor = UIColor(hexValue: 0x808393FF)
var selectedTextColor = UIColor(hexValue: 0x808393FF)
var paddingX: CGFloat = 9.5
var paddingY: CGFloat = 5.5
var tagBackgroundColor = UIColor(hexValue: 0xF3F3F9FF)
var tagSelectedBackgroundColor = UIColor(hexValue: 0xF3F3F9FF).darker(0.1)
var textFont = UIFont.systemFontOfSize(13.5)
var marginX: CGFloat = 8.0
private var tagViews = [TagView]()
private var width: CGFloat = 0
private var height: CGFloat = 0
func addTag(title: String) -> TagView {
let tagView = TagView(title: title)
tagView.textColor = textColor
tagView.selectedTextColor = selectedTextColor
tagView.tagBackgroundColor = tagBackgroundColor
tagView.tagSelectedBackgroundColor = tagSelectedBackgroundColor
tagView.cornerRadius = cornerRadius
tagView.paddingY = paddingY
tagView.paddingX = paddingX
tagView.textFont = textFont
tagViews.append(tagView)
rearrangeViews()
return tagView
}
override func layoutSubviews() {
super.layoutSubviews()
rearrangeViews()
}
override func intrinsicContentSize() -> CGSize {
return CGSize(width: width, height: height)
}
// Public Methods
func updateTags(tags: [String]) {
removeAllTags()
tags.forEach { addTag($0) }
}
func removeAllTags() {
for tagView in tagViews {
tagView.removeFromSuperview()
}
tagViews.removeAll()
rearrangeViews()
}
func removeTag(index: Int) {
if index < 0 || index > tagViews.count {
return
}
tagViews[index].removeFromSuperview()
tagViews.removeAtIndex(index)
rearrangeViews()
}
func prepareRemoveTag(index: Int) {
if index < 0 || index > tagViews.count {
return
}
tagViews[index].backgroundColor = tagSelectedBackgroundColor
}
func cancelPrepareRemoveTag() {
for tagView in tagViews {
tagView.backgroundColor = tagBackgroundColor
}
}
// Internal Helpers
private func rearrangeViews() {
width = 0
height = 0
for tagView in tagViews {
tagView.removeFromSuperview()
}
for tagView in tagViews {
let tagViewWidth = tagView.intrinsicContentSize().width
let tagViewHeight = tagView.intrinsicContentSize().height
var tagViewX: CGFloat
if width == 0 {
tagViewX = 0
} else {
tagViewX = width + marginX
}
tagView.frame = CGRectMake(tagViewX, 0, tagViewWidth, tagViewHeight)
addSubview(tagView)
if tagViewHeight > height {
height = tagViewHeight
}
width = tagViewX + tagViewWidth
}
invalidateIntrinsicContentSize()
}
}
| mit | cb2dbcac9b37134d37bcdee9d50008d3 | 25.007692 | 80 | 0.575274 | 5.193548 | false | false | false | false |
dulingkang/DemoCollect | DemoCollect/DemoCollect/SubClasses/PathAnimation.swift | 1 | 4702 | //
// PathAnimation.swift
// DemoCollect
//
// Created by dulingkang on 2018/5/3.
// Copyright © 2018年 com.shawn. All rights reserved.
//
import UIKit
import CoreGraphics
extension Selector {
static let start = #selector(PathAnimation.startAnimation)
}
class PathAnimation: UIViewController {
struct Layout {
static let radius = kScreenWidth/2
}
lazy var pandaImageView: UIImageView = {
return UIImageView(image: UIImage(named: "panda"))
}()
lazy var startButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("start", for: .normal)
button.frame = CGRect(x: (kScreenWidth - 60)/2, y: 80, width: 60, height: 30)
button.addTarget(self, action: .start, for: .touchUpInside)
return button
}()
lazy var pointA: CALayer = {
let layer = CALayer()
layer.frame = CGRect(x: Layout.radius - 5, y: kScreenHeight/2 - 5, width: 10, height: 10)
layer.backgroundColor = UIColor.red.cgColor
layer.cornerRadius = 5
return layer
}()
lazy var pointB: CALayer = {
let layer = CALayer()
layer.frame = CGRect(x: kScreenWidth - 5, y: kScreenHeight/2 - 5, width: 10, height: 10)
layer.backgroundColor = UIColor.green.cgColor
layer.cornerRadius = 5
return layer
}()
lazy var pointC: CALayer = {
let layer = CALayer()
layer.frame = CGRect(x: Layout.radius - 5, y: kScreenHeight/2 - Layout.radius - 5, width: 10, height: 10)
layer.backgroundColor = UIColor.blue.cgColor
layer.cornerRadius = 5
return layer
}()
lazy var pointD: CALayer = {
let layer = CALayer()
layer.frame = CGRect(x: Layout.radius/2 - 5, y: kScreenHeight/2 - 5, width: 10, height: 10)
layer.backgroundColor = UIColor.darkGray.cgColor
layer.cornerRadius = 5
return layer
}()
lazy var circle: CALayer = {
let circlePath = UIBezierPath(arcCenter: CGPoint(x: kScreenWidth/2,y: kScreenHeight/2), radius: Layout.radius, startAngle: 0, endAngle: .pi * 2, clockwise: false)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
//change the fill color
shapeLayer.fillColor = UIColor.clear.cgColor
//you can change the stroke color
shapeLayer.strokeColor = UIColor.red.cgColor
//you can change the line width
shapeLayer.lineWidth = 3.0
return shapeLayer
}()
let transform = CGAffineTransform(translationX: kScreenWidth/2, y: kScreenHeight/2)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(pandaImageView)
view.addSubview(startButton)
view.layer.addSublayer(pointA)
view.layer.addSublayer(pointB)
view.layer.addSublayer(pointC)
view.layer.addSublayer(pointD)
view.layer.addSublayer(circle)
pandaImageView.transform = transform
pandaImageView.layer.position = CGPoint(x: 0, y: 0)
}
func lineAnimation() {
let animation = CABasicAnimation()
animation.keyPath = "position.x";
animation.fromValue = 0;
animation.toValue = Layout.radius;
animation.duration = 1;
pandaImageView.layer.add(animation, forKey: "line")
pandaImageView.layer.position = CGPoint(x: Layout.radius, y: 0)
}
func roundAnimation() -> CAKeyframeAnimation{
let keyframeAnimation = CAKeyframeAnimation(keyPath: "position")
let path = CGMutablePath()
let radius = kScreenWidth/2
path.addLine(to: CGPoint(x: radius, y: 0))
path.addArc(center: CGPoint(x: 0, y: 0), radius: radius, startAngle: 0, endAngle: 1.5 * .pi, clockwise: true)
path.addLine(to: CGPoint(x: -radius/2, y: 0))
path.addLine(to: CGPoint(x: 0, y: 0))
keyframeAnimation.path = path
keyframeAnimation.calculationMode = kCAAnimationPaced
keyframeAnimation.duration = 2.0;
return keyframeAnimation
}
func scaleAnimation() -> CAKeyframeAnimation{
let keyframeAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
keyframeAnimation.values = [1.25, 0.8, 1]
keyframeAnimation.duration = 1.0;
keyframeAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)]
return keyframeAnimation
}
func startAnimation() {
let roundAnimation = self.roundAnimation()
let scaleAnimation = self.scaleAnimation()
scaleAnimation.beginTime = roundAnimation.duration
let groupAnimation = CAAnimationGroup()
groupAnimation.animations = [roundAnimation, scaleAnimation]
groupAnimation.duration = roundAnimation.duration + scaleAnimation.duration
pandaImageView.layer.add(groupAnimation, forKey: "group")
pandaImageView.layer.position = CGPoint(x: 0, y: 0)
}
}
| mit | b011e3eb378868552191692169d658b3 | 32.564286 | 166 | 0.698659 | 4.221923 | false | false | false | false |
RedRoster/rr-ios | RedRoster/Model/Crosslisting.swift | 1 | 635 | //
// Crosslisting.swift
// RedRoster
//
// Created by Daniel Li on 7/19/16.
// Copyright © 2016 dantheli. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
class Crosslisting: Object {
dynamic var subject: String = ""
dynamic var number: Int = 0
static func create(_ json: JSON) -> Crosslisting {
let crosslisting = Crosslisting()
crosslisting.subject = json["subject"].stringValue
crosslisting.number = Int(json["catalogNbr"].stringValue) ?? 0
return crosslisting
}
var shortHand: String {
return "\(subject) \(number)"
}
}
| apache-2.0 | a931f02c4bc23f0c7389a91ff1468e68 | 22.481481 | 70 | 0.643533 | 4.064103 | false | false | false | false |
petester42/SwiftCharts | Examples/Examples/MasterViewController.swift | 3 | 4689 | //
// MasterViewController.swift
// SwiftCharts
//
// Created by ischuetz on 20/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
enum Example {
case HelloWorld, Bars, StackedBars, BarsPlusMinus, GroupedBars, BarsStackedGrouped, Scatter, Areas, Bubble, Coords, Target, Multival, Notifications, Combination, Scroll, EqualSpacing, Tracker, MultiAxis, MultiAxisInteractive, CandleStick, Cubiclines, NotNumeric, CandleStickInteractive, CustomUnits, Trendline
}
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var examples: [(Example, String)] = [
(.HelloWorld, "Hello World"),
(.Bars, "Bars"),
(.StackedBars, "Stacked bars"),
(.BarsPlusMinus, "+/- bars with dynamic gradient"),
(.GroupedBars, "Grouped bars"),
(.BarsStackedGrouped, "Stacked, grouped bars"),
(.Combination, "+/- bars and line"),
(.Scatter, "Scatter"),
(.Notifications, "Notifications (interactive)"),
(.Target, "Target point animation"),
(.Areas, "Areas, lines, circles (interactive)"),
(.Bubble, "Bubble, gradient bar mapping"),
(.NotNumeric, "Not numeric values"),
(.Scroll, "Multiline, Scroll"),
(.Coords, "Show touch coords (interactive)"),
(.Tracker, "Track touch (interactive)"),
(.EqualSpacing, "Fixed axis spacing"),
(.CustomUnits, "Custom units, rotated labels"),
(.Multival, "Multiple axis labels"),
(.MultiAxis, "Multiple axes"),
(.MultiAxisInteractive, "Multiple axes (interactive)"),
(.CandleStick, "Candlestick"),
(.CandleStickInteractive, "Candlestick (interactive)"),
(.Cubiclines, "Cubic lines"),
(.Trendline, "Trendline")
]
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes = ["NSFontAttributeName" : ExamplesDefaults.fontWithSize(22)]
UIBarButtonItem.appearance().setTitleTextAttributes(["NSFontAttributeName" : ExamplesDefaults.fontWithSize(22)], forState: UIControlState.Normal)
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
let example = self.examples[1]
self.detailViewController?.detailItem = example.0
self.detailViewController?.title = example.1
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
func showExample(index: Int) {
let example = self.examples[index]
let controller = segue.destinationViewController as! DetailViewController
controller.detailItem = example.0
controller.title = example.1
}
if let indexPath = self.tableView.indexPathForSelectedRow() {
showExample(indexPath.row)
} else {
showExample(0)
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
let example = self.examples[indexPath.row]
self.detailViewController?.detailItem = example.0
self.detailViewController?.title = example.1
self.splitViewController?.toggleMasterView()
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return examples.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = examples[indexPath.row].1
cell.textLabel!.font = ExamplesDefaults.fontWithSize(Env.iPad ? 22 : 16)
return cell
}
}
| apache-2.0 | 6a3f8f8a073267984c6f765097c98c7c | 38.075 | 313 | 0.639155 | 5.371134 | false | false | false | false |
raptorxcz/Rubicon | RubiconExtension/InvocationGeneratorOutput.swift | 1 | 1097 | //
// InvocationGeneratorOutput.swift
// RubiconExtension
//
// Created by Kryštof Matěj on 03/02/2018.
// Copyright © 2018 Kryštof Matěj. All rights reserved.
//
import Foundation
import Generator
import XcodeKit
class InvocationGeneratorOutput: GeneratorOutput {
private let indentFormatter = IndentationFormatter()
private let invocation: XCSourceEditorCommandInvocation
private lazy var indent: String = {
let buffer = self.invocation.buffer
var indent: String = ""
if buffer.usesTabsForIndentation {
for _ in 0 ..< buffer.tabWidth {
indent += "\t"
}
} else {
for _ in 0 ..< buffer.indentationWidth {
indent += " "
}
}
return indent
}()
init(invocation: XCSourceEditorCommandInvocation) {
self.invocation = invocation
}
func save(text: String) {
let lines = indentFormatter.format(indent: indent, string: text).components(separatedBy: "\n")
invocation.buffer.lines.addObjects(from: lines)
}
}
| mit | dc7eb6de486930ddb045c915f6e96aba | 25 | 102 | 0.624542 | 4.768559 | false | false | false | false |
Basadev/MakeSchoolNotes | MakeSchoolNotes/External/ConvenienceKit/ConvenienceKitTests/UIKit/PresentViewControllerAnywhere.swift | 2 | 3145 | //
// PresentViewControllerAnywhere.swift
// ConvenienceKit
//
// Created by Benjamin Encz on 4/10/15.
// Copyright (c) 2015 Benjamin Encz. All rights reserved.
//
import Foundation
import UIKit
import Quick
import Nimble
import ConvenienceKit
class PresentViewControllerAnywhereSpec : QuickSpec {
override func spec() {
describe("UIViewController PresentAnywhere Extension") {
context("when used on a plain view controller") {
it("presents the controller on the plain view controller") {
let uiApplication = UIApplication.sharedApplication()
var window = UIApplication.sharedApplication().windows[0] as! UIWindow
let presentedViewController = UIViewController()
window.rootViewController = UIViewController()
let rootViewController = window.rootViewController!
rootViewController.presentViewControllerFromTopViewController(presentedViewController)
expect(presentedViewController.presentingViewController).to(equal(rootViewController))
}
}
// context("when used on a navigation view controller") {
//
// it("presents it on the first content view controller when only one is added") {
// let uiApplication = UIApplication.sharedApplication()
// let window = UIApplication.sharedApplication().windows[0] as! UIWindow
// let firstContentViewController = UIViewController()
// let secondContentViewController = UIViewController()
// let navigationController = UINavigationController(rootViewController: firstContentViewController)
// navigationController.pushViewController(secondContentViewController, animated: false)
// window.rootViewController = navigationController
//
// window.addSubview(navigationController.view)
//
// let presentedViewController = UIViewController()
// let rootViewController = window.rootViewController!
// rootViewController.presentViewControllerFromTopViewController(presentedViewController)
//
//// expect(presentedViewController.presentingViewController).to(equal(secondContentViewController))
// }
// }
// context("when used on a modally presented view controller") {
//
// it("presents it on the modal view controller") {
// let uiApplication = UIApplication.sharedApplication()
// var window = UIApplication.sharedApplication().windows[0] as! UIWindow
// window.rootViewController = UIViewController()
//
// let modalViewController = UIViewController()
// let presentedViewController = UIViewController()
//
// window.rootViewController?.presentViewController(modalViewController, animated: false, completion: nil)
//
// window.rootViewController?.presentViewControllerFromTopViewController(presentedViewController)
//
// expect(presentedViewController.presentingViewController).to(equal(modalViewController))
// }
//
// }
}
}
} | mit | 3cec1bf5b1eee55afd18f8422d1f8923 | 39.333333 | 115 | 0.682035 | 5.889513 | false | false | false | false |
piv199/EZSwiftExtensions | Sources/EZSwiftFunctions.swift | 2 | 11656 | //
// EZSwiftFunctions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 13/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
//TODO: others standart video, gif
public struct ez {
/// EZSE: Returns app's name
public static var appDisplayName: String? {
if let bundleDisplayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
return bundleDisplayName
} else if let bundleName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String {
return bundleName
}
return nil
}
/// EZSE: Returns app's version number
public static var appVersion: String? {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
/// EZSE: Return app's build number
public static var appBuild: String? {
return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String
}
/// EZSE: Return app's bundle ID
public static var appBundleID: String? {
return Bundle.main.bundleIdentifier
}
/// EZSE: Returns both app's version and build numbers "v0.3(7)"
public static var appVersionAndBuild: String? {
if appVersion != nil && appBuild != nil {
if appVersion == appBuild {
return "v\(appVersion!)"
} else {
return "v\(appVersion!)(\(appBuild!))"
}
}
return nil
}
/// EZSE: Return device version ""
public static var deviceVersion: String {
var size: Int = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: Int(size))
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String(cString: machine)
}
/// EZSE: Returns true if DEBUG mode is active //TODO: Add to readme
public static var isDebug: Bool {
#if DEBUG
return true
#else
return false
#endif
}
/// EZSE: Returns true if RELEASE mode is active //TODO: Add to readme
public static var isRelease: Bool {
#if DEBUG
return false
#else
return true
#endif
}
/// EZSE: Returns true if its simulator and not a device //TODO: Add to readme
public static var isSimulator: Bool {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return true
#else
return false
#endif
}
/// EZSE: Returns true if its on a device and not a simulator //TODO: Add to readme
public static var isDevice: Bool {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}
/// EZSE: Returns the top ViewController
public static var topMostVC: UIViewController? {
let topVC = UIApplication.topViewController()
if topVC == nil {
print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
}
return topVC
}
#if os(iOS)
/// EZSE: Returns current screen orientation
public static var screenOrientation: UIInterfaceOrientation {
return UIApplication.shared.statusBarOrientation
}
#endif
/// EZSwiftExtensions
public static var horizontalSizeClass: UIUserInterfaceSizeClass {
return self.topMostVC?.traitCollection.horizontalSizeClass ?? UIUserInterfaceSizeClass.unspecified
}
/// EZSwiftExtensions
public static var verticalSizeClass: UIUserInterfaceSizeClass {
return self.topMostVC?.traitCollection.verticalSizeClass ?? UIUserInterfaceSizeClass.unspecified
}
/// EZSE: Returns screen width
public static var screenWidth: CGFloat {
#if os(iOS)
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.main.bounds.size.width
} else {
return UIScreen.main.bounds.size.height
}
#elseif os(tvOS)
return UIScreen.main.bounds.size.width
#endif
}
/// EZSE: Returns screen height
public static var screenHeight: CGFloat {
#if os(iOS)
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.main.bounds.size.height
} else {
return UIScreen.main.bounds.size.width
}
#elseif os(tvOS)
return UIScreen.main.bounds.size.height
#endif
}
#if os(iOS)
/// EZSE: Returns StatusBar height
public static var screenStatusBarHeight: CGFloat {
return UIApplication.shared.statusBarFrame.height
}
/// EZSE: Return screen's height without StatusBar
public static var screenHeightWithoutStatusBar: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.main.bounds.size.height - screenStatusBarHeight
} else {
return UIScreen.main.bounds.size.width - screenStatusBarHeight
}
}
#endif
/// EZSE: Returns the locale country code. An example value might be "ES". //TODO: Add to readme
public static var currentRegion: String? {
return (Locale.current as NSLocale).object(forKey: NSLocale.Key.countryCode) as? String
}
/// EZSE: Calls action when a screen shot is taken
public static func detectScreenShot(_ action: @escaping () -> ()) {
let mainQueue = OperationQueue.main
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil, queue: mainQueue) { notification in
// executes after screenshot
action()
}
}
//TODO: Document this, add tests to this
/// EZSE: Iterates through enum elements, use with (for element in ez.iterateEnum(myEnum))
/// http://stackoverflow.com/questions/24007461/how-to-enumerate-an-enum-with-string-type
public static func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafePointer(to: &i) { $0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } }
if next.hashValue != i { return nil }
i += 1
return next
}
}
// MARK: - Dispatch
/// EZSE: Runs the function after x seconds
public static func dispatchDelay(_ second: Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(second * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
/// EZSE: Runs function after x seconds
public static func runThisAfterDelay(seconds: Double, after: @escaping () -> ()) {
runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}
//TODO: Make this easier
/// EZSE: Runs function after x seconds with dispatch_queue, use this syntax: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping ()->()) {
let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: after)
}
/// EZSE: Submits a block for asynchronous execution on the main queue
public static func runThisInMainThread(_ block: @escaping ()->()) {
DispatchQueue.main.async(execute: block)
}
/// EZSE: Runs in Default priority queue
public static func runThisInBackground(_ block: @escaping () -> ()) {
DispatchQueue.global(qos: .default).async(execute: block)
}
/// EZSE: Runs every second, to cancel use: timer.invalidate()
public static func runThisEvery(seconds: TimeInterval, startAfterSeconds: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> Timer {
let fireDate = startAfterSeconds + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, seconds, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer!
}
/// EZSE: Gobal main queue
@available(*, deprecated: 1.7, renamed: "DispatchQueue.main")
public var globalMainQueue: DispatchQueue {
return DispatchQueue.main
}
/// EZSE: Gobal queue with user interactive priority
@available(*, deprecated: 1.7, renamed: "DispatchQueue.main")
public var globalUserInteractiveQueue: DispatchQueue {
return DispatchQueue.global(qos: .userInteractive)
}
/// EZSE: Gobal queue with user initiated priority
@available(*, deprecated: 1.7, renamed: "DispatchQueue.global()")
public var globalUserInitiatedQueue: DispatchQueue {
return DispatchQueue.global(qos: .userInitiated)
}
/// EZSE: Gobal queue with utility priority
@available(*, deprecated: 1.7, renamed: "DispatchQueue.global()")
public var globalUtilityQueue: DispatchQueue {
return DispatchQueue.global(qos: .utility)
}
/// EZSE: Gobal queue with background priority
@available(*, deprecated: 1.7, renamed: "DispatchQueue.global()")
public var globalBackgroundQueue: DispatchQueue {
return DispatchQueue.global(qos: .background)
}
/// EZSE: Gobal queue with default priority
@available(*, deprecated: 1.7, renamed: "DispatchQueue.global()")
public var globalQueue: DispatchQueue {
return DispatchQueue.global(qos: .default)
}
// MARK: - DownloadTask
/// EZSE: Downloads image from url string
public static func requestImage(_ url: String, success: @escaping (UIImage?) -> Void) {
requestURL(url, success: { (data) -> Void in
if let d = data {
success(UIImage(data: d))
}
})
}
/// EZSE: Downloads JSON from url string
public static func requestJSON(_ url: String, success: @escaping ((Any?) -> Void), error: ((NSError) -> Void)?) {
requestURL(url,
success: { (data) -> Void in
let json = self.dataToJsonDict(data)
success(json)
},
error: { (err) -> Void in
if let e = error {
e(err)
}
})
}
/// EZSE: converts NSData to JSON dictionary
fileprivate static func dataToJsonDict(_ data: Data?) -> Any? {
if let d = data {
var error: NSError?
let json: Any?
do {
json = try JSONSerialization.jsonObject(
with: d,
options: JSONSerialization.ReadingOptions.allowFragments)
} catch let error1 as NSError {
error = error1
json = nil
}
if let _ = error {
return nil
} else {
return json
}
} else {
return nil
}
}
/// EZSE:
fileprivate static func requestURL(_ url: String, success: @escaping (Data?) -> Void, error: ((NSError) -> Void)? = nil) {
guard let requestURL = URL(string: url) else {
assertionFailure("EZSwiftExtensions Error: Invalid URL")
return
}
URLSession.shared.dataTask(
with: URLRequest(url: requestURL),
completionHandler: { data, response, err in
if let e = err {
error?(e as NSError)
} else {
success(data)
}
}).resume()
}
}
| mit | d41005db63f2ed496cb2232bd3d094ea | 32.687861 | 160 | 0.620882 | 4.826501 | false | false | false | false |
edx/edx-app-ios | Source/SnackbarViews.swift | 1 | 14925 | //
// SnackbarViews.swift
// edX
//
// Created by Saeed Bashir on 7/15/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
private let animationDuration: TimeInterval = 1.0
public class VersionUpgradeView: UIView {
private let messageLabel = UILabel()
private let upgradeButton = UIButton(type: .system)
private let dismissButton = UIButton(type: .system)
private var messageLabelStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().primaryBaseColor())
}
private var buttonLabelStyle : OEXTextStyle {
return OEXTextStyle(weight: .semiBold, size: .base, color: OEXStyles.shared().primaryBaseColor())
}
init(message: String) {
super.init(frame: CGRect.zero)
backgroundColor = OEXStyles.shared().warningXXLight()
messageLabel.numberOfLines = 0
messageLabel.attributedText = messageLabelStyle.attributedString(withText: message)
upgradeButton.setAttributedTitle(buttonLabelStyle.attributedString(withText: Strings.versionUpgradeUpdate), for: .normal)
dismissButton.setAttributedTitle(buttonLabelStyle.attributedString(withText: Strings.VersionUpgrade.dismiss), for: .normal)
addSubview(messageLabel)
addSubview(dismissButton)
addSubview(upgradeButton)
addConstraints()
addButtonActions()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addConstraints() {
messageLabel.snp.makeConstraints { make in
make.top.equalTo(self).offset(StandardVerticalMargin)
make.leading.equalTo(self).offset(StandardHorizontalMargin)
make.trailing.equalTo(self).offset(-StandardHorizontalMargin)
}
upgradeButton.snp.makeConstraints { make in
make.top.equalTo(messageLabel.snp.bottom)
make.trailing.equalTo(self).offset(-StandardHorizontalMargin)
make.bottom.equalTo(self).offset(-StandardVerticalMargin)
}
dismissButton.snp.makeConstraints { make in
make.top.equalTo(messageLabel.snp.bottom)
make.trailing.equalTo(upgradeButton.snp.leading).offset(-StandardHorizontalMargin)
make.bottom.equalTo(self).offset(-StandardVerticalMargin)
}
}
private func addButtonActions() {
dismissButton.oex_addAction({[weak self] _ in
self?.dismissView()
}, for: .touchUpInside)
upgradeButton.oex_addAction({[weak self] _ in
if let URL = OEXConfig.shared().appUpgradeConfig.iOSAppStoreURL() {
if UIApplication.shared.canOpenURL(URL as URL) {
self?.dismissView()
UIApplication.shared.open(URL as URL, options: [:], completionHandler: nil)
isActionTakenOnUpgradeSnackBar = true
}
}
}, for: .touchUpInside)
}
private func dismissView() {
var container = superview
if container == nil {
container = self
}
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: .curveEaseOut, animations: {
self.transform = .identity
}, completion: { _ in
container?.removeFromSuperview()
isActionTakenOnUpgradeSnackBar = true
})
}
}
public class OfflineView: UIView {
private let messageLabel = UILabel()
private let reloadButton = UIButton(type: .system)
private let dismissButton = UIButton(type: .system)
private var selector: Selector?
private var messageLabelStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().primaryBaseColor())
}
private var buttonLabelStyle : OEXTextStyle {
return OEXTextStyle(weight: .semiBold, size: .base, color: OEXStyles.shared().primaryBaseColor())
}
init(message: String, selector: Selector?) {
super.init(frame: CGRect.zero)
self.selector = selector
self.backgroundColor = OEXStyles.shared().warningXXLight()
messageLabel.numberOfLines = 0
messageLabel.attributedText = messageLabelStyle.attributedString(withText: message)
reloadButton.setAttributedTitle(buttonLabelStyle.attributedString(withText: Strings.reload), for: .normal)
dismissButton.setAttributedTitle(buttonLabelStyle.attributedString(withText: Strings.VersionUpgrade.dismiss), for: .normal)
addSubview(messageLabel)
addSubview(dismissButton)
addSubview(reloadButton)
addConstraints()
addButtonActions()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addConstraints() {
messageLabel.snp.makeConstraints { make in
make.top.equalTo(self).offset(StandardVerticalMargin)
make.leading.equalTo(self).offset(StandardHorizontalMargin)
make.trailing.lessThanOrEqualTo(dismissButton).offset(-StandardHorizontalMargin)
make.centerY.equalTo(reloadButton)
}
reloadButton.snp.makeConstraints { make in
make.top.equalTo(messageLabel)
make.trailing.equalTo(self).offset(-StandardHorizontalMargin)
make.bottom.equalTo(self).offset(-StandardVerticalMargin)
}
dismissButton.snp.makeConstraints { make in
make.top.equalTo(reloadButton)
make.trailing.equalTo(reloadButton.snp.leading).offset(-StandardHorizontalMargin)
make.bottom.equalTo(self).offset(-StandardVerticalMargin)
}
}
private func addButtonActions() {
dismissButton.oex_addAction({[weak self] _ in
self?.dismissView()
}, for: .touchUpInside)
reloadButton.oex_addAction({[weak self] _ in
let controller = self?.firstAvailableUIViewController()
if let controller = controller, let selector = self?.selector {
if controller.responds(to: selector) && OEXRouter.shared().environment.reachability.isReachable() {
controller.perform(selector)
self?.dismissView()
}
}
else {
self?.dismissView()
}
}, for: .touchUpInside)
}
private func dismissView() {
var container = superview
if container == nil {
container = self
}
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: .curveEaseOut, animations: {
self.transform = .identity
}, completion: { _ in
container!.removeFromSuperview()
})
}
}
public class DateResetToastView: UIView {
private lazy var container = UIView()
private lazy var buttonContainer = UIView()
private lazy var stackView: TZStackView = {
let stackView = TZStackView()
stackView.spacing = StandardHorizontalMargin / 4
stackView.alignment = .leading
stackView.distribution = .fill
stackView.axis = .vertical
return stackView
}()
private lazy var messageLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
return label
}()
private lazy var button: UIButton = {
let button = UIButton()
button.layer.borderWidth = 1
button.layer.borderColor = OEXStyles.shared().neutralXDark().cgColor
return button
}()
private lazy var dismissButton: UIButton = {
let button = UIButton()
let image = Icon.Close.imageWithFontSize(size: 18)
button.setImage(image, for: UIControl.State())
button.tintColor = OEXStyles.shared().neutralWhiteT()
return button
}()
private lazy var messageLabelStyle: OEXTextStyle = {
return OEXTextStyle(weight: .normal, size: .xSmall, color: OEXStyles.shared().neutralWhiteT())
}()
private lazy var buttonStyle: OEXTextStyle = {
return OEXTextStyle(weight: .normal, size: .xSmall, color: OEXStyles.shared().neutralWhiteT())
}()
init(message: String, buttonText: String? = nil, showButton: Bool = false, buttonAction: (()->())? = nil) {
super.init(frame: .zero)
backgroundColor = OEXStyles.shared().neutralXXDark()
messageLabel.attributedText = messageLabelStyle.attributedString(withText: message).setLineSpacing(3)
messageLabel.sizeToFit()
stackView.addArrangedSubview(messageLabel)
if showButton {
button.setAttributedTitle(buttonStyle.attributedString(withText: buttonText), for: UIControl.State())
button.oex_addAction({ _ in
buttonAction?()
}, for: .touchUpInside)
buttonContainer.addSubview(button)
stackView.addArrangedSubview(buttonContainer)
}
container.addSubview(stackView)
container.addSubview(dismissButton)
addSubview(container)
addConstraints(showButton: showButton)
addButtonActions()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addConstraints(showButton: Bool) {
stackView.snp.makeConstraints { make in
make.leading.equalTo(container).inset(StandardHorizontalMargin)
make.trailing.equalTo(dismissButton.snp.leading)
make.top.equalTo(container).offset(1.5 * StandardVerticalMargin)
make.bottom.equalTo(container).inset(StandardVerticalMargin)
}
container.snp.makeConstraints { make in
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.top.equalTo(self)
make.bottom.equalTo(self)
}
dismissButton.snp.makeConstraints { make in
make.trailing.equalTo(self).inset(StandardVerticalMargin)
make.top.equalTo(container).offset(StandardVerticalMargin/2)
make.width.equalTo(StandardHorizontalMargin * 2)
make.height.equalTo(StandardHorizontalMargin * 2)
}
if showButton {
buttonContainer.snp.makeConstraints { make in
make.leading.equalTo(stackView.snp.leading)
make.trailing.equalTo(stackView.snp.trailing)
}
button.snp.makeConstraints { make in
make.leading.equalTo(buttonContainer.snp.leading)
make.top.equalTo(buttonContainer.snp.top).offset(2 * StandardVerticalMargin)
make.bottom.equalTo(buttonContainer.snp.bottom).inset(StandardVerticalMargin)
make.height.equalTo(StandardVerticalMargin * 4)
make.width.greaterThanOrEqualTo(StandardHorizontalMargin * 7)
}
}
}
private func addButtonActions() {
dismissButton.oex_addAction({ [weak self] _ in
self?.dismissView()
}, for: .touchUpInside)
}
private func dismissView() {
var container = superview
if container == nil {
container = self
}
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: .curveEaseOut, animations: { [weak self] in
self?.transform = .identity
}) { _ in
container?.removeFromSuperview()
}
}
}
public class CalendarActionToastView: UIView {
private lazy var container = UIView()
private lazy var messageLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
return label
}()
private lazy var dismissButton: UIButton = {
let button = UIButton()
let image = Icon.Close.imageWithFontSize(size: 18)
button.setImage(image, for: UIControl.State())
button.tintColor = OEXStyles.shared().neutralWhiteT()
return button
}()
private lazy var messageLabelStyle: OEXTextStyle = {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralWhiteT())
}()
init(message: String) {
super.init(frame: .zero)
backgroundColor = OEXStyles.shared().neutralXXDark()
messageLabel.attributedText = messageLabelStyle.attributedString(withText: message).setLineSpacing(3)
messageLabel.sizeToFit()
container.addSubview(messageLabel)
container.addSubview(dismissButton)
addSubview(container)
addConstraints()
addButtonActions()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addConstraints() {
messageLabel.snp.makeConstraints { make in
make.top.equalTo(container).inset(StandardVerticalMargin)
make.bottom.equalTo(container).inset(StandardVerticalMargin)
make.leading.equalTo(container).offset(StandardHorizontalMargin)
make.trailing.equalTo(dismissButton).inset(StandardHorizontalMargin)
make.height.equalTo(StandardVerticalMargin * 5)
}
dismissButton.snp.makeConstraints { make in
make.trailing.equalTo(self).inset(StandardVerticalMargin)
make.top.equalTo(container).offset(StandardVerticalMargin)
make.width.equalTo(StandardHorizontalMargin * 2)
make.height.equalTo(StandardHorizontalMargin * 2)
}
container.snp.makeConstraints { make in
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.top.equalTo(self)
make.bottom.equalTo(self)
}
}
private func addButtonActions() {
dismissButton.oex_addAction({ [weak self] _ in
self?.dismissView()
}, for: .touchUpInside)
}
private func dismissView() {
var container = superview
if container == nil {
container = self
}
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: .curveEaseOut, animations: { [weak self] in
self?.transform = .identity
}) { _ in
container?.removeFromSuperview()
}
}
}
| apache-2.0 | a7ad44c47ea67dcf15eef2e7f07ba045 | 35.849383 | 173 | 0.626843 | 5.458669 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/SteviaLayout/Source/Stevia+Fill.swift | 2 | 2508 | //
// Stevia+Fill.swift
// Stevia
//
// Created by Sacha Durand Saint Omer on 10/02/16.
// Copyright © 2016 Sacha Durand Saint Omer. All rights reserved.
//
#if canImport(UIKit)
import UIKit
public extension UIView {
/**
Adds the constraints needed for the view to fill its `superview`.
A padding can be used to apply equal spaces between the view and its superview
*/
@discardableResult
func fillContainer(_ padding: CGFloat = 0) -> Self {
fillHorizontally(m: padding)
fillVertically(m: padding)
return self
}
@available(*, deprecated, message: "Use 'fillVertically' instead")
/**
Adds the constraints needed for the view to fill its `superview` Vertically.
A padding can be used to apply equal spaces between the view and its superview
*/
func fillV(m points: CGFloat = 0) -> Self {
return fill(.vertical, points: points)
}
/**
Adds the constraints needed for the view to fill its `superview` Vertically.
A padding can be used to apply equal spaces between the view and its superview
*/
@discardableResult
func fillVertically(m points: CGFloat = 0) -> Self {
return fill(.vertical, points: points)
}
@available(*, deprecated, message: "Use 'fillHorizontally' instead")
/**
Adds the constraints needed for the view to fill its `superview` Horizontally.
A padding can be used to apply equal spaces between the view and its superview
*/
func fillH(m points: CGFloat = 0) -> Self {
return fill(.horizontal, points: points)
}
/**
Adds the constraints needed for the view to fill its `superview` Horizontally.
A padding can be used to apply equal spaces between the view and its superview
*/
@discardableResult
func fillHorizontally(m points: CGFloat = 0) -> Self {
return fill(.horizontal, points: points)
}
fileprivate func fill(_ axis: NSLayoutConstraint.Axis, points: CGFloat = 0) -> Self {
let a: NSLayoutConstraint.Attribute = axis == .vertical ? .top : .leading
let b: NSLayoutConstraint.Attribute = axis == .vertical ? .bottom : .trailing
if let spv = superview {
let c1 = constraint(item: self, attribute: a, toItem: spv, constant: points)
let c2 = constraint(item: self, attribute: b, toItem: spv, constant: -points)
spv.addConstraints([c1, c2])
}
return self
}
}
#endif
| mit | 830f47eb4eb2fb629a2fb672a64c17e8 | 33.819444 | 89 | 0.645792 | 4.468806 | false | false | false | false |
nguyenantinhbk77/practice-swift | playgrounds/Trie.playground/Contents.swift | 3 | 3299 | // Trie Data Structure
// Source: http://goo.gl/515yko
import Foundation
// Trie node data structure
public class TrieNode{
var key: String!
var children: Array<TrieNode>
var isFinal: Bool
var level: Int
init(){
self.children = Array<TrieNode>()
self.isFinal = false
self.level = 0
}
}
// Trie implementation
public class Trie {
private var root: TrieNode!
init(){
root = TrieNode()
}
// Build a recursive tree of dictionary content
func addWord(keyword: String){
if (keyword.length == 0){
return;
}
var current: TrieNode = root
var searchKey: String!
while(keyword.length != current.level){
var childToUse: TrieNode!
var searchKey = keyword.substringToIndex(current.level + 1)
for child in current.children {
if (child.key == searchKey){
childToUse = child
break
}
}
// Create a new node
if (childToUse == nil){
childToUse = TrieNode()
childToUse.key = searchKey
childToUse.level = current.level + 1
current.children.append(childToUse)
}
current = childToUse
// Add final end of word check
if (keyword.length == current.level) {
current.isFinal = true
print("end of the word reached")
return;
}
}
}
// Find all words based on a prefix
func findWord(keyword: String) -> Array<String>! {
if (keyword.length == 0){
return nil
}
var current: TrieNode = root
var searchKey: String!
var wordList: Array<String>! = Array<String>()
while(keyword.length != current.level){
var childToUse: TrieNode!
var searchKey = keyword.substringToIndex(current.level + 1)
// Iterate through any children
for child in current.children {
if (child.key == searchKey){
childToUse = child
current = childToUse
break
}
}
// Prefix not found
if (childToUse == nil){
return nil
}
}
// Retrieve keyword and any descendants
if ((current.key == keyword) && (current.isFinal)){
wordList.append(current.key)
}
// Add children that are words
for child in current.children {
if (child.isFinal == true){
wordList.append(child.key)
}
}
return wordList
}
}
// Extend the native String class
extension String{
// compute the length of string
var length: Int {
return Array(self).count
}
// returns characters of a string up to a specific index
func substringToIndex(to: Int) -> String{
return self.substringToIndex(advance(self.startIndex, to))
}
} | mit | 004ab776f8ea6bfc2bac6e205f7f2036 | 24.78125 | 71 | 0.492574 | 5.355519 | false | false | false | false |
csericksantos/Dribbble | DribbbleTests/Presenter/Util/ShotServiceMock.swift | 1 | 2254 | //
// ShotServiceMock.swift
// Dribbble
//
// Created by Erick Santos on 7/27/16.
// Copyright © 2016 Erick Santos. All rights reserved.
//
import Foundation
@testable import Dribbble
class ShotServiceMock: Gettable {
var callError = false
var callEmpty = false
var wasCalled = false
func get (completion: Result<[Shot], Errors> -> Void) {
wasCalled = true
let firstShot = Shot(id: 1, title: "Title 1", description: "Description 1", images: Images(high: NSURL(), normal: NSURL(), teaser: NSURL()), view: 10, like: 100, comment: 1000, user: User(id: 1, name: "User 1", avatar: NSURL(), location: "Location 1"))
let secondShot = Shot(id: 2, title: "Title 2", description: "Description 2", images: Images(high: NSURL(), normal: NSURL(), teaser: NSURL()), view: 20, like: 200, comment: 2000, user: User(id: 2, name: "User 2", avatar: NSURL(), location: "Location 2"))
if callError {
completion(Result.failure(Errors.undefinedError(description: "Testando falha")))
} else {
if callEmpty {
completion(Result.success(Array<Shot>()))
} else {
completion(Result.success([firstShot, secondShot]))
}
}
}
func get (id: Int, completion: Result<Shot, Errors> -> Void) {
wasCalled = true
switch id {
case 1:
let firstShot = Shot(id: 1, title: "Title 1", description: "Description 1", images: Images(high: NSURL(), normal: NSURL(), teaser: NSURL()), view: 10, like: 100, comment: 1000, user: User(id: 1, name: "User 1", avatar: NSURL(), location: "Location 1"))
completion(Result.success(firstShot))
case 2:
let secondShot = Shot(id: 2, title: "Title 2", description: "Description 2", images: Images(high: NSURL(), normal: NSURL(), teaser: NSURL()), view: 20, like: 200, comment: 2000, user: User(id: 2, name: "User 2", avatar: NSURL(), location: "Location 2"))
completion(Result.success(secondShot))
default:
completion(Result.failure(Errors.undefinedError(description: "Não encontrado")))
}
}
}
| mit | e2f4e958e8ffd114fdae56644ae329ee | 39.214286 | 265 | 0.586146 | 4.087114 | false | false | false | false |
sora0077/APIKit | Sources/RequestType.swift | 1 | 6134 | import Foundation
import Result
/// `RequestType` protocol represents a request for Web API.
/// Following 5 items must be implemented.
/// - `typealias Response`
/// - `var baseURL: URL`
/// - `var method: HTTPMethod`
/// - `var path: String`
/// - `func responseFromObject(object: AnyObject, URLResponse: HTTPURLResponse) throws -> Response`
public protocol RequestType {
/// The response type associated with the request type.
associatedtype Response
/// The base URL.
var baseURL: URL { get }
/// The HTTP request method.
var method: HTTPMethod { get }
/// The path URL component.
var path: String { get }
/// The convenience property for `queryParameters` and `bodyParameters`. If the implementation of
/// `queryParameters` and `bodyParameters` are not provided, the values for them will be computed
/// from this property depending on `method`.
var parameters: AnyObject? { get }
/// The actual parameters for the URL query. The values of this property will be escaped using `URLEncodedSerialization`.
/// If this property is not implemented and `method.prefersQueryParameter` is `true`, the value of this property
/// will be computed from `parameters`.
var queryParameters: [String: AnyObject]? { get }
/// The actual parameters for the HTTP body. If this property is not implemented and `method.prefersQueryParameter` is `false`,
/// the value of this property will be computed from `parameters` using `JSONBodyParameters`.
var bodyParameters: BodyParametersType? { get }
/// The HTTP header fields. In addition to fields defined in this property, `Accept` and `Content-Type`
/// fields will be added by `dataParser` and `bodyParameters`. If you define `Accept` and `Content-Type`
/// in this property, the values in this property are preferred.
var headerFields: [String: String] { get }
/// The parser object that states `Content-Type` to accept and parses response body.
var dataParser: DataParserType { get }
/// Intercepts `URLRequest` which is created by `RequestType.buildURLRequest()`. If an error is
/// thrown in this method, the result of `Session.sendRequest()` turns `.Failure(.RequestError(error))`.
/// - Throws: `ErrorType`
func intercept(urlRequest: URLRequest) throws -> URLRequest
/// Intercepts response `AnyObject` and `HTTPURLResponse`. If an error is thrown in this method,
/// the result of `Session.sendRequest()` turns `.Failure(.ResponseError(error))`.
/// The default implementation of this method is provided to throw `RequestError.UnacceptableStatusCode`
/// if the HTTP status code is not in `200..<300`.
/// - Throws: `ErrorType`
func intercept(object: AnyObject, urlResponse: HTTPURLResponse) throws -> AnyObject
/// Build `Response` instance from raw response object. This method is called after
/// `interceptObject(:URLResponse:)` if it does not throw any error.
/// - Throws: `ErrorType`
func response(from object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response
}
public extension RequestType {
public var parameters: AnyObject? {
return nil
}
public var queryParameters: [String: AnyObject]? {
guard let parameters = parameters as? [String: AnyObject], method.prefersQueryParameters else {
return nil
}
return parameters
}
public var bodyParameters: BodyParametersType? {
guard let parameters = parameters, !method.prefersQueryParameters else {
return nil
}
return JSONBodyParameters(JSONObject: parameters)
}
public var headerFields: [String: String] {
return [:]
}
public var dataParser: DataParserType {
return JSONDataParser(readingOptions: [])
}
public func intercept(urlRequest: URLRequest) throws -> URLRequest {
return urlRequest
}
public func intercept(object: AnyObject, urlResponse: HTTPURLResponse) throws -> AnyObject {
guard (200..<300).contains(urlResponse.statusCode) else {
throw ResponseError.unacceptableStatusCode(urlResponse.statusCode)
}
return object
}
/// Builds `URLRequest` from properties of `self`.
/// - Throws: `RequestError`, `ErrorType`
public func buildURLRequest() throws -> URLRequest {
let URL = path.isEmpty ? baseURL : try! baseURL.appendingPathComponent(path)
guard var components = URLComponents(url: URL, resolvingAgainstBaseURL: true) else {
throw RequestError.invalidBaseURL(baseURL)
}
if let queryParameters = queryParameters, !queryParameters.isEmpty {
components.percentEncodedQuery = URLEncodedSerialization.stringFromDictionary(queryParameters)
}
guard var URLRequest = components.url.map({ Foundation.URLRequest(url: $0) }) else {
throw RequestError.invalidBaseURL(URL)
}
if let bodyParameters = bodyParameters {
URLRequest.setValue(bodyParameters.contentType, forHTTPHeaderField: "Content-Type")
switch try bodyParameters.buildEntity() {
case .data(let data):
URLRequest.httpBody = data
case .inputStream(let inputStream):
URLRequest.httpBodyStream = inputStream
}
}
URLRequest.url = components.url
URLRequest.httpMethod = method.rawValue
URLRequest.setValue(dataParser.contentType, forHTTPHeaderField: "Accept")
headerFields.forEach { key, value in
URLRequest.setValue(value, forHTTPHeaderField: key)
}
return try intercept(urlRequest: URLRequest)
}
/// Builds `Response` from response `Data`.
/// - Throws: `ResponseError`, `ErrorType`
public func parseData(_ data: Data, urlResponse: HTTPURLResponse) throws -> Response {
let parsedObject = try dataParser.parseData(data)
let passedObject = try intercept(object: parsedObject, urlResponse: urlResponse)
return try response(from: passedObject, urlResponse: urlResponse)
}
}
| mit | 9d3aa9b8c731bba61a0209228336b7c0 | 40.445946 | 131 | 0.682752 | 5.145973 | false | false | false | false |
rexmas/Crust | CrustTests/Employee.swift | 1 | 2183 | import Crust
import Foundation
class Employee {
required init() { }
var employer: Company?
var uuid: String = ""
var name: String = ""
var joinDate: Date = Date()
var salary: Int = 0
var isEmployeeOfMonth: Bool = false
var percentYearlyRaise: Double = 0.0
}
enum EmployeeCodingKey: MappingKey {
case employer(Set<CompanyCodingKey>)
case uuid
case name
case joinDate
case salary
case isEmployeeOfMonth
case percentYearlyRaise
var keyPath: String {
switch self {
case .employer(_): return "company"
case .uuid: return "uuid"
case .name: return "name"
case .joinDate: return "joinDate"
case .salary: return "data.salary"
case .isEmployeeOfMonth: return "data.is_employee_of_month"
case .percentYearlyRaise: return "data.percent_yearly_raise"
}
}
public func nestedMappingKeys<Key: MappingKey>() -> AnyKeyCollection<Key>? {
switch self {
case .employer(let companyKeys):
return companyKeys.anyKeyCollection()
default:
return nil
}
}
}
extension Employee: AnyMappable { }
class EmployeeMapping: MockMapping {
var adapter: MockAdapter<Employee>
var primaryKeys: [Mapping.PrimaryKeyDescriptor]? {
return [ ("uuid", "uuid", nil) ]
}
required init(adapter: MockAdapter<Employee>) {
self.adapter = adapter
}
func mapping(toMap: inout Employee, payload: MappingPayload<EmployeeCodingKey>) {
let companyMapping = CompanyMapping(adapter: MockAdapter<Company>())
toMap.employer <- (.mapping(.employer([]), companyMapping), payload)
toMap.joinDate <- (.joinDate, payload)
toMap.uuid <- (.uuid, payload)
toMap.name <- (.name, payload)
toMap.salary <- (.salary, payload)
toMap.isEmployeeOfMonth <- (.isEmployeeOfMonth, payload)
toMap.percentYearlyRaise <- (.percentYearlyRaise, payload)
}
}
| mit | 62bf6dc801ff3cd0fd789b6ac3e7fad7 | 29.746479 | 89 | 0.581768 | 4.605485 | false | false | false | false |
lorentey/swift | test/DebugInfo/inlinescopes.swift | 9 | 1319 | // RUN: %empty-directory(%t)
// RUN: echo "public var x = Int64()" \
// RUN: | %target-swift-frontend -module-name FooBar -emit-module -o %t -
// RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o %t.ll
// RUN: %FileCheck %s < %t.ll
// RUN: %FileCheck %s -check-prefix=TRANSPARENT-CHECK < %t.ll
// CHECK: define{{( dllexport)?}}{{( protected)?( signext)?}} i32 @main
// CHECK: call {{.*}}noinline{{.*}}, !dbg ![[CALL:.*]]
// CHECK-DAG: ![[TOPLEVEL:.*]] = !DIFile(filename: "{{.*}}inlinescopes.swift"
import FooBar
func use<T>(_ t: T) {}
@inline(never)
func noinline(_ x: Int64) -> Int64 { return x }
@_transparent
func transparent(_ x: Int64) -> Int64 { return noinline(x) }
@inline(__always)
func inlined(_ x: Int64) -> Int64 {
// CHECK-DAG: ![[CALL]] = !DILocation(line: [[@LINE+2]], column: {{.*}}, scope: ![[SCOPE:.*]], inlinedAt: ![[INLINED:.*]])
// CHECK-DAG: ![[SCOPE:.*]] = distinct !DILexicalBlock(
let result = transparent(x)
// TRANSPARENT-CHECK-NOT: !DISubprogram(name: "transparent"
return result
}
// CHECK-DAG: !DIGlobalVariable(name: "y",{{.*}} file: ![[TOPLEVEL]],{{.*}} line: [[@LINE+1]]
let y = inlined(x)
use(y)
// Check if the inlined and removed function still has the correct linkage name.
// CHECK-DAG: !DISubprogram(name: "inlined", linkageName: "$s4main7inlinedys5Int64VADF"
| apache-2.0 | 2db27c7aa6322e7f0986914dc5585843 | 35.638889 | 122 | 0.624716 | 3.155502 | false | false | false | false |
TTVS/NightOut | Clubber/CCInfoTableViewController.swift | 1 | 3766 | //
// CCInfoTableViewController.swift
// Clubber
//
// Created by Terra on 8/26/15.
// Copyright (c) 2015 Dino Media Asia. All rights reserved.
//
import UIKit
class CCInfoTableViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet var creditCardNumber: UITextField!
@IBOutlet var creditCardExpirationDate: UITextField!
@IBOutlet var creditCardCardholder: UITextField!
@IBOutlet var billingAddress: UITextField!
@IBOutlet var contactNumber: UITextField!
@IBAction func datePickerTapped(sender: AnyObject) {
DatePopPickerView().show("Expiration Date", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: .Date) {
(date) -> Void in
self.creditCardExpirationDate.text = DatePopPickerView().dateFormatter.stringFromDate(date)
}
self.creditCardNumber.resignFirstResponder()
self.creditCardCardholder.resignFirstResponder()
self.billingAddress.resignFirstResponder()
self.contactNumber.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
//text field properties
self.creditCardCardholder.delegate = self
// self.creditCardExpirationDate.delegate = self
self.creditCardNumber.delegate = self
self.billingAddress.delegate = self
self.contactNumber.delegate = self
//add credit card image to table view
let viewHeight = CGRectGetHeight(self.tableView.frame)
let viewWidth = CGRectGetWidth(self.tableView.frame)
let backgroundImageView: UIImageView
backgroundImageView = UIImageView(frame:CGRectMake(3, 108, viewWidth - 6, 200))
backgroundImageView.image = UIImage(named: "creditCardLayout")
backgroundImageView.contentMode = UIViewContentMode.ScaleToFill
let backgroundViewHolder = UIView()
// let lightBeigeColor : UIColor = UIColor(red: (231/255.0), green: (231/255.0), blue: (231/255.0), alpha: 1.0)
// let lightDarkColor : UIColor = UIColor(red: (20/255.0), green: (20/255.0), blue: (21/255.0), alpha: 1.0)
// backgroundViewHolder.backgroundColor = lightDarkColor
backgroundViewHolder.frame = CGRectMake(0, 0, viewWidth, viewHeight)
backgroundViewHolder.addSubview(backgroundImageView)
self.tableView.backgroundView = backgroundViewHolder
self.tableView.backgroundColor = UIColor.whiteColor()
//remove excess rows from table view
tableView.tableFooterView = UIView(frame:CGRectZero)
//dismiss keyboard when single or multiple tap(s)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
self.view.addGestureRecognizer(tap)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//dismiss keyboard when single or multiple tap(s)
func DismissKeyboard(){
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
//dismiss keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.creditCardCardholder.resignFirstResponder()
// self.creditCardExpirationDate.resignFirstResponder()
self.creditCardNumber.resignFirstResponder()
self.billingAddress.resignFirstResponder()
self.contactNumber.resignFirstResponder()
return true
}
}
| apache-2.0 | c190282e16b78c598415542ec8c28f5e | 33.87037 | 130 | 0.672331 | 5.364672 | false | false | false | false |
jianghongbing/APIReferenceDemo | UIKit/UIView/UIView/HierarchyViewController.swift | 1 | 4992 | //
// HierarchyViewController.swift
// UIView
//
// Created by pantosoft on 2017/9/11.
// Copyright © 2017年 jianghongbing. All rights reserved.
//
import UIKit
class HierarchyViewController: UIViewController {
let redView = UIView()
let blueView = UIView()
let orangeView = UIView()
let testLabel = UILabel()
var purpleView : UIView?
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setToolbarHidden(false, animated: true)
redView.frame = CGRect(x: 100, y: 100, width: 100, height: 100);
redView.backgroundColor = .red
redView.tag = 1000
view.addSubview(redView)
blueView.frame = CGRect(x: 150, y: 150, width: 200, height: 200);
blueView.backgroundColor = .blue
blueView.tag = 10000
view.addSubview(blueView)
orangeView.frame = CGRect(x: 50, y: 400, width: 100, height: 100);
orangeView.backgroundColor = .orange
orangeView.tag = 100000
view.addSubview(orangeView)
let orangeSubview = UIView(frame: CGRect(x: 20, y: 20, width: 50, height: 50))
orangeSubview.backgroundColor = .green
orangeView.addSubview(orangeSubview)
testLabel.frame = CGRect(x: 200, y: 400, width: 100, height: 100)
testLabel.text = "hehe"
testLabel.backgroundColor = .brown
view.addSubview(testLabel)
//1.判断某个view是不是某个view的后代
var isDescendant = orangeView.isDescendant(of: view)
print(isDescendant)
isDescendant = orangeSubview.isDescendant(of: view)
print(isDescendant)
isDescendant = redView.isDescendant(of: blueView)
print(isDescendant)
//2.convert point & rect
convertRectAndPoint()
}
fileprivate func convertRectAndPoint() {
//1.将某个view中的point(以自己的左上角为(0,0))转化到另外一个view中该point的位置
//toPoint的计算方式 topoint.x = self.frame.origin.x + point.x - toView.frame.origin.x;
//toPoint.y = self.frame.origin.y + point.y - toView.frame.origin.y;
var toPoint = redView.convert(CGPoint(x: 20, y: 20), to: view)
//2.将某个view中的point转化到该point在自己frame中的位置
//fromPoint的计算方式 fromPoint.x = fromView.origin.x + point.x - self.frame.origin.x;
//fromPoint.y = fromView.origin.y + point.y - self.frame.origin.y;
var fromPoint = redView.convert(CGPoint(x: 20, y: 20), from: view)
print(toPoint, fromPoint)
toPoint = redView.convert(CGPoint(x: 20, y: 20), to: blueView)
fromPoint = redView.convert(CGPoint(x: 20, y: 20), from: blueView)
print(toPoint, fromPoint)
//3.将以自己为坐标系(左上角为(0,0))的rect转化成以toView为坐标系中的rect
//转换的过程中,size不变,origin的变化同point的转换相同
let toRect = redView.convert(CGRect(x: 50, y: 50, width: 50, height: 50), to: orangeView)
//4.将以fromView中的rect转化成自己为坐标系的rect
let fromRect = redView.convert(CGRect(x: 50, y: 50, width: 50, height: 50), from: orangeView)
print(toRect, fromRect)
}
@IBAction func sendViewToBack(_ sender: Any) {
//1.将某个view移动到最上面
view.bringSubview(toFront: blueView)
}
@IBAction func bringSubviewToFront(_ sender: Any) {
//2.将某个view移动到最下面
view.sendSubview(toBack: blueView)
}
@IBAction func exchangeHierarchy(_ sender: Any) {
//3 交互两个view的index,并不表示index小的就显示在最下面,index大的就显示在最上面
view.exchangeSubview(at: 0, withSubviewAt: 1)
}
@IBAction func insertView(_ sender: Any) {
guard purpleView == nil else {
return
}
purpleView = UIView(frame: CGRect(x: 100, y: 100, width: 50, height: 50))
purpleView?.backgroundColor = .purple
//3.在某个subView的上面插入一个subView
view.insertSubview(purpleView!, aboveSubview: redView)
//4.在某个subView的下面插入一个subView
// view.insertSubview(purpleView!, belowSubview: redView)
//5.插入一个View在指定位置,index的范围必须为0到view的subviews的数量之间
// view.insertSubview(purpleView!, at: 0)
}
@IBAction func sizeFit(_ sender: Any) {
//1.返回某个view的fit size,自定view时,可重写该方法来返回合适的size.如果为可以根据内容计算出合适的size的时候,返回的就是根据内容计算的size
let size = testLabel.sizeThatFits(testLabel.frame.size)
print(size)
//2.自动改为当前的size为sizeThatFits的size, origin不会改变,size自适应
testLabel.sizeToFit()
print(testLabel.frame)
}
}
| mit | 5dcd66fe8b202a4ea1122547963fbf25 | 36.386555 | 101 | 0.636997 | 3.84529 | false | true | false | false |
tapz/MWPhotoBrowserSwift | Pod/Classes/PhotoBrowser.swift | 1 | 72549 | //
// PhotoBrowser.swift
// Pods
//
// Created by Tapani Saarinen on 04/09/15.
//
//
import UIKit
import MBProgressHUD
import MediaPlayer
import QuartzCore
import MBProgressHUD
import MapleBacon
func floorcgf(x: CGFloat) -> CGFloat {
return CGFloat(floorf(Float(x)))
}
public class PhotoBrowser: UIViewController, UIScrollViewDelegate, UIActionSheetDelegate {
private let padding = CGFloat(10.0)
// Data
private var photoCount = -1
private var photos = [Photo?]()
private var thumbPhotos = [Photo?]()
private var fixedPhotosArray: [Photo]? // Provided via init
// Views
private var pagingScrollView = UIScrollView()
// Paging & layout
private var visiblePages = Set<ZoomingScrollView>()
private var recycledPages = Set<ZoomingScrollView>()
private var currentPageIndex = 0
private var previousPageIndex = Int.max
private var previousLayoutBounds = CGRectZero
private var pageIndexBeforeRotation = 0
// Navigation & controls
private var toolbar = UIToolbar()
private var controlVisibilityTimer: NSTimer?
private var previousButton: UIBarButtonItem?
private var nextButton: UIBarButtonItem?
private var actionButton: UIBarButtonItem?
private var doneButton: UIBarButtonItem?
// Grid
private var gridController: GridViewController?
private var gridPreviousLeftNavItem: UIBarButtonItem?
private var gridPreviousRightNavItem: UIBarButtonItem?
// Appearance
public var previousNavBarHidden = false
public var previousNavBarTranslucent = false
public var previousNavBarStyle = UIBarStyle.Default
public var previousStatusBarStyle = UIStatusBarStyle.Default
public var previousNavBarTintColor: UIColor?
public var previousNavBarBarTintColor: UIColor?
public var previousViewControllerBackButton: UIBarButtonItem?
public var previousNavigationBarBackgroundImageDefault: UIImage?
public var previousNavigationBarBackgroundImageLandscapePhone: UIImage?
// Video
var currentVideoPlayerViewController: MPMoviePlayerViewController?
var currentVideoIndex = 0
var currentVideoLoadingIndicator: UIActivityIndicatorView?
// Misc
public var hasBelongedToViewController = false
public var isVCBasedStatusBarAppearance = false
public var statusBarShouldBeHidden = false
public var displayActionButton = true
public var leaveStatusBarAlone = false
public var performingLayout = false
public var rotating = false
public var viewIsActive = false // active as in it's in the view heirarchy
public var didSavePreviousStateOfNavBar = false
public var skipNextPagingScrollViewPositioning = false
public var viewHasAppearedInitially = false
public var currentGridContentOffset = CGPointMake(0, CGFloat.max)
var activityViewController: UIActivityViewController?
public weak var delegate: PhotoBrowserDelegate?
public var zoomPhotosToFill = true
public var displayNavArrows = false
public var displaySelectionButtons = false
public var alwaysShowControls = false
public var enableGrid = true
public var enableSwipeToDismiss = true
public var startOnGrid = false
public var autoPlayOnAppear = false
public var hideControlsOnStartup = false
public var delayToHideElements = NSTimeInterval(5.0)
public var navBarTintColor = UIColor.blackColor()
public var navBarBarTintColor = UIColor.blackColor()
public var navBarTranslucent = true
public var toolbarTintColor = UIColor.blackColor()
public var toolbarBarTintColor = UIColor.whiteColor()
public var toolbarBackgroundColor = UIColor.whiteColor()
public var captionAlpha = CGFloat(0.5)
public var toolbarAlpha = CGFloat(0.8)
// Customise image selection icons as they are the only icons with a colour tint
// Icon should be located in the app's main bundle
public var customImageSelectedIconName = ""
public var customImageSelectedSmallIconName = ""
//MARK: - Init
public override init(nibName: String?, bundle nibBundle: NSBundle?) {
super.init(nibName: nibName, bundle: nibBundle)
initialisation()
}
public convenience init(delegate: PhotoBrowserDelegate) {
self.init()
self.delegate = delegate
initialisation()
}
public convenience init(photos: [Photo]) {
self.init()
fixedPhotosArray = photos
initialisation()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
initialisation()
}
private func initialisation() {
// Defaults
if let vcBasedStatusBarAppearance = NSBundle.mainBundle()
.objectForInfoDictionaryKey("UIViewControllerBasedStatusBarAppearance") as? Bool
{
isVCBasedStatusBarAppearance = vcBasedStatusBarAppearance
}
else {
isVCBasedStatusBarAppearance = true // default
}
hidesBottomBarWhenPushed = true
automaticallyAdjustsScrollViewInsets = false
extendedLayoutIncludesOpaqueBars = true
navigationController?.view.backgroundColor = UIColor.whiteColor()
// Listen for MWPhoto falsetifications
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("handlePhotoLoadingDidEndNotification:"),
name: MWPHOTO_LOADING_DID_END_NOTIFICATION,
object: nil)
}
deinit {
clearCurrentVideo()
pagingScrollView.delegate = nil
NSNotificationCenter.defaultCenter().removeObserver(self)
releaseAllUnderlyingPhotos(false)
MapleBaconStorage.sharedStorage.clearMemoryStorage() // clear memory
}
private func releaseAllUnderlyingPhotos(preserveCurrent: Bool) {
// Create a copy in case this array is modified while we are looping through
// Release photos
var copy = photos
for p in copy {
if let ph = p {
if let paci = photoAtIndex(currentIndex) {
if preserveCurrent && ph.equals(paci) {
continue // skip current
}
}
ph.unloadUnderlyingImage()
}
}
// Release thumbs
copy = thumbPhotos
for p in copy {
if let ph = p {
ph.unloadUnderlyingImage()
}
}
}
public override func didReceiveMemoryWarning() {
// Release any cached data, images, etc that aren't in use.
releaseAllUnderlyingPhotos(true)
recycledPages.removeAll(keepCapacity: false)
// Releases the view if it doesn't have a superview.
super.didReceiveMemoryWarning()
}
//MARK: - View Loading
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
public override dynamic func viewDidLoad() {
// Validate grid settings
if startOnGrid {
enableGrid = true
}
//if enableGrid {
// enableGrid = [delegate respondsToSelector:Selector("photoBrowser:thumbPhotoAtIndex:)]
//}
if !enableGrid {
startOnGrid = false
}
// View
navigationController?.navigationBar.backgroundColor = UIColor.whiteColor()
view.backgroundColor = UIColor.whiteColor()
view.clipsToBounds = true
// Setup paging scrolling view
let pagingScrollViewFrame = frameForPagingScrollView
pagingScrollView = UIScrollView(frame: pagingScrollViewFrame)
pagingScrollView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
pagingScrollView.pagingEnabled = true
pagingScrollView.delegate = self
pagingScrollView.showsHorizontalScrollIndicator = false
pagingScrollView.showsVerticalScrollIndicator = false
pagingScrollView.backgroundColor = UIColor.whiteColor()
pagingScrollView.contentSize = contentSizeForPagingScrollView()
view.addSubview(pagingScrollView)
// Toolbar
toolbar = UIToolbar(frame: frameForToolbar)
toolbar.tintColor = toolbarTintColor
toolbar.barTintColor = toolbarBarTintColor
toolbar.backgroundColor = toolbarBackgroundColor
toolbar.alpha = 0.8
toolbar.setBackgroundImage(nil, forToolbarPosition: .Any, barMetrics: .Default)
toolbar.setBackgroundImage(nil, forToolbarPosition: .Any, barMetrics: .Compact)
toolbar.barStyle = .Default
toolbar.autoresizingMask = [.FlexibleTopMargin, .FlexibleWidth]
// Toolbar Items
if displayNavArrows {
let arrowPathFormat = "MWPhotoBrowserSwift.bundle/UIBarButtonItemArrow"
let previousButtonImage = UIImage.imageForResourcePath(
arrowPathFormat + "Left",
ofType: "png",
inBundle: NSBundle(forClass: PhotoBrowser.self))
let nextButtonImage = UIImage.imageForResourcePath(
arrowPathFormat + "Right",
ofType: "png",
inBundle: NSBundle(forClass: PhotoBrowser.self))
previousButton = UIBarButtonItem(
image: previousButtonImage,
style: UIBarButtonItemStyle.Plain,
target: self,
action: Selector("gotoPreviousPage"))
nextButton = UIBarButtonItem(
image: nextButtonImage,
style: UIBarButtonItemStyle.Plain,
target: self,
action: Selector("gotoNextPage"))
}
if displayActionButton {
actionButton = UIBarButtonItem(
barButtonSystemItem: UIBarButtonSystemItem.Action,
target: self,
action: Selector("actionButtonPressed:"))
}
// Update
reloadData()
// Swipe to dismiss
if enableSwipeToDismiss {
let swipeGesture = UISwipeGestureRecognizer(target: self, action: Selector("doneButtonPressed:"))
swipeGesture.direction = [.Down, .Up]
view.addGestureRecognizer(swipeGesture)
}
// Super
super.viewDidLoad()
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition(nil) { _ in
self.toolbar.frame = self.frameForToolbar
}
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
}
func performLayout() {
// Setup
performingLayout = true
let photos = numberOfPhotos
// Setup pages
visiblePages.removeAll()
recycledPages.removeAll()
// Navigation buttons
if let navi = navigationController {
if navi.viewControllers.count > 0 &&
navi.viewControllers[0] == self
{
// We're first on stack so show done button
doneButton = UIBarButtonItem(
barButtonSystemItem: UIBarButtonSystemItem.Done,
target: self,
action: Selector("doneButtonPressed:"))
// Set appearance
if let done = doneButton {
done.setBackgroundImage(nil, forState: .Normal, barMetrics: .Default)
done.setBackgroundImage(nil, forState: .Normal, barMetrics: .Compact)
done.setBackgroundImage(nil, forState: .Highlighted, barMetrics: .Default)
done.setBackgroundImage(nil, forState: .Highlighted, barMetrics: .Compact)
done.setTitleTextAttributes([String : AnyObject](), forState: .Normal)
done.setTitleTextAttributes([String : AnyObject](), forState: .Highlighted)
self.navigationItem.rightBarButtonItem = done
}
}
else {
// We're not first so show back button
if let navi = navigationController,
previousViewController = navi.viewControllers[navi.viewControllers.count - 2] as? UINavigationController
{
let backButtonTitle = previousViewController.navigationItem.backBarButtonItem != nil ?
previousViewController.navigationItem.backBarButtonItem!.title :
previousViewController.title
let newBackButton = UIBarButtonItem(title: backButtonTitle, style: .Plain, target: nil, action: nil)
// Appearance
newBackButton.setBackButtonBackgroundImage(nil, forState: .Normal, barMetrics: .Default)
newBackButton.setBackButtonBackgroundImage(nil, forState: .Normal, barMetrics: .Compact)
newBackButton.setBackButtonBackgroundImage(nil, forState: .Highlighted, barMetrics: .Default)
newBackButton.setBackButtonBackgroundImage(nil, forState: .Highlighted, barMetrics: .Compact)
newBackButton.setTitleTextAttributes([String : AnyObject](), forState: .Normal)
newBackButton.setTitleTextAttributes([String : AnyObject](), forState: .Highlighted)
previousViewControllerBackButton = previousViewController.navigationItem.backBarButtonItem // remember previous
previousViewController.navigationItem.backBarButtonItem = newBackButton
}
}
}
// Toolbar items
var hasItems = false
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: self, action: nil)
fixedSpace.width = 32.0 // To balance action button
let flexSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
var items = [UIBarButtonItem]()
// Left button - Grid
if enableGrid {
hasItems = true
items.append(UIBarButtonItem(
image: UIImage.imageForResourcePath("MWPhotoBrowserSwift.bundle/UIBarButtonItemGrid",
ofType: "png",
inBundle: NSBundle(forClass: PhotoBrowser.self)),
style: .Plain,
target: self,
action: Selector("showGridAnimated")))
}
else {
items.append(fixedSpace)
}
// Middle - Nav
if previousButton != nil && nextButton != nil && photos > 1 {
hasItems = true
items.append(flexSpace)
items.append(previousButton!)
items.append(flexSpace)
items.append(nextButton!)
items.append(flexSpace)
}
else {
items.append(flexSpace)
}
// Right - Action
if actionButton != nil && !(!hasItems && nil == navigationItem.rightBarButtonItem) {
items.append(actionButton!)
}
else {
// We're falset showing the toolbar so try and show in top right
if actionButton != nil {
navigationItem.rightBarButtonItem = actionButton!
}
items.append(fixedSpace)
}
// Toolbar visibility
toolbar.setItems(items, animated: false)
var hideToolbar = true
for item in items {
if item != fixedSpace && item != flexSpace {
hideToolbar = false
break
}
}
if hideToolbar {
toolbar.removeFromSuperview()
}
else {
view.addSubview(toolbar)
}
// Update nav
updateNavigation()
// Content offset
pagingScrollView.contentOffset = contentOffsetForPageAtIndex(currentPageIndex)
tilePages()
performingLayout = false
}
var presentingViewControllerPrefersStatusBarHidden: Bool {
var presenting = presentingViewController
if let p = presenting as? UINavigationController {
presenting = p.topViewController
}
else {
// We're in a navigation controller so get previous one!
if let navi = navigationController where navi.viewControllers.count > 1 {
presenting = navi.viewControllers[navi.viewControllers.count - 2]
}
}
if let pres = presenting {
return pres.prefersStatusBarHidden()
}
return false
}
//MARK: - Appearance
public override dynamic func viewWillAppear(animated: Bool) {
// Super
super.viewWillAppear(animated)
// Status bar
if !viewHasAppearedInitially {
leaveStatusBarAlone = presentingViewControllerPrefersStatusBarHidden
// Check if status bar is hidden on first appear, and if so then ignore it
if CGRectEqualToRect(UIApplication.sharedApplication().statusBarFrame, CGRectZero) {
leaveStatusBarAlone = true
}
}
// Set style
if !leaveStatusBarAlone && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone {
previousStatusBarStyle = UIApplication.sharedApplication().statusBarStyle
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: animated)
}
// Navigation bar appearance
if !viewIsActive && navigationController?.viewControllers[0] as? PhotoBrowser !== self {
storePreviousNavBarAppearance()
}
setNavBarAppearance(animated)
// Update UI
if hideControlsOnStartup {
hideControls()
}
else {
hideControlsAfterDelay()
}
// Initial appearance
if !viewHasAppearedInitially && startOnGrid {
showGrid(false)
}
// If rotation occured while we're presenting a modal
// and the index changed, make sure we show the right one falsew
if currentPageIndex != pageIndexBeforeRotation {
jumpToPageAtIndex(pageIndexBeforeRotation, animated: false)
}
}
public override dynamic func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
viewIsActive = true
// Autoplay if first is video
if !viewHasAppearedInitially && autoPlayOnAppear {
if let photo = photoAtIndex(currentPageIndex) {
if photo.isVideo {
playVideoAtIndex(currentPageIndex)
}
}
}
viewHasAppearedInitially = true
}
public override dynamic func viewWillDisappear(animated: Bool) {
// Detect if rotation occurs while we're presenting a modal
pageIndexBeforeRotation = currentPageIndex
// Check that we're being popped for good
if let viewControllers = navigationController?.viewControllers
where viewControllers[0] !== self
{
var selfFound = false
for vc in viewControllers {
if vc === self {
selfFound = true
break;
}
}
if !selfFound {
// State
viewIsActive = false
// Bar state / appearance
restorePreviousNavBarAppearance(animated)
}
}
// Controls
navigationController?.navigationBar.layer.removeAllAnimations() // Stop all animations on nav bar
NSObject.cancelPreviousPerformRequestsWithTarget(self) // Cancel any pending toggles from taps
setControlsHidden(false, animated: false, permanent: true)
// Status bar
if !leaveStatusBarAlone && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone {
UIApplication.sharedApplication().setStatusBarStyle(previousStatusBarStyle, animated: animated)
}
// Super
super.viewWillDisappear(animated)
}
public override func willMoveToParentViewController(parent: UIViewController?) {
if parent != nil && hasBelongedToViewController {
fatalError("PhotoBrowser Instance Reuse")
}
}
public override func didMoveToParentViewController(parent: UIViewController?) {
if nil == parent {
hasBelongedToViewController = true
}
}
//MARK: - Nav Bar Appearance
func setNavBarAppearance(animated: Bool) {
navigationController?.setNavigationBarHidden(false, animated: animated)
if let navBar = navigationController?.navigationBar {
navBar.backgroundColor = navBarBarTintColor
navBar.tintColor = navBarTintColor
navBar.barTintColor = navBarBarTintColor
navBar.shadowImage = nil
navBar.translucent = navBarTranslucent
navBar.barStyle = .Default
navBar.setBackgroundImage(nil, forBarMetrics: .Default)
navBar.setBackgroundImage(nil, forBarMetrics: .Compact)
}
}
func storePreviousNavBarAppearance() {
didSavePreviousStateOfNavBar = true
if let navi = navigationController {
previousNavBarBarTintColor = navi.navigationBar.barTintColor
previousNavBarTranslucent = navi.navigationBar.translucent
previousNavBarTintColor = navi.navigationBar.tintColor
previousNavBarHidden = navi.navigationBarHidden
previousNavBarStyle = navi.navigationBar.barStyle
previousNavigationBarBackgroundImageDefault = navi.navigationBar.backgroundImageForBarMetrics(.Default)
previousNavigationBarBackgroundImageLandscapePhone = navi.navigationBar.backgroundImageForBarMetrics(.Compact)
}
}
func restorePreviousNavBarAppearance(animated: Bool) {
if let navi = navigationController where didSavePreviousStateOfNavBar {
navi.setNavigationBarHidden(previousNavBarHidden, animated: animated)
let navBar = navi.navigationBar
navBar.tintColor = previousNavBarTintColor
navBar.translucent = previousNavBarTranslucent
navBar.barTintColor = previousNavBarBarTintColor
navBar.barStyle = previousNavBarStyle
navBar.setBackgroundImage(previousNavigationBarBackgroundImageDefault, forBarMetrics: UIBarMetrics.Default)
navBar.setBackgroundImage(previousNavigationBarBackgroundImageLandscapePhone, forBarMetrics: UIBarMetrics.Compact)
// Restore back button if we need to
if previousViewControllerBackButton != nil {
if let previousViewController = navi.topViewController { // We've disappeared so previous is falsew top
previousViewController.navigationItem.backBarButtonItem = previousViewControllerBackButton
}
previousViewControllerBackButton = nil
}
}
}
//MARK: - Layout
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
layoutVisiblePages()
}
func layoutVisiblePages() {
// Flag
performingLayout = true
// Toolbar
toolbar.frame = frameForToolbar
// Remember index
let indexPriorToLayout = currentPageIndex
// Get paging scroll view frame to determine if anything needs changing
let pagingScrollViewFrame = frameForPagingScrollView
// Frame needs changing
if !skipNextPagingScrollViewPositioning {
pagingScrollView.frame = pagingScrollViewFrame
}
skipNextPagingScrollViewPositioning = false
// Recalculate contentSize based on current orientation
pagingScrollView.contentSize = contentSizeForPagingScrollView()
// Adjust frames and configuration of each visible page
for page in visiblePages {
let index = page.index
page.frame = frameForPageAtIndex(index)
if let caption = page.captionView {
caption.frame = frameForCaptionView(caption, index: index)
}
if let selected = page.selectedButton {
selected.frame = frameForSelectedButton(selected, atIndex: index)
}
if let play = page.playButton {
play.frame = frameForPlayButton(play, atIndex: index)
}
// Adjust scales if bounds has changed since last time
if !CGRectEqualToRect(previousLayoutBounds, view.bounds) {
// Update zooms for new bounds
page.setMaxMinZoomScalesForCurrentBounds()
previousLayoutBounds = view.bounds
}
}
// Adjust video loading indicator if it's visible
positionVideoLoadingIndicator()
// Adjust contentOffset to preserve page location based on values collected prior to location
pagingScrollView.contentOffset = contentOffsetForPageAtIndex(indexPriorToLayout)
didStartViewingPageAtIndex(currentPageIndex) // initial
// Reset
currentPageIndex = indexPriorToLayout
performingLayout = false
}
//MARK: - Rotation
public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.All
}
public override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
// Remember page index before rotation
pageIndexBeforeRotation = currentPageIndex
rotating = true
// In iOS 7 the nav bar gets shown after rotation, but might as well do this for everything!
if areControlsHidden {
// Force hidden
navigationController?.navigationBarHidden = true
}
}
public override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
// Perform layout
currentPageIndex = pageIndexBeforeRotation
// Delay control holding
hideControlsAfterDelay()
// Layout
layoutVisiblePages()
}
public override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
rotating = false
// Ensure nav bar isn't re-displayed
if let navi = navigationController where areControlsHidden {
navi.navigationBarHidden = false
navi.navigationBar.alpha = 0
}
}
//MARK: - Data
var currentIndex: Int {
return currentPageIndex
}
func reloadData() {
// Reset
photoCount = -1
// Get data
let photosNum = numberOfPhotos
releaseAllUnderlyingPhotos(true)
photos.removeAll()
thumbPhotos.removeAll()
for _ in 0...(photosNum - 1) {
photos.append(nil)
thumbPhotos.append(nil)
}
// Update current page index
if numberOfPhotos > 0 {
currentPageIndex = max(0, min(currentPageIndex, photosNum - 1))
}
else {
currentPageIndex = 0
}
// Update layout
if isViewLoaded() {
while pagingScrollView.subviews.count > 0 {
pagingScrollView.subviews.last!.removeFromSuperview()
}
performLayout()
view.setNeedsLayout()
}
}
var numberOfPhotos: Int {
if photoCount == -1 {
if let d = delegate {
photoCount = d.numberOfPhotosInPhotoBrowser(self)
}
if let fpa = fixedPhotosArray {
photoCount = fpa.count
}
}
if -1 == photoCount {
photoCount = 0
}
return photoCount
}
func photoAtIndex(index: Int) -> Photo? {
var photo: Photo? = nil
if index < photos.count {
if photos[index] == nil {
if let d = delegate {
photo = d.photoAtIndex(index, photoBrowser: self)
if nil == photo && fixedPhotosArray != nil && index < fixedPhotosArray!.count {
photo = fixedPhotosArray![index]
}
if photo != nil {
photos[index] = photo
}
}
}
else {
photo = photos[index]
}
}
return photo
}
func thumbPhotoAtIndex(index: Int) -> Photo? {
var photo: Photo?
if index < thumbPhotos.count {
if nil == thumbPhotos[index] {
if let d = delegate {
photo = d.thumbPhotoAtIndex(index, photoBrowser: self)
if let p = photo {
thumbPhotos[index] = p
}
}
}
else {
photo = thumbPhotos[index]
}
}
return photo
}
func captionViewForPhotoAtIndex(index: Int) -> CaptionView? {
var captionView: CaptionView?
if let d = delegate {
captionView = d.captionViewForPhotoAtIndex(index, photoBrowser: self)
if let p = photoAtIndex(index) where nil == captionView {
if p.caption.characters.count > 0 {
captionView = CaptionView(photo: p)
}
}
}
if let cv = captionView {
cv.alpha = areControlsHidden ? 0.0 : captionAlpha // Initial alpha
}
return captionView
}
func photoIsSelectedAtIndex(index: Int) -> Bool {
var value = false
if displaySelectionButtons {
if let d = delegate {
value = d.isPhotoSelectedAtIndex(index, photoBrowser: self)
}
}
return value
}
func setPhotoSelected(selected: Bool, atIndex index: Int) {
if displaySelectionButtons {
if let d = delegate {
d.selectedChanged(selected, index: index, photoBrowser: self)
}
}
}
func imageForPhoto(photo: Photo?) -> UIImage? {
if let p = photo {
// Get image or obtain in background
if let img = p.underlyingImage {
return img
}
else {
p.loadUnderlyingImageAndNotify()
}
}
return nil
}
func loadAdjacentPhotosIfNecessary(photo: Photo) {
let page = pageDisplayingPhoto(photo)
if let p = page {
// If page is current page then initiate loading of previous and next pages
let pageIndex = p.index
if currentPageIndex == pageIndex {
if pageIndex > 0 {
// Preload index - 1
if let photo = photoAtIndex(pageIndex - 1) {
if nil == photo.underlyingImage {
photo.loadUnderlyingImageAndNotify()
//MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex-1)
}
}
}
if pageIndex < numberOfPhotos - 1 {
// Preload index + 1
if let photo = photoAtIndex(pageIndex + 1) {
if nil == photo.underlyingImage {
photo.loadUnderlyingImageAndNotify()
//MWLog(@"Pre-loading image at index %lu", (unsigned long)pageIndex+1)
}
}
}
}
}
}
//MARK: - MWPhoto Loading falsetification
func handlePhotoLoadingDidEndNotification(notification: NSNotification) {
if let photo = notification.object as? Photo {
if let page = pageDisplayingPhoto(photo) {
if photo.underlyingImage != nil {
// Successful load
page.displayImage()
loadAdjacentPhotosIfNecessary(photo)
}
else {
// Failed to load
page.displayImageFailure()
}
// Update nav
updateNavigation()
}
}
}
//MARK: - Paging
func tilePages() {
// Calculate which pages should be visible
// Ignore padding as paging bounces encroach on that
// and lead to false page loads
let visibleBounds = pagingScrollView.bounds
var iFirstIndex = Int(floorf(Float((CGRectGetMinX(visibleBounds) + padding * 2.0) / CGRectGetWidth(visibleBounds))))
var iLastIndex = Int(floorf(Float((CGRectGetMaxX(visibleBounds) - padding * 2.0 - 1.0) / CGRectGetWidth(visibleBounds))))
if iFirstIndex < 0 {
iFirstIndex = 0
}
if iFirstIndex > numberOfPhotos - 1 {
iFirstIndex = numberOfPhotos - 1
}
if iLastIndex < 0 {
iLastIndex = 0
}
if iLastIndex > numberOfPhotos - 1 {
iLastIndex = numberOfPhotos - 1
}
// Recycle false longer needed pages
var pageIndex = 0
for page in visiblePages {
pageIndex = page.index
if pageIndex < iFirstIndex || pageIndex > iLastIndex {
recycledPages.insert(page)
if let cw = page.captionView {
cw.removeFromSuperview()
}
if let selected = page.selectedButton {
selected.removeFromSuperview()
}
if let play = page.playButton {
play.removeFromSuperview()
}
page.prepareForReuse()
page.removeFromSuperview()
//MWLog(@"Removed page at index %lu", (unsigned long)pageIndex)
}
}
visiblePages = visiblePages.subtract(recycledPages)
while recycledPages.count > 2 { // Only keep 2 recycled pages
recycledPages.remove(recycledPages.first!)
}
// Add missing pages
for index in iFirstIndex...iLastIndex {
if !isDisplayingPageForIndex(index) {
// Add new page
var p = dequeueRecycledPage
if nil == p {
p = ZoomingScrollView(photoBrowser: self)
}
let page = p!
visiblePages.insert(page)
configurePage(page, forIndex: index)
pagingScrollView.addSubview(page)
// MWLog(@"Added page at index %lu", (unsigned long)index)
// Add caption
if let captionView = captionViewForPhotoAtIndex(index) {
captionView.frame = frameForCaptionView(captionView, index: index)
pagingScrollView.addSubview(captionView)
page.captionView = captionView
}
// Add play button if needed
if page.displayingVideo() {
let playButton = UIButton(type: .Custom)
playButton.setImage(UIImage.imageForResourcePath(
"MWPhotoBrowserSwift.bundle/PlayButtonOverlayLarge",
ofType: "png",
inBundle: NSBundle(forClass: PhotoBrowser.self)), forState: .Normal)
playButton.setImage(UIImage.imageForResourcePath(
"MWPhotoBrowserSwift.bundle/PlayButtonOverlayLargeTap",
ofType: "png",
inBundle: NSBundle(forClass: PhotoBrowser.self)), forState: .Highlighted)
playButton.addTarget(self, action: Selector("playButtonTapped:"), forControlEvents: .TouchUpInside)
playButton.sizeToFit()
playButton.frame = frameForPlayButton(playButton, atIndex: index)
pagingScrollView.addSubview(playButton)
page.playButton = playButton
}
// Add selected button
if self.displaySelectionButtons {
let selectedButton = UIButton(type: .Custom)
selectedButton.setImage(UIImage.imageForResourcePath(
"MWPhotoBrowserSwift.bundle/ImageSelectedOff",
ofType: "png",
inBundle: NSBundle(forClass: PhotoBrowser.self)),
forState: .Normal)
let selectedOnImage: UIImage?
if customImageSelectedIconName.characters.count > 0 {
selectedOnImage = UIImage(named: customImageSelectedIconName)
}
else {
selectedOnImage = UIImage.imageForResourcePath(
"MWPhotoBrowserSwift.bundle/ImageSelectedOn",
ofType: "png",
inBundle: NSBundle(forClass: PhotoBrowser.self))
}
selectedButton.setImage(selectedOnImage, forState: .Selected)
selectedButton.sizeToFit()
selectedButton.adjustsImageWhenHighlighted = false
selectedButton.addTarget(self, action: Selector("selectedButtonTapped:"), forControlEvents: .TouchUpInside)
selectedButton.frame = frameForSelectedButton(selectedButton, atIndex: index)
pagingScrollView.addSubview(selectedButton)
page.selectedButton = selectedButton
selectedButton.selected = photoIsSelectedAtIndex(index)
}
}
}
}
func updateVisiblePageStates() {
let copy = visiblePages
for page in copy {
// Update selection
if let selected = page.selectedButton {
selected.selected = photoIsSelectedAtIndex(page.index)
}
}
}
func isDisplayingPageForIndex(index: Int) -> Bool {
for page in visiblePages {
if page.index == index {
return true
}
}
return false
}
func pageDisplayedAtIndex(index: Int) -> ZoomingScrollView? {
var thePage: ZoomingScrollView?
for page in visiblePages {
if page.index == index {
thePage = page
break
}
}
return thePage
}
func pageDisplayingPhoto(photo: Photo) -> ZoomingScrollView? {
var thePage: ZoomingScrollView?
for page in visiblePages {
if page.photo != nil && page.photo!.equals(photo) {
thePage = page
break
}
}
return thePage
}
func configurePage(page: ZoomingScrollView, forIndex index: Int) {
page.frame = frameForPageAtIndex(index)
page.index = index
page.photo = photoAtIndex(index)
page.backgroundColor = areControlsHidden ? UIColor.blackColor() : UIColor.whiteColor()
}
var dequeueRecycledPage: ZoomingScrollView? {
let page = recycledPages.first
if let p = page {
recycledPages.remove(p)
}
return page
}
// Handle page changes
func didStartViewingPageAtIndex(index: Int) {
// Handle 0 photos
if 0 == numberOfPhotos {
// Show controls
setControlsHidden(false, animated: true, permanent: true)
return
}
// Handle video on page change
if !rotating || index != currentVideoIndex {
clearCurrentVideo()
}
// Release images further away than +/-1
if index > 0 {
// Release anything < index - 1
if index - 2 >= 0 {
for i in 0...(index - 2) {
if let photo = photos[i] {
photo.unloadUnderlyingImage()
photos[i] = nil
//MWLog.log("Released underlying image at index \(i)")
}
}
}
}
if index < numberOfPhotos - 1 {
// Release anything > index + 1
if index + 2 <= photos.count - 1 {
for i in (index + 2)...(photos.count - 1) {
if let photo = photos[i] {
photo.unloadUnderlyingImage()
photos[i] = nil
//MWLog.log("Released underlying image at index \(i)")
}
}
}
}
// Load adjacent images if needed and the photo is already
// loaded. Also called after photo has been loaded in background
let currentPhoto = photoAtIndex(index)
if let cp = currentPhoto {
if cp.underlyingImage != nil {
// photo loaded so load ajacent falsew
loadAdjacentPhotosIfNecessary(cp)
}
}
// Notify delegate
if index != previousPageIndex {
if let d = delegate {
d.didDisplayPhotoAtIndex(index, photoBrowser: self)
}
previousPageIndex = index
}
// Update nav
updateNavigation()
}
//MARK: - Frame Calculations
var frameForPagingScrollView: CGRect {
var frame = view.bounds// UIScreen.mainScreen().bounds
frame.origin.x -= padding
frame.size.width += (2.0 * padding)
return CGRectIntegral(frame)
}
func frameForPageAtIndex(index: Int) -> CGRect {
// We have to use our paging scroll view's bounds, falset frame, to calculate the page placement. When the device is in
// landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's
// view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape
// because it has a rotation transform applied.
let bounds = pagingScrollView.bounds
var pageFrame = bounds
pageFrame.size.width -= (2.0 * padding)
pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + padding
return CGRectIntegral(pageFrame)
}
func contentSizeForPagingScrollView() -> CGSize {
// We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
let bounds = pagingScrollView.bounds
return CGSizeMake(bounds.size.width * CGFloat(numberOfPhotos), bounds.size.height)
}
func contentOffsetForPageAtIndex(index: Int) -> CGPoint {
let pageWidth = pagingScrollView.bounds.size.width
let newOffset = CGFloat(index) * pageWidth
return CGPointMake(newOffset, 0)
}
var frameForToolbar: CGRect {
var height = CGFloat(44.0)
if view.bounds.height < 768.0 && view.bounds.height < view.bounds.width {
height = 32.0
}
return CGRectIntegral(CGRectMake(0.0, view.bounds.size.height - height, view.bounds.size.width, height))
}
func frameForCaptionView(captionView: CaptionView?, index: Int) -> CGRect {
if let cw = captionView {
let pageFrame = frameForPageAtIndex(index)
let captionSize = cw.sizeThatFits(CGSizeMake(pageFrame.size.width, 0.0))
let captionFrame = CGRectMake(
pageFrame.origin.x,
pageFrame.size.height - captionSize.height - (toolbar.superview != nil ? toolbar.frame.size.height : 0.0),
pageFrame.size.width,
captionSize.height)
return CGRectIntegral(captionFrame)
}
return CGRectZero
}
func frameForSelectedButton(selectedButton: UIButton, atIndex index: Int) -> CGRect {
let pageFrame = frameForPageAtIndex(index)
let padding = CGFloat(20.0)
var yOffset = CGFloat(0.0)
if !areControlsHidden {
if let navBar = navigationController?.navigationBar {
yOffset = navBar.frame.origin.y + navBar.frame.size.height
}
}
let selectedButtonFrame = CGRectMake(
pageFrame.origin.x + pageFrame.size.width - selectedButton.frame.size.width - padding,
padding + yOffset,
selectedButton.frame.size.width,
selectedButton.frame.size.height)
return CGRectIntegral(selectedButtonFrame)
}
func frameForPlayButton(playButton: UIButton, atIndex index: Int) -> CGRect {
let pageFrame = frameForPageAtIndex(index)
return CGRectMake(
CGFloat(floorf(Float(CGRectGetMidX(pageFrame) - playButton.frame.size.width / 2.0))),
CGFloat(floorf(Float(CGRectGetMidY(pageFrame) - playButton.frame.size.height / 2.0))),
playButton.frame.size.width,
playButton.frame.size.height)
}
//MARK: - UIScrollView Delegate
public func scrollViewDidScroll(scrollView: UIScrollView) {
// Checks
if !viewIsActive || performingLayout || rotating {
return
}
// Tile pages
tilePages()
// Calculate current page
let visibleBounds = pagingScrollView.bounds
var index = Int(floorf(Float(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds))))
if index < 0 {
index = 0
}
if index > numberOfPhotos - 1 {
index = numberOfPhotos - 1
}
let previousCurrentPage = currentPageIndex
currentPageIndex = index
if currentPageIndex != previousCurrentPage {
didStartViewingPageAtIndex(index)
}
}
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
// Hide controls when dragging begins
setControlsHidden(true, animated: true, permanent: false)
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
// Update nav when page changes
updateNavigation()
}
//MARK: - Navigation
func updateNavigation() {
// Title
let photos = numberOfPhotos
if let gc = gridController {
if gc.selectionMode {
self.title = NSLocalizedString("Select Photos", comment: "")
}
else {
let photosText: String
if 1 == photos {
photosText = NSLocalizedString("photo", comment: "Used in the context: '1 photo'")
}
else {
photosText = NSLocalizedString("photos", comment: "Used in the context: '3 photos'")
}
title = "\(photos) \(photosText)"
}
}
else
if photos > 1 {
if let d = delegate {
title = d.titleForPhotoAtIndex(currentPageIndex, photoBrowser: self)
}
if nil == title {
let str = NSLocalizedString("of", comment: "Used in the context: 'Showing 1 of 3 items'")
title = "\(currentPageIndex + 1) \(str) \(numberOfPhotos)"
}
}
else {
title = nil
}
// Buttons
if let prev = previousButton {
prev.enabled = (currentPageIndex > 0)
}
if let next = nextButton {
next.enabled = (currentPageIndex < photos - 1)
}
// Disable action button if there is false image or it's a video
if let ab = actionButton {
let photo = photoAtIndex(currentPageIndex)
if photo != nil && (photo!.underlyingImage == nil || photo!.isVideo) {
ab.enabled = false
ab.tintColor = UIColor.clearColor() // Tint to hide button
}
else {
ab.enabled = true
ab.tintColor = nil
}
}
}
func jumpToPageAtIndex(index: Int, animated: Bool) {
// Change page
if index < numberOfPhotos {
let pageFrame = frameForPageAtIndex(index)
pagingScrollView.setContentOffset(CGPointMake(pageFrame.origin.x - padding, 0), animated: animated)
updateNavigation()
}
// Update timer to give more time
hideControlsAfterDelay()
}
func gotoPreviousPage() {
showPreviousPhotoAnimated(false)
}
func gotoNextPage() {
showNextPhotoAnimated(false)
}
func showPreviousPhotoAnimated(animated: Bool) {
jumpToPageAtIndex(currentPageIndex - 1, animated: animated)
}
func showNextPhotoAnimated(animated: Bool) {
jumpToPageAtIndex(currentPageIndex + 1, animated: animated)
}
//MARK: - Interactions
func selectedButtonTapped(sender: AnyObject) {
let selectedButton = sender as! UIButton
selectedButton.selected = !selectedButton.selected
var index = Int.max
for page in visiblePages {
if page.selectedButton == selectedButton {
index = page.index
break
}
}
if index != Int.max {
setPhotoSelected(selectedButton.selected, atIndex: index)
}
}
func playButtonTapped(sender: AnyObject) {
let playButton = sender as! UIButton
var index = Int.max
for page in visiblePages {
if page.playButton == playButton {
index = page.index
break
}
}
if index != Int.max {
if nil == currentVideoPlayerViewController {
playVideoAtIndex(index)
}
}
}
//MARK: - Video
func playVideoAtIndex(index: Int) {
let photo = photoAtIndex(index)
// Valid for playing
currentVideoIndex = index
clearCurrentVideo()
setVideoLoadingIndicatorVisible(true, atPageIndex: index)
// Get video and play
if let p = photo {
p.getVideoURL() { url in
if let u = url {
dispatch_async(dispatch_get_main_queue()) {
self.playVideo(u, atPhotoIndex: index)
}
}
else {
self.setVideoLoadingIndicatorVisible(false, atPageIndex: index)
}
}
}
}
func playVideo(videoURL: NSURL, atPhotoIndex index: Int) {
// Setup player
currentVideoPlayerViewController = MPMoviePlayerViewController(contentURL: videoURL)
if let player = currentVideoPlayerViewController {
player.moviePlayer.prepareToPlay()
player.moviePlayer.shouldAutoplay = true
player.moviePlayer.scalingMode = .AspectFit
player.modalTransitionStyle = .CrossDissolve
// Remove the movie player view controller from the "playback did finish" falsetification observers
// Observe ourselves so we can get it to use the crossfade transition
NSNotificationCenter.defaultCenter().removeObserver(
player,
name: MPMoviePlayerPlaybackDidFinishNotification,
object: player.moviePlayer)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("videoFinishedCallback:"),
name: MPMoviePlayerPlaybackDidFinishNotification,
object: player.moviePlayer)
// Show
presentViewController(player, animated: true, completion: nil)
}
}
func videoFinishedCallback(notification: NSNotification) {
if let player = currentVideoPlayerViewController {
// Remove observer
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: MPMoviePlayerPlaybackDidFinishNotification,
object: player.moviePlayer)
// Clear up
clearCurrentVideo()
// Dismiss
if let errorObj: AnyObject? = notification.userInfo?[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] {
let error = MPMovieFinishReason(rawValue: errorObj as! Int)
if error == .PlaybackError {
// Error occured so dismiss with a delay incase error was immediate and we need to wait to dismiss the VC
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))),
dispatch_get_main_queue())
{
self.dismissViewControllerAnimated(true, completion: nil)
}
return
}
}
}
dismissViewControllerAnimated(true, completion: nil)
}
func clearCurrentVideo() {
if currentVideoPlayerViewController != nil {
currentVideoLoadingIndicator!.removeFromSuperview()
currentVideoPlayerViewController = nil
currentVideoLoadingIndicator = nil
currentVideoIndex = Int.max
}
}
func setVideoLoadingIndicatorVisible(visible: Bool, atPageIndex: Int) {
if currentVideoLoadingIndicator != nil && !visible {
currentVideoLoadingIndicator!.removeFromSuperview()
currentVideoLoadingIndicator = nil
}
else
if nil == currentVideoLoadingIndicator && visible {
currentVideoLoadingIndicator = UIActivityIndicatorView(frame: CGRectZero)
currentVideoLoadingIndicator!.sizeToFit()
currentVideoLoadingIndicator!.startAnimating()
pagingScrollView.addSubview(currentVideoLoadingIndicator!)
positionVideoLoadingIndicator()
}
}
func positionVideoLoadingIndicator() {
if currentVideoLoadingIndicator != nil && currentVideoIndex != Int.max {
let frame = frameForPageAtIndex(currentVideoIndex)
currentVideoLoadingIndicator!.center = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame))
}
}
//MARK: - Grid
func showGridAnimated() {
showGrid(true)
}
func showGrid(animated: Bool) {
if gridController != nil {
return
}
// Init grid controller
gridController = GridViewController()
if let gc = gridController,
navBar = navigationController?.navigationBar
{
let bounds = view.bounds
let naviHeight = navBar.frame.height + UIApplication.sharedApplication().statusBarFrame.height
gc.initialContentOffset = currentGridContentOffset
gc.browser = self
gc.selectionMode = displaySelectionButtons
gc.view.frame = CGRectMake(0.0, naviHeight, bounds.width, bounds.height - naviHeight)
gc.view.alpha = 0.0
// Stop specific layout being triggered
skipNextPagingScrollViewPositioning = true
// Add as a child view controller
addChildViewController(gc)
view.addSubview(gc.view)
// Perform any adjustments
gc.view.layoutIfNeeded()
gc.adjustOffsetsAsRequired()
// Hide action button on nav bar if it exists
if navigationItem.rightBarButtonItem == actionButton {
gridPreviousRightNavItem = actionButton
navigationItem.setRightBarButtonItem(nil, animated: true)
}
else {
gridPreviousRightNavItem = nil
}
// Update
updateNavigation()
setControlsHidden(false, animated: true, permanent: true)
// Animate grid in and photo scroller out
gc.willMoveToParentViewController(self)
UIView.animateWithDuration(
animated ? 0.3 : 0,
animations: {
gc.view.alpha = 1.0
self.pagingScrollView.alpha = 0.0
},
completion: { finished in
gc.didMoveToParentViewController(self)
})
}
}
func hideGrid() {
if let gc = gridController {
// Remember previous content offset
currentGridContentOffset = gc.collectionView!.contentOffset
// Restore action button if it was removed
if gridPreviousRightNavItem == actionButton && actionButton != nil {
navigationItem.setRightBarButtonItem(gridPreviousRightNavItem, animated: true)
}
// Position prior to hide animation
let pagingFrame = frameForPagingScrollView
pagingScrollView.frame = CGRectOffset(
pagingFrame,
0,
(self.startOnGrid ? 1 : -1) * pagingFrame.size.height)
// Remember and remove controller now so things can detect a nil grid controller
gridController = nil
// Update
updateNavigation()
updateVisiblePageStates()
view.layoutIfNeeded()
view.layoutSubviews()
self.pagingScrollView.frame = self.frameForPagingScrollView
// Animate, hide grid and show paging scroll view
UIView.animateWithDuration(
0.3,
animations: {
gc.view.alpha = 0.0
self.pagingScrollView.alpha = 1.0
},
completion: { finished in
gc.willMoveToParentViewController(nil)
gc.view.removeFromSuperview()
gc.removeFromParentViewController()
self.setControlsHidden(false, animated: true, permanent: false) // retrigger timer
})
}
}
//MARK: - Control Hiding / Showing
// If permanent then we don't set timers to hide again
func setControlsHidden(var hidden: Bool, animated: Bool, permanent: Bool) {
// Force visible
if 0 == numberOfPhotos || gridController != nil || alwaysShowControls {
hidden = false
}
// Cancel any timers
cancelControlHiding()
// Animations & positions
let animatonOffset = CGFloat(20)
let animationDuration = CFTimeInterval(animated ? 0.35 : 0.0)
// Status bar
if !leaveStatusBarAlone {
// Hide status bar
if !isVCBasedStatusBarAppearance {
// falsen-view controller based
UIApplication.sharedApplication().setStatusBarHidden(
hidden, withAnimation:
animated ? UIStatusBarAnimation.Slide : UIStatusBarAnimation.None)
}
else {
// View controller based so animate away
statusBarShouldBeHidden = hidden
UIView.animateWithDuration(
animationDuration,
animations: {
self.setNeedsStatusBarAppearanceUpdate()
})
}
}
// Toolbar, nav bar and captions
// Pre-appear animation positions for sliding
if areControlsHidden && !hidden && animated {
// Toolbar
toolbar.frame = CGRectOffset(frameForToolbar, 0, animatonOffset)
// Captions
for page in visiblePages {
if let v = page.captionView {
// Pass any index, all we're interested in is the Y
var captionFrame = frameForCaptionView(v, index: 0)
captionFrame.origin.x = v.frame.origin.x // Reset X
v.frame = CGRectOffset(captionFrame, 0, animatonOffset)
}
}
}
UIView.animateWithDuration(animationDuration, animations: {
self.navigationController?.setNavigationBarHidden(hidden, animated: true)
// Toolbar
self.toolbar.frame = self.frameForToolbar
if hidden {
self.toolbar.frame = CGRectOffset(self.toolbar.frame, 0, animatonOffset)
self.view.backgroundColor = UIColor.blackColor()
self.pagingScrollView.backgroundColor = UIColor.blackColor()
self.navigationController?.view.backgroundColor = UIColor.blackColor()
for page in self.visiblePages {
page.backgroundColor = UIColor.blackColor()
}
}
else {
self.view.backgroundColor = UIColor.whiteColor()
self.pagingScrollView.backgroundColor = UIColor.whiteColor()
self.navigationController?.view.backgroundColor = UIColor.whiteColor()
for page in self.visiblePages {
page.backgroundColor = UIColor.whiteColor()
}
}
self.toolbar.alpha = hidden ? 0.0 : self.toolbarAlpha
// Captions
for page in self.visiblePages {
if let v = page.captionView {
// Pass any index, all we're interested in is the Y
var captionFrame = self.frameForCaptionView(v, index: 0)
captionFrame.origin.x = v.frame.origin.x // Reset X
if hidden {
captionFrame = CGRectOffset(captionFrame, 0, animatonOffset)
}
v.frame = captionFrame
v.alpha = hidden ? 0.0 : self.captionAlpha
}
}
// Selected buttons
for page in self.visiblePages {
if let button = page.selectedButton {
let v = button
var newFrame = self.frameForSelectedButton(v, atIndex: 0)
newFrame.origin.x = v.frame.origin.x
v.frame = newFrame
}
}
})
// Controls
if !permanent {
hideControlsAfterDelay()
}
}
public override func prefersStatusBarHidden() -> Bool {
if !leaveStatusBarAlone {
return statusBarShouldBeHidden
}
return presentingViewControllerPrefersStatusBarHidden
}
public override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
public override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
return .Slide
}
func cancelControlHiding() {
// If a timer exists then cancel and release
if controlVisibilityTimer != nil {
controlVisibilityTimer!.invalidate()
controlVisibilityTimer = nil
}
}
// Enable/disable control visiblity timer
func hideControlsAfterDelay() {
if !areControlsHidden {
cancelControlHiding()
controlVisibilityTimer = NSTimer.scheduledTimerWithTimeInterval(
delayToHideElements,
target: self,
selector: Selector("hideControls"),
userInfo: nil,
repeats: false)
}
}
var areControlsHidden: Bool {
return 0.0 == toolbar.alpha
}
func hideControls() {
setControlsHidden(true, animated: true, permanent: false)
}
func showControls() {
setControlsHidden(false, animated: true, permanent: false)
}
func toggleControls() {
setControlsHidden(!areControlsHidden, animated: true, permanent: false)
}
//MARK: - Properties
var currentPhotoIndex: Int {
set(i) {
var index = i
// Validate
let photoCount = numberOfPhotos
if 0 == photoCount {
index = 0
}
else
if index >= photoCount {
index = photoCount - 1
}
currentPageIndex = index
if isViewLoaded() {
jumpToPageAtIndex(index, animated: false)
if !viewIsActive {
tilePages() // Force tiling if view is falset visible
}
}
}
get {
return currentPageIndex
}
}
//MARK: - Misc
func doneButtonPressed(sender: AnyObject) {
// Only if we're modal and there's a done button
if doneButton != nil {
// See if we actually just want to show/hide grid
if enableGrid {
if startOnGrid && nil == gridController {
showGrid(true)
return
}
else
if !startOnGrid && gridController != nil {
hideGrid()
return
}
}
// Dismiss view controller
// Call delegate method and let them dismiss us
if let d = delegate {
d.photoBrowserDidFinishModalPresentation(self)
}
// dismissViewControllerAnimated:true completion:nil]
}
}
//MARK: - Actions
func actionButtonPressed(sender: AnyObject) {
// Only react when image has loaded
if let photo = photoAtIndex(currentPageIndex) {
if numberOfPhotos > 0 && photo.underlyingImage != nil {
// If they have defined a delegate method then just message them
// Let delegate handle things
if let d = delegate {
d.actionButtonPressedForPhotoAtIndex(currentPageIndex, photoBrowser: self)
}
/*
// Show activity view controller
var items = NSMutableArray(object: photo.underlyingImage)
if photo.caption != nil {
items.append(photo.caption!)
}
activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
// Show loading spinner after a couple of seconds
double delayInSeconds = 2.0
dispatch_timet popTime = dispatchtime(DISPATCH_TIME_NOW, Int64(delayInSeconds * NSEC_PER_SEC))
dispatch_after(popTime, dispatch_get_main_queue()) {
if self.activityViewController {
showProgressHUDWithMessage(nil)
}
}
// Show
activityViewController.setCompletionHandler({ [weak self] activityType, completed in
self!.activityViewController = nil
self!.hideControlsAfterDelay()
self!.hideProgressHUD(true)
})
self.activityViewController.popoverPresentationController.barButtonItem = actionButton
presentViewController(activityViewController, animated: true, completion: nil)
*/
// Keep controls hidden
setControlsHidden(false, animated: true, permanent: true)
}
}
}
//MARK: - Action Progress
var mwProgressHUD: MBProgressHUD?
var progressHUD: MBProgressHUD {
if nil == mwProgressHUD {
mwProgressHUD = MBProgressHUD(view: self.view)
mwProgressHUD!.minSize = CGSizeMake(120, 120)
mwProgressHUD!.minShowTime = 1.0
view.addSubview(mwProgressHUD!)
}
return mwProgressHUD!
}
private func showProgressHUDWithMessage(message: String) {
progressHUD.labelText = message
progressHUD.mode = MBProgressHUDMode.Indeterminate
progressHUD.show(true)
navigationController?.navigationBar.userInteractionEnabled = false
}
private func hideProgressHUD(animated: Bool) {
progressHUD.hide(animated)
navigationController?.navigationBar.userInteractionEnabled = true
}
private func showProgressHUDCompleteMessage(message: String?) {
if let msg = message {
if progressHUD.hidden {
progressHUD.show(true)
}
progressHUD.labelText = msg
progressHUD.mode = MBProgressHUDMode.CustomView
progressHUD.hide(true, afterDelay: 1.5)
}
else {
progressHUD.hide(true)
}
navigationController?.navigationBar.userInteractionEnabled = true
}
}
public protocol PhotoBrowserDelegate: class {
func numberOfPhotosInPhotoBrowser(photoBrowser: PhotoBrowser) -> Int
func photoAtIndex(index: Int, photoBrowser: PhotoBrowser) -> Photo
func thumbPhotoAtIndex(index: Int, photoBrowser: PhotoBrowser) -> Photo
func captionViewForPhotoAtIndex(index: Int, photoBrowser: PhotoBrowser) -> CaptionView?
func titleForPhotoAtIndex(index: Int, photoBrowser: PhotoBrowser) -> String
func didDisplayPhotoAtIndex(index: Int, photoBrowser: PhotoBrowser)
func actionButtonPressedForPhotoAtIndex(index: Int, photoBrowser: PhotoBrowser)
func isPhotoSelectedAtIndex(index: Int, photoBrowser: PhotoBrowser) -> Bool
func selectedChanged(selected: Bool, index: Int, photoBrowser: PhotoBrowser)
func photoBrowserDidFinishModalPresentation(photoBrowser: PhotoBrowser)
}
public extension PhotoBrowserDelegate {
func captionViewForPhotoAtIndex(index: Int, photoBrowser: PhotoBrowser) -> CaptionView? {
return nil
}
func didDisplayPhotoAtIndex(index: Int, photoBrowser: PhotoBrowser) {
}
func actionButtonPressedForPhotoAtIndex(index: Int, photoBrowser: PhotoBrowser) {
}
func isPhotoSelectedAtIndex(index: Int, photoBrowser: PhotoBrowser) -> Bool {
return false
}
func selectedChanged(selected: Bool, index: Int, photoBrowser: PhotoBrowser) {
}
func titleForPhotoAtIndex(index: Int, photoBrowser: PhotoBrowser) -> String {
return ""
}
}
| mit | 10da9bc6539ee4e9bdc9ce753e0db6c9 | 34.580677 | 143 | 0.569836 | 6.210855 | false | false | false | false |
benlangmuir/swift | SwiftCompilerSources/Sources/SIL/Argument.swift | 2 | 6592 | //===--- Argument.swift - Defines the Argument classes --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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
//
//===----------------------------------------------------------------------===//
import Basic
import SILBridging
/// A basic block argument.
///
/// Maps to both, SILPhiArgument and SILFunctionArgument.
public class Argument : Value, Hashable {
public var definingInstruction: Instruction? { nil }
public var definingBlock: BasicBlock { block }
public var block: BasicBlock {
return SILArgument_getParent(bridged).block
}
var bridged: BridgedArgument { BridgedArgument(obj: SwiftObject(self)) }
public var index: Int {
return block.arguments.firstIndex(of: self)!
}
public static func ==(lhs: Argument, rhs: Argument) -> Bool {
lhs === rhs
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
}
final public class FunctionArgument : Argument {
public var convention: ArgumentConvention {
SILArgument_getConvention(bridged).convention
}
}
final public class BlockArgument : Argument {
public var isPhiArgument: Bool {
block.predecessors.allSatisfy {
let term = $0.terminator
return term is BranchInst || term is CondBranchInst
}
}
public var incomingPhiOperands: LazyMapSequence<PredecessorList, Operand> {
assert(isPhiArgument)
let idx = index
return block.predecessors.lazy.map {
switch $0.terminator {
case let br as BranchInst:
return br.operands[idx]
case let condBr as CondBranchInst:
if condBr.trueBlock == self.block {
assert(condBr.falseBlock != self.block)
return condBr.trueOperands[idx]
} else {
assert(condBr.falseBlock == self.block)
return condBr.falseOperands[idx]
}
default:
fatalError("wrong terminator for phi-argument")
}
}
}
public var incomingPhiValues: LazyMapSequence<LazyMapSequence<PredecessorList, Operand>, Value> {
incomingPhiOperands.lazy.map { $0.value }
}
}
public enum ArgumentConvention {
/// This argument is passed indirectly, i.e. by directly passing the address
/// of an object in memory. The callee is responsible for destroying the
/// object. The callee may assume that the address does not alias any valid
/// object.
case indirectIn
/// This argument is passed indirectly, i.e. by directly passing the address
/// of an object in memory. The callee must treat the object as read-only
/// The callee may assume that the address does not alias any valid object.
case indirectInConstant
/// This argument is passed indirectly, i.e. by directly passing the address
/// of an object in memory. The callee may not modify and does not destroy
/// the object.
case indirectInGuaranteed
/// This argument is passed indirectly, i.e. by directly passing the address
/// of an object in memory. The object is always valid, but the callee may
/// assume that the address does not alias any valid object and reorder loads
/// stores to the parameter as long as the whole object remains valid. Invalid
/// single-threaded aliasing may produce inconsistent results, but should
/// remain memory safe.
case indirectInout
/// This argument is passed indirectly, i.e. by directly passing the address
/// of an object in memory. The object is allowed to be aliased by other
/// well-typed references, but is not allowed to be escaped. This is the
/// convention used by mutable captures in @noescape closures.
case indirectInoutAliasable
/// This argument represents an indirect return value address. The callee stores
/// the returned value to this argument. At the time when the function is called,
/// the memory location referenced by the argument is uninitialized.
case indirectOut
/// This argument is passed directly. Its type is non-trivial, and the callee
/// is responsible for destroying it.
case directOwned
/// This argument is passed directly. Its type may be trivial, or it may
/// simply be that the callee is not responsible for destroying it. Its
/// validity is guaranteed only at the instant the call begins.
case directUnowned
/// This argument is passed directly. Its type is non-trivial, and the caller
/// guarantees its validity for the entirety of the call.
case directGuaranteed
public var isExclusiveIndirect: Bool {
switch self {
case .indirectIn,
.indirectInConstant,
.indirectOut,
.indirectInGuaranteed,
.indirectInout:
return true
case .indirectInoutAliasable,
.directUnowned,
.directGuaranteed,
.directOwned:
return false
}
}
public var isInout: Bool {
switch self {
case .indirectInout,
.indirectInoutAliasable:
return true
case .indirectIn,
.indirectInConstant,
.indirectOut,
.indirectInGuaranteed,
.directUnowned,
.directGuaranteed,
.directOwned:
return false
}
}
}
// Bridging utilities
extension BridgedArgument {
public var argument: Argument { obj.getAs(Argument.self) }
public var blockArgument: BlockArgument { obj.getAs(BlockArgument.self) }
public var functionArgument: FunctionArgument { obj.getAs(FunctionArgument.self) }
}
extension BridgedArgumentConvention {
var convention: ArgumentConvention {
switch self {
case ArgumentConvention_Indirect_In: return .indirectIn
case ArgumentConvention_Indirect_In_Constant: return .indirectInConstant
case ArgumentConvention_Indirect_In_Guaranteed: return .indirectInGuaranteed
case ArgumentConvention_Indirect_Inout: return .indirectInout
case ArgumentConvention_Indirect_InoutAliasable: return .indirectInoutAliasable
case ArgumentConvention_Indirect_Out: return .indirectOut
case ArgumentConvention_Direct_Owned: return .directOwned
case ArgumentConvention_Direct_Unowned: return .directUnowned
case ArgumentConvention_Direct_Guaranteed: return .directGuaranteed
default:
fatalError("unsupported argument convention")
}
}
}
| apache-2.0 | ae41ebec3ff94edf2c9a1eca34a67d97 | 33.694737 | 99 | 0.693113 | 4.783745 | false | false | false | false |
mhplong/Projects | iOS/ServiceTracker/MomentTableView.swift | 1 | 3345 | //
// MomentTableView.swift
// ServiceTimeTracker
//
// Created by Mark Long on 5/12/16.
// Copyright © 2016 Mark Long. All rights reserved.
//
import UIKit
import CoreData
class MomentTableView: UITableView, UITableViewDataSource {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
var modelSessions = [Session]()
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
getSessions()
self.dataSource = self
}
override func reloadData() {
getSessions()
super.reloadData()
}
func getDatabaseContext() -> NSManagedObjectContext? {
if let delegate = UIApplication.sharedApplication().delegate as? AppDelegate {
return delegate.managedObjectContext
} else {
return nil
}
}
func getSessions() {
do {
if let dbContext = getDatabaseContext() {
let sessionFetch = NSFetchRequest(entityName: "Session")
let sortDescripter = NSSortDescriptor(key: "id", ascending: false)
sessionFetch.sortDescriptors = [sortDescripter]
if let results = try dbContext.executeFetchRequest(sessionFetch) as? [Session] {
modelSessions = results
}
}
} catch {
print ("Error: \(error)")
}
}
//MARK dataSource Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return modelSessions.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let session = modelSessions[section]
return "\(session.name ?? "nil") -- \(elapsedDateToString(session.getTotalElapsedTime()))"
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let moments = modelSessions[section].moments {
return moments.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("momentCell", forIndexPath: indexPath)
cell.textLabel?.font = UIFont.systemFontOfSize(10)
cell.detailTextLabel?.font = UIFont.systemFontOfSize(10)
let session = modelSessions[indexPath.section]
if var moments = session.moments?.array as? [Moment] {
moments = moments.reverse()
if moments.count > indexPath.row {
let moment = moments[indexPath.row]
let startElapsedDate = dateToElapsedDate(session.date!, end: moment.start_time!)
let elapsedDate = dateToElapsedDate(moment.start_time!, end: moment.end_time!)
cell.textLabel!.text = elapsedDateToString(startElapsedDate) + "-\(moment.name!)"
cell.detailTextLabel!.text = elapsedDateToString(elapsedDate)
}
}
return cell
}
}
| mit | fe71257bd3480cf2259dbe2f705bfa5b | 33.122449 | 109 | 0.616926 | 5.144615 | false | false | false | false |
MuYangZhe/Swift30Projects | Project 11 - Animations/Animations/Common.swift | 1 | 1068 | //
// Common.swift
// Animations
//
// Created by 牧易 on 17/7/24.
// Copyright © 2017年 MuYi. All rights reserved.
//
import Foundation
import UIKit
let screenRect = UIScreen.main.bounds
let generalFrame = CGRect(x: 0, y: 0, width: screenRect.width/2, height: screenRect.height/4)
let generalCenter = CGPoint(x: screenRect.midX, y: screenRect.midY - 50)
func drawSquare(color:UIColor,center:CGPoint,frame:CGRect) ->UIView {
let square = UIView(frame: frame)
square.center = center
square.backgroundColor = color
return square
}
func drawCircleView(color:UIColor,center:CGPoint,radiaus:CGFloat) -> UIView {
let circlePath = UIBezierPath(arcCenter: center, radius: radiaus, startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = color.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = 3.0
let view = UIView()
view.layer.addSublayer(shapeLayer)
return view
}
| mit | 050d2a45bd3cb12a5ce0a2f693369ba3 | 26.921053 | 139 | 0.708765 | 3.802867 | false | false | false | false |
AlexRamey/mbird-iOS | iOS Client/Models/Core Data/MBCategory+CoreDataClass.swift | 1 | 3103 | //
// MBCategory+CoreDataClass.swift
// iOS Client
//
// Created by Alex Ramey on 10/5/17.
// Copyright © 2017 Mockingbird. All rights reserved.
//
//
import Foundation
import CoreData
public class MBCategory: NSManagedObject {
static let entityName: String = "Category"
class func newCategory(fromCategory from: Category, inContext managedContext: NSManagedObjectContext) -> MBCategory? {
let predicate = NSPredicate(format: "categoryID == %d", from.categoryId)
let fetchRequest = NSFetchRequest<MBCategory>(entityName: self.entityName)
fetchRequest.predicate = predicate
var resolvedCategory: MBCategory? = nil
do {
let fetchedEntities = try managedContext.fetch(fetchRequest)
resolvedCategory = fetchedEntities.first
} catch {
print("Error fetching category \(from.categoryId) from core data: \(error)")
return nil
}
if resolvedCategory == nil {
let entity = NSEntityDescription.entity(forEntityName: self.entityName, in: managedContext)!
resolvedCategory = NSManagedObject(entity: entity, insertInto: managedContext) as? MBCategory
}
guard let category = resolvedCategory else {
return nil
}
category.categoryID = Int32(from.categoryId)
category.parentID = Int32(from.parentId)
category.name = from.name
return category
}
// There are multiple top-level categories (whose parentID is 0). The rest are children.
// This method follows the parent links until it encounters a top-level category,
// which it returns. If called on a top-level category, this method returns the
// receiver.
func getTopLevelCategory() -> MBCategory? {
return self.getTopLevelCategoryInternal(loopGuard: 0)
}
private func getTopLevelCategoryInternal(loopGuard: Int) -> MBCategory? {
if loopGuard > 50 {
// just in case they create a cycle . . .
return nil
}
if self.parentID == 0 {
return self
} else {
return self.parent?.getTopLevelCategoryInternal(loopGuard: loopGuard+1) ?? nil
}
}
func getAllDescendants() -> [MBCategory] {
var retVal: Set<MBCategory> = []
var queue: [MBCategory] = (self.children?.allObjects as? [MBCategory]) ?? []
var loopGuard = 0 // just in case they create a cycle
while let current = queue.popLast() {
guard loopGuard < 1000 else {
return Array(retVal)
}
loopGuard += 1
retVal.insert(current)
if let children = current.children?.allObjects as? [MBCategory] {
queue.insert(contentsOf: children, at: 0)
}
}
return Array(retVal)
}
func toDomain() -> Category {
return Category(categoryId: Int(self.categoryID), name: self.name ?? "", parentId: Int(self.parentID))
}
}
| mit | a2e1ad000fe772ef42d89f5887fe5613 | 33.853933 | 122 | 0.607672 | 5.035714 | false | false | false | false |
Henawey/TheArabianCenter | TheArabianCenter/ShareViewController.swift | 1 | 4583 | //
// ShareViewController.swift
// TheArabianCenter
//
// Created by Ahmed Henawey on 2/23/17.
// Copyright (c) 2017 Ahmed Henawey. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
import Kingfisher
import RxSwift
import RxCocoa
import CoreLocation
import MBProgressHUD
protocol ShareViewControllerInput
{
func displayShareSuccess(viewModel: Share.ViewModel)
func displayRetrieveSucceed(syncResponse:Sync.ViewModel)
func displayRetrieveImageSucceed(model:Image.Download.ViewModel)
func displayMessage(title: String, message:String,actionTitle:String)
}
protocol ShareViewControllerOutput
{
func shareOnFacebook(request: UI.Share.Request)
func shareOnTwitter(from viewController: UIViewController,request: UI.Share.Request)
func retrieve(request: UI.Sync.Retrieve.Request)
func retrieveImage(request: UI.Image.Download.Request)
/// Vairable represents some observable state for the value and it will be user to observe any value change.
var image: Variable<UIImage?> {get set}
var userLocation: CLLocation? {get set}
}
class ShareViewController: UIViewController, ShareViewControllerInput
{
var output: ShareViewControllerOutput!
var router: ShareRouter!
@IBOutlet var imageView:UIImageView?
let disposeBag = DisposeBag()
var offer:Variable<Sync.ViewModel?> = Variable(nil)
// MARK: - Object lifecycle
override func awakeFromNib()
{
super.awakeFromNib()
ShareConfigurator.sharedInstance.configure(viewController: self)
}
// MARK: - View lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
/// set image setted then it will shown
//subscribe for image change to set the image view with new image
self.output.image.asObservable().subscribe(onNext: { (image) in
self.imageView?.image = image
}).addDisposableTo(disposeBag)
//subscribe for offer change to download image then display it
self.offer.asObservable().skipWhile({ (viewModel) -> Bool in
return (viewModel == nil)
}).subscribe(onNext: { (viewModel) in
self.output.retrieveImage(request: UI.Image.Download.Request(imageLocation: viewModel?.imageLocation))
}).addDisposableTo(disposeBag)
}
// MARK: - Event handling
/// Load offer from data source
///
/// - Parameter offerId: the required offer id
func loadOffer(offerId: String){
MBProgressHUD.showAdded(to: self.view, animated: true)
self.output.retrieve(request: UI.Sync.Retrieve.Request(id: offerId))
}
@IBAction func facebookShare(){
MBProgressHUD.showAdded(to: self.view, animated: true)
self.output.shareOnFacebook(request: UI.Share.Request(title:"Test Title",description:"Test Description",image:self.output.image.value))
}
@IBAction func twitterShare(){
MBProgressHUD.showAdded(to: self.view, animated: true)
self.output.shareOnTwitter(from: self, request: UI.Share.Request(title: "Test Title", description: "Test Description", image: self.output.image.value))
}
// MARK: - Display logic
/// Download or upload image done successfully
///
/// - Parameter syncResponse: the view model to display
func displayRetrieveSucceed(syncResponse:Sync.ViewModel){
MBProgressHUD.hide(for: self.view, animated: true)
self.offer.value = syncResponse
}
/// Display the result from the Presenter for sharing on social media
func displayShareSuccess(viewModel: Share.ViewModel) {
MBProgressHUD.hide(for: self.view, animated: true)
print("claimed")
}
func displayRetrieveImageSucceed(model:Image.Download.ViewModel){
MBProgressHUD.hide(for: self.view, animated: true)
self.output.image.value = model.image
}
func displayMessage(title: String, message:String,actionTitle:String) {
MBProgressHUD.hide(for: self.view, animated: true)
// NOTE: Display the result from the Presenter
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: actionTitle, style: .destructive, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
| mit | 488a862f9c88b6bcb602c2884cd49df0 | 33.984733 | 159 | 0.690377 | 4.624622 | false | false | false | false |
tavultesoft/keymanweb | ios/keyman/Keyman/Keyman/Classes/DropDownList/DropDownListView.swift | 1 | 2600 | //
// DropDownListView.swift
// Keyman
//
// Created by Gabriel Wong on 2017-09-07.
// Copyright © 2017 SIL International. All rights reserved.
//
import UIKit
import KeymanEngine
class DropDownListView: UIView {
init(listItems items: [UIBarButtonItem], itemSize size: CGSize, position pos: CGPoint) {
let frameHeight = items.count > 0 ? size.height * CGFloat(items.count) : size.height
let frame = CGRect(x: pos.x, y: pos.y, width: size.width, height: frameHeight)
super.init(frame: frame)
backgroundColor = UIColor.clear
let dropDownView = DropDownView(frame: CGRect.zero)
let arrowHeight = dropDownView.arrowHeight
dropDownView.frame = CGRect(x: 0, y: -arrowHeight, width: frame.size.width,
height: frame.size.height + arrowHeight)
dropDownView.arrowPosX = frame.size.width - 29
addSubview(dropDownView)
let count: Int = items.count
let w: CGFloat = frame.width
let h: CGFloat = size.height
let x: CGFloat = 0
var y: CGFloat = 0
for (index, item) in items.enumerated() {
let button = UIButton(type: .custom)
button.setTitleColor(Colors.labelNormal, for: .normal)
button.setTitleColor(Colors.labelHighlighted, for: .highlighted)
button.frame = CGRect(x: x, y: y, width: w, height: h)
button.setTitle(item.title, for: .normal)
addSubview(button)
if let subviews = item.customView?.subviews, subviews.count > 0,
let btn = subviews[0] as? UIButton {
let icon = btn.image(for: .normal)
let iconSelected = btn.image(for: .highlighted)
button.setImage(icon, for: .normal)
button.setImage(iconSelected, for: .highlighted)
button.contentHorizontalAlignment = .left
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
if let iconWidth = icon?.size.width {
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: h - iconWidth, bottom: 0, right: 0)
}
for target in btn.allTargets {
let actions = btn.actions(forTarget: target, forControlEvent: .touchUpInside)
actions?.forEach {
button.addTarget(target, action: NSSelectorFromString($0), for: .touchUpInside)
}
}
}
if index < count - 1 {
let seperator = UIView(frame: CGRect(x: x + 1, y: y + h, width: w - 2, height: 1))
seperator.backgroundColor = Colors.listSeparator
addSubview(seperator)
}
y += h + 1
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | e51e10df3ffe4ef4305432c983d35d9f | 35.605634 | 97 | 0.65102 | 3.980092 | false | false | false | false |
brandonminch/Siren | Siren/Siren.swift | 2 | 24113 | //
// Siren.swift
// Siren
//
// Created by Arthur Sabintsev on 1/3/15.
// Copyright (c) 2015 Sabintsev iOS Projects. All rights reserved.
//
import UIKit
// MARK: SirenDelegate Protocol
@objc public protocol SirenDelegate {
optional func sirenDidShowUpdateDialog() // User presented with update dialog
optional func sirenUserDidLaunchAppStore() // User did click on button that launched App Store.app
optional func sirenUserDidSkipVersion() // User did click on button that skips version update
optional func sirenUserDidCancel() // User did click on button that cancels update dialog
optional func sirenDidDetectNewVersionWithoutAlert(message: String) // Siren performed version check and did not display alert
}
// MARK: Enumerations
/**
Determines the type of alert to present after a successful version check has been performed.
There are four options:
- Force: Forces user to update your app (1 button alert)
- Option: (DEFAULT) Presents user with option to update app now or at next launch (2 button alert)
- Skip: Presents user with option to update the app now, at next launch, or to skip this version all together (3 button alert)
- None: Doesn't show the alert, but instead returns a localized message for use in a custom UI within the sirenDidDetectNewVersionWithoutAlert() delegate method
*/
public enum SirenAlertType
{
case Force // Forces user to update your app (1 button alert)
case Option // (DEFAULT) Presents user with option to update app now or at next launch (2 button alert)
case Skip // Presents user with option to update the app now, at next launch, or to skip this version all together (3 button alert)
case None // Doesn't show the alert, but instead returns a localized message for use in a custom UI within the sirenDidDetectNewVersionWithoutAlert() delegate method
}
/**
Determines the frequency in which the the version check is performed
- .Immediately: Version check performed every time the app is launched
- .Daily: Version check performedonce a day
- .Weekly: Version check performed once a week
*/
public enum SirenVersionCheckType : Int
{
case Immediately = 0 // Version check performed every time the app is launched
case Daily = 1 // Version check performed once a day
case Weekly = 7 // Version check performed once a week
}
/**
Determines the available languages in which the update message and alert button titles should appear.
By default, the operating system's default lanuage setting is used. However, you can force a specific language
by setting the forceLanguageLocalization property before calling checkVersion()
*/
public enum SirenLanguageType: String
{
case Arabic = "ar"
case Basque = "eu"
case ChineseSimplified = "zh-Hans"
case ChineseTraditional = "zh-Hant"
case Danish = "da"
case Dutch = "nl"
case English = "en"
case Estonian = "et"
case French = "fr"
case Hebrew = "he"
case Hungarian = "hu"
case German = "de"
case Italian = "it"
case Japanese = "ja"
case Korean = "ko"
case Latvian = "lv"
case Lithuanian = "lt"
case Polish = "pl"
case PortugueseBrazil = "pt"
case PortuguesePortugal = "pt-PT"
case Russian = "ru"
case Slovenian = "sl"
case Spanish = "es"
case Swedish = "sv"
case Thai = "th"
case Turkish = "tr"
}
// MARK: Siren
/**
The Siren Class.
A singleton that is initialized using the sharedInstance() method.
*/
public class Siren: NSObject
{
// MARK: Constants
// NSUserDefault key that stores the timestamp of the last version check
let sirenDefaultStoredVersionCheckDate = "Siren Stored Date From Last Version Check"
// NSUserDefault key that stores the version that a user decided to skip
let sirenDefaultSkippedVersion = "Siren User Decided To Skip Version Update"
// Current installed version of your app
let currentInstalledVersion = NSBundle.mainBundle().currentInstalledVersion()
// NSBundle path for localization
let bundlePath = NSBundle.mainBundle().pathForResource("Siren", ofType: "Bundle")
// MARK: Variables
/**
The SirenDelegate variable, which should be set if you'd like to be notified:
- When a user views or interacts with the alert
- sirenDidShowUpdateDialog()
- sirenUserDidLaunchAppStore()
- sirenUserDidSkipVersion()
- sirenUserDidCancel()
- When a new version has been detected, and you would like to present a localized message in a custom UI
- sirenDidDetectNewVersionWithoutAlert(message: String)
*/
public weak var delegate: SirenDelegate?
/**
The debug flag, which is disabled by default.
When enabled, a stream of println() statements are logged to your console when a version check is performed.
*/
public lazy var debugEnabled = false
// Alert Vars
/**
Determines the type of alert that should be shown.
See the SirenAlertType enum for full details.
*/
public var alertType = SirenAlertType.Option
/**
Determines the type of alert that should be shown for major version updates: A.b.c
Defaults to SirenAlertType.Option.
See the SirenAlertType enum for full details.
*/
public var majorUpdateAlertType = SirenAlertType.Option
/**
Determines the type of alert that should be shown for minor version updates: a.B.c
Defaults to SirenAlertType.Option.
See the SirenAlertType enum for full details.
*/
public var minorUpdateAlertType = SirenAlertType.Option
/**
Determines the type of alert that should be shown for minor patch updates: a.b.C
Defaults to SirenAlertType.Option.
See the SirenAlertType enum for full details.
*/
public var patchUpdateAlertType = SirenAlertType.Option
/**
Determines the type of alert that should be shown for revision updates: a.b.c.D
Defaults to SirenAlertType.Option.
See the SirenAlertType enum for full details.
*/
public var revisionUpdateAlertType = SirenAlertType.Option
// Required Vars
/**
The App Store / iTunes Connect ID for your app.
*/
public var appID: String?
// Optional Vars
/**
The name of your app.
By default, it's set to the name of the app that's stored in your plist.
*/
public lazy var appName: String = (NSBundle.mainBundle().infoDictionary?[kCFBundleNameKey] as? String) ?? ""
/**
The region or country of an App Store in which your app is available.
By default, all version checks are performed against the US App Store.
If your app is not available in the US App Store, you should set it to the identifier
of at least one App Store within which it is available.
*/
public var countryCode: String?
/**
Overrides the default localization of a user's device when presenting the update message and button titles in the alert.
See the SirenLanguageType enum for more details.
*/
public var forceLanguageLocalization: SirenLanguageType?
/**
Overrides the tint color for UIAlertController.
*/
public var alertControllerTintColor: UIColor?
// Private
private var lastVersionCheckPerformedOnDate: NSDate?
private var currentAppStoreVersion: String?
private var updaterWindow: UIWindow!
// MARK: Initialization
public class var sharedInstance: Siren {
struct Singleton {
static let instance = Siren()
}
return Singleton.instance
}
override init() {
lastVersionCheckPerformedOnDate = NSUserDefaults.standardUserDefaults().objectForKey(sirenDefaultStoredVersionCheckDate) as? NSDate;
}
// MARK: Check Version
/**
Checks the currently installed version of your app against the App Store.
The default check is against the US App Store, but if your app is not listed in the US,
you should set the `countryCode` property before calling this method. Please refer to the countryCode property for more information.
:param: checkType The frequency in days in which you want a check to be performed. Please refer to the SirenVersionCheckType enum for more details.
*/
public func checkVersion(checkType: SirenVersionCheckType) {
if (appID == nil) {
println("[Siren] Please make sure that you have set 'appID' before calling checkVersion.")
} else {
if checkType == .Immediately {
performVersionCheck()
} else {
if let lastCheckDate = lastVersionCheckPerformedOnDate {
if daysSinceLastVersionCheckDate() >= checkType.rawValue {
performVersionCheck()
}
} else {
performVersionCheck()
}
}
}
}
private func performVersionCheck() {
// Create Request
let itunesURL = iTunesURLFromString()
let request = NSMutableURLRequest(URL: itunesURL)
request.HTTPMethod = "GET"
// Perform Request
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if data.length > 0 {
// Convert JSON data to Swift Dictionary of type [String : AnyObject]
let appData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as? [String: AnyObject]
if let appData = appData {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// Print iTunesLookup results from appData
if self.debugEnabled {
println("[Siren] JSON results: \(appData)");
}
// Process Results (e.g., extract current version on the AppStore)
self.processVersionCheckResults(appData)
})
} else { // appData == nil
if self.debugEnabled {
println("[Siren] Error retrieving App Store data as data was nil: \(error.localizedDescription)")
}
}
} else { // data.length == 0
if self.debugEnabled {
println("[Siren] Error retrieving App Store data as no data was returned: \(error.localizedDescription)")
}
}
})
task.resume()
}
private func processVersionCheckResults(lookupResults: [String: AnyObject]) {
// Store version comparison date
self.storeVersionCheckDate()
let results = lookupResults["results"] as? [[String: AnyObject]]
if let results = results {
if results.isEmpty == false { // Conditional that avoids crash when app not in App Store or appID mistyped
self.currentAppStoreVersion = results[0]["version"] as? String
if let currentAppStoreVersion = self.currentAppStoreVersion {
if self.isAppStoreVersionNewer() {
self.showAlertIfCurrentAppStoreVersionNotSkipped()
} else {
if self.debugEnabled {
println("[Siren] App Store version of app is not newer")
}
}
} else { // lookupResults["results"][0] does not contain "version" key
if self.debugEnabled {
println("[Siren] Error retrieving App Store verson number as results[0] does not contain a 'version' key")
}
}
} else { // lookupResults does not contain any data as the returned array is empty
if self.debugEnabled {
println("[Siren] Error retrieving App Store verson number as results returns an empty array")
}
}
} else { // lookupResults does not contain any data
if self.debugEnabled {
println("[Siren] Error retrieving App Store verson number as there was no data returned")
}
}
}
}
// MARK: Alert
private extension Siren
{
func showAlertIfCurrentAppStoreVersionNotSkipped() {
self.alertType = self.setAlertType()
if let previouslySkippedVersion = NSUserDefaults.standardUserDefaults().objectForKey(sirenDefaultSkippedVersion) as? String {
if currentAppStoreVersion! != previouslySkippedVersion {
showAlert()
}
} else {
showAlert()
}
}
func showAlert() {
let updateAvailableMessage = NSBundle().localizedString("Update Available", forceLanguageLocalization: forceLanguageLocalization)
var newVersionMessage = localizedNewVersionMessage();
if (useAlertController) { // iOS 8
let alertController = UIAlertController(title: updateAvailableMessage, message: newVersionMessage, preferredStyle: .Alert)
if let alertControllerTintColor = alertControllerTintColor {
alertController.view.tintColor = alertControllerTintColor
}
switch alertType {
case .Force:
alertController.addAction(updateAlertAction());
case .Option:
alertController.addAction(nextTimeAlertAction());
alertController.addAction(updateAlertAction());
case .Skip:
alertController.addAction(nextTimeAlertAction());
alertController.addAction(updateAlertAction());
alertController.addAction(skipAlertAction());
case .None:
delegate?.sirenDidDetectNewVersionWithoutAlert?(newVersionMessage)
}
if alertType != .None {
alertController.show()
}
} else { // iOS 7
var alertView: UIAlertView?
let updateButtonTitle = localizedUpdateButtonTitle()
let nextTimeButtonTitle = localizedNextTimeButtonTitle()
let skipButtonTitle = localizedSkipButtonTitle()
switch alertType {
case .Force:
alertView = UIAlertView(title: updateAvailableMessage, message: newVersionMessage, delegate: self, cancelButtonTitle: updateButtonTitle)
case .Option:
alertView = UIAlertView(title: updateAvailableMessage, message: newVersionMessage, delegate: self, cancelButtonTitle: nextTimeButtonTitle)
alertView!.addButtonWithTitle(updateButtonTitle)
case .Skip:
alertView = UIAlertView(title: updateAvailableMessage, message: newVersionMessage, delegate: self, cancelButtonTitle: skipButtonTitle)
alertView!.addButtonWithTitle(updateButtonTitle)
alertView!.addButtonWithTitle(nextTimeButtonTitle)
case .None:
delegate?.sirenDidDetectNewVersionWithoutAlert?(newVersionMessage)
}
if let alertView = alertView {
alertView.show()
}
}
}
func updateAlertAction() -> UIAlertAction {
let title = localizedUpdateButtonTitle()
let action = UIAlertAction(title: title, style: .Default) { (alert: UIAlertAction!) -> Void in
self.hideWindow()
self.launchAppStore()
self.delegate?.sirenUserDidLaunchAppStore?()
return
}
return action
}
func nextTimeAlertAction() -> UIAlertAction {
let title = localizedNextTimeButtonTitle()
let action = UIAlertAction(title: title, style: .Default) { (alert: UIAlertAction!) -> Void in
self.hideWindow()
self.delegate?.sirenUserDidCancel?()
return
}
return action
}
func skipAlertAction() -> UIAlertAction {
let title = localizedSkipButtonTitle()
let action = UIAlertAction(title: title, style: .Default) { (alert: UIAlertAction!) -> Void in
self.hideWindow()
self.delegate?.sirenUserDidSkipVersion?()
return
}
return action
}
}
// MARK: Helpers
private extension Siren
{
func iTunesURLFromString() -> NSURL {
var storeURLString = "https://itunes.apple.com/lookup?id=\(appID!)"
if let countryCode = countryCode {
storeURLString += "&country=\(countryCode)"
}
if debugEnabled {
println("[Siren] iTunes Lookup URL: \(storeURLString)");
}
return NSURL(string: storeURLString)!
}
func daysSinceLastVersionCheckDate() -> Int {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitDay, fromDate: NSDate(), toDate: lastVersionCheckPerformedOnDate!, options: nil)
return components.day
}
func isAppStoreVersionNewer() -> Bool {
var newVersionExists = false
if let currentInstalledVersion = self.currentInstalledVersion {
if (currentInstalledVersion.compare(currentAppStoreVersion!, options: .NumericSearch) == NSComparisonResult.OrderedAscending) {
newVersionExists = true
}
}
return newVersionExists
}
func storeVersionCheckDate() {
lastVersionCheckPerformedOnDate = NSDate()
if let lastVersionCheckPerformedOnDate = self.lastVersionCheckPerformedOnDate {
NSUserDefaults.standardUserDefaults().setObject(self.lastVersionCheckPerformedOnDate!, forKey: self.sirenDefaultStoredVersionCheckDate)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func setAlertType() -> SirenAlertType {
let oldVersion = split(currentInstalledVersion!) {$0 == "."}.map {$0.toInt() ?? 0}
let newVersion = split(currentAppStoreVersion!) {$0 == "."}.map {$0.toInt() ?? 0}
if 2...4 ~= oldVersion.count && oldVersion.count == newVersion.count {
if newVersion[0] > oldVersion[0] { // A.b[.c][.d]
alertType = majorUpdateAlertType
} else if newVersion[1] > oldVersion[1] { // a.B[.c][.d]
alertType = minorUpdateAlertType
} else if newVersion.count > 2 && newVersion[2] > oldVersion[2] { // a.b.C[.d]
alertType = patchUpdateAlertType
} else if newVersion.count > 3 && newVersion[3] > oldVersion[3] { // a.b.c.D
alertType = revisionUpdateAlertType
}
}
return alertType
}
func hideWindow() {
updaterWindow.hidden = true
updaterWindow = nil
}
// iOS 8 Compatibility Check
var useAlertController: Bool { // iOS 8 check
return objc_getClass("UIAlertController") != nil
}
// Actions
func launchAppStore() {
let iTunesString = "https://itunes.apple.com/app/id\(appID!)";
let iTunesURL = NSURL(string: iTunesString);
UIApplication.sharedApplication().openURL(iTunesURL!);
}
}
// MARK: UIAlertController
private extension UIAlertController
{
func show() {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.rootViewController = UIViewController()
window.windowLevel = UIWindowLevelAlert + 1
Siren.sharedInstance.updaterWindow = window
window.makeKeyAndVisible()
window.rootViewController!.presentViewController(self, animated: true, completion: nil)
}
}
// MARK: String Localization
private extension Siren
{
func localizedNewVersionMessage() -> String {
let newVersionMessageToLocalize = "A new version of %@ is available. Please update to version %@ now."
var newVersionMessage = NSBundle().localizedString(newVersionMessageToLocalize, forceLanguageLocalization: forceLanguageLocalization)
newVersionMessage = String(format: newVersionMessage!, appName, currentAppStoreVersion!)
return newVersionMessage!
}
func localizedUpdateButtonTitle() -> String {
return NSBundle().localizedString("Update", forceLanguageLocalization: forceLanguageLocalization)!
}
func localizedNextTimeButtonTitle() -> String {
return NSBundle().localizedString("Next time", forceLanguageLocalization: forceLanguageLocalization)!
}
func localizedSkipButtonTitle() -> String {
return NSBundle().localizedString("Skip this version", forceLanguageLocalization: forceLanguageLocalization)!;
}
}
// MARK: NSBundle Extension
private extension NSBundle
{
func currentInstalledVersion() -> String? {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
}
func sirenBundlePath() -> String {
return NSBundle(forClass: Siren.self).pathForResource("Siren", ofType: "bundle") as String!
}
func sirenForcedBundlePath(forceLanguageLocalization: SirenLanguageType) -> String {
let path = sirenBundlePath()
let name = forceLanguageLocalization.rawValue
return NSBundle(path: path)!.pathForResource(name, ofType: "lproj")!
}
func localizedString(stringKey: String, forceLanguageLocalization: SirenLanguageType?) -> String? {
var path: String
let table = "SirenLocalizable"
if let forceLanguageLocalization = forceLanguageLocalization {
path = sirenForcedBundlePath(forceLanguageLocalization)
} else {
path = sirenBundlePath()
}
return NSBundle(path: path)?.localizedStringForKey(stringKey, value: stringKey, table: table)
}
}
// MARK: UIAlertViewDelegate
extension Siren: UIAlertViewDelegate
{
public func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
switch alertType {
case .Force:
launchAppStore()
case .Option:
if buttonIndex == 1 { // Launch App Store.app
launchAppStore()
self.delegate?.sirenUserDidLaunchAppStore?()
} else { // Ask user on next launch
self.delegate?.sirenUserDidCancel?()
}
case .Skip:
if buttonIndex == 0 { // Launch App Store.app
NSUserDefaults.standardUserDefaults().setObject(currentAppStoreVersion!, forKey: sirenDefaultSkippedVersion)
NSUserDefaults.standardUserDefaults().synchronize()
self.delegate?.sirenUserDidSkipVersion?()
} else if buttonIndex == 1 {
launchAppStore()
self.delegate?.sirenUserDidLaunchAppStore?()
} else if buttonIndex == 2 { // Ask user on next launch
self.delegate?.sirenUserDidCancel?()
}
case .None:
if debugEnabled {
println("[Siren] No alert presented due to alertType == .None")
}
}
}
}
| mit | d6ccc36cc086c40f30708afb17584a30 | 37.033123 | 177 | 0.617426 | 5.799182 | false | false | false | false |
LYM-mg/DemoTest | indexView/Extesion/Category(扩展)/UIColor+Extension.swift | 2 | 4795 | //
// UIColor+Extension.swift
// chart2
//
// Created by i-Techsys.com on 16/11/23.
// Copyright © 2016年 i-Techsys. All rights reserved.
/*
1. 关键字static和class的区别:
在方法的func关键字之前加上关键字static或者class都可以用于指定类方法.
不同的是用class关键字指定的类方法可以被子类重写, 如下:
override class func work() {
print("Teacher: University Teacher")
}
但是用static关键字指定的类方法是不能被子类重写的, 根据报错信息: Class method overrides a 'final' class method.
我们可以知道被static指定的类方法包含final关键字的特性--防止被重写.
*/
import UIKit
// MARK: - 自定义颜色和随机颜色
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
let r = r/255.0
let g = g/255.0
let b = b/255.0
self.init(red: r, green: g, blue: b, alpha: a)
}
static func randomColor() -> UIColor {
let r = CGFloat(arc4random_uniform(256))
let g = CGFloat(arc4random_uniform(256))
let b = CGFloat(arc4random_uniform(256))
return colorWithCustom(r: r, g: g, b: b)
}
static func colorWithCustom(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
let r = r/255.0
let g = g/255.0
let b = b/255.0
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
}
// MARK: - 16进制转UIColor
extension UIColor {
/**
16进制转UIColor
- parameter hex: 16进制颜色字符串
- returns: 转换后的颜色
*/
static func colorHex(hex: String) -> UIColor {
return proceesHex(hex: hex,alpha: 1.0)
}
/**
16进制转UIColor,
- parameter hex: 16进制颜色字符串
- parameter alpha: 透明度
- returns: 转换后的颜色
*/
static func colorHexWithAlpha(hex: String, alpha: CGFloat) -> UIColor {
return proceesHex(hex: hex, alpha: alpha)
}
/** 主要逻辑 */
fileprivate static func proceesHex(hex: String, alpha: CGFloat) -> UIColor{
/** 如果传入的字符串为空 */
if hex.isEmpty {
return UIColor.clear
}
/** 传进来的值。 去掉了可能包含的空格、特殊字符, 并且全部转换为大写 */
let whitespace = NSCharacterSet.whitespacesAndNewlines
var hHex = (hex.trimmingCharacters(in: whitespace)).uppercased()
/** 如果处理过后的字符串少于6位 */
if hHex.count < 6 {
return UIColor.clear
}
/** 开头是用0x开始的 或者 开头是以##开始的 */
if hHex.hasPrefix("0X") || hHex.hasPrefix("##") {
hHex = String(hHex.dropFirst(2))
}
/** 开头是以#开头的 */
if hHex.hasPrefix("#") {
hHex = (hHex as NSString).substring(from: 1)
}
/** 截取出来的有效长度是6位, 所以不是6位的直接返回 */
if hHex.count != 6 {
return UIColor.clear
}
/** R G B */
var range = NSMakeRange(0, 2)
/** R */
let rHex = (hHex as NSString).substring(with: range)
/** G */
range.location = 2
let gHex = (hHex as NSString).substring(with: range)
/** B */
range.location = 4
let bHex = (hHex as NSString).substring(with: range)
/** 类型转换 */
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rHex).scanHexInt32(&r)
Scanner(string: gHex).scanHexInt32(&g)
Scanner(string: bHex).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
}
// convenience init(hex string: String) {
// var hex = string.hasPrefix("#") ? String(string.characters.dropFirst()) : string
//
// guard hex.characters.count == 3 || hex.characters.count == 6
// else {
// self.init(white: 1.0, alpha: 0.0)
// return
// }
//
// if hex.characters.count == 3 {
// for (index, char) in hex.characters.enumerated() {
// hex.insert(char, at: hex.index(hex.startIndex, offsetBy: index * 2))
// }
// }
//
// self.init(
// red: CGFloat((Int(hex, radix: 16)! >> 16) & 0xFF) / 255.0,
// green: CGFloat((Int(hex, radix: 16)! >> 8) & 0xFF) / 255.0,
// blue: CGFloat((Int(hex, radix: 16)!) & 0xFF) / 255.0, alpha: 1.0)
// }
}
| mit | 2e9726bfedfb1b12e5d594a625219dc0 | 28.150685 | 114 | 0.531485 | 3.600677 | false | false | false | false |
bparish628/iFarm-Health | iOS/iFarm-Health/Pods/Charts/Source/Charts/Utils/ChartUtils.swift | 4 | 11984 | //
// Utils.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class ChartUtils
{
fileprivate static var _defaultValueFormatter: IValueFormatter = ChartUtils.generateDefaultValueFormatter()
internal struct Math
{
internal static let FDEG2RAD = CGFloat(Double.pi / 180.0)
internal static let FRAD2DEG = CGFloat(180.0 / Double.pi)
internal static let DEG2RAD = Double.pi / 180.0
internal static let RAD2DEG = 180.0 / Double.pi
}
internal class func roundToNextSignificant(number: Double) -> Double
{
if number.isInfinite || number.isNaN || number == 0
{
return number
}
let d = ceil(log10(number < 0.0 ? -number : number))
let pw = 1 - Int(d)
let magnitude = pow(Double(10.0), Double(pw))
let shifted = round(number * magnitude)
return shifted / magnitude
}
internal class func decimals(_ number: Double) -> Int
{
if number.isNaN || number.isInfinite || number == 0.0
{
return 0
}
let i = roundToNextSignificant(number: Double(number))
if i.isInfinite || i.isNaN
{
return 0
}
return Int(ceil(-log10(i))) + 2
}
internal class func nextUp(_ number: Double) -> Double
{
if number.isInfinite || number.isNaN
{
return number
}
else
{
return number + Double.ulpOfOne
}
}
/// Calculates the position around a center point, depending on the distance from the center, and the angle of the position around the center.
internal class func getPosition(center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint
{
return CGPoint(
x: center.x + dist * cos(angle * Math.FDEG2RAD),
y: center.y + dist * sin(angle * Math.FDEG2RAD)
)
}
open class func drawImage(
context: CGContext,
image: NSUIImage,
x: CGFloat,
y: CGFloat,
size: CGSize)
{
var drawOffset = CGPoint()
drawOffset.x = x - (size.width / 2)
drawOffset.y = y - (size.height / 2)
NSUIGraphicsPushContext(context)
if image.size.width != size.width && image.size.height != size.height
{
let key = "resized_\(size.width)_\(size.height)"
// Try to take scaled image from cache of this image
var scaledImage = objc_getAssociatedObject(image, key) as? NSUIImage
if scaledImage == nil
{
// Scale the image
NSUIGraphicsBeginImageContextWithOptions(size, false, 0.0)
image.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: size))
scaledImage = NSUIGraphicsGetImageFromCurrentImageContext()
NSUIGraphicsEndImageContext()
// Put the scaled image in a cache owned by the original image
objc_setAssociatedObject(image, key, scaledImage, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
scaledImage?.draw(in: CGRect(origin: drawOffset, size: size))
}
else
{
image.draw(in: CGRect(origin: drawOffset, size: size))
}
NSUIGraphicsPopContext()
}
open class func drawText(context: CGContext, text: String, point: CGPoint, align: NSTextAlignment, attributes: [NSAttributedStringKey : Any]?)
{
var point = point
if align == .center
{
point.x -= text.size(withAttributes: attributes).width / 2.0
}
else if align == .right
{
point.x -= text.size(withAttributes: attributes).width
}
NSUIGraphicsPushContext(context)
(text as NSString).draw(at: point, withAttributes: attributes)
NSUIGraphicsPopContext()
}
open class func drawText(context: CGContext, text: String, point: CGPoint, attributes: [NSAttributedStringKey : Any]?, anchor: CGPoint, angleRadians: CGFloat)
{
var drawOffset = CGPoint()
NSUIGraphicsPushContext(context)
if angleRadians != 0.0
{
let size = text.size(withAttributes: attributes)
// Move the text drawing rect in a way that it always rotates around its center
drawOffset.x = -size.width * 0.5
drawOffset.y = -size.height * 0.5
var translate = point
// Move the "outer" rect relative to the anchor, assuming its centered
if anchor.x != 0.5 || anchor.y != 0.5
{
let rotatedSize = sizeOfRotatedRectangle(size, radians: angleRadians)
translate.x -= rotatedSize.width * (anchor.x - 0.5)
translate.y -= rotatedSize.height * (anchor.y - 0.5)
}
context.saveGState()
context.translateBy(x: translate.x, y: translate.y)
context.rotate(by: angleRadians)
(text as NSString).draw(at: drawOffset, withAttributes: attributes)
context.restoreGState()
}
else
{
if anchor.x != 0.0 || anchor.y != 0.0
{
let size = text.size(withAttributes: attributes)
drawOffset.x = -size.width * anchor.x
drawOffset.y = -size.height * anchor.y
}
drawOffset.x += point.x
drawOffset.y += point.y
(text as NSString).draw(at: drawOffset, withAttributes: attributes)
}
NSUIGraphicsPopContext()
}
internal class func drawMultilineText(context: CGContext, text: String, knownTextSize: CGSize, point: CGPoint, attributes: [NSAttributedStringKey : Any]?, constrainedToSize: CGSize, anchor: CGPoint, angleRadians: CGFloat)
{
var rect = CGRect(origin: CGPoint(), size: knownTextSize)
NSUIGraphicsPushContext(context)
if angleRadians != 0.0
{
// Move the text drawing rect in a way that it always rotates around its center
rect.origin.x = -knownTextSize.width * 0.5
rect.origin.y = -knownTextSize.height * 0.5
var translate = point
// Move the "outer" rect relative to the anchor, assuming its centered
if anchor.x != 0.5 || anchor.y != 0.5
{
let rotatedSize = sizeOfRotatedRectangle(knownTextSize, radians: angleRadians)
translate.x -= rotatedSize.width * (anchor.x - 0.5)
translate.y -= rotatedSize.height * (anchor.y - 0.5)
}
context.saveGState()
context.translateBy(x: translate.x, y: translate.y)
context.rotate(by: angleRadians)
(text as NSString).draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
context.restoreGState()
}
else
{
if anchor.x != 0.0 || anchor.y != 0.0
{
rect.origin.x = -knownTextSize.width * anchor.x
rect.origin.y = -knownTextSize.height * anchor.y
}
rect.origin.x += point.x
rect.origin.y += point.y
(text as NSString).draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
}
NSUIGraphicsPopContext()
}
internal class func drawMultilineText(context: CGContext, text: String, point: CGPoint, attributes: [NSAttributedStringKey : Any]?, constrainedToSize: CGSize, anchor: CGPoint, angleRadians: CGFloat)
{
let rect = text.boundingRect(with: constrainedToSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
drawMultilineText(context: context, text: text, knownTextSize: rect.size, point: point, attributes: attributes, constrainedToSize: constrainedToSize, anchor: anchor, angleRadians: angleRadians)
}
/// - returns: An angle between 0.0 < 360.0 (not less than zero, less than 360)
internal class func normalizedAngleFromAngle(_ angle: CGFloat) -> CGFloat
{
var angle = angle
while (angle < 0.0)
{
angle += 360.0
}
return angle.truncatingRemainder(dividingBy: 360.0)
}
fileprivate class func generateDefaultValueFormatter() -> IValueFormatter
{
let formatter = DefaultValueFormatter(decimals: 1)
return formatter
}
/// - returns: The default value formatter used for all chart components that needs a default
open class func defaultValueFormatter() -> IValueFormatter
{
return _defaultValueFormatter
}
internal class func sizeOfRotatedRectangle(_ rectangleSize: CGSize, degrees: CGFloat) -> CGSize
{
let radians = degrees * Math.FDEG2RAD
return sizeOfRotatedRectangle(rectangleWidth: rectangleSize.width, rectangleHeight: rectangleSize.height, radians: radians)
}
internal class func sizeOfRotatedRectangle(_ rectangleSize: CGSize, radians: CGFloat) -> CGSize
{
return sizeOfRotatedRectangle(rectangleWidth: rectangleSize.width, rectangleHeight: rectangleSize.height, radians: radians)
}
internal class func sizeOfRotatedRectangle(rectangleWidth: CGFloat, rectangleHeight: CGFloat, degrees: CGFloat) -> CGSize
{
let radians = degrees * Math.FDEG2RAD
return sizeOfRotatedRectangle(rectangleWidth: rectangleWidth, rectangleHeight: rectangleHeight, radians: radians)
}
internal class func sizeOfRotatedRectangle(rectangleWidth: CGFloat, rectangleHeight: CGFloat, radians: CGFloat) -> CGSize
{
return CGSize(
width: abs(rectangleWidth * cos(radians)) + abs(rectangleHeight * sin(radians)),
height: abs(rectangleWidth * sin(radians)) + abs(rectangleHeight * cos(radians))
)
}
/// MARK: - Bridging functions
internal class func bridgedObjCGetNSUIColorArray (swift array: [NSUIColor?]) -> [NSObject]
{
var newArray = [NSObject]()
for val in array
{
if val == nil
{
newArray.append(NSNull())
}
else
{
newArray.append(val!)
}
}
return newArray
}
internal class func bridgedObjCGetNSUIColorArray (objc array: [NSObject]) -> [NSUIColor?]
{
var newArray = [NSUIColor?]()
for object in array
{
newArray.append(object as? NSUIColor)
}
return newArray
}
internal class func bridgedObjCGetStringArray (swift array: [String?]) -> [NSObject]
{
var newArray = [NSObject]()
for val in array
{
if val == nil
{
newArray.append(NSNull())
}
else
{
newArray.append(val! as NSObject)
}
}
return newArray
}
internal class func bridgedObjCGetStringArray (objc array: [NSObject]) -> [String?]
{
var newArray = [String?]()
for object in array
{
newArray.append(object as? String)
}
return newArray
}
}
| apache-2.0 | 2ac59d470a98af78b49ec56feb1aa86a | 32.568627 | 225 | 0.56759 | 5.116994 | false | false | false | false |
JanGorman/Chester | Chester/DefaultStringInterpolation+Chester.swift | 1 | 2956 | //
// Copyright © 2019 Jan Gorman. All rights reserved.
//
import Foundation
struct GraphQLEscapedString: LosslessStringConvertible {
var value: String
init?(_ description: String) {
self.value = description
}
var description: String {
value
}
}
struct GraphQLEscapedDictionary {
let value: [String: Any]
init(_ value: [String: Any]) {
self.value = value
}
}
struct GraphQLEscapedArray {
let value: [Any]
init(_ value: [Any]) {
self.value = value
}
}
extension DefaultStringInterpolation {
mutating func appendInterpolation(repeat str: String, _ count: Int) {
for _ in 0..<count {
appendInterpolation(str)
}
}
mutating func appendInterpolation(_ value: GraphQLEscapedString) {
appendInterpolation(#""\#(escape(string: value.description))""#)
}
/// Escape strings according to https://facebook.github.io/graphql/#sec-String-Value
/// - Parameter input: The string to escape
/// - Returns: The escaped string
private func escape(string input: String) -> String {
var output = ""
for scalar in input.unicodeScalars {
switch scalar {
case "\"":
output.append("\\\"")
case "\\":
output.append("\\\\")
case "\u{8}":
output.append("\\b")
case "\u{c}":
output.append("\\f")
case "\n":
output.append("\\n")
case "\r":
output.append("\\r")
case "\t":
output.append("\\t")
case UnicodeScalar(0x0)...UnicodeScalar(0xf), UnicodeScalar(0x10)...UnicodeScalar(0x1f):
output.append(String(format: "\\u%04x", scalar.value))
default:
output.append(Character(scalar))
}
}
return output
}
mutating func appendInterpolation(_ value: GraphQLEscapedDictionary) {
let output = value.value.map { key, value in
let serializedValue: String
if let value = value as? String, let escapable = GraphQLEscapedString(value) {
serializedValue = "\(escapable)"
} else if let value = value as? [String: Any] {
serializedValue = "\(GraphQLEscapedDictionary(value))"
} else if let value = value as? [Any] {
serializedValue = "\(GraphQLEscapedArray(value))"
} else {
serializedValue = "\(value)"
}
return "\(key): \(serializedValue)"
}.joined(separator: ",")
appendInterpolation("{\(output)}")
}
mutating func appendInterpolation(_ value: GraphQLEscapedArray) {
let output = value.value.map { element in
if let element = element as? String, let escapable = GraphQLEscapedString(element) {
return "\(escapable)"
} else if let element = element as? [String: Any] {
return "\(GraphQLEscapedDictionary(element))"
} else if let element = element as? [Any] {
return "\(GraphQLEscapedArray(element))"
}
return "\(element)"
}.joined(separator: ",")
appendInterpolation("[\(output)]")
}
}
| mit | fcbeb22ad64590e12fb60e7bc556f503 | 24.042373 | 94 | 0.615228 | 4.270231 | false | false | false | false |
brentsimmons/Evergreen | iOS/NavigationStateController.swift | 1 | 15821 | //
// NavigationModelController.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 4/21/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Foundation
import Account
import Articles
import RSCore
import RSTree
public extension Notification.Name {
static let MasterSelectionDidChange = Notification.Name(rawValue: "MasterSelectionDidChange")
static let BackingStoresDidRebuild = Notification.Name(rawValue: "BackingStoresDidRebuild")
static let ArticlesReinitialized = Notification.Name(rawValue: "ArticlesReinitialized")
static let ArticleDataDidChange = Notification.Name(rawValue: "ArticleDataDidChange")
static let ArticlesDidChange = Notification.Name(rawValue: "ArticlesDidChange")
static let ArticleSelectionDidChange = Notification.Name(rawValue: "ArticleSelectionDidChange")
}
class NavigationStateController {
static let fetchAndMergeArticlesQueue = CoalescingQueue(name: "Fetch and Merge Articles", interval: 0.5)
private var articleRowMap = [String: Int]() // articleID: rowIndex
private var animatingChanges = false
private var expandedNodes = [Node]()
private var shadowTable = [[Node]]()
private var sortDirection = AppDefaults.timelineSortDirection {
didSet {
if sortDirection != oldValue {
sortDirectionDidChange()
}
}
}
private let treeControllerDelegate = FeedTreeControllerDelegate()
lazy var treeController: TreeController = {
return TreeController(delegate: treeControllerDelegate)
}()
var rootNode: Node {
return treeController.rootNode
}
var numberOfSections: Int {
return shadowTable.count
}
var currentMasterIndexPath: IndexPath? {
didSet {
guard let ip = currentMasterIndexPath, let node = nodeFor(ip) else {
assertionFailure()
return
}
if let fetcher = node.representedObject as? ArticleFetcher {
timelineFetcher = fetcher
}
NotificationCenter.default.post(name: .MasterSelectionDidChange, object: self, userInfo: nil)
}
}
var timelineName: String? {
return (timelineFetcher as? DisplayNameProvider)?.nameForDisplay
}
var timelineFetcher: ArticleFetcher? {
didSet {
currentArticleIndexPath = nil
if timelineFetcher is Feed {
showFeedNames = false
} else {
showFeedNames = true
}
fetchArticles()
NotificationCenter.default.post(name: .ArticlesReinitialized, object: self, userInfo: nil)
}
}
var showFeedNames = false
var showAvatars = false
var isPrevArticleAvailable: Bool {
guard let indexPath = currentArticleIndexPath else {
return false
}
return indexPath.row > 0
}
var isNextArticleAvailable: Bool {
guard let indexPath = currentArticleIndexPath else {
return false
}
return indexPath.row + 1 < articles.count
}
var prevArticleIndexPath: IndexPath? {
guard let indexPath = currentArticleIndexPath else {
return nil
}
return IndexPath(row: indexPath.row - 1, section: indexPath.section)
}
var nextArticleIndexPath: IndexPath? {
guard let indexPath = currentArticleIndexPath else {
return nil
}
return IndexPath(row: indexPath.row + 1, section: indexPath.section)
}
var firstUnreadArticleIndexPath: IndexPath? {
for (row, article) in articles.enumerated() {
if !article.status.read {
return IndexPath(row: row, section: 0)
}
}
return nil
}
var currentArticle: Article? {
if let indexPath = currentArticleIndexPath {
return articles[indexPath.row]
}
return nil
}
var currentArticleIndexPath: IndexPath? {
didSet {
if currentArticleIndexPath != oldValue {
NotificationCenter.default.post(name: .ArticleSelectionDidChange, object: self, userInfo: nil)
}
}
}
var articles = ArticleArray() {
didSet {
if articles == oldValue {
return
}
if articles.representSameArticlesInSameOrder(as: oldValue) {
articleRowMap = [String: Int]()
NotificationCenter.default.post(name: .ArticleDataDidChange, object: self, userInfo: nil)
return
}
updateShowAvatars()
articleRowMap = [String: Int]()
NotificationCenter.default.post(name: .ArticlesDidChange, object: self, userInfo: nil)
}
}
var isTimelineUnreadAvailable: Bool {
if let unreadProvider = timelineFetcher as? UnreadCountProvider {
return unreadProvider.unreadCount > 0
}
return false
}
var isAnyUnreadAvailable: Bool {
return appDelegate.unreadCount > 0
}
init() {
for section in treeController.rootNode.childNodes {
expandedNodes.append(section)
shadowTable.append([Node]())
}
rebuildShadowTable()
NotificationCenter.default.addObserver(self, selector: #selector(containerChildrenDidChange(_:)), name: .ChildrenDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(batchUpdateDidPerform(_:)), name: .BatchUpdateDidPerform, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountStateDidChange(_:)), name: .AccountStateDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .AccountsDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountDidDownloadArticles(_:)), name: .AccountDidDownloadArticles, object: nil)
}
// MARK: Notifications
@objc func containerChildrenDidChange(_ note: Notification) {
rebuildBackingStores()
}
@objc func batchUpdateDidPerform(_ notification: Notification) {
rebuildBackingStores()
}
@objc func displayNameDidChange(_ note: Notification) {
rebuildBackingStores()
}
@objc func accountStateDidChange(_ note: Notification) {
rebuildBackingStores()
}
@objc func accountsDidChange(_ note: Notification) {
rebuildBackingStores()
}
@objc func userDefaultsDidChange(_ note: Notification) {
self.sortDirection = AppDefaults.timelineSortDirection
}
@objc func accountDidDownloadArticles(_ note: Notification) {
guard let feeds = note.userInfo?[Account.UserInfoKey.feeds] as? Set<Feed> else {
return
}
let shouldFetchAndMergeArticles = timelineFetcherContainsAnyFeed(feeds) || timelineFetcherContainsAnyPseudoFeed()
if shouldFetchAndMergeArticles {
queueFetchAndMergeArticles()
}
}
// MARK: API
func beginUpdates() {
animatingChanges = true
}
func endUpdates() {
animatingChanges = false
}
func rowsInSection(_ section: Int) -> Int {
return shadowTable[section].count
}
func rebuildShadowTable() {
shadowTable = [[Node]]()
for i in 0..<treeController.rootNode.numberOfChildNodes {
var result = [Node]()
if let nodes = treeController.rootNode.childAtIndex(i)?.childNodes {
for node in nodes {
result.append(node)
if expandedNodes.contains(node) {
for child in node.childNodes {
result.append(child)
}
}
}
}
shadowTable.append(result)
}
}
func isExpanded(_ node: Node) -> Bool {
return expandedNodes.contains(node)
}
func nodeFor(_ indexPath: IndexPath) -> Node? {
guard indexPath.section < shadowTable.count || indexPath.row < shadowTable[indexPath.section].count else {
return nil
}
return shadowTable[indexPath.section][indexPath.row]
}
func indexPathFor(_ node: Node) -> IndexPath? {
for i in 0..<shadowTable.count {
if let row = shadowTable[i].firstIndex(of: node) {
return IndexPath(row: row, section: i)
}
}
return nil
}
func expand(section: Int, completion: ([IndexPath]) -> ()) {
guard let expandNode = treeController.rootNode.childAtIndex(section) else {
return
}
expandedNodes.append(expandNode)
animatingChanges = true
var indexPathsToInsert = [IndexPath]()
var i = 0
func addNode(_ node: Node) {
indexPathsToInsert.append(IndexPath(row: i, section: section))
shadowTable[section].insert(node, at: i)
i = i + 1
}
for child in expandNode.childNodes {
addNode(child)
if expandedNodes.contains(child) {
for gChild in child.childNodes {
addNode(gChild)
}
}
}
completion(indexPathsToInsert)
animatingChanges = false
}
func expand(_ indexPath: IndexPath, completion: ([IndexPath]) -> ()) {
let expandNode = shadowTable[indexPath.section][indexPath.row]
expandedNodes.append(expandNode)
animatingChanges = true
var indexPathsToInsert = [IndexPath]()
for i in 0..<expandNode.childNodes.count {
if let child = expandNode.childAtIndex(i) {
let nextIndex = indexPath.row + i + 1
indexPathsToInsert.append(IndexPath(row: nextIndex, section: indexPath.section))
shadowTable[indexPath.section].insert(child, at: nextIndex)
}
}
completion(indexPathsToInsert)
animatingChanges = false
}
func collapse(section: Int, completion: ([IndexPath]) -> ()) {
animatingChanges = true
guard let collapseNode = treeController.rootNode.childAtIndex(section) else {
return
}
if let removeNode = expandedNodes.firstIndex(of: collapseNode) {
expandedNodes.remove(at: removeNode)
}
var indexPathsToRemove = [IndexPath]()
for i in 0..<shadowTable[section].count {
indexPathsToRemove.append(IndexPath(row: i, section: section))
}
shadowTable[section] = [Node]()
completion(indexPathsToRemove)
animatingChanges = false
}
func collapse(_ indexPath: IndexPath, completion: ([IndexPath]) -> ()) {
animatingChanges = true
let collapseNode = shadowTable[indexPath.section][indexPath.row]
if let removeNode = expandedNodes.firstIndex(of: collapseNode) {
expandedNodes.remove(at: removeNode)
}
var indexPathsToRemove = [IndexPath]()
for child in collapseNode.childNodes {
if let index = shadowTable[indexPath.section].firstIndex(of: child) {
indexPathsToRemove.append(IndexPath(row: index, section: indexPath.section))
}
}
for child in collapseNode.childNodes {
if let index = shadowTable[indexPath.section].firstIndex(of: child) {
shadowTable[indexPath.section].remove(at: index)
}
}
completion(indexPathsToRemove)
animatingChanges = false
}
func indexesForArticleIDs(_ articleIDs: Set<String>) -> IndexSet {
var indexes = IndexSet()
articleIDs.forEach { (articleID) in
guard let oneIndex = row(for: articleID) else {
return
}
if oneIndex != NSNotFound {
indexes.insert(oneIndex)
}
}
return indexes
}
func selectNextUnread() {
// This should never happen, but I don't want to risk throwing us
// into an infinate loop searching for an unread that isn't there.
if appDelegate.unreadCount < 1 {
return
}
if selectNextUnreadArticleInTimeline() {
return
}
selectNextUnreadFeedFetcher()
selectNextUnreadArticleInTimeline()
}
}
private extension NavigationStateController {
func rebuildBackingStores() {
if !animatingChanges && !BatchUpdate.shared.isPerforming {
treeController.rebuild()
rebuildShadowTable()
NotificationCenter.default.post(name: .BackingStoresDidRebuild, object: self, userInfo: nil)
}
}
func updateShowAvatars() {
if showFeedNames {
self.showAvatars = true
return
}
for article in articles {
if let authors = article.authors {
for author in authors {
if author.avatarURL != nil {
self.showAvatars = true
return
}
}
}
}
self.showAvatars = false
}
// MARK: Select Next Unread
@discardableResult
func selectNextUnreadArticleInTimeline() -> Bool {
let startingRow: Int = {
if let indexPath = currentArticleIndexPath {
return indexPath.row
} else {
return 0
}
}()
for i in startingRow..<articles.count {
let article = articles[i]
if !article.status.read {
currentArticleIndexPath = IndexPath(row: i, section: 0)
return true
}
}
return false
}
func selectNextUnreadFeedFetcher() {
guard let indexPath = currentMasterIndexPath else {
assertionFailure()
return
}
// Increment or wrap around the IndexPath
let nextIndexPath: IndexPath = {
if indexPath.row + 1 >= shadowTable[indexPath.section].count {
if indexPath.section + 1 >= shadowTable.count {
return IndexPath(row: 0, section: 0)
} else {
return IndexPath(row: 0, section: indexPath.section + 1)
}
} else {
return IndexPath(row: indexPath.row + 1, section: indexPath.section)
}
}()
if selectNextUnreadFeedFetcher(startingWith: nextIndexPath) {
return
}
selectNextUnreadFeedFetcher(startingWith: IndexPath(row: 0, section: 0))
}
@discardableResult
func selectNextUnreadFeedFetcher(startingWith indexPath: IndexPath) -> Bool {
for i in indexPath.section..<shadowTable.count {
for j in indexPath.row..<shadowTable[indexPath.section].count {
let nextIndexPath = IndexPath(row: j, section: i)
guard let node = nodeFor(nextIndexPath), let unreadCountProvider = node.representedObject as? UnreadCountProvider else {
assertionFailure()
return true
}
if expandedNodes.contains(node) {
continue
}
if unreadCountProvider.unreadCount > 0 {
currentMasterIndexPath = nextIndexPath
return true
}
}
}
return false
}
// MARK: Fetching Articles
func fetchArticles() {
guard let timelineFetcher = timelineFetcher else {
articles = ArticleArray()
return
}
let fetchedArticles = timelineFetcher.fetchArticles()
updateArticles(with: fetchedArticles)
}
func emptyTheTimeline() {
if !articles.isEmpty {
articles = [Article]()
}
}
func sortDirectionDidChange() {
updateArticles(with: Set(articles))
}
func updateArticles(with unsortedArticles: Set<Article>) {
let sortedArticles = Array(unsortedArticles).sortedByDate(sortDirection)
if articles != sortedArticles {
articles = sortedArticles
}
}
func row(for articleID: String) -> Int? {
updateArticleRowMapIfNeeded()
return articleRowMap[articleID]
}
func updateArticleRowMap() {
var rowMap = [String: Int]()
var index = 0
articles.forEach { (article) in
rowMap[article.articleID] = index
index += 1
}
articleRowMap = rowMap
}
func updateArticleRowMapIfNeeded() {
if articleRowMap.isEmpty {
updateArticleRowMap()
}
}
func queueFetchAndMergeArticles() {
NavigationStateController.fetchAndMergeArticlesQueue.add(self, #selector(fetchAndMergeArticles))
}
@objc func fetchAndMergeArticles() {
guard let timelineFetcher = timelineFetcher else {
return
}
var unsortedArticles = timelineFetcher.fetchArticles()
// Merge articles by articleID. For any unique articleID in current articles, add to unsortedArticles.
let unsortedArticleIDs = unsortedArticles.articleIDs()
for article in articles {
if !unsortedArticleIDs.contains(article.articleID) {
unsortedArticles.insert(article)
}
}
updateArticles(with: unsortedArticles)
}
func timelineFetcherContainsAnyPseudoFeed() -> Bool {
if timelineFetcher is PseudoFeed {
return true
}
return false
}
func timelineFetcherContainsAnyFeed(_ feeds: Set<Feed>) -> Bool {
// Return true if there’s a match or if a folder contains (recursively) one of feeds
if let feed = timelineFetcher as? Feed {
for oneFeed in feeds {
if feed.feedID == oneFeed.feedID || feed.url == oneFeed.url {
return true
}
}
} else if let folder = timelineFetcher as? Folder {
for oneFeed in feeds {
if folder.hasFeed(with: oneFeed.feedID) || folder.hasFeed(withURL: oneFeed.url) {
return true
}
}
}
return false
}
}
| mit | 3b711fcf067d77beb3b61a4c14d9bf8c | 23.448223 | 149 | 0.71052 | 4.003543 | false | false | false | false |
deonisiy162980/PinButton | PinButton/PinButton.swift | 1 | 7820 | //
// PinButton.swift
// DLS
//
// Created by Denis on 08.02.17.
// Copyright © 2017 Denis Petrov. All rights reserved.
//
import UIKit
@IBDesignable public class PinButton: UIButton
{
fileprivate var gradient = CAGradientLayer()
fileprivate var colorsForGradient = [UIColor.yellow, UIColor.blue]
fileprivate var subText : UILabel!
fileprivate var buttonInTouchState = false
@IBInspectable
public var subTextOffset : CGFloat = 5
{
didSet {
subText.frame = CGRect(x: self.bounds.width / 2 - subText.bounds.width / 2,
y: self.bounds.height / 2 + subText.bounds.height / 2 + subTextOffset,
width: subText.bounds.width,
height: subText.bounds.height)
}
}
@IBInspectable
public var numberOffset : CGFloat = 10 {
didSet {
self.titleEdgeInsets = UIEdgeInsetsMake(-numberOffset, 0.0, 0.0, 0.0)
}
}
@IBInspectable
public var subTextColor : UIColor = UIColor.white
{
didSet {
subText.textColor = subTextColor
}
}
@IBInspectable
public var borderColor : UIColor = UIColor.white
{
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable
public var subTextSize : CGFloat = 10
{
didSet {
subText.font = UIFont.systemFont(ofSize: subTextSize, weight: UIFontWeightThin)
}
}
@IBInspectable
public var borderWidth : CGFloat = 1
{
didSet {
self.layer.borderWidth = borderWidth
}
}
@IBInspectable
public var needSubText : Bool = true
{
didSet {
addOrUpdateSubText()
}
}
@IBInspectable
public var beginColor : UIColor = .clear
{
didSet {
let newGradient : [UIColor] = [beginColor, colorsForGradient.last!]
colorsForGradient = newGradient
configure()
}
}
@IBInspectable
public var endColor : UIColor = .clear
{
didSet {
let newGradient : [UIColor] = [colorsForGradient.first!, endColor]
colorsForGradient = newGradient
configure()
}
}
@IBInspectable
public var gradientAlpha : Float = 0.7
{
didSet {
configure()
}
}
@IBInspectable
public var showGradient : Bool = false
{
didSet {
configure()
}
}
@IBInspectable
public var animDuration : Double = 0.09
{
didSet {
}
}
//MARK: Initializers
override public init(frame : CGRect)
{
super.init(frame : frame)
setup()
configure()
}
convenience public init()
{
self.init(frame:CGRect.zero)
setup()
configure()
}
required public init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
setup()
configure()
}
override public func awakeFromNib()
{
super.awakeFromNib()
setup()
configure()
}
override public func prepareForInterfaceBuilder()
{
super.prepareForInterfaceBuilder()
setup()
configure()
}
override public func layoutSublayers(of layer: CALayer)
{
super.layoutSublayers(of: layer)
configure()
}
}
//MARK: - EVENTS
public extension PinButton
{
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
super.touchesBegan(touches, with: event)
buttonInTouchState = true
let animation = CABasicAnimation()
animation.fromValue = 0
animation.toValue = gradientAlpha
animation.duration = animDuration
gradient.opacity = gradientAlpha
gradient.add(animation, forKey: "opacity")
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
super.touchesEnded(touches, with: event)
let animation = CABasicAnimation()
animation.fromValue = gradientAlpha
animation.toValue = 0
animation.duration = animDuration + 0.3
gradient.opacity = 0.0
gradient.add(animation, forKey: "opacity")
buttonInTouchState = false
}
}
//MARK: - ADD SUB TEXT
public extension PinButton
{
fileprivate func addOrUpdateSubText()
{
if needSubText
{
if subText == nil
{
subText = UILabel()
subText.font = UIFont.systemFont(ofSize: subTextSize, weight: UIFontWeightThin)
subText.textColor = subTextColor
#if TARGET_INTERFACE_BUILDER
subText.text = "ABC"
#else
subText.text = getSubTextForButton()
#endif
subText.sizeToFit()
subText.frame = CGRect(x: self.bounds.width / 2 - subText.bounds.width / 2,
y: self.bounds.height / 2 + subText.bounds.height / 2 + subTextOffset,
width: subText.bounds.width,
height: subText.bounds.height)
self.insertSubview(subText, aboveSubview: self)
}
else
{
subText.frame = CGRect(x: self.bounds.width / 2 - subText.bounds.width / 2,
y: self.bounds.height / 2 + subText.bounds.height / 2 + subTextOffset,
width: subText.bounds.width,
height: subText.bounds.height)
}
}
else
{
if subText != nil
{
subText.removeFromSuperview()
subText = nil
}
}
}
fileprivate func getSubTextForButton() -> String
{
switch self.tag
{
case 2:
return "ABC"
case 3:
return "DEF"
case 4:
return "GHI"
case 5:
return "JKL"
case 6:
return "MNO"
case 7:
return "PQRS"
case 8:
return "TUV"
case 9:
return "WXYZ"
default:
return ""
}
}
}
//MARK: - SETUP AND CONFIGURE
public extension PinButton
{
fileprivate func setup()
{
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor.cgColor
self.layer.cornerRadius = self.bounds.width / 2
self.titleEdgeInsets = UIEdgeInsetsMake(-numberOffset, 0.0, 0.0, 0.0)
gradient.frame = CGRect(x: 0, y: 0, width: self.bounds.width - borderWidth, height: self.bounds.height - borderWidth)
gradient.cornerRadius = gradient.bounds.width / 2
if showGradient { gradient.opacity = gradientAlpha } else { gradient.opacity = 0.0 }
self.layer.insertSublayer(gradient, at: 0)
self.setTitle("\(self.tag)", for: .normal)
}
fileprivate func configure()
{
self.layer.cornerRadius = self.bounds.width / 2
gradient.cornerRadius = gradient.bounds.width / 2
gradient.frame = CGRect(x: 0, y: 0, width: self.bounds.width - borderWidth, height: self.bounds.height - borderWidth)
gradient.colors = colorsForGradient.map { $0.cgColor }
addOrUpdateSubText()
}
}
| mit | d0836d50f09cd31bd0cb7042986dc376 | 25.063333 | 125 | 0.525771 | 5.070687 | false | false | false | false |
xsunsmile/TwitterApp | Twitter/TweetReplyViewController.swift | 1 | 2082 | //
// TweetReplyViewController.swift
// Twitter
//
// Created by Hao Sun on 2/22/15.
// Copyright (c) 2015 Hao Sun. All rights reserved.
//
import UIKit
class TweetReplyViewController: UIViewController {
var tweet: Tweet?
@IBOutlet weak var tweetTextView: UITextView!
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var userScreenNameLabel: UILabel!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tweetTextView.becomeFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
var user = User.currentUser
userImageView.setImageWithURL(user?.imageUrl())
userNameLabel.text = user?.name()
userScreenNameLabel.text = user?.screenName()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func onCancel(sender: AnyObject) {
navigationController?.popViewControllerAnimated(true)
}
@IBAction func onTweet(sender: AnyObject) {
if tweet != nil {
tweet!.replyTweetWithMessage(tweetTextView.text)
} else {
var params = [ "status": tweetTextView.text ]
TwitterClient.sharedInstance.performPOSTWithCompletion("1.1/statuses/update.json", params: params, completion: { (result, error) -> Void in
if result != nil {
println("posted message")
} else {
println("got error: \(error)")
}
})
}
navigationController?.popViewControllerAnimated(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | dcccc621a788235b35f34e74a281e5f4 | 30.074627 | 151 | 0.636407 | 5.218045 | false | false | false | false |
lukevanin/OCRAI | CardScanner/PostalAddress.swift | 1 | 2457 | //
// Location.swift
// CardScanner
//
// Created by Luke Van In on 2017/03/28.
// Copyright © 2017 Luke Van In. All rights reserved.
//
import Foundation
import CoreData
import CoreLocation
import Contacts
private let entityName = "PostalAddress"
extension PostalAddress: Actionable {
var actionsTitle: String? {
return "Postal Address"
}
var actionsDescription: String? {
return String(describing: self)
}
var actions: [Action] {
return [
ShowAddressAction(address: self.address, coordinate: self.location),
CopyTextAction(text: description),
ShareAction(items: [description])
// DeleteAction(object: self, context: self.managedObjectContext!)
]
}
}
extension PostalAddress {
public override var description: String {
return CNPostalAddressFormatter.string(from: self.address, style: .mailingAddress)
}
}
extension PostalAddress {
var address: CNPostalAddress {
get {
let output = CNMutablePostalAddress()
output.street = street ?? ""
output.city = city ?? ""
output.postalCode = postalCode ?? ""
output.country = country ?? ""
return output
}
set {
street = newValue.street
city = newValue.city
postalCode = newValue.postalCode
country = newValue.country
}
}
var location: CLLocationCoordinate2D? {
get {
guard hasCoordinate else {
return nil
}
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
set {
guard let value = newValue else {
hasCoordinate = false
return
}
hasCoordinate = true
latitude = value.latitude
longitude = value.longitude
}
}
convenience init(address: CNPostalAddress? = nil, location: CLLocationCoordinate2D? = nil, context: NSManagedObjectContext) {
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else {
fatalError("Cannot initialize entity \(entityName)")
}
self.init(entity: entity, insertInto: context)
if let address = address {
self.address = address
}
self.location = location
}
}
| mit | 4c8ade0b8eb036d9e98e8f8f10428127 | 26.595506 | 129 | 0.586319 | 5.170526 | false | false | false | false |
radu-costea/ATests | ATests/ATests/UI/EditMixedContentViewController.swift | 1 | 2937 | //
// EditMixedContentViewController.swift
// ATests
//
// Created by Radu Costea on 29/05/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import UIKit
class EditMixedContentViewController: EditContentController, ContentProviderDelegate {
var imageObject: MixedContentObject?
var image: UIImage?
var text: String?
@IBOutlet var imageView: UIImageView!
@IBOutlet var textView: UILabel!
lazy var imageProvider: PhotoViewController! = { [unowned self] in
let provider = PhotoViewController.photoProvider(self.image)
provider?.delegate = self
return provider
}()
lazy var textProvider: TextProviderViewController! = {
let provider = TextProviderViewController.textProvider(self.text)
provider?.delegate = self
return provider
}()
func loadImage() {
if let data = imageObject?.base64Image?.toBase64Data(),
let img = UIImage(data: data) {
image = img
imageProvider.loadWith(img)
}
}
override func loadWith<T : RawContent>(content: T?) {
if let mixed = content as? MixedRawContent {
image = mixed.image
text = mixed.text
}
}
/// MARK: -
/// MARK: Class
override static var storyboardName: String { return "EditQuestionStoryboard" }
override static var storyboardId: String { return "editMixed" }
/// MARK: -
/// MARK: Actions
@IBAction func didTapOnImageContent(sender: AnyObject?) {
presentViewController(self.imageProvider, animated: true, completion: nil)
}
@IBAction func didTapOnTextContent(sender: AnyObject?) {
startEditing()
}
/// MARK: -
/// MARK: Actions
override func startEditing() {
presentViewController(self.textProvider, animated: true, completion: nil)
}
/// MARK: -
/// MARK: Content Provider Delegate
func contentProvider<Provider: ContentProvider>(provider: Provider, finishedLoadingWith content: Provider.ContentType?) -> Void {
if let currentProvider = provider as? PhotoViewController,
let img = content as? UIImage {
currentProvider.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
imageView.image = img
}
if let currentProvider = provider as? TextProviderViewController,
let txt = content as? String {
currentProvider.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
textView.text = txt
}
}
}
extension EditContentFabric {
// class func mixedController(mixed: MixedRawContent?) -> EditMixedContentViewController? {
// return EditMixedContentViewController.editController(mixed) as? EditMixedContentViewController
// }
}
| mit | f653c31f153ef644226fac89e07ee070 | 30.569892 | 141 | 0.642371 | 5.338182 | false | false | false | false |
auth0/Auth0.swift | Auth0Tests/CredentialsManagerErrorSpec.swift | 1 | 5806 | import Foundation
import Quick
import Nimble
@testable import Auth0
class CredentialsManagerErrorSpec: QuickSpec {
override func spec() {
describe("init") {
it("should initialize with code") {
let error = CredentialsManagerError(code: .noCredentials)
expect(error.code) == CredentialsManagerError.Code.noCredentials
expect(error.cause).to(beNil())
}
it("should initialize with code & cause") {
let cause = AuthenticationError(description: "")
let error = CredentialsManagerError(code: .noCredentials, cause: cause)
expect(error.cause).to(matchError(cause))
}
}
describe("operators") {
it("should be equal by code") {
let error = CredentialsManagerError(code: .noCredentials)
expect(error) == CredentialsManagerError.noCredentials
}
it("should not be equal to an error with a different code") {
let error = CredentialsManagerError(code: .noCredentials)
expect(error) != CredentialsManagerError.noRefreshToken
}
it("should not be equal to an error with a different description") {
let error = CredentialsManagerError(code: .largeMinTTL(minTTL: 1000, lifetime: 500))
expect(error) != CredentialsManagerError(code: .largeMinTTL(minTTL: 2000, lifetime: 1000))
}
it("should pattern match by code") {
let error = CredentialsManagerError(code: .noCredentials)
expect(error ~= CredentialsManagerError.noCredentials) == true
}
it("should not pattern match by code with a different error") {
let error = CredentialsManagerError(code: .noCredentials)
expect(error ~= CredentialsManagerError.noRefreshToken) == false
}
it("should pattern match by code with a generic error") {
let error = CredentialsManagerError(code: .noCredentials)
expect(error ~= (CredentialsManagerError.noCredentials) as Error) == true
}
it("should not pattern match by code with a different generic error") {
let error = CredentialsManagerError(code: .noCredentials)
expect(error ~= (CredentialsManagerError.noRefreshToken) as Error) == false
}
}
describe("debug description") {
it("should match the localized message") {
let error = CredentialsManagerError(code: .noCredentials)
expect(error.debugDescription) == CredentialsManagerError.noCredentials.debugDescription
}
it("should match the error description") {
let error = CredentialsManagerError(code: .noCredentials)
expect(error.debugDescription) == CredentialsManagerError.noCredentials.errorDescription
}
}
describe("error message") {
it("should return message for no credentials") {
let message = "No credentials were found in the store."
let error = CredentialsManagerError(code: .noCredentials)
expect(error.localizedDescription) == message
}
it("should return message for no refresh token") {
let message = "The stored credentials instance does not contain a refresh token."
let error = CredentialsManagerError(code: .noRefreshToken)
expect(error.localizedDescription) == message
}
it("should return message for renew failed") {
let message = "The credentials renewal failed."
let error = CredentialsManagerError(code: .renewFailed)
expect(error.localizedDescription) == message
}
it("should return message for store failed") {
let message = "Storing the renewed credentials failed."
let error = CredentialsManagerError(code: .storeFailed)
expect(error.localizedDescription) == message
}
it("should return message for biometrics failed") {
let message = "The biometric authentication failed."
let error = CredentialsManagerError(code: .biometricsFailed)
expect(error.localizedDescription) == message
}
it("should return message for revoke failed") {
let message = "The revocation of the refresh token failed."
let error = CredentialsManagerError(code: .revokeFailed)
expect(error.localizedDescription) == message
}
it("should return message when minTTL is too big") {
let minTTL = 7200
let lifetime = 3600
let message = "The minTTL requested (\(minTTL)s) is greater than the"
+ " lifetime of the renewed access token (\(lifetime)s). Request a lower minTTL or increase the"
+ " 'Token Expiration' value in the settings page of your Auth0 API."
let error = CredentialsManagerError(code: .largeMinTTL(minTTL: minTTL, lifetime: lifetime))
expect(error.localizedDescription) == message
}
it("should append the cause error message") {
let cause = MockError()
let message = "The revocation of the refresh token failed. CAUSE: \(cause.localizedDescription)"
let error = CredentialsManagerError(code: .revokeFailed, cause: cause)
expect(error.localizedDescription) == message
}
}
}
}
| mit | b57f30973d7f526566ee2c4f5ad08685 | 40.769784 | 112 | 0.592146 | 5.858729 | false | false | false | false |
yaobanglin/viossvc | viossvc/Scenes/User/PhotoPreviewView.swift | 2 | 2341 | //
// PhotoPreviewView.swift
// viossvc
//
// Created by 陈奕涛 on 16/12/3.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import Foundation
import SnapKit
class PhotoPreviewView: UIView {
private static var view = PhotoPreviewView.init(frame: UIScreen.mainScreen().bounds)
class func defaultView() ->PhotoPreviewView {
view.tag = 196349143
return view
}
var photoInfo:PhotoModel?
var photo:UIImageView?
static func showOnline(photoInfo: PhotoModel) {
let view = PhotoPreviewView.defaultView()
view.setPhotoInfoModel(photoInfo)
UIApplication.sharedApplication().keyWindow?.addSubview(view)
}
static func showLocal(image: UIImage) {
let view = PhotoPreviewView.defaultView()
view.photo?.image = image
UIApplication.sharedApplication().keyWindow?.addSubview(view)
}
static func update(image: UIImage) {
if let view = UIApplication.sharedApplication().keyWindow?.viewWithTag(196349143) as? PhotoPreviewView {
dispatch_async(dispatch_get_main_queue(), { () in
view.photo?.image = image
})
}
}
override init(frame: CGRect) {
super.init(frame: frame)
userInteractionEnabled = true
backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.7)
let gst = UITapGestureRecognizer()
gst.addTarget(self, action: #selector(touched(_:)))
addGestureRecognizer(gst)
createView()
}
func touched(sender: UITapGestureRecognizer) {
PhotoPreviewView.defaultView().removeFromSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createView() {
photo = UIImageView()
photo?.contentMode = .ScaleAspectFit
addSubview(photo!)
photo?.snp_makeConstraints(closure: { (make) in
make.edges.equalTo(self)
})
}
func setPhotoInfoModel(info: PhotoModel) {
photoInfo = info
photo?.kf_setImageWithURL(NSURL(string: photoInfo!.thumbnail_url!))
if photoInfo?.photo_url != nil {
photo?.kf_setImageWithURL(NSURL(string: photoInfo!.photo_url!))
}
}
}
| apache-2.0 | f934afdc2e225b8a61c0260351bee773 | 27.790123 | 112 | 0.62693 | 4.858333 | false | false | false | false |
Eonil/Monolith.Swift | ParsingEngine/Sources/Rule.swift | 3 | 7126 | //
// Rule.swift
// EDXC
//
// Created by Hoon H. on 10/14/14.
// Copyright (c) 2014 Eonil. All rights reserved.
//
import Foundation
public class Rule {
public typealias Composition = (cursor:Cursor) -> Stepping
let name:String
let composition:Composition
init(name:String, composition:Composition) {
self.name = name
self.composition = composition
}
var description:String {
get {
return name
}
}
func parse(cursor:Cursor) -> Stepping {
func resolutionNode(p1:Stepping) -> Stepping.Node {
assert(p1.match)
func resolveSubnodes(ns1:NodeList) -> NodeList {
assert(ns1.count > 0)
return ns1.filter({ n in return n.origin != nil })
}
func resolveRange(ns1:NodeList) -> (start:Cursor, end:Cursor) {
let nz1 = ns1.count > 0
let c1 = nz1 ? ns1.first!.startCursor : p1.location
let c2 = nz1 ? ns1.last!.endCursor : p1.location
assert(c2 == p1.location)
return (c1, c2)
}
let ns1 = p1.nodes
let ns2 = ns1.count == 0 ? NodeList() : resolveSubnodes(ns1)
let cs2 = resolveRange(ns1)
let n2 = Stepping.Node(start: cs2.start, end: cs2.end, origin: self, subnodes: ns2)
return n2
}
let p1 = composition(cursor: cursor)
return p1.match == false ? p1 : Stepping.match(location: p1.location, nodes: NodeList([resolutionNode(p1)]))
}
public enum Component {
public static func literal(string:String) -> Composition {
var a1 = [] as [Character]
for ch in string {
a1 += [ch]
}
let a2 = a1.map({ n in return self.pattern(Pattern.one(n)) }) as [Composition]
let s1 = sequence(a2)
return s1
}
public static func pattern(pattern:Pattern.Test)(cursor:Cursor) -> Stepping {
let ok = pattern(cursor.current)
if ok {
let c2 = cursor.continuation
let n1 = Stepping.Node(start: cursor, end:c2)
return Stepping.match(location: c2, nodes: NodeList([n1]))
}
return Stepping.mismatch(location: cursor)
}
public static func subrule(r1:Rule)(cursor:Cursor) -> Stepping {
return r1.parse(cursor)
}
/// A marker component marks special concern.
/// If a marker component discovered at an expected position
/// then the syntax rule becomes *requirement*, and the
/// rule pattern recognition will emit errors rather than
/// skipping on unmatching on other parts.
/// Usually keywords and punctuators are marked using this.
/// This is the only way to produce errors.
public static func expect(composition c1:Composition, expectation e1:String?)(cursor:Cursor) -> Stepping {
let p1 = c1(cursor: cursor)
let p2 = p1.match ? p1.remark(Node.Mark(expectation: e1)) : p1
return p2
}
public static func mark(composition c1:Composition)(cursor:Cursor) -> Stepping {
let p1 = c1(cursor: cursor)
let p2 = p1.match ? p1.remark(Node.Mark(expectation: nil)) : p1
return p2
}
/// if `require` is `true`, repetition with insufficient occurrence will be treated as error
/// instead of non-matching.
static func sequence(components:[Composition])(cursor:Cursor) -> Stepping {
assert(components.count > 0)
var c2 = cursor
var ns1 = NodeList()
for comp in components {
/// Exit immediately on unexpected end of source.
if c2.available == false {
/// Add an error if marked at current level.
if ns1.marking {
return Stepping.error(location: c2, nodes: ns1, message: "Some component is marked, and unexpected end of stream has been found.")
}
return Stepping.mismatch(location: c2)
}
let p1 = comp(cursor: c2)
c2 = p1.location
ns1 += p1.nodes ||| NodeList()
assert(ns1.count == 0 || c2 >= ns1.last!.endCursor)
/// Exit early on any error.
if p1.error {
return p1
}
/// Exit early on any mismatch.
if p1.mismatch {
/// Add an error if marked at current level.
if ns1.marking {
return Stepping.error(location: c2, nodes: ns1, message: "Some node is marked, but current sequence was not fully satisfied.")
}
return Stepping.mismatch(location: c2)
}
}
/// All green. Returns OK.
return Stepping.match(location: c2, nodes: ns1)
}
/// if `require` is `true`, repetition with insufficient occurrence will be treated as error
/// instead of non-matching.
static func choice(components:[Composition])(cursor:Cursor) -> Stepping {
var c2 = cursor
var ns1 = NodeList()
for comp in components {
let p1 = comp(cursor: c2)
/// Exit early on any error.
if p1.error {
return p1
}
/// Exit early on exact matching.
if p1.match {
return p1
}
c2 = p1.location
}
/// No need to concern about marking.
/// It's not related to choice rules.
/// Returns mismatch on no matching.
assert(ns1.count == 0)
return Stepping.mismatch(location: c2)
}
/// if `require` is `true`, repetition with insufficient occurrence will be treated as error
/// instead of non-matching.
static func repetition(unit:Composition, range:ClosedInterval<Int>)(cursor:Cursor) -> Stepping {
var c2 = cursor
var ns1 = NodeList()
while c2.available {
let p1 = unit(cursor: c2)
ns1 += p1.nodes ||| NodeList()
c2 = p1.location
/// Exit early on any error.
if p1.error {
return p1
}
// Stops on mismatch or overflow.
let over_max = ns1.count > range.end
let should_stop = p1.mismatch | over_max
if should_stop {
break
}
}
// Returns mismatch on underflow.
let under_min = ns1.count < range.start
if under_min {
return Stepping.mismatch(location: c2)
}
/// All green. Returns OK.
/// Node-list can be empty.
/// No need to concern about marking.
/// It's not related to choice rules.
return Stepping.match(location: c2, nodes: ns1)
}
}
private typealias Node = Stepping.Node
private typealias NodeList = Stepping.NodeList
}
extension Cursor {
/// Disabled due to compiler bug.
// /// Empty-range node. Used for error or virtual tokens.
// func nodify<T:Node>() -> T {
// return T(start: self, end: self)
// }
// func nodify<T:Node>(from c1:Cursor) -> T {
// return T(start: c1, end: self)
// }
// func nodify<T:Node>(to c1:Cursor) -> T {
// return T(start: self, end: c1)
// }
// func errify(message:String) -> Node.Error {
// let n1 = nodify() as Node.Error
// n1.message = message
// return n1
// }
// func errify(message:String) -> Stepping.Node {
// return Parsing.Node(location: self, error: message)
// }
}
infix operator ~~~ {
}
public func ~~~ (left:String, right:Rule.Composition) -> Rule {
return Rule(name: left, composition: right)
}
public func + (left:Rule.Composition, right:Rule.Composition) -> Rule.Composition {
return Rule.Component.sequence([left, right])
}
public func | (left:Rule.Composition, right:Rule.Composition) -> Rule.Composition {
return Rule.Component.choice([left, right])
}
public func * (left:Rule.Composition, right:ClosedInterval<Int>) -> Rule.Composition {
return Rule.Component.repetition(left, range:right)
}
| mit | 02359235c87f6f581f54754f6a25f900 | 24.633094 | 136 | 0.647769 | 2.961762 | false | false | false | false |
iAugux/iBBS-Swift | iBBS/TinderSwipeCardsSwift/DraggableView.swift | 1 | 5451 | //
// DraggableView.swift
// TinderSwipeCardsSwift
//
// Created by Gao Chao on 4/30/15.
// Copyright (c) 2015 gcweb. All rights reserved.
//
import Foundation
import UIKit
let ACTION_MARGIN: Float = 120 //%%% distance from center where the action applies. Higher = swipe further in order for the action to be called
let SCALE_STRENGTH: Float = 4 //%%% how quickly the card shrinks. Higher = slower shrinking
let SCALE_MAX:Float = 0.93 //%%% upper bar for how much the card shrinks. Higher = shrinks less
let ROTATION_MAX: Float = 1 //%%% the maximum rotation allowed in radians. Higher = card can keep rotating longer
let ROTATION_STRENGTH: Float = 320 //%%% strength of rotation. Higher = weaker rotation
let ROTATION_ANGLE: Float = 3.14/8 //%%% Higher = stronger rotation angle
protocol DraggableViewDelegate {
func cardSwipedLeft(card: UIView) -> Void
func cardSwipedRight(card: UIView) -> Void
}
class DraggableView: UIView {
var delegate: DraggableViewDelegate!
var panGestureRecognizer: UIPanGestureRecognizer!
var originPoint: CGPoint!
var xFromCenter: Float!
var yFromCenter: Float!
var avatar: UIImageView!
var content: UITextView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
self.backgroundColor = UIColor.randomColor()
panGestureRecognizer = PanDirectionGestureRecognizer(direction: .Horizontal, target: self, action: #selector(DraggableView.beingDragged(_:)))
self.addGestureRecognizer(panGestureRecognizer)
avatar = UIImageView()
avatar.backgroundColor = UIColor.randomColor()
avatar.clipsToBounds = true
avatar.layer.cornerRadius = 25.0
avatar.contentMode = UIViewContentMode.ScaleToFill
addSubview(avatar)
avatar.snp_makeConstraints { (make) in
make.width.height.equalTo(50)
make.top.equalTo(8)
make.centerX.equalTo(0)
}
content = UITextView()
content.textAlignment = NSTextAlignment.Center
content.font = UIFont.systemFontOfSize(17.0)
content.editable = false
content.backgroundColor = UIColor.clearColor()
content.textColor = UIColor.blackColor()
addSubview(content)
content.snp_makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsMake(63, 8, -16, -8))
}
xFromCenter = 0
yFromCenter = 0
}
func setupView() -> Void {
self.layer.cornerRadius = 5;
self.layer.shadowRadius = 3;
self.layer.shadowOpacity = 0.2;
self.layer.shadowOffset = CGSizeMake(1, 1);
}
func beingDragged(gestureRecognizer: UIPanGestureRecognizer) -> Void {
xFromCenter = Float(gestureRecognizer.translationInView(self).x)
yFromCenter = Float(gestureRecognizer.translationInView(self).y)
switch gestureRecognizer.state {
case UIGestureRecognizerState.Began:
self.originPoint = self.center
case UIGestureRecognizerState.Changed:
let rotationStrength: Float = min(xFromCenter/ROTATION_STRENGTH, ROTATION_MAX)
let rotationAngle = ROTATION_ANGLE * rotationStrength
let scale = max(1 - fabsf(rotationStrength) / SCALE_STRENGTH, SCALE_MAX)
self.center = CGPointMake(self.originPoint.x + CGFloat(xFromCenter), self.originPoint.y + CGFloat(yFromCenter))
let transform = CGAffineTransformMakeRotation(CGFloat(rotationAngle))
let scaleTransform = CGAffineTransformScale(transform, CGFloat(scale), CGFloat(scale))
self.transform = scaleTransform
case UIGestureRecognizerState.Ended:
self.afterSwipeAction()
case UIGestureRecognizerState.Possible:
fallthrough
case UIGestureRecognizerState.Cancelled:
fallthrough
case UIGestureRecognizerState.Failed:
fallthrough
default:
break
}
}
func afterSwipeAction() -> Void {
let floatXFromCenter = Float(xFromCenter)
if floatXFromCenter > ACTION_MARGIN {
self.rightAction()
} else if floatXFromCenter < -ACTION_MARGIN {
self.leftAction()
} else {
UIView.animateWithDuration(0.3, animations: {() -> Void in
self.center = self.originPoint
self.transform = CGAffineTransformMakeRotation(0)
})
}
}
func rightAction() -> Void {
let finishPoint: CGPoint = CGPointMake(500, 2 * CGFloat(yFromCenter) + self.originPoint.y)
UIView.animateWithDuration(0.3,
animations: {
self.center = finishPoint
}, completion: {
(value: Bool) in
self.removeFromSuperview()
})
delegate.cardSwipedRight(self)
}
func leftAction() -> Void {
let finishPoint: CGPoint = CGPointMake(-500, 2 * CGFloat(yFromCenter) + self.originPoint.y)
UIView.animateWithDuration(0.3,
animations: {
self.center = finishPoint
}, completion: {
(value: Bool) in
self.removeFromSuperview()
})
delegate.cardSwipedLeft(self)
}
} | mit | 44e0dcf90d70ef650fce7b156427a1ce | 34.868421 | 149 | 0.632728 | 4.982633 | false | false | false | false |
tomguthrie/RelativeDateFormatter | Sources/RelativeDateFormatter/RelativeDateFormatter.swift | 1 | 5787 | //
// RelativeDateFormatter.swift
//
// Copyright (c) 2016 Thomas Guthrie
//
// 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
/// Instances of `RelativeDateFormatter` can be used to get a localized relative date string similar
/// to how iOS' Mail app displays dates.
open class RelativeDateFormatter: Formatter {
open override func string(for obj: Any?) -> String? {
guard let date = obj as? Date else { return nil }
return string(from: date)
}
/// Returns a string representation of a given date relative to another date
/// using the reciever's current settings.
///
/// - parameter date: The date to format.
/// - parameter relativeTo: The date the string should be relative to;
/// defaults to the current date/time.
open func string(from date: Date, relativeTo: Date = Date()) -> String? {
var todayComponents = calendar.dateComponents([.hour, .minute, .second], from: relativeTo)
todayComponents.hour = -todayComponents.hour!
todayComponents.minute = -todayComponents.minute!
todayComponents.second = -todayComponents.second!
if let today = calendar.date(byAdding: todayComponents, to: relativeTo), date >= today {
return timeFormatter.string(from: date)
}
var yesterdayComponents = todayComponents
yesterdayComponents.day = -1
if let yesterday = calendar.date(byAdding: yesterdayComponents, to: relativeTo), date >= yesterday {
// FIXME: Localise
return "Yesterday"
}
var beginningOfWeekComponents = DateComponents()
beginningOfWeekComponents.day = -(calendar.dateComponents([.weekday], from: relativeTo).weekday! - calendar.firstWeekday)
if let beginningOfWeek = calendar.date(byAdding: beginningOfWeekComponents, to: relativeTo), date >= beginningOfWeek {
return weekFormatter.string(from: date)
}
var beginningOfYearComponents = calendar.dateComponents([.month, .day], from: relativeTo)
beginningOfYearComponents.month = 1 - beginningOfYearComponents.month!
beginningOfYearComponents.day = 1 - beginningOfYearComponents.day!
if let beginningOfYear = calendar.date(byAdding: beginningOfYearComponents, to: relativeTo), date >= beginningOfYear {
return monthFormatter.string(from: date)
}
return dateFormatter.string(from: date)
}
// MARK: Locale/Calendar
open var locale: Locale! = .current {
willSet {
reset()
}
}
open var calendar: Calendar! = .current {
willSet {
reset()
}
}
// MARK: Formatters
private func reset() {
_storedDateFormatter = nil
_storedTimeFormatter = nil
_storedWeekFormatter = nil
_storedMonthFormatter = nil
}
private var dateFormatter: DateFormatter {
if let formatter = _storedDateFormatter {
return formatter
} else {
let formatter = DateFormatter()
formatter.locale = locale
formatter.calendar = calendar
formatter.dateStyle = .short
_storedDateFormatter = formatter
return formatter
}
}
private var _storedDateFormatter: DateFormatter?
private var timeFormatter: DateFormatter {
if let formatter = _storedTimeFormatter {
return formatter
} else {
let formatter = DateFormatter()
formatter.locale = locale
formatter.calendar = calendar
formatter.timeStyle = .short
_storedTimeFormatter = formatter
return formatter
}
}
private var _storedTimeFormatter: DateFormatter?
private var weekFormatter: DateFormatter {
if let formatter = _storedWeekFormatter {
return formatter
} else {
let formatter = DateFormatter()
formatter.locale = locale
formatter.calendar = calendar
formatter.dateFormat = "EEEE"
_storedWeekFormatter = formatter
return formatter
}
}
private var _storedWeekFormatter: DateFormatter?
private var monthFormatter: DateFormatter {
if let formatter = _storedMonthFormatter {
return formatter
} else {
let formatter = DateFormatter()
formatter.locale = locale
formatter.calendar = calendar
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "d MMM", options: 0, locale: locale)
_storedMonthFormatter = formatter
return formatter
}
}
private var _storedMonthFormatter: DateFormatter?
}
| mit | fa3dcf0af5cf74360555038eda7a3036 | 36.335484 | 129 | 0.658199 | 5.284932 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/Utility/Networking/RequestAuthenticator.swift | 1 | 14681 | import AutomatticTracks
import Foundation
/// Authenticator for requests to self-hosted sites, wp.com sites, including private
/// sites and atomic sites.
///
/// - Note: at some point I considered moving this module to the WordPressAuthenticator pod.
/// Unfortunately the effort required for this makes it unfeasible for me to focus on it
/// right now, as it involves also moving at least CookieJar, AuthenticationService and AtomicAuthenticationService over there as well. - @diegoreymendez
///
class RequestAuthenticator: NSObject {
enum Error: Swift.Error {
case atomicSiteWithoutDotComID(blog: Blog)
}
enum DotComAuthenticationType {
case regular
case regularMapped(siteID: Int)
case atomic(loginURL: String)
case privateAtomic(blogID: Int)
}
enum WPNavigationActionType {
case reload
case allow
}
enum Credentials {
case dotCom(username: String, authToken: String, authenticationType: DotComAuthenticationType)
case siteLogin(loginURL: URL, username: String, password: String)
}
fileprivate let credentials: Credentials
// MARK: - Services
private let authenticationService: AuthenticationService
// MARK: - Initializers
init(credentials: Credentials, authenticationService: AuthenticationService = AuthenticationService()) {
self.credentials = credentials
self.authenticationService = authenticationService
}
@objc convenience init?(account: WPAccount, blog: Blog? = nil) {
guard let username = account.username,
let token = account.authToken else {
return nil
}
var authenticationType: DotComAuthenticationType = .regular
if let blog = blog, let dotComID = blog.dotComID as? Int {
if blog.isAtomic() {
authenticationType = blog.isPrivate() ? .privateAtomic(blogID: dotComID) : .atomic(loginURL: blog.loginUrl())
} else if blog.hasMappedDomain() {
authenticationType = .regularMapped(siteID: dotComID)
}
}
self.init(credentials: .dotCom(username: username, authToken: token, authenticationType: authenticationType))
}
@objc convenience init?(blog: Blog) {
if let account = blog.account {
self.init(account: account, blog: blog)
} else if let username = blog.usernameForSite,
let password = blog.password,
let loginURL = URL(string: blog.loginUrl()) {
self.init(credentials: .siteLogin(loginURL: loginURL, username: username, password: password))
} else {
DDLogError("Can't authenticate blog \(String(describing: blog.displayURL)) yet")
return nil
}
}
/// Potentially rewrites a request for authentication.
///
/// This method will call the completion block with the request to be used.
///
/// - Warning: On WordPress.com, this uses a special redirect system. It
/// requires the web view to call `interceptRedirect(request:)` before
/// loading any request.
///
/// - Parameters:
/// - url: the URL to be loaded.
/// - cookieJar: a CookieJar object where the authenticator will look
/// for existing cookies.
/// - completion: this will be called with either the request for
/// authentication, or a request for the original URL.
///
@objc func request(url: URL, cookieJar: CookieJar, completion: @escaping (URLRequest) -> Void) {
switch self.credentials {
case .dotCom(let username, let authToken, let authenticationType):
requestForWPCom(
url: url,
cookieJar: cookieJar,
username: username,
authToken: authToken,
authenticationType: authenticationType,
completion: completion)
case .siteLogin(let loginURL, let username, let password):
requestForSelfHosted(
url: url,
loginURL: loginURL,
cookieJar: cookieJar,
username: username,
password: password,
completion: completion)
}
}
private func requestForWPCom(url: URL, cookieJar: CookieJar, username: String, authToken: String, authenticationType: DotComAuthenticationType, completion: @escaping (URLRequest) -> Void) {
switch authenticationType {
case .regular:
requestForWPCom(
url: url,
cookieJar: cookieJar,
username: username,
authToken: authToken,
completion: completion)
case .regularMapped(let siteID):
requestForMappedWPCom(url: url,
cookieJar: cookieJar,
username: username,
authToken: authToken,
siteID: siteID,
completion: completion)
case .privateAtomic(let siteID):
requestForPrivateAtomicWPCom(
url: url,
cookieJar: cookieJar,
username: username,
siteID: siteID,
completion: completion)
case .atomic(let loginURL):
requestForAtomicWPCom(
url: url,
loginURL: loginURL,
cookieJar: cookieJar,
username: username,
authToken: authToken,
completion: completion)
}
}
private func requestForSelfHosted(url: URL, loginURL: URL, cookieJar: CookieJar, username: String, password: String, completion: @escaping (URLRequest) -> Void) {
func done() {
let request = URLRequest(url: url)
completion(request)
}
authenticationService.loadAuthCookiesForSelfHosted(into: cookieJar, loginURL: loginURL, username: username, password: password, success: {
done()
}) { [weak self] error in
// Make sure this error scenario isn't silently ignored.
self?.logErrorIfNeeded(error)
// Even if getting the auth cookies fail, we'll still try to load the URL
// so that the user sees a reasonable error situation on screen.
// We could opt to create a special screen but for now I'd rather users report
// the issue when it happens.
done()
}
}
private func requestForPrivateAtomicWPCom(url: URL, cookieJar: CookieJar, username: String, siteID: Int, completion: @escaping (URLRequest) -> Void) {
func done() {
let request = URLRequest(url: url)
completion(request)
}
// We should really consider refactoring how we retrieve the default account since it doesn't really use
// a context at all...
guard let account = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext).defaultWordPressComAccount() else {
WordPressAppDelegate.crashLogging?.logMessage("It shouldn't be possible to reach this point without an account.", properties: nil, level: .error)
return
}
let authenticationService = AtomicAuthenticationService(account: account)
authenticationService.loadAuthCookies(into: cookieJar, username: username, siteID: siteID, success: {
done()
}) { [weak self] error in
// Make sure this error scenario isn't silently ignored.
self?.logErrorIfNeeded(error)
// Even if getting the auth cookies fail, we'll still try to load the URL
// so that the user sees a reasonable error situation on screen.
// We could opt to create a special screen but for now I'd rather users report
// the issue when it happens.
done()
}
}
private func requestForAtomicWPCom(url: URL, loginURL: String, cookieJar: CookieJar, username: String, authToken: String, completion: @escaping (URLRequest) -> Void) {
func done() {
// For non-private Atomic sites, proxy the request through wp-login like Calypso does.
// If the site has SSO enabled auth should happen and we get redirected to our preview.
// If SSO is not enabled wp-admin prompts for credentials, then redirected.
var components = URLComponents(string: loginURL)
var queryItems = components?.queryItems ?? []
queryItems.append(URLQueryItem(name: "redirect_to", value: url.absoluteString))
components?.queryItems = queryItems
let requestURL = components?.url ?? url
let request = URLRequest(url: requestURL)
completion(request)
}
authenticationService.loadAuthCookiesForWPCom(into: cookieJar, username: username, authToken: authToken, success: {
done()
}) { [weak self] error in
// Make sure this error scenario isn't silently ignored.
self?.logErrorIfNeeded(error)
// Even if getting the auth cookies fail, we'll still try to load the URL
// so that the user sees a reasonable error situation on screen.
// We could opt to create a special screen but for now I'd rather users report
// the issue when it happens.
done()
}
}
private func requestForMappedWPCom(url: URL, cookieJar: CookieJar, username: String, authToken: String, siteID: Int, completion: @escaping (URLRequest) -> Void) {
func done() {
guard
let host = url.host,
!host.contains(WPComDomain)
else {
// The requested URL is to the unmapped version of the domain,
// so skip proxying the request through r-login.
completion(URLRequest(url: url))
return
}
let rlogin = "https://r-login.wordpress.com/remote-login.php?action=auth"
guard var components = URLComponents(string: rlogin) else {
// Safety net in case something unexpected changes in the future.
DDLogError("There was an unexpected problem initializing URLComponents via the rlogin string.")
completion(URLRequest(url: url))
return
}
var queryItems = components.queryItems ?? []
queryItems.append(contentsOf: [
URLQueryItem(name: "host", value: host),
URLQueryItem(name: "id", value: String(siteID)),
URLQueryItem(name: "back", value: url.absoluteString)
])
components.queryItems = queryItems
let requestURL = components.url ?? url
let request = URLRequest(url: requestURL)
completion(request)
}
authenticationService.loadAuthCookiesForWPCom(into: cookieJar, username: username, authToken: authToken, success: {
done()
}) { [weak self] error in
// Make sure this error scenario isn't silently ignored.
self?.logErrorIfNeeded(error)
// Even if getting the auth cookies fail, we'll still try to load the URL
// so that the user sees a reasonable error situation on screen.
// We could opt to create a special screen but for now I'd rather users report
// the issue when it happens.
done()
}
}
private func requestForWPCom(url: URL, cookieJar: CookieJar, username: String, authToken: String, completion: @escaping (URLRequest) -> Void) {
func done() {
let request = URLRequest(url: url)
completion(request)
}
authenticationService.loadAuthCookiesForWPCom(into: cookieJar, username: username, authToken: authToken, success: {
done()
}) { [weak self] error in
// Make sure this error scenario isn't silently ignored.
self?.logErrorIfNeeded(error)
// Even if getting the auth cookies fail, we'll still try to load the URL
// so that the user sees a reasonable error situation on screen.
// We could opt to create a special screen but for now I'd rather users report
// the issue when it happens.
done()
}
}
private func logErrorIfNeeded(_ error: Swift.Error) {
let nsError = error as NSError
switch nsError.code {
case NSURLErrorTimedOut, NSURLErrorNotConnectedToInternet:
return
default:
WordPressAppDelegate.crashLogging?.logError(error)
}
}
}
private extension RequestAuthenticator {
static let wordPressComLoginUrl = URL(string: "https://wordpress.com/wp-login.php")!
}
extension RequestAuthenticator {
func isLogin(url: URL) -> Bool {
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
components?.queryItems = nil
return components?.url == RequestAuthenticator.wordPressComLoginUrl
}
}
/// MARK: Navigation Validator
extension RequestAuthenticator {
/// Validates that the navigation worked as expected then provides a recommendation on if the screen should reload or not.
func decideActionFor(response: URLResponse, cookieJar: CookieJar, completion: @escaping (WPNavigationActionType) -> Void) {
switch self.credentials {
case .dotCom(let username, _, let authenticationType):
decideActionForWPCom(response: response, cookieJar: cookieJar, username: username, authenticationType: authenticationType, completion: completion)
case .siteLogin:
completion(.allow)
}
}
private func decideActionForWPCom(response: URLResponse, cookieJar: CookieJar, username: String, authenticationType: DotComAuthenticationType, completion: @escaping (WPNavigationActionType) -> Void) {
guard didEncouterRecoverableChallenge(response) else {
completion(.allow)
return
}
cookieJar.removeWordPressComCookies {
completion(.reload)
}
}
private func didEncouterRecoverableChallenge(_ response: URLResponse) -> Bool {
guard let url = response.url?.absoluteString else {
return false
}
if url.contains("r-login.wordpress.com") || url.contains("wordpress.com/log-in?") {
return true
}
guard let statusCode = (response as? HTTPURLResponse)?.statusCode else {
return false
}
return 400 <= statusCode && statusCode < 500
}
}
| gpl-2.0 | fea2ce3c68bad22a0d9413fc7c47697c | 39.332418 | 204 | 0.621756 | 5.405376 | false | false | false | false |
Jappsy/jappsy | src/platform/iOS/SwiftExample/OmLauncher/DrumsViewController.swift | 1 | 5613 | //
// DrumsViewController.swift
// OM
//
// Created by Артем Янковский on 28.11.16.
// Copyright © 2016 Cox. All rights reserved.
//
// Update by Jappsy on 08.12.16.
//
import UIKit
import libGameOM
import libJappsyEngine
class DrumsViewController: UIViewController
{
var gameView: UIView!
var reloadButton: UIButton!
var omView: OMView!
override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }
override func viewDidLoad()
{
self.view.backgroundColor = UIColor.black
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
// gameView
gameView = UIView()
gameView.isOpaque = false
gameView.backgroundColor = UIColor.green
gameView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(gameView)
// omView won't work w/o it's container constraints
self.view.addConstraint(NSLayoutConstraint(item: gameView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 0.0).priority(999))
self.view.addConstraint(NSLayoutConstraint(item: gameView, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1.0, constant: 0.0).priority(999))
self.view.addConstraint(NSLayoutConstraint(item: gameView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0.0).priority(999))
self.view.addConstraint(NSLayoutConstraint(item: gameView, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1.0, constant: 0.0).priority(999))
UIApplication.shared.isIdleTimerDisabled = true
self.startGame()
}
func startGame()
{
#if OMEXAMPLE
omView = OMView.init(
"https://dev03-om.jappsy.com/jappsy/",
token: "52c6fe74a76200e9e1619e5db30cce2c8e5713552102bfe0d94caf18fa294726",
sessid: "8ea5f70b15263872760d7e14ce8e579a",
devid: "",
locale: "RU"
)
#else
omView = OMView.init(
IS_DEV ? "https://dev03-om.jappsy.com/jappsy/" : "https://om.jappsy.com/jappsy/",
token: UserModel.shared().access_token,
sessid: CoxKit.sharedCox().getDeviceId,
devid: "",
locale: CoxKit.sharedCox().getCurrentLocale
)
#endif
gameView.addSubview(omView)
gameView.addConstraint(NSLayoutConstraint(item: omView, attribute: .top, relatedBy: .equal, toItem: gameView, attribute: .top, multiplier: 1.0, constant: 0.0).priority(999))
gameView.addConstraint(NSLayoutConstraint(item: omView, attribute: .left, relatedBy: .equal, toItem: gameView, attribute: .left, multiplier: 1.0, constant: 0.0).priority(999))
gameView.addConstraint(NSLayoutConstraint(item: omView, attribute: .bottom, relatedBy: .equal, toItem: gameView, attribute: .bottom, multiplier: 1.0, constant: 0.0).priority(999))
gameView.addConstraint(NSLayoutConstraint(item: omView, attribute: .right, relatedBy: .equal, toItem: gameView, attribute: .right, multiplier: 1.0, constant: 0.0).priority(999))
omView.onStart()
omView.updateState(OMVIEW_RUN)
omView.updateState(OMVIEW_SHOW)
#if OMEXAMPLE
#else
//Constants.TOGGLE_LEFT_PANEL
NotificationCenter.default.addObserver(self, selector: #selector(DrumsViewController.leftPanelAnimation(_:)), name: NSNotification.Name(rawValue: String(format: "%@%@" , Constants.NOTIFY_MESSAGE_PREFIX, Constants.TOGGLE_LEFT_PANEL)), object: nil)
#endif
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
// Setup Notifications
self.omView.setupNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(DrumsViewController.showMenu(_:)), name: NSNotification.Name(rawValue: "UIOMShowMenuNotification"), object:nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated);
// Clear Notifications
self.omView.clearNotifications()
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "UIOMShowMenuNotification"), object: nil)
}
func showMenu(_ notification: Notification)
{
#if OMEXAMPLE
self.omView.updateState(OMVIEW_SHOW)
#else
DispatchQueue.main.async(execute: {
CoxKit.sharedCox().toggleLeftPanel()
UIApplication.shared.isIdleTimerDisabled = false
})
#endif
}
open override var shouldAutorotate: Bool {
get
{
return true
}
}
#if OMEXAMPLE
#else
func leftPanelAnimation(_ notification: Notification)
{
let params = notification.userInfo as! Dictionary<String, AnyObject>
var state = params["state"] as? Bool ?? false
var controller = params["controller"] as? String ?? ""
if(controller != "drums")
{
return
}
if(!state)
{
self.omView.updateState(OMVIEW_HIDE)
}
else
{
self.omView.updateState(OMVIEW_SHOW)
}
}
#endif
}
| gpl-3.0 | 7fc13099882b9fcc2e706a7d7bd572c6 | 37.342466 | 258 | 0.625045 | 4.496386 | false | false | false | false |
cp3hnu/PrivacyManager | PrivacyContact/PrivacyManager+Contact.swift | 1 | 2111 | //
// PrivacyManager+Contact.swift
// PrivacyManager
//
// Created by CP3 on 10/23/19.
// Copyright © 2019 CP3. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import Contacts
import PrivacyManager
/// Contact
public extension PrivacyManager {
/// 获取通讯录访问权限的状态
var contactStatus: PermissionStatus {
let status = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
switch status {
case .notDetermined:
return .unknown
case .authorized:
return .authorized
case .denied:
return .unauthorized
case .restricted:
return .disabled
@unknown default:
return .unknown
}
}
/// 获取通讯录访问权限的状态 - Observable
var rxContactPermission: Observable<Bool> {
return Observable.create{ observer -> Disposable in
let status = self.contactStatus
switch status {
case .unknown:
CNContactStore().requestAccess(for: CNEntityType.contacts, completionHandler: { (granted, error) in
onMainThread {
observer.onNext(granted)
observer.onCompleted()
}
})
case .authorized:
observer.onNext(true)
observer.onCompleted()
default:
observer.onNext(false)
observer.onCompleted()
}
return Disposables.create()
}
}
/// Present alert view controller for contact
func contactPermission(presenting: UIViewController, desc: String? = nil, authorized authorizedAction: @escaping PrivacyClosure, canceled cancelAction: PrivacyClosure? = nil, setting settingAction: PrivacyClosure? = nil) {
return privacyPermission(type: PermissionType.contact, rxPersission: rxContactPermission, desc: desc, presenting: presenting, authorized: authorizedAction, canceled: cancelAction, setting: settingAction)
}
}
| mit | 45bf6265f84268f5ce3410f3fed65316 | 32.258065 | 226 | 0.610572 | 5.369792 | false | false | false | false |
natestedman/NSErrorRepresentable | NSErrorRepresentable/UserInfoConvertible.swift | 1 | 3211 | // NSErrorRepresentable
// Written in 2016 by Nate Stedman <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
import Foundation
// MARK: - User Info Convertible
/// A protocol for types that can be converted to a user info value.
///
/// All properties of this protocol have default implementations, which return empty values.
public protocol UserInfoConvertible
{
// MARK: - Text Content
/// A value for `NSLocalizedDescriptionKey`.
var localizedDescription: String? { get }
/// A value for `NSLocalizedRecoveryOptionsErrorKey`.
var localizedRecoveryOptions: [String]? { get }
/// A value for `NSLocalizedRecoverySuggestionErrorKey`.
var localizedRecoverySuggestion: String? { get }
/// A value for `NSLocalizedFailureReasonErrorKey`.
var localizedFailureReason: String? { get }
// MARK: - Underlying Error
/// A value for `NSUnderlyingErrorKey`.
var underlyingError: NSError? { get }
// MARK: - Additional User Info Values
/// Additional user info keys and values to apply.
///
/// These are applied after the built-in properties, so any repeated keys will be overridden.
var additionalUserInfoValues: [String:AnyObject] { get }
}
extension UserInfoConvertible
{
// MARK: - Text Content
/// This property's default implementation returns `nil`.
public var localizedDescription: String? { return nil }
/// This property's default implementation returns `nil`.
public var localizedRecoveryOptions: [String]? { return nil }
/// This property's default implementation returns `nil`.
public var localizedRecoverySuggestion: String? { return nil }
/// This property's default implementation returns `nil`.
public var localizedFailureReason: String? { return nil }
// MARK: - Underlying Error
/// This property's default implementation returns `nil`.
public var underlyingError: NSError? { return nil }
// MARK: - Additional User Info Values
/// This property's default implementation returns an empty dictionary.
public var additionalUserInfoValues: [String:AnyObject] { return [:] }
}
extension NSErrorConvertible where Self: UserInfoConvertible
{
// MARK: - User Info
/// A user info representation of the value.
public var userInfo: [String:AnyObject]?
{
var userInfo = [String:AnyObject]()
userInfo[NSLocalizedDescriptionKey] = localizedDescription
userInfo[NSLocalizedRecoveryOptionsErrorKey] = localizedRecoveryOptions
userInfo[NSLocalizedRecoverySuggestionErrorKey] = localizedRecoverySuggestion
userInfo[NSLocalizedFailureReasonErrorKey] = localizedFailureReason
userInfo[NSUnderlyingErrorKey] = underlyingError
additionalUserInfoValues.forEach({ key, value in userInfo[key] = value })
return userInfo
}
}
| cc0-1.0 | 525e7306aa627affa114c58295ef67b5 | 33.526882 | 97 | 0.721893 | 5.289951 | false | false | false | false |
TTVS/NightOut | Clubber/OauthLoginViewController.swift | 1 | 3769 | ////
//// OauthLoginViewController.swift
//// Clubber
////
//// Created by Terra on 26/6/15.
//// Copyright (c) 2015 Dino Media Asia. All rights reserved.
////
//
//import UIKit
//import Foundation
//import CoreData
//import Alamofire
//import SwiftyJSON
//
//class OauthLoginViewController: UIViewController {
//
// @IBOutlet weak var webView: UIWebView!
// var coreDataStack: CoreDataStack!
// override func viewDidLoad() {
// super.viewDidLoad()
// }
//
// override func viewWillAppear(animated: Bool) {
// super.viewWillAppear(animated)
// webView.hidden = true
// NSURLCache.sharedURLCache().removeAllCachedResponses()
// if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as? [NSHTTPCookie]{
// for cookie in cookies {
// NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(cookie)
// }
// }
//
// let request = NSURLRequest(URL: Instagram.Router.authorizationURL, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0)
// self.webView.loadRequest(request)
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// }
//
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// if segue.identifier == "unwindToPhotoBrowser" && segue.destinationViewController.isKindOfClass(PhotoBrowserCollectionViewController.classForCoder()) {
// let photoBrowserCollectionViewController = segue.destinationViewController as! PhotoBrowserCollectionViewController
// if let user = sender?.valueForKey("user") as? User {
// photoBrowserCollectionViewController.user = user
//
// }
// }
// }
//
//}
//
//extension OauthLoginViewController: UIWebViewDelegate {
// func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
// println(request.URLString)
// let urlString = request.URLString
// if let range = urlString.rangeOfString(Instagram.Router.redirectURI + "?code=") {
//
// let location = range.endIndex
// let code = urlString.substringFromIndex(location)
// println(code)
// requestAccessToken(code)
// return false
// }
// return true
// }
//
// func requestAccessToken(code: String) {
// let request = Instagram.Router.requestAccessTokenURLStringAndParms(code)
//
// Alamofire.request(.POST, request.URLString, parameters: request.Params)
// .responseJSON {
// (_, _, jsonObject, error) in
//
// if (error == nil) {
// //println(jsonObject)
// let json = JSON(jsonObject!)
//
// if let accessToken = json["access_token"].string, userID = json["user"]["id"].string {
// let user = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: self.coreDataStack.context) as! User
// user.userID = userID
// user.accessToken = accessToken
// self.coreDataStack.saveContext()
// self.performSegueWithIdentifier("unwindToPhotoBrowser", sender: ["user": user])
// }
// }
//
// }
// }
// func webViewDidFinishLoad(webView: UIWebView) {
// webView.hidden = false
// }
//
// func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
//
// }
//} | apache-2.0 | 971b5737ebc45b7ce547be00f60fa48a | 37.865979 | 160 | 0.595649 | 4.91395 | false | false | false | false |
getstalkr/stalkr-cloud | Sources/StalkrCloud/Controllers/RoleAssignmentController.swift | 1 | 2092 | //
// RoleAssignmentController.swift
// stalkr-cloud
//
// Created by Matheus Martins on 5/25/17.
//
//
import HTTP
import Vapor
import Foundation
import FluentExtended
import AuthProvider
class RoleAssignmentController {
let drop: Droplet
init(drop: Droplet) {
self.drop = drop
}
func addRoutes() {
drop.group("roleassignment") {
let authed = $0.grouped(TokenAuthenticationMiddleware(User.self))
$0.get("all", handler: all)
$0.get("role", handler: role)
$0.get("user", handler: user)
authed.group(RoleMiddleware.admin) {
$0.post("create", handler: create)
}
}
}
func all(request: Request) throws -> ResponseRepresentable {
return try RoleAssignment.all().makeJSON()
}
func user(request: Request) throws -> ResponseRepresentable {
let id = try request.assertHeaderValue(forKey: "id")
let user = try User.assertFind(id)
let assignments = try RoleAssignment.all(with: (RoleAssignment.Keys.userId, .equals, user.id))
return try assignments.makeJSON()
}
func role(request: Request) throws -> ResponseRepresentable {
let id = try request.assertHeaderValue(forKey: "id")
let role = try Role.assertFind(id)
let assignments = try RoleAssignment.all(with: (RoleAssignment.Keys.roleId, .equals, role.id))
return try assignments.makeJSON()
}
func create(request: Request) throws -> ResponseRepresentable {
let userid = try request.assertHeaderValue(forKey: "user_id")
let user = try User.assertFind(userid)
let roleid = try request.assertHeaderValue(forKey: "role_id")
let role = try Role.assertFind(roleid)
let assignment = RoleAssignmentBuilder.build {
$0.roleId = role.id
$0.userId = user.id
}!
try assignment.save()
return assignment
}
}
| mit | c409162e484833a60771bf23bd5904b9 | 27.27027 | 102 | 0.590344 | 4.498925 | false | false | false | false |
hatjs880328/DZHTTPRequest | HTTPRequest/HTTPRequestFactory.swift | 1 | 3778 | //
// HTTPRequestFactory.swift
// FSZCItem
//
// Created by MrShan on 16/6/23.
// Copyright © 2016年 Mrshan. All rights reserved.
//
import Foundation
//MARK:基本返回类
/// 返回数据类(基类)
public class ResponseClass {
/// 需要处理的数据
public var responseData:AnyObject!
/// 是否展示提示信息
var ifshowalertinfo:HTTPERRORInfoShow!
/// 当前数据的数据类型
var datatype:ResponseType!
/// 错误处理的方法参数
var errorAction :(errorType:ERRORMsgType)->Void!
func setData(data:AnyObject) {
self.responseData = data as! String
self.datatype = ResponseType.STRING
}
init(data:AnyObject,alertinfoshouldshow:HTTPERRORInfoShow,errorAction:(errorType:ERRORMsgType)->Void) {
self.ifshowalertinfo = alertinfoshouldshow
self.errorAction = errorAction
self.setData(data)
}
}
/// 返回数据类-字典
public class ResponseDataDictionary:ResponseClass {
override init(data: AnyObject, alertinfoshouldshow: HTTPERRORInfoShow,errorAction:(errorType:ERRORMsgType)->Void) {
super.init(data: data, alertinfoshouldshow: alertinfoshouldshow,errorAction:errorAction)
}
/**
返回的数据类型为字典
- parameter data: dic数据
*/
override func setData(data: AnyObject) {
let dicResponseData = data as! NSDictionary
if(dicResponseData["state"] as! String == "1"){
let responseSecondLeveldata = dicResponseData["data"]
switch responseSecondLeveldata!.self {
case is NSDictionary : self.responseData = responseSecondLeveldata as! NSDictionary;self.datatype = ResponseType.DIC
case is NSArray: self.responseData = responseSecondLeveldata as! NSArray;self.datatype = ResponseType.ARRAY
case is String: self.responseData = responseSecondLeveldata as! String;self.datatype = ResponseType.STRING
default:break
}
}else{
if dicResponseData["errcode"] as! String != "999" {
//返回错误数据 ERRMSG 字典中的KEY
NETWORKErrorProgress().errorMsgProgress(ERRORMsgType.progressError, ifcanshow: self.ifshowalertinfo, errormsg: dicResponseData["errmsg"] as! String, errorAction: { (errorType) -> Void in
self.errorAction(errorType: errorType)
})
}else{
NETWORKErrorProgress().moreThanoneUserLoginwithsameoneAPPID()
}
}
}
}
/// 返回数据类-数组
public class ResponseDataNSArray:ResponseClass {
override init(data: AnyObject, alertinfoshouldshow: HTTPERRORInfoShow,errorAction:(errorType:ERRORMsgType)->Void) {
super.init(data: data, alertinfoshouldshow: alertinfoshouldshow,errorAction:errorAction)
}
/**
返回的数据类型为数组
- parameter data: 数组数据
*/
override func setData(data: AnyObject) {
self.responseData = data as! NSArray
}
}
/// 数据处理工厂类
public class ResponseFactoary: NSObject {
func responseInstance(instancename:ResponseType,data:AnyObject,alertinfoshouldshow:HTTPERRORInfoShow,errorAction:(errorType:ERRORMsgType)->Void)->ResponseClass {
if instancename == ResponseType.DIC {
return ResponseDataDictionary(data: data,alertinfoshouldshow:alertinfoshouldshow,errorAction:errorAction)
}else if instancename == ResponseType.ARRAY {
return ResponseDataNSArray(data: data,alertinfoshouldshow:alertinfoshouldshow,errorAction:errorAction)
}else{
return ResponseClass(data: data,alertinfoshouldshow:alertinfoshouldshow,errorAction:errorAction)
}
}
} | mit | c4b3fdaddfb0d6e4f149dab9688fed77 | 33.980392 | 202 | 0.678441 | 4.800808 | false | false | false | false |
antlr/grammars-v4 | swift/swift5/examples/Control Flow/Contents.swift | 1 | 4036 | //: ## Control Flow
//:
//: Use `if` and `switch` to make conditionals, and use `for`-`in`, `while`, and `repeat`-`while` to make loops. Parentheses around the condition or loop variable are optional. Braces around the body are required.
//:
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
//: In an `if` statement, the conditional must be a Boolean expression—this means that code such as `if score { ... }` is an error, not an implicit comparison to zero.
//:
//: You can use `if` and `let` together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains `nil` to indicate that a value is missing. Write a question mark (`?`) after the type of a value to mark the value as optional.
//:
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
//: - Experiment:
//: Change `optionalName` to `nil`. What greeting do you get? Add an `else` clause that sets a different greeting if `optionalName` is `nil`.
//:
//: If the optional value is `nil`, the conditional is `false` and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after `let`, which makes the unwrapped value available inside the block of code.
//:
//: Another way to handle optional values is to provide a default value using the `??` operator. If the optional value is missing, the default value is used instead.
//:
let nickname: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickname ?? fullName)"
//: Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality.
//:
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
//: - Experiment:
//: Try removing the default case. What error do you get?
//:
//: Notice how `let` can be used in a pattern to assign the value that matched the pattern to a constant.
//:
//: After executing the code inside the switch case that matched, the program exits from the switch statement. Execution doesn’t continue to the next case, so you don’t need to explicitly break out of the switch at the end of each case’s code.
//:
//: You use `for`-`in` to iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unordered collection, so their keys and values are iterated over in an arbitrary order.
//:
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (_, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
//: - Experiment:
//: Replace the `_` with a variable name, and keep track of which kind of number was the largest.
//:
//: Use `while` to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once.
//:
var n = 2
while n < 100 {
n *= 2
}
print(n)
var m = 2
repeat {
m *= 2
} while m < 100
print(m)
//: You can keep an index in a loop by using `..<` to make a range of indexes.
//:
var total = 0
for i in 0..<4 {
total += i
}
print(total)
//: Use `..<` to make a range that omits its upper value, and use `...` to make a range that includes both values.
//:
//: [Previous](@previous) | [Next](@next) | mit | 208b7bc9519d63e05350ae2397a8e9cb | 36.616822 | 307 | 0.678926 | 3.914397 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Components/Grades/Models/Grade_old.swift | 1 | 2622 | ////
//// Grade.swift
//// HTWDD
////
//// Created by Benjamin Herzog on 04/01/2017.
//// Copyright © 2017 HTW Dresden. All rights reserved.
////
//
//import Foundation
//import RxSwift
//import Marshal
//
//struct Grade: Codable, Identifiable {
//
// enum Status: String, Codable {
// case signedUp = "AN"
// case passed = "BE"
// case failed = "NB"
// case ultimatelyFailed = "EN"
//
// var localizedDescription: String {
// switch self {
// case .signedUp: return Loca.Grades.status.signedUp
// case .passed: return Loca.Grades.status.passed
// case .failed: return Loca.Grades.status.failed
// case .ultimatelyFailed: return Loca.Grades.status.ultimatelyFailed
// }
// }
// }
//
// let nr: Int
// let state: Status
// let credits: Double
// let text: String
// let semester: Semester
// let numberOfTry: Int
// let date: Date?
// let mark: Double?
// let note: String?
// let form: String?
//
// static func get(network: Network, course: Course) -> Observable<[Grade]> {
// return Observable.empty()
//// let parameters = [
//// "POVersion": "\(course.POVersion)",
//// "AbschlNr": course.abschlNr,
//// "StgNr": course.stgNr
//// ]
//// Log.debug("\(parameters)")
////
//// return network.getArrayM(url: Grade.url, params: parameters)
// }
//
//}
//
//extension Grade: Unmarshaling {
// static let url = "https://wwwqis.htw-dresden.de/appservice/v2/getgrades"
//
// init(object: MarshaledObject) throws {
// self.nr = try object <| "nr"
// self.state = try object <| "state"
// self.credits = try object <| "credits"
// self.text = try object <| "text"
// self.semester = try object <| "semester"
// self.numberOfTry = try object <| "tries"
//
// let dateRaw: String? = try object <| "examDate"
// self.date = try dateRaw.map {
// try Date.from(string: $0, format: "yyyy-MM-dd'T'HH:mmZ")
// }
//
// let markRaw: Double? = try object <| "grade"
// self.mark = markRaw.map { $0 / 100 }
//
// self.note = try? object <| "note"
// self.form = try? object <| "form"
// }
//
//}
//
//extension Grade: Equatable {
//
// static func ==(lhs: Grade, rhs: Grade) -> Bool {
// return lhs.nr == rhs.nr
// && lhs.mark == rhs.mark
// && lhs.credits == rhs.credits
// && lhs.semester == rhs.semester
// && lhs.state == rhs.state
// }
//
//}
| gpl-2.0 | c6a8b63041922efb3157cbdd3c8f4122 | 27.802198 | 80 | 0.533384 | 3.421671 | false | false | false | false |
soapyigu/LeetCode_Swift | DP/BestTimeBuySellStockCooldown.swift | 1 | 920 | /**
* Question Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
* Primary idea: Dynamic programming, dp array means the max value sold at today
* Time Complexity: O(n^2), Space Complexity: O(n)
*
*/
class BestTimeBuySellStockCooldown {
func maxProfit(_ prices: [Int]) -> Int {
guard prices.count > 1 else {
return 0
}
var res = 0
var dp = Array(repeating: 0, count: prices.count)
for i in 1..<prices.count {
for j in (0..<i).reversed() {
if j >= 2 {
dp[i] = max(dp[i], prices[i] - prices[j] + dp[j - 2])
} else {
dp[i] = max(dp[i], prices[i] - prices[j])
}
}
dp[i] = max(dp[i], dp[i - 1])
res = max(res, dp[i])
}
return res
}
} | mit | 19f1eba4c36585069d0480e08f5c1dc0 | 27.78125 | 94 | 0.461957 | 3.650794 | false | false | false | false |
ncalexan/firefox-ios | UITests/HistoryTests.swift | 4 | 7201 | /* 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 EarlGrey
class HistoryTests: KIFTestCase {
fileprivate var webRoot: String!
override func setUp() {
super.setUp()
webRoot = SimplePageServer.start()
BrowserUtils.dismissFirstRunUI()
}
func addHistoryItemPage(_ pageNo: Int) -> String {
// Load a page
let url = "\(webRoot!)/numberedPage.html?page=\(pageNo)"
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_replaceText(url))
EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_typeText("\n"))
tester().waitForWebViewElementWithAccessibilityLabel("Page \(pageNo)")
return url
}
func addHistoryItems(_ noOfItemsToAdd: Int) -> [String] {
var urls = [String]()
for index in 1...noOfItemsToAdd {
urls.append(addHistoryItemPage(index))
}
return urls
}
/**
* Tests for listed history visits
*/
func testAddHistoryUI() {
_ = addHistoryItems(2)
// Check that both appear in the history home panel
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("History")).perform(grey_tap())
// Wait until the dialog shows up
let listAppeared = GREYCondition(name: "Wait the history list to appear", block: { _ in
var errorOrNil: NSError?
let matcher = grey_allOf([grey_accessibilityLabel("Page 2"),
grey_sufficientlyVisible()])
EarlGrey.select(elementWithMatcher: matcher)
.inRoot(grey_accessibilityID("History List"))
.assert(grey_notNil(), error: &errorOrNil)
return errorOrNil == nil
}).wait(withTimeout: 20)
GREYAssertTrue(listAppeared, reason: "Failed to display history")
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Page 2"))
.inRoot(grey_accessibilityID("History List"))
.assert(grey_sufficientlyVisible())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Page 1"))
.inRoot(grey_accessibilityID("History List"))
.assert(grey_sufficientlyVisible())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("\(webRoot!)/numberedPage.html?page=2"))
.inRoot(grey_accessibilityID("History List"))
.assert(grey_sufficientlyVisible())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("\(webRoot!)/numberedPage.html?page=1"))
.inRoot(grey_accessibilityID("History List"))
.assert(grey_sufficientlyVisible())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Cancel"))
.inRoot(grey_kindOfClass(NSClassFromString("Client.InsetButton")!))
.perform(grey_tap())
}
func testDeleteHistoryItemFromListWith2Items() {
// add 2 history items
let urls = addHistoryItems(2)
// Check that both appear in the history home panel
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("History")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(urls[0]))
.perform(grey_longPress())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Delete from History"))
.inRoot(grey_kindOfClass(NSClassFromString("UITableViewCellContentView")!))
.perform(grey_tap())
// The second history entry still exists
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(urls[1]))
.inRoot(grey_kindOfClass(NSClassFromString("UITableViewCellContentView")!))
.assert(grey_notNil())
// check page 1 does not exist
let historyRemoved = GREYCondition(name: "Check entry is removed", block: { _ in
var errorOrNil: NSError?
let matcher = grey_allOf([grey_accessibilityLabel(urls[0]),
grey_sufficientlyVisible()])
EarlGrey.select(elementWithMatcher: matcher).assert(grey_notNil(), error: &errorOrNil)
let success = errorOrNil != nil
return success
}).wait(withTimeout: 5)
GREYAssertTrue(historyRemoved, reason: "Failed to remove history")
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Cancel"))
.inRoot(grey_kindOfClass(NSClassFromString("Client.InsetButton")!))
.perform(grey_tap())
}
func testDeleteHistoryItemFromListWithMoreThan100Items() {
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Top sites")).perform(grey_tap())
for pageNo in 1...102 {
BrowserUtils.addHistoryEntry("Page \(pageNo)", url: URL(string: "\(webRoot!)/numberedPage.html?page=\(pageNo)")!)
}
let urlToDelete = "\(webRoot!)/numberedPage.html?page=\(102)"
let oldestUrl = "\(webRoot!)/numberedPage.html?page=\(101)"
EarlGrey.select(elementWithMatcher:grey_accessibilityLabel("History"))
.perform(grey_tap())
EarlGrey.select(elementWithMatcher:grey_accessibilityLabel(urlToDelete))
// .perform(grey_swipeSlowInDirection(GREYDirection.left))
.perform(grey_swipeFastInDirectionWithStartPoint(GREYDirection.left, 40.0, 0.0))
EarlGrey.select(elementWithMatcher:grey_accessibilityLabel("Delete"))
.inRoot(grey_kindOfClass(NSClassFromString("UISwipeActionStandardButton")!))
.perform(grey_tap())
// The history list still exists
EarlGrey.select(elementWithMatcher: grey_accessibilityID("History List"))
.assert(grey_notNil())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(oldestUrl))
.assert(grey_notNil())
// check page 1 does not exist
let historyRemoved = GREYCondition(name: "Check entry is removed", block: { _ in
var errorOrNil: NSError?
let matcher = grey_allOf([grey_accessibilityLabel(urlToDelete),
grey_sufficientlyVisible()])
EarlGrey.select(elementWithMatcher:matcher).assert(grey_notNil(), error: &errorOrNil)
let success = errorOrNil != nil
return success
}).wait(withTimeout: 5)
GREYAssertTrue(historyRemoved, reason: "Failed to remove history")
}
override func tearDown() {
BrowserUtils.resetToAboutHome(tester())
BrowserUtils.clearPrivateData(tester: tester())
super.tearDown()
}
}
| mpl-2.0 | 2ec89812d7ef2457de24ebb6c83a415e | 46.375 | 125 | 0.640605 | 5.260044 | false | true | false | false |
neoneye/SwiftyFORM | Source/FormItems/SectionFormItem.swift | 1 | 1625 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
public class SectionFormItem: FormItem {
override func accept(visitor: FormItemVisitor) {
visitor.visit(object: self)
}
}
public class SectionHeaderTitleFormItem: FormItem {
public init(title: String? = nil) {
self.title = title
super.init()
}
override func accept(visitor: FormItemVisitor) {
visitor.visit(object: self)
}
/// The section title is shown in uppercase.
///
/// Works best with texts shorter than 50 characters
///
/// Longer texts that spans multiple lines can cause crashes with expand/collapse animations.
/// In this case consider using the `SectionHeaderViewFormItem` class.
public var title: String?
@discardableResult
public func title(_ title: String) -> Self {
self.title = title
return self
}
}
public class SectionHeaderViewFormItem: FormItem {
override func accept(visitor: FormItemVisitor) {
visitor.visit(object: self)
}
public typealias CreateUIView = () -> UIView?
public var viewBlock: CreateUIView?
}
public class SectionFooterTitleFormItem: FormItem {
public init(title: String? = nil) {
self.title = title
super.init()
}
override func accept(visitor: FormItemVisitor) {
visitor.visit(object: self)
}
public var title: String?
@discardableResult
public func title(_ title: String) -> Self {
self.title = title
return self
}
}
public class SectionFooterViewFormItem: FormItem {
override func accept(visitor: FormItemVisitor) {
visitor.visit(object: self)
}
public typealias CreateUIView = () -> UIView?
public var viewBlock: CreateUIView?
}
| mit | 800b23d47c8cbe96d3d6f2abb24ffeb0 | 22.214286 | 94 | 0.733538 | 3.735632 | false | false | false | false |
kstaring/swift | test/SILGen/objc_extensions.swift | 4 | 7694 | // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import objc_extensions_helper
class Sub : Base {}
extension Sub {
override var prop: String! {
didSet {
// Ignore it.
}
// Make sure that we are generating the @objc thunk and are calling the actual method.
//
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC15objc_extensions3Subg4propGSQSS_ : $@convention(objc_method) (Sub) -> @autoreleased Optional<NSString> {
// CHECK: bb0([[SELF:%.*]] : $Sub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[GETTER_FUNC:%.*]] = function_ref @_TFC15objc_extensions3Subg4propGSQSS_ : $@convention(method) (@guaranteed Sub) -> @owned Optional<String>
// CHECK: apply [[GETTER_FUNC]]([[SELF_COPY]])
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: } // end sil function '_TToFC15objc_extensions3Subg4propGSQSS_'
// Then check the body of the getter calls the super_method.
// CHECK-LABEL: sil hidden [transparent] @_TFC15objc_extensions3Subg4propGSQSS_ : $@convention(method) (@guaranteed Sub) -> @owned Optional<String> {
// CHECK: bb0([[SELF:%.*]] : $Sub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[SELF_COPY_CAST:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base
// CHECK: [[SUPER_METHOD:%.*]] = super_method [volatile] [[SELF_COPY]] : $Sub, #Base.prop!getter.1.foreign
// CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[SELF_COPY_CAST]])
// CHECK: bb3(
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: } // end sil function '_TFC15objc_extensions3Subg4propGSQSS_'
// Then check the setter @objc thunk.
//
// TODO: This codegens using a select_enum + cond_br. It would be better to
// just use a switch_enum so we can consume the value. This change will be
// necessary in a semantic ARC world.
//
// CHECK-LABEL: sil hidden [thunk] @_TToFC15objc_extensions3Subs4propGSQSS_ : $@convention(objc_method) (Optional<NSString>, Sub) -> () {
// CHECK: bb0([[NEW_VALUE:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $Sub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Sub
// CHECK: bb1:
// CHECK: bb3([[BRIDGED_NEW_VALUE:%.*]] : $Optional<String>):
// CHECK: [[NORMAL_FUNC:%.*]] = function_ref @_TFC15objc_extensions3Subs4propGSQSS_ : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> ()
// CHECK: apply [[NORMAL_FUNC]]([[BRIDGED_NEW_VALUE]], [[SELF_COPY]])
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: } // end sil function '_TToFC15objc_extensions3Subs4propGSQSS_'
// Then check the body of the actually setter value and make sure that we
// call the didSet function.
// CHECK-LABEL: sil hidden @_TFC15objc_extensions3Subs4propGSQSS_ : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () {
// First we get the old value.
// CHECK: bb0([[NEW_VALUE:%.*]] : $Optional<String>, [[SELF:%.*]] : $Sub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base
// CHECK: [[GET_SUPER_METHOD:%.*]] = super_method [volatile] [[SELF_COPY]] : $Sub, #Base.prop!getter.1.foreign : (Base) -> () -> String! , $@convention(objc_method) (Base) -> @autoreleased Optional<NSString>
// CHECK: [[OLD_NSSTRING:%.*]] = apply [[GET_SUPER_METHOD]]([[UPCAST_SELF_COPY]])
// CHECK: bb3([[OLD_NSSTRING_BRIDGED:%.*]] : $Optional<String>):
// This next line is completely not needed. But we are emitting it now.
// CHECK: [[OLD_NSSTRING_BRIDGED_CAST:%.*]] = unchecked_bitwise_cast [[OLD_NSSTRING_BRIDGED]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base
// CHECK: [[SET_SUPER_METHOD:%.*]] = super_method [volatile] [[SELF_COPY]] : $Sub, #Base.prop!setter.1.foreign : (Base) -> (String!) -> () , $@convention(objc_method) (Optional<NSString>, Base) -> ()
// CHECK: bb4:
// CHECK: bb6([[BRIDGED_NEW_STRING:%.*]] : $Optional<NSString>):
// CHECK: apply [[SET_SUPER_METHOD]]([[BRIDGED_NEW_STRING]], [[UPCAST_SELF_COPY]])
// CHECK: destroy_value [[BRIDGED_NEW_STRING]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[DIDSET_NOTIFIER:%.*]] = function_ref @_TFC15objc_extensions3SubW4propGSQSS_ : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> ()
// CHECK: [[COPIED_OLD_NSSTRING_BRIDGED_CAST:%.*]] = copy_value [[OLD_NSSTRING_BRIDGED_CAST]]
// This is an identity cast that should be eliminated by SILGen peepholes.
// CHECK: [[COPIED_OLD_NSSTRING_BRIDGED_CAST2:%.*]] = unchecked_bitwise_cast [[COPIED_OLD_NSSTRING_BRIDGED_CAST]]
// CHECK: apply [[DIDSET_NOTIFIER]]([[COPIED_OLD_NSSTRING_BRIDGED_CAST2]], [[SELF]])
// CHECK: destroy_value [[OLD_NSSTRING_BRIDGED_CAST]]
// CHECK: destroy_value [[NEW_VALUE]]
// CHECK: } // end sil function '_TFC15objc_extensions3Subs4propGSQSS_'
}
func foo() {
}
override func objCBaseMethod() {}
}
// CHECK-LABEL: sil hidden @_TF15objc_extensions20testOverridePropertyFCS_3SubT_
func testOverrideProperty(_ obj: Sub) {
// CHECK: = class_method [volatile] %0 : $Sub, #Sub.prop!setter.1.foreign : (Sub) -> (String!) -> ()
obj.prop = "abc"
} // CHECK: }
testOverrideProperty(Sub())
// CHECK-LABEL: sil shared [thunk] @_TFC15objc_extensions3Sub3fooFT_T_
// CHECK: function_ref @_TTDFC15objc_extensions3Sub3foofT_T_
// CHECK: } // end sil function '_TFC15objc_extensions3Sub3fooFT_T_'
// CHECK: sil shared [transparent] [thunk] @_TTDFC15objc_extensions3Sub3foofT_T_
// CHECK: bb0([[SELF:%.*]] : $Sub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: class_method [volatile] [[SELF_COPY]] : $Sub, #Sub.foo!1.foreign
// CHECK: } // end sil function '_TTDFC15objc_extensions3Sub3foofT_T_'
func testCurry(_ x: Sub) {
_ = x.foo
}
extension Sub {
var otherProp: String {
get { return "hello" }
set { }
}
}
class SubSub : Sub {
// CHECK-LABEL: sil hidden @_TFC15objc_extensions6SubSub14objCBaseMethodfT_T_
// CHECK: bb0([[SELF:%.*]] : $SubSub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: super_method [volatile] [[SELF_COPY]] : $SubSub, #Sub.objCBaseMethod!1.foreign : (Sub) -> () -> () , $@convention(objc_method) (Sub) -> ()
// CHECK: } // end sil function '_TFC15objc_extensions6SubSub14objCBaseMethodfT_T_'
override func objCBaseMethod() {
super.objCBaseMethod()
}
}
extension SubSub {
// CHECK-LABEL: sil hidden @_TFC15objc_extensions6SubSubs9otherPropSS
// CHECK: bb0([[NEW_VALUE:%.*]] : $String, [[SELF:%.*]] : $SubSub):
// CHECK: [[SELF_COPY_1:%.*]] = copy_value [[SELF]]
// CHECK: = super_method [volatile] [[SELF_COPY_1]] : $SubSub, #Sub.otherProp!getter.1.foreign
// CHECK: [[SELF_COPY_2:%.*]] = copy_value [[SELF]]
// CHECK: = super_method [volatile] [[SELF_COPY_2]] : $SubSub, #Sub.otherProp!setter.1.foreign
// CHECK: } // end sil function '_TFC15objc_extensions6SubSubs9otherPropSS'
override var otherProp: String {
didSet {
// Ignore it.
}
}
}
// SR-1025
extension Base {
fileprivate static var x = 1
}
// CHECK-LABEL: sil hidden @_TF15objc_extensions19testStaticVarAccessFT_T_
func testStaticVarAccess() {
// CHECK: [[F:%.*]] = function_ref @_TFE15objc_extensionsCSo4BaseauP33_1F05E59585E0BB585FCA206FBFF1A92D1xSi
// CHECK: [[PTR:%.*]] = apply [[F]]()
// CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]]
_ = Base.x
}
| apache-2.0 | d3fc9efd5718265450aa7fb25400385f | 48.006369 | 213 | 0.625032 | 3.448678 | false | false | false | false |
natecook1000/swift | test/SILGen/external_definitions.swift | 2 | 2524 | // RUN: %target-swift-emit-silgen -sdk %S/Inputs %s -enable-sil-ownership -enable-objc-interop | %FileCheck %s
import ansible
var a = NSAnse(Ansible(bellsOn: NSObject()))
var anse = NSAnse
hasNoPrototype()
// CHECK-LABEL: sil @main
// -- Foreign function is referenced with C calling conv and ownership semantics
// CHECK: [[NSOBJECT_CTOR:%.*]] = function_ref @$SSo8NSObjectC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick NSObject.Type) -> @owned NSObject
// CHECK: [[ANSIBLE_CTOR:%.*]] = function_ref @$SSo7AnsibleC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[ANSIBLE:%.*]] = apply [[ANSIBLE_CTOR]]
// CHECK: [[NSANSE:%.*]] = function_ref @NSAnse : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
// CHECK: [[NSANSE_RESULT:%.*]] = apply [[NSANSE]]([[ANSIBLE]])
// CHECK: destroy_value [[ANSIBLE]] : $Optional<Ansible>
// -- Referencing unapplied C function goes through a thunk
// CHECK: [[NSANSE:%.*]] = function_ref @$SSo6NSAnseySo7AnsibleCSgADFTO : $@convention(thin) (@guaranteed Optional<Ansible>) -> @owned Optional<Ansible>
// -- Referencing unprototyped C function passes no parameters
// CHECK: [[NOPROTO:%.*]] = function_ref @hasNoPrototype : $@convention(c) () -> ()
// CHECK: apply [[NOPROTO]]()
// -- Constructors for imported NSObject
// CHECK-LABEL: sil shared [serializable] @$SSo8NSObjectC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick NSObject.Type) -> @owned NSObject
// -- Constructors for imported Ansible
// CHECK-LABEL: sil shared [serializable] @$SSo7AnsibleC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@in Optional<Any>, @thick Ansible.Type) -> @owned Optional<Ansible>
// -- Native Swift thunk for NSAnse
// CHECK: sil shared [serializable] [thunk] @$SSo6NSAnseySo7AnsibleCSgADFTO : $@convention(thin) (@guaranteed Optional<Ansible>) -> @owned Optional<Ansible> {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $Optional<Ansible>):
// CHECK: [[ARG0_COPY:%.*]] = copy_value [[ARG0]]
// CHECK: [[FUNC:%.*]] = function_ref @NSAnse : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
// CHECK: [[RESULT:%.*]] = apply [[FUNC]]([[ARG0_COPY]]) : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
// CHECK: destroy_value [[ARG0_COPY]] : $Optional<Ansible>
// CHECK: return [[RESULT]] : $Optional<Ansible>
// CHECK: }
// -- Constructor for imported Ansible was unused, should not be emitted.
// CHECK-NOT: sil {{.*}} @$SSo7AnsibleC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick Ansible.Type) -> @owned Ansible
| apache-2.0 | 804f144e161a1a314041aea204da4353 | 57.697674 | 167 | 0.665214 | 3.54993 | false | false | false | false |
dtp5/OneApp | Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Evaporate.swift | 4 | 3080 | //
// LTMorphingLabel+Evaporate.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2014 Lex Tang, http://LexTang.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
extension LTMorphingLabel {
func EvaporateLoad() {
_progressClosures["Evaporate\(LTMorphingPhaseManipulateProgress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
let j: Int = Int(round(cos(Double(index)) * 1.2))
let delay = isNewChar ? self.morphingCharacterDelay * -1.0 : self.morphingCharacterDelay
return min(1.0, max(0.0, self.morphingProgress + delay * Float(j)))
}
_effectClosures["Evaporate\(LTMorphingPhaseDisappear)"] = {
(char:Character, index: Int, progress: Float) in
let newProgress = LTEasing.easeOutQuint(progress, 0.0, 1.0, 1.0)
let yOffset: CGFloat = -0.8 * CGFloat(self.font.pointSize) * CGFloat(newProgress)
let currentRect = CGRectOffset(self._originRects[index], 0, yOffset)
let currentAlpha = CGFloat(1.0 - newProgress)
return LTCharacterLimbo(
char: char,
rect: currentRect,
alpha: currentAlpha,
size: self.font.pointSize,
drawingProgress: 0.0)
}
_effectClosures["Evaporate\(LTMorphingPhaseAppear)"] = {
(char:Character, index: Int, progress: Float) in
let newProgress = 1.0 - LTEasing.easeOutQuint(progress, 0.0, 1.0)
let yOffset = CGFloat(self.font.pointSize) * CGFloat(newProgress) * 1.2
return LTCharacterLimbo(
char: char,
rect: CGRectOffset(self._newRects[index], 0.0, yOffset),
alpha: CGFloat(self.morphingProgress),
size: self.font.pointSize,
drawingProgress: 0.0
)
}
}
}
| bsd-3-clause | ebaf2cd353502daa7e5698e600d0ec29 | 41.666667 | 100 | 0.631836 | 4.471616 | false | false | false | false |
statuser/Dimensional | Dimensional/DimensionalTests/DimensionalTests.swift | 1 | 4248 | //
// DimensionalTests.swift
// DimensionalTests
//
// Created by Jaden Geller on 1/5/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
import XCTest
@testable import Dimensional
class DimensionalTests: XCTestCase {
func testRowsColumns() {
let matrix: Matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
XCTAssertEqual([[1, 2, 3], [4, 5, 6], [7, 8, 9]].flatMap{ $0 }, Array(matrix.rows).flatMap{ $0 })
XCTAssertEqual([[1, 4, 7], [2, 5, 8], [3, 6, 9]].flatMap{ $0 }, Array(matrix.columns).flatMap{ $0 })
}
func testAppending() {
var matrix: Matrix<Int> = [[1, 2], [4, 5], [7, 8]]
matrix.columns.append([3, 6, 9])
XCTAssertTrue([[1, 2, 3], [4, 5, 6], [7, 8, 9]] == matrix)
matrix.rows.append([10, 11, 12])
XCTAssertTrue([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] == matrix)
matrix.columns.removeFirst(2)
XCTAssertTrue([[3], [6], [9], [12]] == matrix)
matrix.columns.append(contentsOf: [[0, 0, 0, 0], [1, 2, 3, 4]])
XCTAssertTrue([[3, 0, 1], [6, 0, 2], [9, 0, 3], [12, 0, 4]] == matrix)
matrix.columns.removeAll()
XCTAssertTrue(matrix.rows.count == 0)
matrix.rows.append([1, 2, 3, 4, 5, 6])
matrix.columns.append([7])
XCTAssertTrue(matrix == [[1, 2, 3, 4, 5, 6, 7]])
matrix.rows.removeAll()
matrix.columns.append(contentsOf: [[1, 2, 3], [4, 5, 6]])
XCTAssertTrue(matrix == [[1, 4], [2, 5], [3, 6]])
matrix.rows.insert([11, 12], at: 2)
matrix.columns.insert([0, -1, -2, -3], at: 1)
XCTAssertTrue(matrix == [[1, 0, 4], [2, -1, 5], [11, -2, 12], [3, -3, 6]])
}
func testMapping() {
let matrix: Matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
XCTAssertTrue([[true, false, true], [false, true, false], [true, false, true]] == matrix.map { $0 % 2 == 1 })
XCTAssertTrue([[1, 4, 9], [16, 25, 36], [49, 64, 81]] == matrix.map { $0 * $0 })
}
func testTranspose() {
let matrix: Matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
XCTAssertTrue([[1, 4, 7], [2, 5, 8], [3, 6, 9]] == matrix.transposed)
}
func testRepeatedValue() {
XCTAssertTrue([[1, 1, 1], [1, 1, 1]] == Matrix(repeating: 1, dimensions: (3, 2)))
XCTAssertTrue([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] == Matrix.identity(size: 4))
}
func testArithmetic() {
let a: Matrix = [[1, 2], [3, 4], [5, 6]]
XCTAssertTrue(-a == a - (2 * a))
XCTAssertTrue(a - 1 == [[0, 1], [2,3], [4,5]])
XCTAssertTrue(1 - a == [[0, -1], [-2,-3], [-4,-5]])
XCTAssertTrue(1 + a == [[2, 3], [4,5], [6,7]])
XCTAssertTrue(a + 1 == [[2, 3], [4,5], [6,7]])
}
func testDot() {
let a: Matrix = [[1, 2], [3, 4], [5, 6]]
let b: Matrix = [[2, 2], [4, 3], [1, 7]]
XCTAssertTrue(77 == a.dot(b))
}
func testDeterminant() {
XCTAssertTrue(3 == Matrix([[1, 3], [1, 6]]).determinant)
XCTAssertTrue(-4627 == Matrix([[2, 3, 3, 6], [2, 3, 6, 7], [21, 82, 0 ,3], [2, 23, 1, 1]]).determinant)
}
func testCofactor() {
XCTAssertTrue([[24, 5, -4], [-12, 3, 2], [-2, -5, 4]] == Matrix([[1, 2, 3], [0, 4, 5], [1, 0, 6]]).cofactor)
XCTAssertTrue([[24, -12, -2], [5, 3, -5], [-4, 2, 4]] == Matrix([[1, 2, 3], [0, 4, 5], [1, 0, 6]]).adjoint)
XCTAssertTrue((1.0 / 22) * [[24, -12, -2], [5, 3, -5], [-4, 2, 4]] == Matrix([[1, 2, 3], [0, 4, 5], [1, 0, 6]]).inverse)
}
func testMatrixMultiplication() {
XCTAssertTrue([[0, -5], [-6, -7]] == [[1, 0, -2], [0, 3, -1]] * [[0, 3], [-2, -1], [0, 4]])
}
func testRowViewColumnViewInitialization() {
let a: Matrix = Matrix([[1, 2], [3, 4]] as RowView)
let b: Matrix = Matrix([[1, 3], [2, 4]] as ColumnView)
XCTAssertTrue(a == b)
}
func testCholeskyDecomposition() {
let test = Matrix<Double>([[1,5,9,13],
[0,6,10,14],
[0,0,11,15],
[0,0,0,16]])
let testMatrix = test.transposed * test
XCTAssertTrue(test == testMatrix.cholesky)
}
}
| mit | 5ad06e184f8eab0f786bd2b1608e4454 | 40.23301 | 128 | 0.466447 | 2.922918 | false | true | false | false |
DadosAbertosBrasil/swift-radar-politico | swift-radar-político/DeputadoCell.swift | 1 | 2053 | //
// DeputadoCell.swift
// swift-radar-político
//
// Created by Ulysses on 3/29/16.
// Copyright © 2016 Francisco José A. C. Souza. All rights reserved.
//
import UIKit
class DeputadoCell: UITableViewCell {
@IBOutlet weak var seguindoSwitch: UISwitch!
@IBOutlet weak var nomeLabel: UILabel!
@IBOutlet weak var partidoLabel: UILabel!
@IBOutlet weak var fotoImage: UIImageView!
private var deputado:CDDeputado?
@IBAction func seguirSwitch(sender: AnyObject) {
if self.deputado == nil{
return
}
if seguindoSwitch.on == false{
DeputadosDataController.sharedInstance.unfollowDeputadoWithId(Int(self.deputado!.ideCadastro))
}else{
DeputadosDataController.sharedInstance.followDeputadoWithId(Int(self.deputado!.ideCadastro))
}
}
func loadWithDeputado(deputado:CDDeputado){
self.deputado = deputado
self.nomeLabel.text = self.deputado?.nomeParlamentar.capitalizedString
let suplenteSufix = (self.deputado!.condicao! != "Titular" ? " - "+self.deputado!.condicao : "")
self.partidoLabel.text = (self.deputado?.partido)!+" - "+(self.deputado?.uf)!+suplenteSufix
self.fotoImage.layer.cornerRadius = 15;
self.fotoImage.layer.masksToBounds = true
self.fotoImage.layer.borderWidth = 1.0
self.fotoImage.layer.borderColor = UIColor(netHex: Constants.green).CGColor
self.deputado?.loadPhoto(self.fotoImage)
if DeputadosDataController.sharedInstance.isDeputadoFoollowed(Int(self.deputado!.ideCadastro)){
self.seguindoSwitch.on = true
}
}
override func awakeFromNib(){
self.seguindoSwitch.onImage = UIImage(named: "Unfollow")
self.seguindoSwitch.offImage = UIImage(named: "Follow")
}
override func prepareForReuse() {
self.deputado = nil
self.fotoImage.image = nil
self.seguindoSwitch.on = false
}
}
| gpl-2.0 | 7449d3fc11183b29d84604f92390abbc | 29.597015 | 106 | 0.646341 | 4.20082 | false | false | false | false |
hellogaojun/Swift-coding | swift学习教材案例/GuidedTour-2.0.playground/Pages/Simple Values.xcplaygroundpage/Contents.swift | 2 | 3691 | //: # A Swift Tour
//:
//: Tradition suggests that the first program in a new language should print the words “Hello, world!” on the screen. In Swift, this can be done in a single line:
//:
print("Hello, world!")
//: If you have written code in C or Objective-C, this syntax looks familiar to you—in Swift, this line of code is a complete program. You don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program, so you don’t need a `main()` function. You also don’t need to write semicolons at the end of every statement.
//:
//: This tour gives you enough information to start writing code in Swift by showing you how to accomplish a variety of programming tasks. Don’t worry if you don’t understand something—everything introduced in this tour is explained in detail in the rest of this book.
//:
//: ## Simple Values
//:
//: Use `let` to make a constant and `var` to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.
//:
var myVariable = 42
myVariable = 50
let myConstant = 42
//: A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that `myVariable` is an integer because its initial value is an integer.
//:
//: If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.
//:
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
//: > **Experiment**:
//: > Create a constant with an explicit type of `Float` and a value of `4`.
//:
//: Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.
//:
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
//: > **Experiment**:
//: > Try removing the conversion to `String` from the last line. What error do you get?
//:
//: There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (`\`) before the parentheses. For example:
//:
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
//: > **Experiment**:
//: > Use `\()` to include a floating-point calculation in a string and to include someone’s name in a greeting.
//:
//: Create arrays and dictionaries using brackets (`[]`), and access their elements by writing the index or key in brackets. A comma is allowed after the last element.
//:
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
//: To create an empty array or dictionary, use the initializer syntax.
//:
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
//: If type information can be inferred, you can write an empty array as `[]` and an empty dictionary as `[:]`—for example, when you set a new value for a variable or pass an argument to a function.
//:
shoppingList = []
occupations = [:]
//: See [License](License) for this sample's licensing information.
//:
//: [Next](@next) | apache-2.0 | c19e8c192dc5d84b1c6977bfa140ab8f | 48.486486 | 417 | 0.724119 | 4.081382 | false | false | false | false |
edwardvalentini/AsyncMessagesViewController | AsyncMessagesViewController/Classes/Utilities/UIImage+AsyncMessagesViewController.swift | 1 | 1464 | //
// UIImage+AsyncMessagesViewController.swift
// Pods
//
// Created by Edward Valentini on 6/16/16.
//
//
import UIKit
import Foundation
extension UIImage {
func makeCircularImageWithSize(_ size: CGSize) -> UIImage {
let circleRect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(circleRect.size, false, 0.0)
let circle = UIBezierPath(roundedRect: circleRect, cornerRadius: circleRect.size.width/2.0)
circle.addClip()
self.draw(in: circleRect)
circle.lineWidth = 1
UIColor.darkGray.set()
circle.stroke()
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return roundedImage!
}
func imageMaskedWith(_ color: UIColor) -> UIImage {
let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(imageRect.size, false, scale)
let context = UIGraphicsGetCurrentContext()
context?.scaleBy(x: 1, y: -1)
context?.translateBy(x: 0, y: -(imageRect.size.height))
context?.clip(to: imageRect, mask: cgImage!)
context?.setFillColor(color.cgColor)
context?.fill(imageRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| mit | b10d3de1ac78b9ca5c1f242f77128859 | 31.533333 | 99 | 0.64959 | 4.753247 | false | false | false | false |
pengleelove/TextFieldEffects | TextFieldEffects/TextFieldEffects/AkiraTextField.swift | 11 | 3335 | //
// AkiraTextField.swift
// TextFieldEffects
//
// Created by Mihaela Miches on 5/31/15.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
@IBDesignable public class AkiraTextField : TextFieldEffects {
private let borderSize : (active: CGFloat, inactive: CGFloat) = (1,3)
private let borderLayer = CALayer()
private let textFieldInsets = CGPoint(x: 6, y: 0)
private let placeHolderInsets = CGPoint(x: 6, y: 0)
@IBInspectable public var borderColor: UIColor? {
didSet {
updateBorder()
}
}
@IBInspectable public var placeholderColor: UIColor? {
didSet {
updatePlaceholder()
}
}
override public var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override public var bounds: CGRect {
didSet {
updateBorder()
}
}
override public func drawViewsForRect(rect: CGRect) {
updateBorder()
updatePlaceholder()
addSubview(placeholderLabel)
layer.addSublayer(borderLayer)
}
override func animateViewsForTextEntry() {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.updateBorder()
self.updatePlaceholder()
})
}
override func animateViewsForTextDisplay() {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.updateBorder()
self.updatePlaceholder()
})
}
private func updatePlaceholder()
{
placeholderLabel.frame = placeholderRectForBounds(bounds)
placeholderLabel.text = placeholder
placeholderLabel.font = placeholderFontFromFont(self.font)
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
}
private func updateBorder() {
borderLayer.frame = rectForBounds(bounds)
borderLayer.borderWidth = (isFirstResponder() || !text.isEmpty) ? borderSize.active : borderSize.inactive
borderLayer.borderColor = borderColor?.CGColor
}
private func placeholderFontFromFont(font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.7)
return smallerFont
}
private var placeholderHeight : CGFloat
{
return placeHolderInsets.y + placeholderFontFromFont(self.font).lineHeight;
}
private func rectForBounds(bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x, y: bounds.origin.y + placeholderHeight, width: bounds.size.width, height: bounds.size.height - placeholderHeight)
}
public override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
if isFirstResponder() || !text.isEmpty {
return CGRectMake(placeHolderInsets.x, placeHolderInsets.y, bounds.width, placeholderHeight)
} else {
return textRectForBounds(bounds)
}
}
public override func editingRectForBounds(bounds: CGRect) -> CGRect {
return textRectForBounds(bounds)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y + placeholderHeight/2)
}
}
| mit | 829b92222d45a1f688e48019147b0d1d | 29.59633 | 155 | 0.638081 | 5.260252 | false | false | false | false |
MukeshKumarS/Swift | test/SILOptimizer/definite_init_objc_factory_init.swift | 1 | 2891 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -emit-sil | FileCheck %s
// REQUIRES: objc_interop
import Foundation
// CHECK-LABEL: sil shared @_TTOFCSo4HiveCfT5queenGSQCSo3Bee__GSQS__ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Bee>, @thick Hive.Type) -> @owned ImplicitlyUnwrappedOptional<Hive>
func testInstanceTypeFactoryMethod(queen: Bee) {
// CHECK: bb0([[QUEEN:%[0-9]+]] : $ImplicitlyUnwrappedOptional<Bee>, [[HIVE_META:%[0-9]+]] : $@thick Hive.Type):
// CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK-NEXT: [[FACTORY:%[0-9]+]] = class_method [volatile] [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : Hive.Type -> (queen: Bee!) -> Hive! , $@convention(objc_method) (ImplicitlyUnwrappedOptional<Bee>, @objc_metatype Hive.Type) -> @autoreleased ImplicitlyUnwrappedOptional<Hive>
// CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (ImplicitlyUnwrappedOptional<Bee>, @objc_metatype Hive.Type) -> @autoreleased ImplicitlyUnwrappedOptional<Hive>
// CHECK-NEXT: release_value [[QUEEN]]
// CHECK-NEXT: return [[HIVE]] : $ImplicitlyUnwrappedOptional<Hive>
var hive1 = Hive(queen: queen)
}
extension Hive {
// FIXME: This whole approach is wrong. This should be a factory
// initializer, not a convenience initializer, which means it does
// not have an initializing entry point at all.
// CHECK-LABEL: sil hidden @_TFE31definite_init_objc_factory_initCSo4HivecfT10otherQueenCSo3Bee_S0_ : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive
convenience init(otherQueen other: Bee) {
// CHECK: [[SELF_ADDR:%[0-9]+]] = alloc_stack $Hive
// CHECK: store [[OLD_SELF:%[0-9]+]] to [[SELF_ADDR]]#1
// CHECK: [[META:%[0-9]+]] = value_metatype $@thick Hive.Type, [[OLD_SELF]] : $Hive
// CHECK: [[FACTORY:%[0-9]+]] = class_method [volatile] [[META]] : $@thick Hive.Type, #Hive.init!allocator.1.foreign : Hive.Type -> (queen: Bee!) -> Hive! , $@convention(objc_method) (ImplicitlyUnwrappedOptional<Bee>, @objc_metatype Hive.Type) -> @autoreleased ImplicitlyUnwrappedOptional<Hive>
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: apply [[FACTORY]]([[QUEEN:%[0-9]+]], [[OBJC_META]]) : $@convention(objc_method) (ImplicitlyUnwrappedOptional<Bee>, @objc_metatype Hive.Type) -> @autoreleased ImplicitlyUnwrappedOptional<Hive>
// CHECK: store [[NEW_SELF:%[0-9]+]] to [[SELF_ADDR]]#1
// CHECK: strong_release [[OLD_SELF]] : $Hive
// CHECK: dealloc_stack [[SELF_ADDR]]#0
// CHECK: return [[NEW_SELF]]
self.init(queen: other)
}
convenience init(otherFlakyQueen other: Bee) throws {
try self.init(flakyQueen: other)
}
}
| apache-2.0 | e1335404945d1c0cf9c197e4869343c0 | 69.512195 | 321 | 0.67762 | 3.591304 | false | false | false | false |
lucaslouca/swift-concurrency | app-ios/Fluxcapacitor/FXCOperationItemImageDownloader.swift | 1 | 994 | //
// FXCOperationItemImageDownloader.swift
// Fluxcapacitor
//
// Created by Lucas Louca on 07/06/15.
// Copyright (c) 2015 Lucas Louca. All rights reserved.
//
import UIKit
class FXCOperationItemImageDownloader: NSOperation {
let item: FXCItem
init(item: FXCItem) {
self.item = item
}
override func main() {
if self.cancelled {
return
}
self.item.imageUrl = self.item.imageUrl.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let url = NSURL(string: self.item.imageUrl)
let imageData = NSData(contentsOfURL:url!)
if self.cancelled {
return
}
if imageData?.length > 0 {
self.item.image = UIImage(data:imageData!)
self.item.state = .Parsed
} else {
self.item.state = .Failed
self.item.image = UIImage(named: "Failed")
}
}
}
| mit | 8c20784a1668391cdf94a9d8f9e2bca4 | 23.243902 | 130 | 0.577465 | 4.518182 | false | false | false | false |
richeterre/SwiftGoal | SwiftGoalTests/ViewModels/RankingsViewModelSpec.swift | 3 | 5534 | //
// RankingsViewModelSpec.swift
// SwiftGoal
//
// Created by Martin Richter on 04/01/16.
// Copyright © 2016 Martin Richter. All rights reserved.
//
import Quick
import Nimble
import ReactiveCocoa
@testable import SwiftGoal
class RankingsViewModelSpec: QuickSpec {
override func spec() {
describe("RankingsViewModel") {
var mockStore: MockStore!
var rankingsViewModel: RankingsViewModel!
beforeEach {
mockStore = MockStore()
rankingsViewModel = RankingsViewModel(store: mockStore)
}
it("has the correct title") {
expect(rankingsViewModel.title).to(equal("Rankings"))
}
it("initially has a only single, empty section") {
expect(rankingsViewModel.numberOfSections()).to(equal(1))
expect(rankingsViewModel.numberOfRankingsInSection(0)).to(equal(0))
}
context("after becoming active") {
beforeEach {
rankingsViewModel.active.value = true
}
it("fetches a list of rankings") {
expect(mockStore.didFetchRankings).to(beTrue())
}
it("has only a single section") {
expect(rankingsViewModel.numberOfSections()).to(equal(1))
}
it("has the right number of rankings") {
expect(rankingsViewModel.numberOfRankingsInSection(0)).to(equal(4))
}
it("displays the right player names") {
let indexPath1 = NSIndexPath(forRow: 0, inSection: 0)
let indexPath2 = NSIndexPath(forRow: 1, inSection: 0)
let indexPath3 = NSIndexPath(forRow: 2, inSection: 0)
let indexPath4 = NSIndexPath(forRow: 3, inSection: 0)
expect(rankingsViewModel.playerNameAtIndexPath(indexPath1)).to(equal("A"))
expect(rankingsViewModel.playerNameAtIndexPath(indexPath2)).to(equal("C"))
expect(rankingsViewModel.playerNameAtIndexPath(indexPath3)).to(equal("D"))
expect(rankingsViewModel.playerNameAtIndexPath(indexPath4)).to(equal("B"))
}
it("displays the right ratings") {
let indexPath1 = NSIndexPath(forRow: 0, inSection: 0)
let indexPath2 = NSIndexPath(forRow: 1, inSection: 0)
let indexPath3 = NSIndexPath(forRow: 2, inSection: 0)
let indexPath4 = NSIndexPath(forRow: 3, inSection: 0)
expect(rankingsViewModel.ratingAtIndexPath(indexPath1)).to(equal("10.00"))
expect(rankingsViewModel.ratingAtIndexPath(indexPath2)).to(equal("5.00"))
expect(rankingsViewModel.ratingAtIndexPath(indexPath3)).to(equal("5.00"))
expect(rankingsViewModel.ratingAtIndexPath(indexPath4)).to(equal("0.00"))
}
}
context("when asked to refresh") {
it("fetches a list of rankings") {
rankingsViewModel.refreshObserver.sendNext(())
expect(mockStore.didFetchRankings).to(beTrue())
}
}
context("when becoming active and upon refresh") {
it("indicates its loading state") {
// Aggregate loading states into an array
var loadingStates: [Bool] = []
rankingsViewModel.isLoading.producer
.take(5)
.collect()
.startWithNext({ values in
loadingStates = values
})
rankingsViewModel.active.value = true
rankingsViewModel.refreshObserver.sendNext(())
expect(loadingStates).to(equal([false, true, false, true, false]))
}
it("notifies subscribers about content changes") {
var changeset: Changeset<Ranking>?
rankingsViewModel.contentChangesSignal.observeNext { contentChanges in
changeset = contentChanges
}
let expectedInsertions = [
NSIndexPath(forRow: 0, inSection: 0),
NSIndexPath(forRow: 1, inSection: 0),
NSIndexPath(forRow: 2, inSection: 0),
NSIndexPath(forRow: 3, inSection: 0)
]
rankingsViewModel.active.value = true
expect(changeset?.deletions).to(beEmpty())
expect(changeset?.insertions).to(equal(expectedInsertions))
rankingsViewModel.refreshObserver.sendNext(())
expect(changeset?.deletions).to(beEmpty())
expect(changeset?.insertions).to(beEmpty())
}
}
it("raises an alert when rankings cannot be fetched") {
mockStore.rankings = nil // will cause fetch error
var didRaiseAlert = false
rankingsViewModel.alertMessageSignal.observeNext({ alertMessage in
didRaiseAlert = true
})
rankingsViewModel.active.value = true
expect(didRaiseAlert).to(beTrue())
}
}
}
}
| mit | 1ea04c5005c30806d31107e94dbb7f12 | 39.985185 | 94 | 0.532442 | 5.757544 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/Integration/ZMUserSessionLegalHoldTests.swift | 1 | 4532 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireSyncEngine
class ZMUserSessionLegalHoldTests: IntegrationTest {
override func setUp() {
super.setUp()
createSelfUserAndConversation()
}
func testThatUserClientIsInsertedWhenUserReceivesLegalHoldRequest() {
// GIVEN
var team: MockTeam!
// 1) I come from a legal-hold enabled team
mockTransportSession.performRemoteChanges { session in
team = session.insertTeam(withName: "Team", isBound: true, users: [self.selfUser])
team.hasLegalHoldService = true
team.creator = self.selfUser
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// 2) I log in
XCTAssert(login())
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
let realSelfUser = user(for: selfUser)!
XCTAssertEqual(realSelfUser.legalHoldStatus, .disabled)
// 3) My team admin requests legal hold for me
mockTransportSession.performRemoteChanges { _ in
XCTAssertTrue(self.selfUser.requestLegalHold())
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
guard case let .pending(legalHoldRequest) = realSelfUser.legalHoldStatus else {
return XCTFail("No update event was fired for the incoming legal hold request.")
}
// WHEN: I accept the legal hold request
let completionExpectation = expectation(description: "The request completes.")
userSession?.accept(legalHoldRequest: legalHoldRequest, password: IntegrationTest.SelfUserPassword) { error in
XCTAssertNil(error)
completionExpectation.fulfill()
}
// THEN
XCTAssertTrue(waitForCustomExpectations(withTimeout: 1))
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
XCTAssertEqual(realSelfUser.clients.count, 2)
XCTAssertEqual(realSelfUser.legalHoldStatus, .enabled)
}
func testThatLegalHoldClientIsRemovedWhenLegalHoldRequestFails() {
var team: MockTeam!
// 1) I come from up a legal-hold enabled team
mockTransportSession.performRemoteChanges { session in
team = session.insertTeam(withName: "Team", isBound: true, users: [self.selfUser])
team.hasLegalHoldService = true
team.creator = self.selfUser
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// 2) I log in
XCTAssert(login())
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
let realSelfUser = user(for: selfUser)!
XCTAssertEqual(realSelfUser.legalHoldStatus, .disabled)
// 3) My team admin requests legal hold for me (even though
mockTransportSession.performRemoteChanges { _ in
XCTAssertTrue(self.selfUser.requestLegalHold())
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
guard case let .pending(legalHoldRequest) = realSelfUser.legalHoldStatus else {
return XCTFail("No update event was fired for the incoming legal hold request.")
}
// WHEN: I accept the legal hold request with the wrong password
let completionExpectation = expectation(description: "The request completes.")
userSession?.accept(legalHoldRequest: legalHoldRequest, password: "I tRieD 3 tImeS!") { error in
XCTAssertEqual(error, .invalidPassword)
completionExpectation.fulfill()
}
// THEN
XCTAssertTrue(waitForCustomExpectations(withTimeout: 1))
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
XCTAssertEqual(realSelfUser.clients.count, 1)
XCTAssertEqual(realSelfUser.legalHoldStatus, .pending(legalHoldRequest))
}
}
| gpl-3.0 | e80085e84d141fae74d2638727910fc6 | 36.766667 | 118 | 0.685349 | 5.24537 | false | false | false | false |
mobgeek/swift | Swift em 4 Semanas/App Lista/Lista Semana 2/Lista/ListaTableViewController.swift | 3 | 3412 | //
// ListaTableViewController.swift
// Lista
//
// Created by Fabio Santos on 11/3/14.
// Copyright (c) 2014 Fabio Santos. All rights reserved.
//
import UIKit
class ListaTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
@IBAction func voltaParaLista(segue: UIStoryboardSegue!) {
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | 1df97d7b164204958d301bc94627085d | 32.126214 | 157 | 0.680832 | 5.584288 | false | false | false | false |
bitjammer/swift | test/decl/protocol/conforms/inherited.swift | 27 | 5158 | // RUN: %target-typecheck-verify-swift
// Inheritable: method with 'Self' in its signature
protocol P1 {
func f1(_ x: Self?) -> Bool
}
// Never inheritable: property with 'Self' in its signature.
protocol P2 {
var prop2: Self { get }
}
// Never inheritable: subscript with 'Self' in its result type.
protocol P3 {
subscript (i: Int) -> Self { get }
}
// Inheritable: subscript with 'Self' in its index type.
protocol P4 {
subscript (s: Self) -> Int { get }
}
// Potentially inheritable: method returning Self
protocol P5 {
func f5() -> Self
}
// Inheritable: method returning Self
protocol P6 {
func f6() -> Self
}
// Inheritable: method involving associated type.
protocol P7 {
associatedtype Assoc
func f7() -> Assoc
}
// Inheritable: initializer requirement.
protocol P8 {
init(int: Int)
}
// Inheritable: operator requirement.
protocol P9 {
static func ==(x: Self, y: Self) -> Bool
}
// Never inheritable: method with 'Self' in a non-contravariant position.
protocol P10 {
func f10(_ arr: [Self])
}
// Never inheritable: method with 'Self' in curried position.
protocol P11 {
func f11() -> (_ x: Self) -> Int
}
// Inheritable: parameter is a function returning 'Self'.
protocol P12 {
func f12(_ s: () -> (Self, Self))
}
// Never inheritable: parameter is a function accepting 'Self'.
protocol P13 {
func f13(_ s: (Self) -> ())
}
// Inheritable: parameter is a function accepting a function
// accepting 'Self'.
protocol P14 {
func f14(_ s: ((Self) -> ()) -> ())
}
// Never inheritable: parameter is a function accepting a function
// returning 'Self'.
protocol P15 {
func f15(_ s: (() -> Self) -> ())
}
// Class A conforms to everything that can be conformed to by a
// non-final class.
class A : P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 {
// P1
func f1(_ x: A?) -> Bool { return true }
// P2
var prop2: A { // expected-error{{protocol 'P2' requirement 'prop2' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}}
return self
}
// P3
subscript (i: Int) -> A { // expected-error{{protocol 'P3' requirement 'subscript' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}}
get {
return self
}
}
// P4
subscript (a: A) -> Int {
get {
return 5
}
}
// P5
func f5() -> A { return self } // expected-error{{method 'f5()' in non-final class 'A' must return `Self` to conform to protocol 'P5'}}
// P6
func f6() -> Self { return self }
// P7
func f7() -> Int { return 5 }
// P8
required init(int: Int) { }
// P10
func f10(_ arr: [A]) { } // expected-error{{protocol 'P10' requirement 'f10' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}}
// P11
func f11() -> (_ x: A) -> Int { return { x in 5 } }
}
// P9
func ==(x: A, y: A) -> Bool { return true }
// Class B inherits A; gets all of its conformances.
class B : A {
required init(int: Int) { }
}
func testB(_ b: B) {
var _: P1 = b // expected-error{{has Self or associated type requirements}}
var _: P4 = b // expected-error{{has Self or associated type requirements}}
var _: P5 = b
var _: P6 = b
var _: P7 = b // expected-error{{has Self or associated type requirements}}
var _: P8 = b // okay
var _: P9 = b // expected-error{{has Self or associated type requirements}}
}
// Class A5 conforms to P5 in an inheritable manner.
class A5 : P5 {
// P5
func f5() -> Self { return self }
}
// Class B5 inherits A5; gets all of its conformances.
class B5 : A5 { }
func testB5(_ b5: B5) {
var _: P5 = b5 // okay
}
// Class A8 conforms to P8 in an inheritable manner.
class A8 : P8 {
required init(int: Int) { }
}
class B8 : A8 {
required init(int: Int) { }
}
func testB8(_ b8: B8) {
var _: P8 = b8 // okay
}
// Class A9 conforms to everything.
final class A9 : P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 {
// P1
func f1(_ x: A9?) -> Bool { return true }
// P2
var prop2: A9 {
return self
}
// P3
subscript (i: Int) -> A9 {
get {
return self
}
}
// P4
subscript (a: A9) -> Int {
get {
return 5
}
}
// P5
func f5() -> A9 { return self }
// P6
func f6() -> Self { return self }
// P7
func f7() -> Int { return 5 }
// P8
required init(int: Int) { }
// P10
func f10(_ arr: [A9]) { }
// P11
func f11() -> (_ x: A9) -> Int { return { x in 5 } }
}
// P9
func ==(x: A9, y: A9) -> Bool { return true }
class A12 : P12 {
func f12(_ s: () -> (A12, A12)) {}
}
class A13 : P13 {
func f13(_ s: (A13) -> ()) {} // expected-error{{protocol 'P13' requirement 'f13' cannot be satisfied by a non-final class ('A13') because it uses 'Self' in a non-parameter, non-result type position}}
}
class A14 : P14 {
func f14(_ s: ((A14) -> ()) -> ()) {}
}
class A15 : P15 {
func f15(_ s: (() -> A15) -> ()) {} // expected-error{{protocol 'P15' requirement 'f15' cannot be satisfied by a non-final class ('A15') because it uses 'Self' in a non-parameter, non-result type position}}
}
| apache-2.0 | 4006299922aa8fe33ea68fdf9e00c4a7 | 21.426087 | 208 | 0.603528 | 3.059312 | false | false | false | false |
alexth/VIPER-test | ViperTest/ViperTest/Flows/Master/MasterViewController.swift | 1 | 3111 | //
// MasterViewController.swift
// ViperTest
//
// Created by Alex Golub on 10/29/16.
// Copyright (c) 2016 Alex Golub. All rights reserved.
//
import UIKit
protocol MasterViewControllerInput: MasterPresenterOutput {
}
protocol MasterViewControllerOutput {
func setupDataSourceWith(tableView: UITableView)
func insertNewObject()
func deleteObjectAt(indexPath: IndexPath)
func eventAt(indexPath: IndexPath) -> Event
}
final class MasterViewController: UIViewController, MasterViewControllerInput {
var output: MasterViewControllerOutput!
var router: MasterRouter!
var detailViewController: DetailViewController? = nil
@IBOutlet weak var tableView: UITableView!
// MARK: Object lifecycle
override func awakeFromNib() {
super.awakeFromNib()
ViperConfigurator.configure(viewController: self,
interactorType: MasterInteractor.self,
presenterType: MasterPresenter.self,
routerType: MasterRouter.self)
}
// MARK: View lifecycle
override func viewDidLoad() {
output.setupDataSourceWith(tableView: tableView)
super.viewDidLoad()
if let split = splitViewController {
let controllers = split.viewControllers
detailViewController = (controllers[controllers.count - 1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let selectedEvent = output.eventAt(indexPath: indexPath)
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.event = selectedEvent
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: Event handling
@IBAction func didPress(addButton: UIBarButtonItem) {
output.insertNewObject()
}
@IBAction func didPress(editButton: UIBarButtonItem) {
}
// MARK: Display logic
}
extension MasterViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
output.deleteObjectAt(indexPath: indexPath)
}
}
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "Delete"
}
}
extension MasterViewController: ViperViewController {
func setOutput(output: ViperInteractor){
self.output = output as! MasterViewControllerOutput
}
func setRouter(router: ViperRouter) {
self.router = router as! MasterRouter
}
}
| mit | 3f0d5f133f47072d85b09cc54c5ff42d | 30.424242 | 141 | 0.697203 | 5.595324 | false | false | false | false |
brokenseal/iOS-exercises | Team Treehouse/RestaurantFinder/RestaurantFinder/DetailViewController.swift | 1 | 1656 | //
// DetailViewController.swift
// RestaurantFinder
//
// Created by Pasan Premaratne on 5/4/16.
// Copyright © 2017 Davide Callegar. All rights reserved.
//
import UIKit
import MapKit
class DetailViewController: UIViewController {
@IBOutlet weak var detailDescriptionLabel: UILabel!
@IBOutlet weak var map: MKMapView!
var venue: Venue? {
didSet {
self.configureView()
}
}
private func configureView() {
// Update the user interface for the detail item.
updateLabel()
updateMap()
}
private func updateLabel(){
guard let venue = self.venue, let label = self.detailDescriptionLabel else { return }
label.text = venue.name
}
private func updateMap(){
guard let venue = self.venue,
let map = map,
let latitude = venue.location?.coordinate?.latitude,
let longitude = venue.location?.coordinate?.longitude
else { return }
let mapManager = SimpleMapManager(map, regionRadius: 200.0)
mapManager.showRegion(latitude: latitude, longitude: longitude)
mapManager.addPin(title: venue.name, latitude: latitude, longitude: longitude)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidDisappear(_ animated: Bool) {
self.venue = nil
}
}
| mit | b5486562366ec014979d015512f0cb6d | 26.131148 | 93 | 0.636254 | 4.95509 | false | false | false | false |
sachin004/firefox-ios | Shared/UserAgent.swift | 3 | 4593 | /* 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 AVFoundation
import UIKit
public class UserAgent {
private static var defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
public static var syncUserAgent: String {
let appName = DeviceInfo.appName()
return "Firefox-iOS-Sync/\(AppInfo.appVersion) (\(appName))"
}
public static var tokenServerClientUserAgent: String {
let appName = DeviceInfo.appName()
return "Firefox-iOS-Token/\(AppInfo.appVersion) (\(appName))"
}
public static var fxaUserAgent: String {
let appName = DeviceInfo.appName()
return "Firefox-iOS-FxA/\(AppInfo.appVersion) (\(appName))"
}
/**
* Use this if you know that a value must have been computed before your
* code runs, or you don't mind failure.
*/
public static func cachedUserAgent(checkiOSVersion checkiOSVersion: Bool = true) -> String? {
let currentiOSVersion = UIDevice.currentDevice().systemVersion
let lastiOSVersion = defaults.stringForKey("LastDeviceSystemVersionNumber")
if let firefoxUA = defaults.stringForKey("UserAgent") {
if !checkiOSVersion || (lastiOSVersion == currentiOSVersion) {
return firefoxUA
}
}
return nil
}
/**
* This will typically return quickly, but can require creation of a UIWebView.
* As a result, it must be called on the UI thread.
*/
public static func defaultUserAgent() -> String {
assert(NSThread.currentThread().isMainThread, "This method must be called on the main thread.")
if let firefoxUA = UserAgent.cachedUserAgent(checkiOSVersion: true) {
return firefoxUA
}
let webView = UIWebView()
let appVersion = AppInfo.appVersion
let currentiOSVersion = UIDevice.currentDevice().systemVersion
defaults.setObject(currentiOSVersion,forKey: "LastDeviceSystemVersionNumber")
let userAgent = webView.stringByEvaluatingJavaScriptFromString("navigator.userAgent")!
// Extract the WebKit version and use it as the Safari version.
let webKitVersionRegex = try! NSRegularExpression(pattern: "AppleWebKit/([^ ]+) ", options: [])
let match = webKitVersionRegex.firstMatchInString(userAgent, options:[],
range: NSMakeRange(0, userAgent.characters.count))
if match == nil {
print("Error: Unable to determine WebKit version in UA.")
return userAgent // Fall back to Safari's.
}
let webKitVersion = (userAgent as NSString).substringWithRange(match!.rangeAtIndex(1))
// Insert "FxiOS/<version>" before the Mobile/ section.
let mobileRange = (userAgent as NSString).rangeOfString("Mobile/")
if mobileRange.location == NSNotFound {
print("Error: Unable to find Mobile section in UA.")
return userAgent // Fall back to Safari's.
}
let mutableUA = NSMutableString(string: userAgent)
mutableUA.insertString("FxiOS/\(appVersion) ", atIndex: mobileRange.location)
let firefoxUA = "\(mutableUA) Safari/\(webKitVersion)"
defaults.setObject(firefoxUA, forKey: "UserAgent")
return firefoxUA
}
public static func desktopUserAgent() -> String {
let userAgent = NSMutableString(string: defaultUserAgent())
// Spoof platform section
let platformRegex = try! NSRegularExpression(pattern: "\\([^\\)]+\\)", options: [])
guard let platformMatch = platformRegex.firstMatchInString(userAgent as String, options:[], range: NSMakeRange(0, userAgent.length)) else {
print("Error: Unable to determine platform in UA.")
return String(userAgent)
}
userAgent.replaceCharactersInRange(platformMatch.range, withString: "(Macintosh; Intel Mac OS X 10_11_1)")
// Strip mobile section
let mobileRegex = try! NSRegularExpression(pattern: " FxiOS/[^ ]+ Mobile/[^ ]+", options: [])
guard let mobileMatch = mobileRegex.firstMatchInString(userAgent as String, options:[], range: NSMakeRange(0, userAgent.length)) else {
print("Error: Unable to find Mobile section in UA.")
return String(userAgent)
}
userAgent.replaceCharactersInRange(mobileMatch.range, withString: "")
return String(userAgent)
}
}
| mpl-2.0 | cc5af5b9cb6d749dd46a26bb63170b14 | 40.008929 | 147 | 0.661659 | 5.063947 | false | false | false | false |
gravicle/library | LibraryTests/BoolArray+AtleastOneTrueTests.swift | 1 | 382 | import XCTest
import Nimble
import Library
class BoolArrayTests: XCTestCase {
func testAtLeastOneTrue() {
let bools = [false, false, false, true]
expect(bools.constainsAtleastOneTrue) == true
}
func testAtLeastOneTrueWhenThereAreNone() {
let bools = [false, false, false, false]
expect(bools.constainsAtleastOneTrue) == false
}
}
| mit | d0b8977d0988314a6a54126381bc496e | 21.470588 | 54 | 0.675393 | 4.107527 | false | true | false | false |
Fenrikur/ef-app_ios | Domain Model/EurofurenceModelTests/Upgrade Path/WhenUpgradingBetweenAppVersions_ApplicationShould.swift | 1 | 2021 | import EurofurenceModel
import EurofurenceModelTestDoubles
import XCTest
class WhenUpgradingBetweenAppVersions_ApplicationShould: XCTestCase {
func testIndicateStoreIsStale() {
let forceUpgradeRequired = StubForceRefreshRequired(isForceRefreshRequired: true)
let presentDataStore = InMemoryDataStore(response: .randomWithoutDeletions)
presentDataStore.performTransaction { (transaction) in
transaction.saveLastRefreshDate(.random)
}
let context = EurofurenceSessionTestBuilder().with(presentDataStore).with(forceUpgradeRequired).build()
var dataStoreState: EurofurenceSessionState?
context.sessionStateService.determineSessionState { dataStoreState = $0 }
XCTAssertEqual(EurofurenceSessionState.stale, dataStoreState)
}
func testAlwaysEnquireWhetherUpgradeRequiredEvenWhenRefreshWouldOccurByPreference() {
let forceUpgradeRequired = CapturingForceRefreshRequired()
let presentDataStore = InMemoryDataStore(response: .randomWithoutDeletions)
let preferences = StubUserPreferences()
preferences.refreshStoreOnLaunch = true
let context = EurofurenceSessionTestBuilder().with(preferences).with(presentDataStore).with(forceUpgradeRequired).build()
context.sessionStateService.determineSessionState { (_) in }
XCTAssertTrue(forceUpgradeRequired.wasEnquiredWhetherForceRefreshRequired)
}
func testDetermineWhetherForceRefreshRequiredBeforeFirstEverSync() {
let forceUpgradeRequired = CapturingForceRefreshRequired()
let absentDataStore = InMemoryDataStore()
let preferences = StubUserPreferences()
preferences.refreshStoreOnLaunch = true
let context = EurofurenceSessionTestBuilder().with(preferences).with(absentDataStore).with(forceUpgradeRequired).build()
context.sessionStateService.determineSessionState { (_) in }
XCTAssertTrue(forceUpgradeRequired.wasEnquiredWhetherForceRefreshRequired)
}
}
| mit | ad0e393f803350182a28c67dc17797b9 | 46 | 129 | 0.769421 | 6.335423 | false | true | false | false |
buttacciot/Hiragana | Hiragana/UIView+Utils.swift | 1 | 2060 | //
// UIView+Utils.swift
// Hiragana
//
// Created by Travis Buttaccio on 7/10/16.
// Copyright © 2016 LangueMatch. All rights reserved.
//
import Foundation
extension UIView {
public class func viewFromNib<T>() -> T {
let name = description().componentsSeparatedByString(".").last
assert(name != nil)
let view: T? = viewFromNibNamed(name!)
assert(view != nil)
return view!
}
public class func viewFromNibNamed<T>(name: String) -> T? {
let arrayOfViews = NSBundle.mainBundle().loadNibNamed(name, owner: self, options: nil)
return arrayOfViews.first as? T
}
public func firstDescendant<T>() -> T? {
for view in subviews {
if let view = view as? T {
return view
} else if let view: T = view.firstDescendant() {
return view
}
}
return nil
}
public func blur(blurRadius: CGFloat = 5.0, completion:(UIImage)->()) {
UIGraphicsBeginImageContext(frame.size)
drawViewHierarchyInRect(frame, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
let beginImage = CoreImage.CIImage(CGImage: image.CGImage!)
let gaussianFilter = CIFilter(name: "CIGaussianBlur")
gaussianFilter?.setDefaults()
gaussianFilter?.setValue(beginImage, forKey: kCIInputImageKey)
gaussianFilter?.setValue(blurRadius, forKey: kCIInputRadiusKey)
let outputImage = gaussianFilter?.outputImage?.imageByCroppingToRect(CGRectMake(blurRadius, blurRadius, beginImage.extent.size.width - 2*blurRadius, beginImage.extent.size.height - 2*blurRadius))
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(UIImage(CIImage: outputImage!))
})
}
}
} | mit | f09fc2f807c0a1a9be5e211151a06a3c | 35.140351 | 207 | 0.616804 | 4.856132 | false | false | false | false |
david1mdavis/IOS-nRF-Toolbox | nRF Toolbox/HTS/NORHTSViewController.swift | 1 | 15809 | //
// NORHTSViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 09/05/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
//
import UIKit
import CoreBluetooth
class NORHTSViewController: NORBaseViewController, CBCentralManagerDelegate, CBPeripheralDelegate, NORScannerDelegate {
//MARK: - ViewController properties
var bluetoothManager : CBCentralManager?
var connectedPeripheral : CBPeripheral?
var htsServiceUUID : CBUUID
var htsMeasurementCharacteristicUUID : CBUUID
var batteryServiceUUID : CBUUID
var batteryLevelCharacteristicUUID : CBUUID
var temperatureValueFahrenheit : Bool?
var temperatureValue : Double?
//MARK: - ViewController outlets
@IBOutlet weak var type: UILabel!
@IBOutlet weak var timestamp: UILabel!
@IBOutlet weak var connectionButon: UIButton!
@IBOutlet weak var temperatureUnit: UILabel!
@IBOutlet weak var temperature: UILabel!
@IBOutlet weak var deviceName: UILabel!
@IBOutlet weak var battery: UIButton!
@IBOutlet weak var verticalLabel: UILabel!
@IBOutlet weak var degreeControl: UISegmentedControl!
//MARK: - ViewControllerActions
@IBAction func aboutButtonTapped(_ sender: AnyObject) {
self.showAbout(message: NORAppUtilities.getHelpTextForService(service: .htm))
}
@IBAction func connectionButtonTapped(_ sender: AnyObject) {
if connectedPeripheral != nil {
bluetoothManager?.cancelPeripheralConnection(connectedPeripheral!)
}
}
@IBAction func degreeHasChanged(_ sender: AnyObject) {
let control = sender as! UISegmentedControl
if (control.selectedSegmentIndex == 0) {
// Celsius
temperatureValueFahrenheit = false
UserDefaults.standard.set(false, forKey: "fahrenheit")
self.temperatureUnit.text = "°C"
if temperatureValue != nil {
temperatureValue = (temperatureValue! - 32.0) * 5.0 / 9.0
}
} else {
// Fahrenheit
temperatureValueFahrenheit = true
UserDefaults.standard.set(true, forKey: "fahrenheit")
self.temperatureUnit.text = "°F"
if temperatureValue != nil {
temperatureValue = temperatureValue! * 9.0 / 5.0 + 32.0
}
}
UserDefaults.standard.synchronize()
if temperatureValue != nil {
self.temperature.text = String(format:"%.2f", temperatureValue!)
}
}
//MARK: - Segue handling
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// The 'scan' seque will be performed only if connectedPeripheral == nil (if we are not connected already).
return identifier != "scan" || connectedPeripheral == nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "scan" {
// Set this contoller as scanner delegate
let navigationController = segue.destination as! UINavigationController
let scannerController = navigationController.childViewControllerForStatusBarHidden as! NORScannerViewController
scannerController.filterUUID = htsServiceUUID
scannerController.delegate = self
}
}
//MARK: - UIViewControllerDelegate
required init?(coder aDecoder: NSCoder) {
// Custom initialization
htsServiceUUID = CBUUID(string: NORServiceIdentifiers.htsServiceUUIDString)
htsMeasurementCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.htsMeasurementCharacteristicUUIDString)
batteryServiceUUID = CBUUID(string: NORServiceIdentifiers.batteryServiceUUIDString)
batteryLevelCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.batteryLevelCharacteristicUUIDString)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.verticalLabel.transform = CGAffineTransform(translationX: -(verticalLabel.frame.width/2) + (verticalLabel.frame.height / 2), y: 0.0).rotated(by: CGFloat(-M_PI_2))
self.updateUnits()
}
//MARK: - CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard error == nil else {
print("An error occured while discovering services: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return;
}
for aService : CBService in peripheral.services! {
// Discovers the characteristics for a given service
if aService.uuid == htsServiceUUID {
peripheral.discoverCharacteristics([htsMeasurementCharacteristicUUID], for: aService)
}else if aService.uuid == batteryServiceUUID {
peripheral.discoverCharacteristics([batteryLevelCharacteristicUUID], for: aService)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard error == nil else {
print("Error occurred while discovering characteristic: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return
}
// Characteristics for one of those services has been found
if service.uuid == htsServiceUUID {
for aCharacteristic : CBCharacteristic in service.characteristics! {
if aCharacteristic.uuid == htsMeasurementCharacteristicUUID {
// Enable notification on data characteristic
peripheral.setNotifyValue(true, for: aCharacteristic)
break
}
}
} else if service.uuid == batteryServiceUUID {
for aCharacteristic : CBCharacteristic in service.characteristics! {
if aCharacteristic.uuid == batteryLevelCharacteristicUUID {
peripheral.readValue(for: aCharacteristic)
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
print("Error occurred while updating characteristic value: \(error!.localizedDescription)")
return
}
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
// Decode the characteristic data
let data = characteristic.value
var array = UnsafeMutablePointer<UInt8>(OpaquePointer(((data as NSData?)?.bytes)!))
if characteristic.uuid == self.batteryLevelCharacteristicUUID {
let batteryLevel = NORCharacteristicReader.readUInt8Value(ptr: &array)
let text = "\(batteryLevel)%"
self.battery.setTitle(text, for: UIControlState.disabled)
if self.battery.tag == 0 {
// If battery level notifications are available, enable them
if characteristic.properties.rawValue & CBCharacteristicProperties.notify.rawValue > 0 {
self.battery.tag = 1; // mark that we have enabled notifications
// Enable notification on data characteristic
peripheral.setNotifyValue(true, for: characteristic)
}
}
} else if characteristic.uuid == self.htsMeasurementCharacteristicUUID {
let flags = NORCharacteristicReader.readUInt8Value(ptr: &array)
let tempInFahrenheit : Bool = (flags & 0x01) > 0
let timestampPresent : Bool = (flags & 0x02) > 0
let typePresent : Bool = (flags & 0x04) > 0
var tempValue : Float = NORCharacteristicReader.readFloatValue(ptr: &array)
if tempInFahrenheit == false && self.temperatureValueFahrenheit! == true {
tempValue = tempValue * 9.0 / 5.0 + 32.0
}
if tempInFahrenheit == true && self.temperatureValueFahrenheit == false {
tempValue = (tempValue - 32.0) * 5.0 / 9.0
}
self.temperatureValue = Double(tempValue)
self.temperature.text = String(format: "%.2f", tempValue)
if timestampPresent == true {
let date = NORCharacteristicReader.readDateTime(ptr: &array)
let dateFormat = DateFormatter()
dateFormat.dateFormat = "dd.MM.yyyy, hh:mm"
let dateFormattedString = dateFormat.string(from: date)
self.timestamp.text = dateFormattedString
} else {
self.timestamp.text = "Date n/a"
}
/* temperature type */
if typePresent == true {
let type = NORCharacteristicReader.readUInt8Value(ptr: &array)
var location : NSString = ""
switch (type)
{
case 0x01:
location = "Armpit";
break;
case 0x02:
location = "Body - general";
break;
case 0x03:
location = "Ear";
break;
case 0x04:
location = "Finger";
break;
case 0x05:
location = "Gastro-intenstinal Tract";
break;
case 0x06:
location = "Mouth";
break;
case 0x07:
location = "Rectum";
break;
case 0x08:
location = "Toe";
break;
case 0x09:
location = "Tympanum - ear drum";
break;
default:
location = "Unknown";
break;
}
self.type.text = String(format: "Location: %@", location)
} else {
self.type.text = "Location: n/a";
}
if NORAppUtilities.isApplicationInactive() {
var message : String = ""
if (self.temperatureValueFahrenheit == true) {
message = String(format:"New temperature reading: %.2f°F", tempValue)
} else {
message = String(format:"New temperature reading: %.2f°C", tempValue)
}
NORAppUtilities.showBackgroundNotification(message: message)
}
}
})
}
//MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOff {
print("Bluetooth powered off")
} else {
print("Bluetooth powered on")
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
self.deviceName.text = peripheral.name
self.connectionButon.setTitle("DISCONNECT", for: UIControlState())
})
NotificationCenter.default.addObserver(self, selector: #selector(self.appDidEnterBackrgoundCallback), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.appDidBecomeActiveCallback), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
// Peripheral has connected. Discover required services
connectedPeripheral = peripheral;
peripheral.discoverServices([htsServiceUUID, batteryServiceUUID])
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
NORAppUtilities.showAlert(title: "Error", andMessage: "Connecting to peripheral failed. Try again")
self.connectionButon.setTitle("CONNECT", for: UIControlState())
self.connectedPeripheral = nil
self.clearUI()
})
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
self.connectionButon.setTitle("CONNECT", for: UIControlState())
if NORAppUtilities.isApplicationInactive() {
let name = peripheral.name ?? "Peripheral"
NORAppUtilities.showBackgroundNotification(message: "\(name) is disconnected.")
}
self.connectedPeripheral = nil
self.clearUI()
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
})
}
//MARK: - NORScannerDelegate
func centralManagerDidSelectPeripheral(withManager aManager: CBCentralManager, andPeripheral aPeripheral: CBPeripheral) {
// We may not use more than one Central Manager instance. Let's just take the one returned from Scanner View Controller
bluetoothManager = aManager
bluetoothManager!.delegate = self
// The sensor has been selected, connect to it
aPeripheral.delegate = self
let options = [CBConnectPeripheralOptionNotifyOnNotificationKey : NSNumber(value: true as Bool)]
bluetoothManager!.connect(aPeripheral, options: options)
}
//MARK: - NORHTSViewController implementation
func updateUnits() {
temperatureValueFahrenheit = UserDefaults.standard.bool(forKey: "fahrenheit")
if temperatureValueFahrenheit == true {
degreeControl.selectedSegmentIndex = 1
self.temperatureUnit.text = "°F"
} else {
degreeControl.selectedSegmentIndex = 0
self.temperatureUnit.text = "°C"
}
}
func appDidEnterBackrgoundCallback() {
let name = connectedPeripheral?.name ?? "peripheral"
NORAppUtilities.showBackgroundNotification(message: "You are still connected to \(name). It will collect data also in background.")
}
func appDidBecomeActiveCallback() {
UIApplication.shared.cancelAllLocalNotifications()
self.updateUnits()
}
func clearUI() {
deviceName.text = "DEFAULT HTM"
battery.tag = 0
battery.setTitle("n/a", for: UIControlState.disabled)
self.temperature.text = "-"
self.timestamp.text = ""
self.type.text = ""
}
}
| bsd-3-clause | c47d5ce2d48d063d47345591ce759bc7 | 44.148571 | 181 | 0.591634 | 5.891872 | false | false | false | false |
AkshayNG/iSwift | iSwift/Extensions/UIImage+Extension.swift | 1 | 1872 | //
// UIImage+Extension.swift
// All List
//
// Created by Amol Bapat on 30/01/17.
// Copyright © 2017 Olive. All rights reserved.
//
import UIKit
public extension UIImage
{
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1))
{
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
func alpha(value:CGFloat)->UIImage
{
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: CGPoint.zero, blendMode: .normal, alpha: value)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func toBase64String(isPNG:Bool) -> String?
{
if isPNG {
if let pngData = UIImagePNGRepresentation(self) {
return pngData.base64EncodedString()
}
} else {
if let jpgData = UIImageJPEGRepresentation(self, 1.0) {
return jpgData.base64EncodedString()
}
}
return nil
}
static func thumbnail(forVideoURL url: URL) -> UIImage? {
do {
let asset = AVURLAsset(url: url)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
let cgImage = try imageGenerator.copyCGImage(at: kCMTimeZero, actualTime: nil)
return UIImage(cgImage: cgImage)
} catch {
print(error.localizedDescription)
return nil
}
}
}
| mit | 06049b92ad0713e89fd585e11a2856f6 | 29.177419 | 90 | 0.610903 | 4.962865 | false | false | false | false |
RCOS-QuickCast/quickcast_ios | new QuickCast/FollowingViewController.swift | 1 | 2405 | //
// FollowingViewController.swift
// new QuickCast
//
// Created by Ethan Geng on 21/10/2016.
// Copyright © 2016 Ethan. All rights reserved.
//
import UIKit
class FollowingViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var menuButton: UIBarButtonItem!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return Match.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MatchTableViewCell
cell.TeamImageView1.image = UIImage(named: "Dota2")
cell.TeamImageView2.image = UIImage(named: "Dota2")
// Configure the cell...
cell.TeamName1.text = TeamNames1[indexPath.row]
cell.TeamName2.text = TeamNames2[indexPath.row]
return cell
}
var Match = ["match 1", "match 2", "match 3", "match 4", "match 5", "match 6", "match 7", "match 8", "match 9", "match 10"]
var TeamNames1 = ["Team 1", "Team 3", "Team 5", "Team 7", "Team 9", "Team 11", "Team 13", "Team 15", "Team 17", "Team 19"]
var TeamNames2 = ["Team 2", "Team 4", "Team 6", "Team 8", "Team 10", "Team 12", "Team 14", "Team 16", "Team 18", "Team 20"]
override func viewDidLoad() {
super.viewDidLoad()
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
} // 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?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 193be07c50304152f6776e9fdfb5f488 | 38.409836 | 127 | 0.652246 | 4.535849 | false | false | false | false |
icerockdev/IRPDFKit | IRPDFKit/Classes/Search/IRPDFLoadingTableViewCell.swift | 1 | 1391 | //
// Created by Aleksey Mikhailov on 19/10/16.
// Copyright © 2016 IceRock Development. All rights reserved.
//
import Foundation
class IRPDFLoadingTableViewCell: UITableViewCell {
let activityIndicator: UIActivityIndicatorView
init(reuseIdentifier identifier: String?) {
activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = false
activityIndicator.hidden = false
activityIndicator.color = UIColor.blackColor()
super.init(style: .Default, reuseIdentifier: identifier)
contentView.addSubview(activityIndicator)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let rect = contentView.bounds
let itemSize = activityIndicator.bounds.size
let halfItemSize = CGSizeMake(itemSize.width / 2.0, itemSize.height / 2.0)
activityIndicator.frame = CGRectMake(rect.width / 2.0 - halfItemSize.width,
rect.height / 2.0 - halfItemSize.height,
itemSize.width,
itemSize.height)
}
override func didMoveToSuperview() {
if let _ = superview {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
}
| mit | d069f00fc8f884fb21474ec02a8ac06c | 29.217391 | 81 | 0.654676 | 5.285171 | false | false | false | false |
0xfeedface1993/Xs8-Safari-Block-Extension-Mac | Sex8BlockExtension/CoreDataExtension.swift | 1 | 14298 | //
// CoreDataExtension.swift
// Sex8BlockExtension
//
// Created by virus1993 on 2017/9/24.
// Copyright © 2017年 ascp. All rights reserved.
//
import Foundation
import CoreData
/// CoreData 执行状态
///
/// - success: 成功
/// - failed: 失败
enum SaveState {
case success
case failed
}
/// 页面模型
struct PageData : Equatable {
var links : [String]
var password : String
var title : String
var pics : [String]
var fileName : String
var url : String
init(data : [String:Any]?) {
links = data?["links"] as? [String] ?? []
pics = data?["pics"] as? [String] ?? []
password = data?["passwod"] as? String ?? ""
title = data?["title"] as? String ?? ""
fileName = data?["fileName"] as? String ?? ""
url = data?["url"] as? String ?? ""
}
static func ==(lhs: PageData, rhs: PageData) -> Bool {
return lhs.url == rhs.url
}
}
/// 单例数据库类
class DataBase {
static let share = DataBase()
lazy var managedObjectContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let persistentContainer = NSPersistentContainer(name: "NetdiskModel")
let storeURL = URL.storeURL(for: "E6NP67H473.ascp.netdisk", databaseName: "NetdiskModel")
let storeDescription = NSPersistentStoreDescription(url: storeURL)
persistentContainer.persistentStoreDescriptions = [storeDescription]
persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error)")
}
})
return persistentContainer
}()
// 检查是否已经存在数据
static func checkPropertyExist<T: NSFetchRequestResult>(entity: String, property: String, value: String) -> T? {
let fetch = NSFetchRequest<T>(entityName: entity)
fetch.predicate = NSPredicate(format: "SELF.\(property) == '\(value)'")
do {
let datas = try DataBase.share.managedObjectContext.fetch(fetch)
return datas.first
} catch {
fatalError("Failed to fetch \(property): \(error)")
}
}
/// 保存页面信息
///
/// - Parameters:
/// - data: js脚本返回的页面数据,是键值对
/// - completion: 执行回调
func saveDownloadLink(data: PageData, completion: ((SaveState) -> ())?) {
if let _ : NetDisk = DataBase.checkPropertyExist(entity: NetDisk.className(), property: "pageurl", value: data.url) {
print("------- netdisk exists ------ : \(data.url)")
completion?(.success)
return
}
let netdisk = NSEntityDescription.insertNewObject(forEntityName: "NetDisk", into: DataBase.share.managedObjectContext) as! NetDisk
netdisk.creattime = Date()
netdisk.fileName = data.fileName
netdisk.title = data.title
netdisk.passwod = data.password
netdisk.pageurl = data.url
netdisk.pic = nil
netdisk.link = nil
for sLink in data.links {
if let exitLink : Link = DataBase.checkPropertyExist(entity: Link.className(), property: "link", value: sLink) {
netdisk.addToLink(exitLink)
continue
}
let link = NSEntityDescription.insertNewObject(forEntityName: "Link", into: DataBase.share.managedObjectContext) as! Link
link.creattime = Date()
link.link = sLink
link.addToLinknet(netdisk)
}
for sLink in data.pics {
if let exitLink : Pic = DataBase.checkPropertyExist(entity: Pic.className(), property: "pic", value: sLink) {
netdisk.addToPic(exitLink)
continue
}
let link = NSEntityDescription.insertNewObject(forEntityName: "Pic", into: DataBase.share.managedObjectContext) as! Pic
link.creattime = Date()
link.pic = sLink
link.addToPicnet(netdisk)
}
do {
let context = DataBase.share.managedObjectContext
if !context.commitEditing() {
NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing before saving")
}
if context.hasChanges {
try context.save()
}
completion?(.success)
} catch {
completion?(.failed)
print("Failure to save context: \(error)")
}
}
func saveFetchBotDownloadLink(data: ContentInfo, completion: ((SaveState) -> ())?) {
if let _ : NetDisk = DataBase.checkPropertyExist(entity: NetDisk.className(), property: "pageurl", value: data.page) {
print("------- netdisk exists ------ : \(data.page)")
completion?(.success)
return
}
if let _ : NetDisk = DataBase.checkPropertyExist(entity: NetDisk.className(), property: "title", value: data.title) {
print("------- netdisk exists ------ : \(data.title)")
completion?(.success)
return
}
let netdisk = NSEntityDescription.insertNewObject(forEntityName: "NetDisk", into: DataBase.share.managedObjectContext) as! NetDisk
netdisk.creattime = Date()
netdisk.fileName = ""
netdisk.title = data.title
netdisk.passwod = data.passwod
netdisk.pageurl = data.page
netdisk.msk = data.msk
netdisk.time = data.time
netdisk.format = data.format
netdisk.size = data.size
netdisk.pic = nil
netdisk.link = nil
for sLink in data.downloafLink {
if let exitLink : Link = DataBase.checkPropertyExist(entity: Link.className(), property: "link", value: sLink) {
netdisk.addToLink(exitLink)
continue
}
let link = NSEntityDescription.insertNewObject(forEntityName: "Link", into: DataBase.share.managedObjectContext) as! Link
link.creattime = Date()
link.link = sLink
link.addToLinknet(netdisk)
}
for sLink in data.imageLink {
if let exitLink : Pic = DataBase.checkPropertyExist(entity: Pic.className(), property: "pic", value: sLink) {
netdisk.addToPic(exitLink)
continue
}
let link = NSEntityDescription.insertNewObject(forEntityName: "Pic", into: DataBase.share.managedObjectContext) as! Pic
link.creattime = Date()
link.pic = sLink
link.addToPicnet(netdisk)
}
do {
let context = DataBase.share.managedObjectContext
if !context.commitEditing() {
NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing before saving")
}
if context.hasChanges {
try context.save()
}
completion?(.success)
} catch {
completion?(.failed)
print("Failure to save context: \(error)")
}
}
func save(downloadLinks: [ContentInfo], completion: ((SaveState) -> ())?) {
for data in downloadLinks {
if let _ : NetDisk = DataBase.checkPropertyExist(entity: NetDisk.className(), property: "pageurl", value: data.page) {
print("------- netdisk exists ------ : \(data.page)")
completion?(.success)
return
}
if let _ : NetDisk = DataBase.checkPropertyExist(entity: NetDisk.className(), property: "title", value: data.title) {
print("------- netdisk exists ------ : \(data.title)")
completion?(.success)
return
}
let netdisk = NSEntityDescription.insertNewObject(forEntityName: "NetDisk", into: DataBase.share.managedObjectContext) as! NetDisk
netdisk.creattime = Date()
netdisk.fileName = ""
netdisk.title = data.title
netdisk.passwod = data.passwod
netdisk.pageurl = data.page
netdisk.msk = data.msk
netdisk.time = data.time
netdisk.format = data.format
netdisk.size = data.size
netdisk.pic = nil
netdisk.link = nil
for sLink in data.downloafLink {
if let exitLink : Link = DataBase.checkPropertyExist(entity: Link.className(), property: "link", value: sLink) {
netdisk.addToLink(exitLink)
continue
}
let link = NSEntityDescription.insertNewObject(forEntityName: "Link", into: DataBase.share.managedObjectContext) as! Link
link.creattime = Date()
link.link = sLink
link.addToLinknet(netdisk)
}
for sLink in data.imageLink {
if let exitLink : Pic = DataBase.checkPropertyExist(entity: Pic.className(), property: "pic", value: sLink) {
netdisk.addToPic(exitLink)
continue
}
let link = NSEntityDescription.insertNewObject(forEntityName: "Pic", into: DataBase.share.managedObjectContext) as! Pic
link.creattime = Date()
link.pic = sLink
link.addToPicnet(netdisk)
}
}
do {
let context = DataBase.share.managedObjectContext
if !context.commitEditing() {
NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing before saving")
}
if context.hasChanges {
try context.save()
}
completion?(.success)
} catch {
completion?(.failed)
print("Failure to save context: \(error)")
}
}
func saveRemoteDownloadLink(data: RemoteNetDisk, completion: ((SaveState) -> ())?) {
if let _ : NetDisk = DataBase.checkPropertyExist(entity: NetDisk.className(), property: "pageurl", value: data.pageurl) {
print("------- netdisk exists ------ : \(data.pageurl)")
completion?(.success)
return
}
if let _ : NetDisk = DataBase.checkPropertyExist(entity: NetDisk.className(), property: "title", value: data.title) {
print("------- netdisk exists ------ : \(data.title)")
completion?(.success)
return
}
let netdisk = NSEntityDescription.insertNewObject(forEntityName: "NetDisk", into: DataBase.share.managedObjectContext) as! NetDisk
netdisk.creattime = Date()
netdisk.fileName = ""
netdisk.title = data.title
netdisk.passwod = data.passwod
netdisk.pageurl = data.pageurl
netdisk.msk = data.msk
netdisk.time = data.time
netdisk.format = data.format
netdisk.size = data.size
netdisk.pic = nil
netdisk.link = nil
for sLink in data.links {
if let exitLink : Link = DataBase.checkPropertyExist(entity: Link.className(), property: "link", value: sLink) {
netdisk.addToLink(exitLink)
continue
}
let link = NSEntityDescription.insertNewObject(forEntityName: "Link", into: DataBase.share.managedObjectContext) as! Link
link.creattime = Date()
link.link = sLink
link.addToLinknet(netdisk)
}
for sLink in data.pics {
if let exitLink : Pic = DataBase.checkPropertyExist(entity: Pic.className(), property: "pic", value: sLink) {
netdisk.addToPic(exitLink)
continue
}
let link = NSEntityDescription.insertNewObject(forEntityName: "Pic", into: DataBase.share.managedObjectContext) as! Pic
link.creattime = Date()
link.pic = sLink
link.addToPicnet(netdisk)
}
do {
let context = DataBase.share.managedObjectContext
if !context.commitEditing() {
NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing before saving")
}
if context.hasChanges {
try context.save()
}
completion?(.success)
} catch {
completion?(.failed)
print("Failure to save context: \(error)")
}
}
}
public extension URL {
/// Returns a URL for the given app group and database pointing to the sqlite database.
static func storeURL(for appGroup: String, databaseName: String) -> URL {
guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
fatalError("Shared file container could not be created.")
}
return fileContainer.appendingPathComponent("\(databaseName).sqlite")
}
}
| apache-2.0 | c0bf3d636e19d2dcd9f607e23de3e85e | 39.661891 | 199 | 0.576563 | 5.228814 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Requests/Groups/GroupsResponseHandler.swift | 1 | 2166 | //
// GroupsResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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
import ObjectMapper
class GroupsResponseHandler: ResponseHandler {
fileprivate let completion: GroupsClosure?
init(completion: GroupsClosure?) {
self.completion = completion
}
override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) {
if let response = response,
let mappers = Mapper<GroupMapper>().mapArray(JSONObject: response["data"]) {
let metadata = MappingUtils.metadataFromResponse(response)
let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata)
let objects = mappers.map({ Group(mapper: $0, dataMapper: dataMapper) })
executeOnMainQueue { self.completion?(objects, ErrorTransformer.errorFromResponse(response, error: error)) }
} else {
executeOnMainQueue { self.completion?(nil, ErrorTransformer.errorFromResponse(response, error: error)) }
}
}
}
| mit | d8c1459f37e9d98b7b7fdee665fee49a | 44.125 | 120 | 0.724377 | 4.708696 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.