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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AliceAponasko/LJReader
|
LJReader/Controllers/ReadingListTableDataSource.swift
|
1
|
1646
|
//
// ReadingListTableDataSource.swift
// LJReader
//
// Created by Alice Aponasko on 9/12/16.
// Copyright © 2016 aliceaponasko. All rights reserved.
//
import UIKit
class ReadingListTableDataSource: NSObject, UITableViewDataSource {
var authors = [String]()
var defaults: NSUserDefaults?
convenience init(defaults: NSUserDefaults) {
self.init()
self.defaults = defaults
}
private override init() {
super.init()
}
func numberOfSectionsInTableView(
tableView: UITableView) -> Int {
return 1
}
func tableView(
tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return authors.count
}
func tableView(
tableView: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(
"AuthorCell",
forIndexPath: indexPath)
cell.textLabel?.text = authors[indexPath.row]
return cell
}
func tableView(
tableView: UITableView,
canEditRowAtIndexPath
indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(
tableView: UITableView,
commitEditingStyle
editingStyle: UITableViewCellEditingStyle,
forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let author = authors.removeAtIndex(indexPath.row)
defaults?.removeAuthor(author)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
}
|
mit
|
7325db277ad59277f743e39117d3c3b4
| 21.22973 | 82 | 0.631611 | 5.465116 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/Controller/Option/COptionPollutedGarden.swift
|
1
|
1490
|
import SpriteKit
class COptionPollutedGarden:ControllerGame<MOptionPollutedGarden>
{
override func didBegin(_ contact:SKPhysicsContact)
{
model.contact.addContact(contact:contact)
}
override func game1up()
{
super.game1up()
let sound1up:SKAction = model.sounds.sound1up
playSound(actionSound:sound1up)
newGameScene()
}
override func gamePlayNoMore()
{
let soundFail:SKAction = model.sounds.soundFail
playSound(actionSound:soundFail)
super.gamePlayNoMore()
}
//MAKR: private
private func newGameScene()
{
let newScene:VOptionPollutedGardenScene = VOptionPollutedGardenScene(
controller:self)
presentScene(newScene:newScene)
model.startLevel()
}
private func presentScene(newScene:SKScene)
{
let transition:SKTransition = model.actions.transitionCrossFade
guard
let view:SKView = self.view as? SKView
else
{
return
}
view.presentScene(newScene, transition:transition)
}
//MARK: public
func showGameOver()
{
model.strategyWait()
postScore()
let newScene:VOptionPollutedGardenSceneOver = VOptionPollutedGardenSceneOver(
controller:self)
presentScene(newScene:newScene)
}
}
|
mit
|
6330d800d06b35b16aae2da77952b440
| 21.575758 | 85 | 0.589933 | 4.885246 | false | false | false | false |
geekaurora/ReactiveListViewKit
|
ReactiveListViewKit/Supported Files/CZUtils/Sources/CZUtils/CZConcurrentOperation.swift
|
1
|
3912
|
//
// CZConcurrentOperation.swift
//
// Created by Cheng Zhang on 1/5/16.
// Copyright © 2016 Cheng Zhang. All rights reserved.
//
import Foundation
/// An abstract class that makes subclassing ConcurrentOperation easy to udpate KVO props `isReady`/`isExecuting`/`isFinished` automatically
///
/// Usage:
/// - Subclass must implement `execute()` when execute task
/// - Subclass must invoke `finish()` any work is done or after a call to `cancel()` to move the operation into a completed state.
///
/// https://gist.github.com/calebd
/// https://gist.github.com/alexaubry/1ee81a952b11a2ddc6a43480cc59032c
@objc open class CZConcurrentOperation: Operation {
/// Concurrent DispatchQueue acting as mutex read/write lock of rawState
private let stateQueue = DispatchQueue(label: "com.tony.operation.state", attributes: [.concurrent])
private var rawState: OperationState = .ready
@objc private dynamic var state: OperationState {
get {
return stateQueue.sync{ rawState}
}
set {
willChangeValue(forKey: #keyPath(state))
stateQueue.sync(flags: .barrier) {
rawState = newValue
}
didChangeValue(forKey: #keyPath(state))
}
}
public final override var isReady: Bool {
return state == .ready && super.isReady
}
public final override var isExecuting: Bool {
return state == .executing
}
public final override var isFinished: Bool {
return state == .finished
}
public final override var isConcurrent: Bool {
return true
}
// MARK: - Public Methods
/// Subclasses must implement `execute` and must not call super
open func execute() {
fatalError("Subclasses must implement `\(#function)`.")
}
/// Call this function after any work is done or after a call to `cancel()`
/// to move the operation into a completed state.
public final func finish() {
/**
Cancelled operations can still be in Queue, should verify not `.finished` before cancel again
ref: https://stackoverflow.com/questions/9409994/cancelling-nsoperation-from-nsoperationqueue-cause-crash
*/
guard state != .finished else {
return
}
// Set state to `.executing` if not before finish to avoid crash
if !isExecuting {
state = .executing
}
state = .finished
}
// MARK: - Override methods
public final override func start() {
guard state != .finished else {
return
}
if isCancelled {
finish()
return
}
state = .executing
execute()
}
open override func cancel() {
super.cancel()
/**
Invoke finish() only if it's `.excuting`, otherwise it will crash.
For un-started operation, OperationQueue will start it after being cancelled. We can `finish()` it in `start()` if `isCancelled` is true
ref: https://stackoverflow.com/questions/9409994/cancelling-nsoperation-from-nsoperationqueue-cause-crash
*/
if isExecuting {
finish()
}
}
// MARK: - Dependent KVO
/// Bind dependency of KVO between `state` and `isReady`, `isExecuting`,`isFinished`: `state` change automatically triggers KVO notification of the other 3 props
@objc private dynamic class func keyPathsForValuesAffectingIsReady() -> Set<String> {
return [#keyPath(state)]
}
@objc private dynamic class func keyPathsForValuesAffectingIsExecuting() -> Set<String> {
return [#keyPath(state)]
}
@objc private dynamic class func keyPathsForValuesAffectingIsFinished() -> Set<String> {
return [#keyPath(state)]
}
}
@objc private enum OperationState: Int {
case ready = 0, executing, finished
}
|
mit
|
616ac56c1b75dc737cc52e42ca6195e6
| 33.919643 | 165 | 0.631296 | 4.706378 | false | false | false | false |
ttilley/docopt.swift
|
Tests/DocoptTests.swift
|
2
|
19887
|
//
// DocoptTests.swift
// docoptTests
//
// Created by Pavel S. Mazurin on 2/28/15.
// Copyright (c) 2015 kovpas. All rights reserved.
//
import XCTest
@testable import Docopt
class DocoptTests: XCTestCase {
override func setUp() {
DocoptError.test = true
}
func testPatternFlat() {
XCTAssertEqual(Required([OneOrMore(Argument("N")), Option("-a"), Argument("M")]).flat(), [Argument("N"), Option("-a"), Argument("M")])
XCTAssertEqual(Required([Optional(OptionsShortcut()), Optional(Option("-a"))]).flat(OptionsShortcut.self), [OptionsShortcut()])
}
func testParseDefaults() {
let section = "options:\n\t-a Add\n\t-r Remote\n\t-m <msg> Message"
let parsedDefaults = Docopt.parseDefaults(section)
let fixture = [Option("-a"), Option("-r"), Option("-m", argCount: 1)]
XCTAssertEqual(parsedDefaults, fixture)
}
func testParseSection() {
let usage = "usage: this\nusage:hai\nusage: this that\nusage: foo\n bar\nPROGRAM USAGE:\n foo\n bar\nusage:\n\ttoo\n\ttar\nUsage: eggs spam\nBAZZ\nusage: pit stop"
XCTAssertEqual(Docopt.parseSection("usage:", source: "foo bar fizz buzz"), [])
XCTAssertEqual(Docopt.parseSection("usage:", source: "usage: prog"), ["usage: prog"])
XCTAssertEqual(Docopt.parseSection("usage:", source: "usage: -x\n -y"), ["usage: -x\n -y"])
XCTAssertEqual(Docopt.parseSection("usage:", source: usage), [
"usage: this",
"usage:hai",
"usage: this that",
"usage: foo\n bar",
"PROGRAM USAGE:\n foo\n bar",
"usage:\n\ttoo\n\ttar",
"Usage: eggs spam",
"usage: pit stop",
])
}
func testFormalUsage() {
let doc = "\nUsage: prog [-hv] ARG\n prog N M\n\n prog is a program."
let usage = Docopt.parseSection("usage:", source: doc)[0]
let formalUsage = Docopt.formalUsage(usage)
XCTAssertEqual(usage, "Usage: prog [-hv] ARG\n prog N M")
XCTAssertEqual(formalUsage, "( [-hv] ARG ) | ( N M )")
}
func testParseArgv() {
var o = [Option("-h"), Option("-v", long: "--verbose"), Option("-f", long:"--file", argCount: 1)]
let TS = {(s: String) in return Tokens(s, error: DocoptExit()) }
XCTAssertEqual(Docopt.parseArgv(TS(""), options: &o), [])
XCTAssertEqual(Docopt.parseArgv(TS("-h"), options: &o), [Option("-h", value: true as AnyObject)])
XCTAssertEqual(Docopt.parseArgv(TS("-h --verbose"), options: &o),
[Option("-h", value: true as AnyObject), Option("-v", long: "--verbose", value: true as AnyObject)])
XCTAssertEqual(Docopt.parseArgv(TS("-h --file f.txt"), options: &o),
[Option("-h", value: true as AnyObject), Option("-f", long: "--file", argCount: 1, value: "f.txt" as AnyObject)])
XCTAssertEqual(Docopt.parseArgv(TS("-h --file f.txt arg"), options: &o),
[Option("-h", value: true as AnyObject),
Option("-f", long: "--file", argCount: 1, value: "f.txt" as AnyObject),
Argument(nil, value: "arg" as AnyObject)])
XCTAssertEqual(Docopt.parseArgv(TS("-h --file f.txt arg arg2"), options: &o),
[Option("-h", value: true as AnyObject),
Option("-f", long: "--file", argCount: 1, value: "f.txt" as AnyObject),
Argument(nil, value: "arg" as AnyObject),
Argument(nil, value: "arg2" as AnyObject)])
XCTAssertEqual(Docopt.parseArgv(TS("-h arg -- -v"), options: &o),
[Option("-h", value: true as AnyObject),
Argument(nil, value: "arg" as AnyObject),
Argument(nil, value: "--" as AnyObject),
Argument(nil, value: "-v" as AnyObject)])
}
func testOptionParse() {
XCTAssertEqual(Option.parse("-h"), Option("-h"))
XCTAssertEqual(Option.parse("--help"), Option(long: "--help"))
XCTAssertEqual(Option.parse("-h --help"), Option("-h", long: "--help"))
XCTAssertEqual(Option.parse("-h, --help"), Option("-h", long: "--help"))
XCTAssertEqual(Option.parse("-h TOPIC"), Option("-h", argCount: 1))
XCTAssertEqual(Option.parse("--help TOPIC"), Option(long: "--help", argCount: 1))
XCTAssertEqual(Option.parse("-h TOPIC --help TOPIC"), Option("-h", long: "--help", argCount: 1))
XCTAssertEqual(Option.parse("-h TOPIC, --help TOPIC"), Option("-h", long: "--help", argCount: 1))
XCTAssertEqual(Option.parse("-h TOPIC, --help=TOPIC"), Option("-h", long: "--help", argCount: 1))
XCTAssertEqual(Option.parse("-h Description..."), Option("-h"))
XCTAssertEqual(Option.parse("-h --help Description..."), Option("-h", long: "--help"))
XCTAssertEqual(Option.parse("-h TOPIC Description..."), Option("-h", argCount: 1))
XCTAssertEqual(Option.parse(" -h"), Option("-h"))
XCTAssertEqual(Option.parse("-h TOPIC Descripton... [default: 2]"),
Option("-h", argCount: 1, value: "2" as AnyObject))
XCTAssertEqual(Option.parse("-h TOPIC Descripton... [default: topic-1]"),
Option("-h", argCount: 1, value: "topic-1" as AnyObject))
XCTAssertEqual(Option.parse("--help=TOPIC ... [default: 3.14]"),
Option(long: "--help", argCount: 1, value: "3.14" as AnyObject))
XCTAssertEqual(Option.parse("-h, --help=DIR ... [default: ./]"),
Option("-h", long: "--help", argCount: 1, value: "./" as AnyObject))
XCTAssertEqual(Option.parse("-h TOPIC Descripton... [dEfAuLt: 2]"),
Option("-h", argCount: 1, value: "2" as AnyObject))
}
func testOptionName() {
XCTAssertEqual(Option("-h").name!, "-h")
XCTAssertEqual(Option("-h", long: "--help").name!, "--help")
XCTAssertEqual(Option(long: "--help").name!, "--help")
}
func testParsePattern() {
var o = [Option("-h"), Option("-v", long: "--verbose"), Option("-f", long:"--file", argCount: 1)]
XCTAssertEqual(Docopt.parsePattern("[ -h ]", options: &o), Required(Optional(Option("-h"))))
XCTAssertEqual(Docopt.parsePattern("[ ARG ... ]", options: &o), Required(Optional(OneOrMore(Argument("ARG")))))
XCTAssertEqual(Docopt.parsePattern("[ -h | -v ]", options: &o), Required(Optional(Either([Option("-h"), Option("-v", long: "--verbose")]))))
XCTAssertEqual(Docopt.parsePattern("( -h | -v [ --file <f> ] )", options: &o),
Required(Required(
Either([Option("-h"),
Required([Option("-v", long: "--verbose"),
Optional(Option("-f", long: "--file", argCount: 1))])]))))
XCTAssertEqual(Docopt.parsePattern("(-h|-v[--file=<f>]N...)", options: &o),
Required(Required(Either([Option("-h"),
Required([Option("-v", long: "--verbose"),
Optional(Option("-f", long: "--file", argCount: 1)),
OneOrMore(Argument("N"))])]))))
var tmp = [Option]()
XCTAssertEqual(Docopt.parsePattern("(N [M | (K | L)] | O P)", options: &tmp),
Required(Required(Either([
Required([Argument("N"),
Optional(Either([Argument("M"),
Required(Either([Argument("K"),
Argument("L")]))]))]),
Required([Argument("O"), Argument("P")])]))))
XCTAssertEqual(Docopt.parsePattern("[ -h ] [N]", options: &o),
Required([Optional(Option("-h")),
Optional(Argument("N"))]))
XCTAssertEqual(Docopt.parsePattern("[options]", options: &o),
Required(Optional(OptionsShortcut())))
XCTAssertEqual(Docopt.parsePattern("[options] A", options: &o),
Required([Optional(OptionsShortcut()),
Argument("A")]))
XCTAssertEqual(Docopt.parsePattern("-v [options]", options: &o),
Required([Option("-v", long: "--verbose"),
Optional(OptionsShortcut())]))
XCTAssertEqual(Docopt.parsePattern("ADD", options: &o), Required(Argument("ADD")))
XCTAssertEqual(Docopt.parsePattern("<add>", options: &o), Required(Argument("<add>")))
XCTAssertEqual(Docopt.parsePattern("add", options: &o), Required(Command("add")))
}
func testOptionMatch() {
XCTAssertTrue(Option("-a").match([Option("-a", value: true as AnyObject)]) ==
(true, [], [Option("-a", value: true as AnyObject)]))
XCTAssertTrue(Option("-a").match([Option("-x")]) ==
(false, [Option("-x")], []))
XCTAssertTrue(Option("-a").match([Argument("N")]) ==
(false, [Argument("N")], []))
XCTAssertTrue(Option("-a").match([Option("-x"), Option("-a"), Argument("N")]) ==
(true, [Option("-x"), Argument("N")], [Option("-a")]))
XCTAssertTrue(Option("-a").match([Option("-a", value: true as AnyObject), Option("-a")]) ==
(true, [Option("-a")], [Option("-a", value: true as AnyObject)]))
}
func testArgumentMatch() {
XCTAssertTrue(Argument("N").match(Argument(nil, value: 9)) ==
(true, [], [Argument("N", value: 9)]))
XCTAssertTrue(Argument("N").match(Option("-x")) ==
(false, [Option("-x")], []))
XCTAssertTrue(Argument("N").match([Option("-x"), Option("-a"), Argument(nil, value: 5 as AnyObject)]) ==
(true, [Option("-x"), Option("-a")], [Argument("N", value: 5 as AnyObject)]))
XCTAssertTrue(Argument("N").match([Argument(nil, value: 9 as AnyObject), Argument(nil, value: 0 as AnyObject)]) ==
(true, [Argument(nil, value: 0 as AnyObject)], [Argument("N", value: 9 as AnyObject)]))
}
func testCommandMatch() {
XCTAssertTrue(Command("c").match(Argument(nil, value: "c" as AnyObject)) ==
(true, [], [Command("c", value: true as AnyObject)]))
XCTAssertTrue(Command("c").match(Option("-x")) ==
(false, [Option("-x")], []))
XCTAssertTrue(Command("c").match([Option("-x"), Option("-a"), Argument(nil, value: "c" as AnyObject)]) ==
(true, [Option("-x"), Option("-a")], [Command("c", value: true as AnyObject)]))
XCTAssertTrue(Either([Command("add"), Command("rm")]).match(Argument(nil, value: "rm" as AnyObject)) ==
(true, [], [Command("rm", value: true as AnyObject)]))
}
func testOptionalMatch() {
XCTAssertTrue(Optional(Option("-a")).match([Option("-a")]) ==
(true, [], [Option("-a")]))
XCTAssertTrue(Optional(Option("-a")).match([]) == (true, [], []))
XCTAssertTrue(Optional(Option("-a")).match([Option("-x")]) ==
(true, [Option("-x")], []))
XCTAssertTrue(Optional([Option("-a"), Option("-b")]).match([Option("-a")]) ==
(true, [], [Option("-a")]))
XCTAssertTrue(Optional([Option("-a"), Option("-b")]).match([Option("-b")]) ==
(true, [], [Option("-b")]))
XCTAssertTrue(Optional([Option("-a"), Option("-b")]).match([Option("-x")]) ==
(true, [Option("-x")], []))
XCTAssertTrue(Optional(Argument("N")).match([Argument(nil, value: 9 as AnyObject)]) ==
(true, [], [Argument("N", value: 9 as AnyObject)]))
XCTAssertTrue(Optional([Option("-a"), Option("-b")]).match(
[Option("-b"), Option("-x"), Option("-a")]) ==
(true, [Option("-x")], [Option("-a"), Option("-b")]))
}
func testRequiredMatch() {
XCTAssertTrue(Required(Option("-a")).match([Option("-a")]) ==
(true, [], [Option("-a")]))
XCTAssertTrue(Required(Option("-a")).match([]) == (false, [], []))
XCTAssertTrue(Required(Option("-a")).match([Option("-x")]) ==
(false, [Option("-x")], []))
XCTAssertTrue(Required([Option("-a"), Option("-b")]).match([Option("-a")]) ==
(false, [Option("-a")], []))
}
func testEitherMatch() {
// i'm too lazy to mock up a fixture of some kind. deal with it.
var expected: MatchResult
var actual: MatchResult
expected = (true, [], [Option("-a")])
actual = Either([Option("-a"), Option("-b")]).match([Option("-a")])
XCTAssertTrue(actual == expected, "\nExpected: \(expected)\nActual: \(actual)\n\n")
expected = (true, [Option("-b")], [Option("-a")])
actual = Either([Option("-a"), Option("-b")]).match([Option("-a"), Option("-b")])
XCTAssertTrue(actual == expected, "\nExpected: \(expected)\nActual: \(actual)\n\n")
expected = (false, [Option("-x")], [])
actual = Either([Option("-a"), Option("-b")]).match([Option("-x")])
XCTAssertTrue(actual == expected, "\nExpected: \(expected)\nActual: \(actual)\n\n")
expected = (true, [Option("-x")], [Option("-b")])
actual = Either([Option("-a"), Option("-b"), Option("-c")]).match([Option("-x"), Option("-b")])
XCTAssertTrue(actual == expected, "\nExpected: \(expected)\nActual: \(actual)\n\n")
expected = (true, [], [Argument("N", value: 1 as AnyObject), Argument("M", value: 2 as AnyObject)])
actual = Either([Argument("M"), Required([Argument("N"), Argument("M")])]).match([Argument(nil, value: 1 as AnyObject), Argument(nil, value: 2 as AnyObject)])
XCTAssertTrue(actual == expected, "\nExpected: \(expected)\nActual: \(actual)\n\n")
}
func testOneOrMoreMatch() {
XCTAssertTrue(OneOrMore(Argument("N")).match([Argument(nil, value: 9 as AnyObject)]) ==
(true, [], [Argument("N", value: 9 as AnyObject)]))
XCTAssertTrue(OneOrMore(Argument("N")).match([]) == (false, [], []))
XCTAssertTrue(OneOrMore(Argument("N")).match([Option("-x")]) ==
(false, [Option("-x")], []))
XCTAssertTrue(OneOrMore(Argument("N")).match(
[Argument(nil, value: 9 as AnyObject), Argument(nil, value: 8 as AnyObject)]) == (
true, [], [Argument("N", value: 9 as AnyObject), Argument("N", value: 8 as AnyObject)]))
XCTAssertTrue(OneOrMore(Argument("N")).match(
[Argument(nil, value: 9 as AnyObject), Option("-x"), Argument(nil, value: 8 as AnyObject)]) == (
true, [Option("-x")], [Argument("N", value: 9 as AnyObject), Argument("N", value: 8 as AnyObject)]))
XCTAssertTrue(OneOrMore(Option("-a")).match(
[Option("-a"), Argument(nil, value: 8 as AnyObject), Option("-a")]) ==
(true, [Argument(nil, value: 8 as AnyObject)], [Option("-a"), Option("-a")]))
XCTAssertTrue(OneOrMore(Option("-a")).match([Argument(nil, value: 8 as AnyObject),
Option("-x")]) ==
(false, [Argument(nil, value: 8 as AnyObject), Option("-x")], []))
XCTAssertTrue(OneOrMore(Required([Option("-a"), Argument("N")])).match(
[Option("-a"), Argument(nil, value: 1 as AnyObject), Option("-x"),
Option("-a"), Argument(nil, value: 2 as AnyObject)]) ==
(true, [Option("-x")],
[Option("-a"), Argument("N", value: 1 as AnyObject), Option("-a"), Argument("N", value: 2 as AnyObject)]))
XCTAssertTrue(OneOrMore(Optional(Argument("N"))).match([Argument(nil, value: 9 as AnyObject)]) ==
(true, [], [Argument("N", value: 9 as AnyObject)]))
}
func testPatternEither() {
XCTAssertEqual(Pattern.transform(Option("-a")), Either(Required(Option("-a"))))
XCTAssertEqual(Pattern.transform(Argument("A")), Either(Required(Argument("A"))))
XCTAssertEqual(Pattern.transform(Required([Either([Option("-a"), Option("-b")]),
Option("-c")])),
Either([Required([Option("-a"), Option("-c")]),
Required([Option("-b"), Option("-c")])]))
XCTAssertEqual(Pattern.transform(Optional([Option("-a"), Either([Option("-b"),
Option("-c")])])),
Either([Required([Option("-b"), Option("-a")]),
Required([Option("-c"), Option("-a")])]))
XCTAssertEqual(Pattern.transform(Either([Option("-x"),
Either([Option("-y"), Option("-z")])])),
Either([Required(Option("-x")),
Required(Option("-y")),
Required(Option("-z"))]))
XCTAssertEqual(Pattern.transform(OneOrMore([Argument("N"), Argument("M")])),
Either(Required([Argument("N"), Argument("M"),
Argument("N"), Argument("M")])))
}
func testFixRepeatingArguments() {
XCTAssertEqual(Option("-a").fixRepeatingArguments(), Option("-a"))
XCTAssertEqual(Argument("N").fixRepeatingArguments(), Argument("N"))
XCTAssertEqual(Required([Argument("N"),
Argument("N")]).fixRepeatingArguments(),
Required([Argument("N", value: []), Argument("N", value: [])]))
XCTAssertEqual(Either([Argument("N"),
OneOrMore(Argument("N"))]).fix(),
Either([Argument("N", value: []), OneOrMore(Argument("N", value: []))]))
}
func testListArgumentMatch() {
XCTAssertTrue(Required([Argument("N"), Argument("N")]).fix().match(
[Argument(nil, value: "1" as AnyObject), Argument(nil, value: "2" as AnyObject)]) ==
(true, [], [Argument("N", value: ["1", "2"])]))
XCTAssertTrue(OneOrMore(Argument("N")).fix().match(
[Argument(nil, value: "1" as AnyObject), Argument(nil, value: "2" as AnyObject), Argument(nil, value: "3" as AnyObject)]) ==
(true, [], [Argument("N", value: ["1", "2", "3"])]))
XCTAssertTrue(Required([Argument("N"), OneOrMore(Argument("N"))]).fix().match(
[Argument(nil, value: "1" as AnyObject), Argument(nil, value: "2" as AnyObject), Argument(nil, value: "3" as AnyObject)]) ==
(true, [], [Argument("N", value: ["1", "2", "3"])]))
XCTAssertTrue(Required([Argument("N"), Required(Argument("N"))]).fix().match(
[Argument(nil, value: "1" as AnyObject), Argument(nil, value: "2" as AnyObject)]) ==
(true, [], [Argument("N", value: ["1", "2"])]))
}
func testBasicPatternMatch() {
// ( -a N [ -x Z ] )
let pattern = Required([Option("-a"), Argument("N"), Optional([Option("-x"), Argument("Z")])])
// -a N
XCTAssertTrue(pattern.match([Option("-a"), Argument(nil, value: 9 as AnyObject)]) ==
(true, [], [Option("-a"), Argument("N", value: 9 as AnyObject)]))
// -a -x N Z
XCTAssertTrue(pattern.match([Option("-a"), Option("-x"), Argument(nil, value: 9 as AnyObject), Argument(nil, value: 5 as AnyObject)]) ==
(true, [], [Option("-a"), Argument("N", value: 9 as AnyObject), Option("-x"), Argument("Z", value: 5 as AnyObject)]))
// -x N Z # BZZ!
XCTAssertTrue(pattern.match([Option("-x"), Argument(nil, value: 9 as AnyObject), Argument(nil, value: 5 as AnyObject)]) ==
(false, [Option("-x"), Argument(nil, value: 9 as AnyObject), Argument(nil, value: 5 as AnyObject)], []))
}
func testSet() {
XCTAssertEqual(Argument("N"), Argument("N"))
XCTAssertEqual(Set([Argument("N"), Argument("N")]), Set([Argument("N")]))
}
func testDocopt() {
let doc = "Usage: prog [-v] A\n\n Options: -v Be verbose."
let result = Docopt(doc, argv: ["arg"]).result
let fixture = ["-v": false as AnyObject, "A": "arg" as AnyObject]
for (key, value) in result!
{
XCTAssertEqual(value as! NSObject, fixture[key]! as! NSObject)
}
XCTAssertEqual(result!.count, fixture.count)
}
}
internal func ==(lhs: MatchResult, rhs: MatchResult) -> Bool {
return lhs.match == rhs.match
&& lhs.left == rhs.left
&& lhs.collected == rhs.collected
}
|
mit
|
0bd9683fb16faf41403ecc72c4b73411
| 54.705882 | 177 | 0.547996 | 4.029787 | false | true | false | false |
lorentey/swift
|
stdlib/public/core/BridgeObjectiveC.swift
|
3
|
26778
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A Swift Array or Dictionary of types conforming to
/// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or
/// NSDictionary, respectively. The elements of the resulting NSArray
/// or NSDictionary will be the result of calling `_bridgeToObjectiveC`
/// on each element of the source container.
public protocol _ObjectiveCBridgeable {
associatedtype _ObjectiveCType: AnyObject
/// Convert `self` to Objective-C.
func _bridgeToObjectiveC() -> _ObjectiveCType
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for forced downcasting (e.g.,
/// via as), and may defer complete checking until later. For
/// example, when bridging from `NSArray` to `Array<Element>`, we can defer
/// the checking for the individual elements of the array.
///
/// - parameter result: The location where the result is written. The optional
/// will always contain a value.
static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
)
/// Try to bridge from an Objective-C object of the bridged class
/// type to a value of the Self type.
///
/// This conditional bridging operation is used for conditional
/// downcasting (e.g., via as?) and therefore must perform a
/// complete conversion to the value type; it cannot defer checking
/// to a later time.
///
/// - parameter result: The location where the result is written.
///
/// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant
/// information is provided for the convenience of the runtime's `dynamic_cast`
/// implementation, so that it need not look into the optional representation
/// to determine success.
@discardableResult
static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
) -> Bool
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for unconditional bridging when
/// interoperating with Objective-C code, either in the body of an
/// Objective-C thunk or when calling Objective-C code, and may
/// defer complete checking until later. For example, when bridging
/// from `NSArray` to `Array<Element>`, we can defer the checking
/// for the individual elements of the array.
///
/// \param source The Objective-C object from which we are
/// bridging. This optional value will only be `nil` in cases where
/// an Objective-C method has returned a `nil` despite being marked
/// as `_Nonnull`/`nonnull`. In most such cases, bridging will
/// generally force the value immediately. However, this gives
/// bridging the flexibility to substitute a default value to cope
/// with historical decisions, e.g., an existing Objective-C method
/// that returns `nil` to for "empty result" rather than (say) an
/// empty array. In such cases, when `nil` does occur, the
/// implementation of `Swift.Array`'s conformance to
/// `_ObjectiveCBridgeable` will produce an empty array rather than
/// dynamically failing.
@_effects(readonly)
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self
}
#if _runtime(_ObjC)
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(*, deprecated)
@_cdecl("_SwiftCreateBridgedArray")
@usableFromInline
internal func _SwiftCreateBridgedArray(
values: UnsafePointer<AnyObject>,
numValues: Int
) -> Unmanaged<AnyObject> {
let bufPtr = UnsafeBufferPointer(start: values, count: numValues)
let bridged = Array(bufPtr)._bridgeToObjectiveCImpl()
return Unmanaged<AnyObject>.passRetained(bridged)
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@available(*, deprecated)
@_cdecl("_SwiftCreateBridgedMutableArray")
@usableFromInline
internal func _SwiftCreateBridgedMutableArray(
values: UnsafePointer<AnyObject>,
numValues: Int
) -> Unmanaged<AnyObject> {
let bufPtr = UnsafeBufferPointer(start: values, count: numValues)
let bridged = _SwiftNSMutableArray(Array(bufPtr))
return Unmanaged<AnyObject>.passRetained(bridged)
}
@_silgen_name("swift_stdlib_connectNSBaseClasses")
internal func _connectNSBaseClasses() -> Bool
private let _bridgeInitializedSuccessfully = _connectNSBaseClasses()
internal var _orphanedFoundationSubclassesReparented: Bool = false
/// Reparents the SwiftNativeNS*Base classes to be subclasses of their respective
/// Foundation types, or is false if they couldn't be reparented. Must be run
/// in order to bridge Swift Strings, Arrays, Dictionarys, Sets, or Enumerators to ObjC.
internal func _connectOrphanedFoundationSubclassesIfNeeded() -> Void {
let bridgeWorks = _bridgeInitializedSuccessfully
_debugPrecondition(bridgeWorks)
_orphanedFoundationSubclassesReparented = true
}
//===--- Bridging for metatypes -------------------------------------------===//
/// A stand-in for a value of metatype type.
///
/// The language and runtime do not yet support protocol conformances for
/// structural types like metatypes. However, we can use a struct that contains
/// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table
/// will be ABI-compatible with one that directly provided conformance to the
/// metatype type itself.
public struct _BridgeableMetatype: _ObjectiveCBridgeable {
internal var value: AnyObject.Type
internal init(value: AnyObject.Type) {
self.value = value
}
public typealias _ObjectiveCType = AnyObject
public func _bridgeToObjectiveC() -> AnyObject {
return value
}
public static func _forceBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) {
result = _BridgeableMetatype(value: source as! AnyObject.Type)
}
public static func _conditionallyBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) -> Bool {
if let type = source as? AnyObject.Type {
result = _BridgeableMetatype(value: type)
return true
}
result = nil
return false
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> _BridgeableMetatype {
var result: _BridgeableMetatype?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
//===--- Bridging facilities written in Objective-C -----------------------===//
// Functions that must discover and possibly use an arbitrary type's
// conformance to a given protocol. See ../runtime/Casting.cpp for
// implementations.
//===----------------------------------------------------------------------===//
/// Bridge an arbitrary value to an Objective-C object.
///
/// - If `T` is a class type, it is always bridged verbatim, the function
/// returns `x`;
///
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,
/// returns the result of `x._bridgeToObjectiveC()`;
///
/// - otherwise, we use **boxing** to bring the value into Objective-C.
/// The value is wrapped in an instance of a private Objective-C class
/// that is `id`-compatible and dynamically castable back to the type of
/// the boxed value, but is otherwise opaque.
///
// COMPILER_INTRINSIC
@inlinable
public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return unsafeBitCast(x, to: AnyObject.self)
}
return _bridgeAnythingNonVerbatimToObjectiveC(x)
}
@_silgen_name("")
public // @testable
func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: __owned T) -> AnyObject
/// Convert a purportedly-nonnull `id` value from Objective-C into an Any.
///
/// Since Objective-C APIs sometimes get their nullability annotations wrong,
/// this includes a failsafe against nil `AnyObject`s, wrapping them up as
/// a nil `AnyObject?`-inside-an-`Any`.
///
// COMPILER_INTRINSIC
public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any {
if let nonnullObject = possiblyNullObject {
return nonnullObject // AnyObject-in-Any
}
return possiblyNullObject as Any
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, trap;
/// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`;
/// - otherwise, trap.
@inlinable
public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as! T
}
var result: T?
_bridgeNonVerbatimFromObjectiveC(x, T.self, &result)
return result!
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
// COMPILER_INTRINSIC
@inlinable
public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (
_ x: T._ObjectiveCType,
_: T.Type
) -> T {
var result: T?
T._forceBridgeFromObjectiveC(x, result: &result)
return result!
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, the result is empty;
/// + otherwise, returns the result of
/// `T._conditionallyBridgeFromObjectiveC(x)`;
/// - otherwise, the result is empty.
@inlinable
public func _conditionallyBridgeFromObjectiveC<T>(
_ x: AnyObject,
_: T.Type
) -> T? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as? T
}
var result: T?
_ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result)
return result
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
// COMPILER_INTRINSIC
@inlinable
public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(
_ x: T._ObjectiveCType,
_: T.Type
) -> T? {
var result: T?
T._conditionallyBridgeFromObjectiveC (x, result: &result)
return result
}
@_silgen_name("")
@usableFromInline
internal func _bridgeNonVerbatimFromObjectiveC<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
)
/// Helper stub to upcast to Any and store the result to an inout Any?
/// on the C++ runtime's behalf.
@_silgen_name("_bridgeNonVerbatimFromObjectiveCToAny")
internal func _bridgeNonVerbatimFromObjectiveCToAny(
_ x: AnyObject,
_ result: inout Any?
) {
result = x as Any
}
/// Helper stub to upcast to Optional on the C++ runtime's behalf.
@_silgen_name("_bridgeNonVerbatimBoxedValue")
internal func _bridgeNonVerbatimBoxedValue<NativeType>(
_ x: UnsafePointer<NativeType>,
_ result: inout NativeType?
) {
result = x.pointee
}
/// Runtime optional to conditionally perform a bridge from an object to a value
/// type.
///
/// - parameter result: Will be set to the resulting value if bridging succeeds, and
/// unchanged otherwise.
///
/// - Returns: `true` to indicate success, `false` to indicate failure.
@_silgen_name("")
public func _bridgeNonVerbatimFromObjectiveCConditional<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
) -> Bool
/// Determines if values of a given type can be converted to an Objective-C
/// representation.
///
/// - If `T` is a class type, returns `true`;
/// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`.
public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return true
}
return _isBridgedNonVerbatimToObjectiveC(T.self)
}
@_silgen_name("")
public func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool
/// A type that's bridged "verbatim" does not conform to
/// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an
/// `AnyObject`. When this function returns true, the storage of an
/// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`.
@inlinable // FIXME(sil-serialize-all)
public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool {
return _isClassOrObjCExistential(T.self)
}
/// Retrieve the Objective-C type to which the given type is bridged.
@inlinable // FIXME(sil-serialize-all)
public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return T.self
}
return _getBridgedNonVerbatimObjectiveCType(T.self)
}
@_silgen_name("")
public func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type?
// -- Pointer argument bridging
/// A mutable pointer addressing an Objective-C reference that doesn't own its
/// target.
///
/// `Pointee` must be a class type or `Optional<C>` where `C` is a class.
///
/// This type has implicit conversions to allow passing any of the following
/// to a C or ObjC API:
///
/// - `nil`, which gets passed as a null pointer,
/// - an inout argument of the referenced type, which gets passed as a pointer
/// to a writeback temporary with autoreleasing ownership semantics,
/// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is.
///
/// Passing pointers to mutable arrays of ObjC class pointers is not
/// directly supported. Unlike `UnsafeMutablePointer<Pointee>`,
/// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that
/// does not own a reference count to the referenced
/// value. UnsafeMutablePointer's operations, by contrast, assume that
/// the referenced storage owns values loaded from or stored to it.
///
/// This type does not carry an owner pointer unlike the other C*Pointer types
/// because it only needs to reference the results of inout conversions, which
/// already have writeback-scoped lifetime.
@frozen
public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */>
: _Pointer {
public let _rawValue: Builtin.RawPointer
@_transparent
public // COMPILER_INTRINSIC
init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Retrieve or set the `Pointee` instance referenced by `self`.
///
/// `AutoreleasingUnsafeMutablePointer` is assumed to reference a value with
/// `__autoreleasing` ownership semantics, like `NSFoo **` declarations in
/// ARC. Setting the pointee autoreleases the new value before trivially
/// storing it in the referenced memory.
///
/// - Precondition: the pointee has been initialized with an instance of type
/// `Pointee`.
@inlinable
public var pointee: Pointee {
@_transparent get {
// The memory addressed by this pointer contains a non-owning reference,
// therefore we *must not* point an `UnsafePointer<AnyObject>` to
// it---otherwise we would allow the compiler to assume it has a +1
// refcount, enabling some optimizations that wouldn't be valid.
//
// Instead, we need to load the pointee as a +0 unmanaged reference. For
// an extra twist, `Pointee` is allowed (but not required) to be an
// optional type, so we actually need to load it as an optional, and
// explicitly handle the nil case.
let unmanaged =
UnsafePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee
return _unsafeReferenceCast(
unmanaged?.takeUnretainedValue(),
to: Pointee.self)
}
@_transparent nonmutating set {
// Autorelease the object reference.
let object = _unsafeReferenceCast(newValue, to: Optional<AnyObject>.self)
Builtin.retain(object)
Builtin.autorelease(object)
// Convert it to an unmanaged reference and trivially assign it to the
// memory addressed by this pointer.
let unmanaged: Optional<Unmanaged<AnyObject>>
if let object = object {
unmanaged = Unmanaged.passUnretained(object)
} else {
unmanaged = nil
}
UnsafeMutablePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee =
unmanaged
}
}
/// Access the `i`th element of the raw array pointed to by
/// `self`.
///
/// - Precondition: `self != nil`.
@inlinable // unsafe-performance
public subscript(i: Int) -> Pointee {
@_transparent
get {
return self.advanced(by: i).pointee
}
}
/// Explicit construction from an UnsafeMutablePointer.
///
/// This is inherently unsafe; UnsafeMutablePointer assumes the
/// referenced memory has +1 strong ownership semantics, whereas
/// AutoreleasingUnsafeMutablePointer implies +0 semantics.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent
public init<U>(_ from: UnsafeMutablePointer<U>) {
self._rawValue = from._rawValue
}
/// Explicit construction from an UnsafeMutablePointer.
///
/// Returns nil if `from` is nil.
///
/// This is inherently unsafe; UnsafeMutablePointer assumes the
/// referenced memory has +1 strong ownership semantics, whereas
/// AutoreleasingUnsafeMutablePointer implies +0 semantics.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent
public init?<U>(_ from: UnsafeMutablePointer<U>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Explicit construction from a UnsafePointer.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@usableFromInline @_transparent
internal init<U>(
@_nonEphemeral _ from: UnsafePointer<U>
) {
self._rawValue = from._rawValue
}
/// Explicit construction from a UnsafePointer.
///
/// Returns nil if `from` is nil.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@usableFromInline @_transparent
internal init?<U>(
@_nonEphemeral _ from: UnsafePointer<U>?
) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
}
extension UnsafeMutableRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(
@_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>
) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(
@_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>?
) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
extension UnsafeRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(
@_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>
) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(
@_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>?
) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
internal struct _CocoaFastEnumerationStackBuf {
// Clang uses 16 pointers. So do we.
internal var _item0: UnsafeRawPointer?
internal var _item1: UnsafeRawPointer?
internal var _item2: UnsafeRawPointer?
internal var _item3: UnsafeRawPointer?
internal var _item4: UnsafeRawPointer?
internal var _item5: UnsafeRawPointer?
internal var _item6: UnsafeRawPointer?
internal var _item7: UnsafeRawPointer?
internal var _item8: UnsafeRawPointer?
internal var _item9: UnsafeRawPointer?
internal var _item10: UnsafeRawPointer?
internal var _item11: UnsafeRawPointer?
internal var _item12: UnsafeRawPointer?
internal var _item13: UnsafeRawPointer?
internal var _item14: UnsafeRawPointer?
internal var _item15: UnsafeRawPointer?
@_transparent
internal var count: Int {
return 16
}
internal init() {
_item0 = nil
_item1 = _item0
_item2 = _item0
_item3 = _item0
_item4 = _item0
_item5 = _item0
_item6 = _item0
_item7 = _item0
_item8 = _item0
_item9 = _item0
_item10 = _item0
_item11 = _item0
_item12 = _item0
_item13 = _item0
_item14 = _item0
_item15 = _item0
_internalInvariant(MemoryLayout.size(ofValue: self) >=
MemoryLayout<Optional<UnsafeRawPointer>>.size * count)
}
}
/// Get the ObjC type encoding for a type as a pointer to a C string.
///
/// This is used by the Foundation overlays. The compiler will error if the
/// passed-in type is generic or not representable in Objective-C
@_transparent
public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> {
// This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is
// only supported by the compiler for concrete types that are representable
// in ObjC.
return UnsafePointer(Builtin.getObjCTypeEncoding(type))
}
#endif
//===--- Bridging without the ObjC runtime --------------------------------===//
#if !_runtime(_ObjC)
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
// COMPILER_INTRINSIC
@inlinable
public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (
_ x: T._ObjectiveCType,
_: T.Type
) -> T {
var result: T?
T._forceBridgeFromObjectiveC(x, result: &result)
return result!
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
// COMPILER_INTRINSIC
@inlinable
public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(
_ x: T._ObjectiveCType,
_: T.Type
) -> T? {
var result: T?
T._conditionallyBridgeFromObjectiveC (x, result: &result)
return result
}
public // SPI(Foundation)
protocol _NSSwiftValue: class {
init(_ value: Any)
var value: Any { get }
static var null: AnyObject { get }
}
@usableFromInline
internal class __SwiftValue {
@usableFromInline
let value: Any
@usableFromInline
init(_ value: Any) {
self.value = value
}
@usableFromInline
static let null = __SwiftValue(Optional<Any>.none as Any)
}
// Internal stdlib SPI
@_silgen_name("swift_unboxFromSwiftValueWithType")
public func swift_unboxFromSwiftValueWithType<T>(
_ source: inout AnyObject,
_ result: UnsafeMutablePointer<T>
) -> Bool {
if source === _nullPlaceholder {
if let unpacked = Optional<Any>.none as? T {
result.initialize(to: unpacked)
return true
}
}
if let box = source as? __SwiftValue {
if let value = box.value as? T {
result.initialize(to: value)
return true
}
} else if let box = source as? _NSSwiftValue {
if let value = box.value as? T {
result.initialize(to: value)
return true
}
}
return false
}
// Internal stdlib SPI
@_silgen_name("swift_swiftValueConformsTo")
public func _swiftValueConformsTo<T>(_ type: T.Type) -> Bool {
if let foundationType = _foundationSwiftValueType {
return foundationType is T.Type
} else {
return __SwiftValue.self is T.Type
}
}
@_silgen_name("_swift_extractDynamicValue")
public func _extractDynamicValue<T>(_ value: T) -> AnyObject?
@_silgen_name("_swift_bridgeToObjectiveCUsingProtocolIfPossible")
public func _bridgeToObjectiveCUsingProtocolIfPossible<T>(_ value: T) -> AnyObject?
internal protocol _Unwrappable {
func _unwrap() -> Any?
}
extension Optional: _Unwrappable {
internal func _unwrap() -> Any? {
return self
}
}
private let _foundationSwiftValueType = _typeByName("Foundation.__SwiftValue") as? _NSSwiftValue.Type
@usableFromInline
internal var _nullPlaceholder: AnyObject {
if let foundationType = _foundationSwiftValueType {
return foundationType.null
} else {
return __SwiftValue.null
}
}
@usableFromInline
func _makeSwiftValue(_ value: Any) -> AnyObject {
if let foundationType = _foundationSwiftValueType {
return foundationType.init(value)
} else {
return __SwiftValue(value)
}
}
/// Bridge an arbitrary value to an Objective-C object.
///
/// - If `T` is a class type, it is always bridged verbatim, the function
/// returns `x`;
///
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,
/// returns the result of `x._bridgeToObjectiveC()`;
///
/// - otherwise, we use **boxing** to bring the value into Objective-C.
/// The value is wrapped in an instance of a private Objective-C class
/// that is `id`-compatible and dynamically castable back to the type of
/// the boxed value, but is otherwise opaque.
///
// COMPILER_INTRINSIC
public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {
var done = false
var result: AnyObject!
let source: Any = x
if let dynamicSource = _extractDynamicValue(x) {
result = dynamicSource as AnyObject
done = true
}
if !done, let wrapper = source as? _Unwrappable {
if let value = wrapper._unwrap() {
result = value as AnyObject
} else {
result = _nullPlaceholder
}
done = true
}
if !done {
if type(of: source) as? AnyClass != nil {
result = unsafeBitCast(x, to: AnyObject.self)
} else if let object = _bridgeToObjectiveCUsingProtocolIfPossible(source) {
result = object
} else {
result = _makeSwiftValue(source)
}
}
return result
}
#endif // !_runtime(_ObjC)
|
apache-2.0
|
3f6a4f171325b293737e139fbc71784c
| 31.497573 | 101 | 0.690866 | 4.280371 | false | false | false | false |
rdlester/simply-giphy
|
Pods/Gloss/Sources/Encoder.swift
|
1
|
12753
|
//
// Encoder.swift
// Gloss
//
// Copyright (c) 2015 Harlan Kellaway
//
// 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
/**
Encodes objects to JSON.
*/
public struct Encoder {
/**
Encodes a generic value to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T>(key: String) -> (T?) -> JSON? {
return {
property in
if let property = property {
return [key : property]
}
return nil
}
}
/**
Encodes a generic value array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T>(arrayForKey key: String) -> ([T]?) -> JSON? {
return {
array in
if let array = array {
return [key : array]
}
return nil
}
}
/**
Encodes a date to JSON.
- parameter key: Key used in JSON for decoded value.
- parameter dateFormatter: Date formatter used to encode date.
- returns: JSON encoded from value.
*/
public static func encode(dateForKey key: String, dateFormatter: DateFormatter) -> (Date?) -> JSON? {
return {
date in
if let date = date {
return [key : dateFormatter.string(from: date)]
}
return nil
}
}
/**
Encodes a date array to JSON.
- parameter key: Key used in JSON for decoded value.
- parameter dateFormatter: Date formatter used to encode date.
- returns: JSON encoded from value.
*/
public static func encode(dateArrayForKey key: String, dateFormatter: DateFormatter) -> ([Date]?) -> JSON? {
return {
dates in
if let dates = dates {
var dateStrings: [String] = []
for date in dates {
let dateString = dateFormatter.string(from: date)
dateStrings.append(dateString)
}
return [key : dateStrings]
}
return nil
}
}
/**
Encodes an ISO8601 date to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(dateISO8601ForKey key: String) -> (Date?) -> JSON? {
return Encoder.encode(dateForKey: key, dateFormatter: GlossDateFormatterISO8601)
}
/**
Encodes an ISO8601 date array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(dateISO8601ArrayForKey key: String) -> ([Date]?) -> JSON? {
return Encoder.encode(dateArrayForKey: key, dateFormatter: GlossDateFormatterISO8601)
}
/**
Encodes an Encodable object to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: Encodable>(encodableForKey key: String) -> (T?) -> JSON? {
return {
model in
if let model = model, let json = model.toJSON() {
return [key : json]
}
return nil
}
}
/**
Encodes an Encodable array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: Encodable>(encodableArrayForKey key: String) -> ([T]?) -> JSON? {
return {
array in
if let array = array {
var encodedArray: [JSON] = []
for model in array {
guard let json = model.toJSON() else {
return nil
}
encodedArray.append(json)
}
return [key : encodedArray]
}
return nil
}
}
/**
Encodes a dictionary of String to Encodable to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: Encodable>(encodableDictionaryForKey key: String) -> ([String : T]?) -> JSON? {
return {
dictionary in
guard let dictionary = dictionary else {
return nil
}
let encoded : [String : JSON] = dictionary.flatMap { (key, value) in
guard let json = value.toJSON() else {
return nil
}
return (key, json)
}
return [key : encoded]
}
}
/**
Encodes a dictionary of String to Encodable array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: Encodable>(encodableDictionaryForKey key: String) -> ([String : [T]]?) -> JSON? {
return {
dictionary in
guard let dictionary = dictionary else {
return nil
}
let encoded : [String : [JSON]] = dictionary.flatMap {
(key, value) in
guard let jsonArray = value.toJSONArray() else {
return nil
}
return (key, jsonArray)
}
return [key : encoded]
}
}
/**
Encodes an enum value to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: RawRepresentable>(enumForKey key: String) -> (T?) -> JSON? {
return {
enumValue in
if let enumValue = enumValue {
return [key : enumValue.rawValue]
}
return nil
}
}
/**
Encodes an enum value array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: RawRepresentable>(enumArrayForKey key: String) -> ([T]?) -> JSON? {
return {
enumValues in
if let enumValues = enumValues {
var rawValues: [T.RawValue] = []
for enumValue in enumValues {
rawValues.append(enumValue.rawValue)
}
return [key : rawValues]
}
return nil
}
}
/**
Encodes an Int32 to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(int32ForKey key: String) -> (Int32?) -> JSON? {
return {
int32 in
if let int32 = int32 {
return [key : NSNumber(value: int32)]
}
return nil
}
}
/**
Encodes an Int32 array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(int32ArrayForKey key: String) -> ([Int32]?) -> JSON? {
return {
int32Array in
if let int32Array = int32Array {
let numbers: [NSNumber] = int32Array.map { NSNumber(value: $0) }
return [key : numbers]
}
return nil
}
}
/**
Encodes an UInt32 to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uint32ForKey key: String) -> (UInt32?) -> JSON? {
return {
uint32 in
if let uint32 = uint32 {
return [key : NSNumber(value: uint32)]
}
return nil
}
}
/**
Encodes an UInt32 array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uint32ArrayForKey key: String) -> ([UInt32]?) -> JSON? {
return {
uInt32Array in
if let uInt32Array = uInt32Array {
let numbers: [NSNumber] = uInt32Array.map { NSNumber(value: $0) }
return [key : numbers]
}
return nil
}
}
/**
Encodes an Int64 to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(int64ForKey key: String) -> (Int64?) -> JSON? {
return {
int64 in
if let int64 = int64 {
return [key : NSNumber(value: int64)]
}
return nil
}
}
/**
Encodes an Int64 array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(int64ArrayForKey key: String) -> ([Int64]?) -> JSON? {
return {
int64Array in
if let int64Array = int64Array {
let numbers: [NSNumber] = int64Array.map { NSNumber(value: $0) }
return [key : numbers]
}
return nil
}
}
/**
Encodes an UInt64 to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uint64ForKey key: String) -> (UInt64?) -> JSON? {
return {
uInt64 in
if let uInt64 = uInt64 {
return [key : NSNumber(value: uInt64)]
}
return nil
}
}
/**
Encodes an UInt64 array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uint64ArrayForKey key: String) -> ([UInt64]?) -> JSON? {
return {
uInt64Array in
if let uInt64Array = uInt64Array {
let numbers: [NSNumber] = uInt64Array.map { NSNumber(value: $0) }
return [key : numbers]
}
return nil
}
}
/**
Encodes a URL to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(urlForKey key: String) -> (URL?) -> JSON? {
return {
url in
if let absoluteURLString = url?.absoluteString {
return [key : absoluteURLString]
}
return nil
}
}
/**
Encodes a UUID to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uuidForKey key: String) -> (UUID?) -> JSON? {
return {
uuid in
if let uuidString = uuid?.uuidString {
return [key : uuidString]
}
return nil
}
}
/**
Encodes a Decimal to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(decimalForKey key: String) -> (Decimal?) -> JSON? {
return {
decimal in
if let decimal = decimal {
return [key : NSDecimalNumber(decimal: decimal)]
}
return nil
}
}
/**
Encodes a Decimal array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(decimalArrayForKey key: String) -> ([Decimal]?) -> JSON? {
return {
decimalArray in
if let decimalArray = decimalArray {
let numbers: [NSDecimalNumber] = decimalArray.map { NSDecimalNumber(decimal: $0) }
return [key : numbers]
}
return nil
}
}
}
|
apache-2.0
|
0439244b41d35e9647d74cfb1a8f8799
| 23.245247 | 114 | 0.553282 | 4.528764 | false | false | false | false |
sivakumarscorpian/INTPushnotification1
|
REIOSSDK/REiosDeeplinking.swift
|
1
|
5829
|
//
// ResulticksDeeplinking.swift
// INTPushNotification
//
// Created by Sivakumar on 15/9/17.
// Copyright © 2017 Interakt. All rights reserved.
//
import UIKit
public class REiosDeeplinking: NSObject {
public func handleDeeplink(application: UIApplication, userActivity: NSUserActivity) {
if REiosDataManager.shared.isNotRunning == true {
let delayInSeconds = 5.0
DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) {
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let url = userActivity.webpageURL,
let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else {
return
}
REiosScreenNavigation.navigateScreenWithSid(screenUrl: components.path)
REiosDataManager.shared.isNotRunning = false
}
} else {
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let url = userActivity.webpageURL,
let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else {
return
}
REiosScreenNavigation.navigateScreenWithSid(screenUrl: components.path)
}
}
public func handleOpenlink(url: URL) {
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
// if let items = urlComponents?.queryItems {
// print(items.last ?? "No val")
//
// if items.first?.name == "_resulticks_link_unique_Id" {
// getProgressiveProfileUrl(linkId: (items.first?.value!)!)
// }
// }
}
private func getProgressiveProfileUrl(linkId: String) {
if REiosReachability.isInternetReachable() {
REiosDeeplinking.buildProgressiveProfileRequest(urlId: linkId, successHandler: { response in
print("Deeplinking url \(response)")
REiosDataManager.shared.setDeepLinkData(data: response)
var _storyBoardId = ""
var ios:[String:Any] = [:]
if response["MobileFriendlyUrl"] != nil {
if let _campaign = response["CampaignAppStoreUrl"] {
let campaign = response["CampaignAppStoreUrl"] as! String
let jsonData = campaign.data(using: .utf8)!
do {
let array = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]]
ios = array![1] as [String:Any]
_storyBoardId = ios["AppScreen"] as! String
REiosScreenNavigation.navigateScreenWithSid(screenUrl: _storyBoardId)
} catch {
print("array error")
}
} else {
return
}
}
}, failureHandler: { error in
print("SDK failure \(error.description)")
DispatchQueue.main.async {
UIApplication.shared.keyWindow?.removeFromSuperview()
}
})
} else {
print("Internet not available")
}
}
private class func getProgressiveProfileUrl(urlId: String) -> String {
var u = "https://b.resu.io/GCM/GetSmartCodeDetail?smartCode="
u += urlId
return u
}
private class func progressiveProfileHeader() -> [String:String] {
let header: [String:String] = [
"Accept": "application/json"
]
return header
}
class func buildProgressiveProfileRequest(urlId:String, successHandler: @escaping (_ returnData: [String:Any]) -> (Void), failureHandler: @escaping (_ error: String) -> (Void)) {
getData(url: getProgressiveProfileUrl(urlId: urlId), headers: progressiveProfileHeader(), successHandler: {retunData in
successHandler(retunData)
}, failureHandler: {error in
failureHandler(error)
})
}
class func getData(url: String, headers: [String:String],successHandler: @escaping (_ returnData: [String:Any]) -> (Void), failureHandler: @escaping (_ error: String) -> (Void)) {
// url
let url : URL = URL(string: url )!
// create post request
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if (error != nil) {
print(error?.localizedDescription ?? "No data")
failureHandler((error?.localizedDescription)!)
}
if (data != nil) && error == nil {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
successHandler(json)
} catch {
failureHandler(error.localizedDescription)
}
}
}; task.resume()
}
}
|
mit
|
362700b8203522b6de8c8723acd15149
| 34.975309 | 183 | 0.505148 | 5.69697 | false | false | false | false |
superpixelhq/AbairLeat-iOS
|
Abair Leat/View Controllers/SettingsController.swift
|
1
|
1469
|
//
// SettingsController.swift
// Abair Leat
//
// Created by Aaron Signorelli on 27/11/2015.
// Copyright © 2015 Superpixel. All rights reserved.
//
import UIKit
import FBSDKLoginKit
import Firebase
class SettingsController: UITableViewController {
@IBOutlet weak var status: UILabel!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var id: UILabel!
@IBOutlet weak var provider: UILabel!
override func viewDidLoad() {
setupConnectedWatcher()
setupProfile()
}
func setupConnectedWatcher() {
let connectedRef = AbairLeat.shared.baseFirebaseRef.childByAppendingPath("/.info/connected")
connectedRef.observeEventType(.Value, withBlock: { snapshot in
let connected = snapshot.value as? Bool
if connected != nil && connected! {
self.status.text = "Connected"
self.status.textColor = UIColor.greenColor()
} else {
self.status.text = "Offline"
self.status.textColor = UIColor.redColor()
}
})
}
func setupProfile() {
let fb = AbairLeat.shared.baseFirebaseRef
self.provider.text = fb.authData?.provider
let me = AbairLeat.shared.profile.me
self.name.text = me?.name
self.id.text = me?.id
}
@IBAction func logout() {
self.performSegueWithIdentifier("unwindToLogin", sender: self)
}
}
|
apache-2.0
|
9e7f11438670b799a3eceaa5b96fd8f9
| 27.230769 | 100 | 0.614441 | 4.516923 | false | false | false | false |
MadAppGang/SmartLog
|
iOS/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift
|
30
|
2472
|
//
// RadarHighlighter.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
@objc(RadarChartHighlighter)
open class RadarHighlighter: PieRadarHighlighter
{
open override func closestHighlight(index: Int, x: CGFloat, y: CGFloat) -> Highlight?
{
guard let chart = self.chart as? RadarChartView
else { return nil }
let highlights = getHighlights(forIndex: index)
let distanceToCenter = Double(chart.distanceToCenter(x: x, y: y) / chart.factor)
var closest: Highlight? = nil
var distance = Double.greatestFiniteMagnitude
for high in highlights
{
let cdistance = abs(high.y - distanceToCenter)
if cdistance < distance
{
closest = high
distance = cdistance
}
}
return closest
}
/// - returns: An array of Highlight objects for the given index.
/// The Highlight objects give information about the value at the selected index and DataSet it belongs to.
///
/// - parameter index:
internal func getHighlights(forIndex index: Int) -> [Highlight]
{
var vals = [Highlight]()
guard let chart = self.chart as? RadarChartView
else { return vals }
let phaseX = chart.chartAnimator.phaseX
let phaseY = chart.chartAnimator.phaseY
let sliceangle = chart.sliceAngle
let factor = chart.factor
for i in 0..<(chart.data?.dataSetCount ?? 0)
{
guard let dataSet = chart.data?.getDataSetByIndex(i)
else { continue }
guard let entry = dataSet.entryForIndex(index)
else { continue }
let y = (entry.y - chart.chartYMin)
let p = ChartUtils.getPosition(
center: chart.centerOffsets,
dist: CGFloat(y) * factor * CGFloat(phaseY),
angle: sliceangle * CGFloat(index) * CGFloat(phaseX) + chart.rotationAngle)
vals.append(Highlight(x: Double(index), y: entry.y, xPx: p.x, yPx: p.y, dataSetIndex: i, axis: dataSet.axisDependency))
}
return vals
}
}
|
mit
|
6d0e269034c640f5521660bf633de1eb
| 30.291139 | 131 | 0.575243 | 4.914513 | false | false | false | false |
muukii/ZoomImageView
|
Demo/StraightenViewController.swift
|
1
|
1196
|
//
// StraightenViewController.swift
// Demo
//
// Created by muukii on 10/5/18.
// Copyright © 2018 muukii. All rights reserved.
//
import Foundation
import ZoomImageView
class StraightenViewController: UIViewController {
@IBOutlet weak var imageView: ZoomImageView!
@IBOutlet weak var slider: UISlider!
private var originalImageViewSize: CGSize!
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.zoomMode = .fill
self.imageView.image = #imageLiteral(resourceName: "5")
originalImageViewSize = imageView.bounds.size
print(originalImageViewSize)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
@IBAction func didChangeSliderValue(_ sender: Any) {
let value = CGFloat(slider.value)
let angle = value * (.pi / 4)
let t = CGAffineTransform(rotationAngle: angle)
let height = cos(abs(angle)) * originalImageViewSize.height + sin(abs(angle)) * originalImageViewSize.width
let width = sin(abs(angle)) * originalImageViewSize.height + cos(abs(angle)) * originalImageViewSize.width
imageView.bounds.size = CGSize(width: width, height: height)
imageView.transform = t
}
}
|
mit
|
0d14e0105c6bb0439fa3fd9ca2e7cea1
| 22.9 | 111 | 0.720502 | 4.178322 | false | false | false | false |
lyft/SwiftLint
|
Source/SwiftLintFramework/Rules/ProtocolPropertyAccessorsOrderRule.swift
|
1
|
2384
|
import Foundation
import SourceKittenFramework
public struct ProtocolPropertyAccessorsOrderRule: ConfigurationProviderRule, CorrectableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "protocol_property_accessors_order",
name: "Protocol Property Accessors Order",
description: "When declaring properties in protocols, the order of accessors should be `get set`.",
kind: .style,
nonTriggeringExamples: [
"protocol Foo {\n var bar: String { get set }\n }",
"protocol Foo {\n var bar: String { get }\n }",
"protocol Foo {\n var bar: String { set }\n }"
],
triggeringExamples: [
"protocol Foo {\n var bar: String { ↓set get }\n }"
],
corrections: [
"protocol Foo {\n var bar: String { ↓set get }\n }":
"protocol Foo {\n var bar: String { get set }\n }"
]
)
public func validate(file: File) -> [StyleViolation] {
return violationRanges(file: file).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
private func violationRanges(file: File) -> [NSRange] {
return file.match(pattern: "\\bset\\s*get\\b", with: [.keyword, .keyword])
}
public func correct(file: File) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(file: file), for: self)
var correctedContents = file.contents
var adjustedLocations = [Int]()
for violatingRange in violatingRanges.reversed() {
if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) {
correctedContents = correctedContents
.replacingCharacters(in: indexRange, with: "get set")
adjustedLocations.insert(violatingRange.location, at: 0)
}
}
file.write(correctedContents)
return adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0))
}
}
}
|
mit
|
a9337db242cf70e3d73bf208290087a7
| 38.016393 | 107 | 0.607563 | 4.867076 | false | true | false | false |
haolloyin/XYViewPlaceholder
|
XYViewPlaceholder/ViewController.swift
|
1
|
2593
|
//
// ViewController.swift
// XYViewPlaceholder
//
// Created by hao on 10/18/15.
// Copyright © 2015 hao. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var placeholderVisible = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let width = self.view.frame.width
let height = self.view.frame.height
let superView = UIView.init(frame: CGRectMake(0, 0, width, height / 2 + 30))
superView.backgroundColor = UIColor.yellowColor()
self.view.addSubview(superView)
self.addViewWith(superView, frame: CGRectMake(20, 80, 40, 40), color: UIColor.greenColor())
self.addViewWith(superView, frame: CGRectMake(20, 125, 40, 40), color: UIColor.grayColor())
self.addViewWith(superView, frame: CGRectMake(65, 80, 80, 80), color: UIColor.greenColor())
self.addViewWith(superView, frame: CGRectMake(165, 80, 140.6, 182.3), color: UIColor.redColor())
// show all subviews
superView.showPlaceholderWithAllSubviews()
let imageView = UIImageView.init(frame: CGRectMake(20, height/2 + 40, 100, 100))
imageView.image = UIImage.init(named: "avatar.png")
self.view.addSubview(imageView)
imageView.showPlaceholderWith(UIColor.redColor())
let button = UIButton.init(frame: CGRectMake(width/2 + 10, height/2 + 40, 100.5, 80.5))
button.backgroundColor = UIColor.greenColor()
self.view.addSubview(button)
button.showPlaceholderWith(UIColor.whiteColor(), backColor: UIColor.greenColor(), arrowSize: 10, lineWidth: 2)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Private
func addViewWith(superView: UIView, frame: CGRect, color: UIColor) {
let v = UIView.init(frame: frame)
v.backgroundColor = color;
superView.addSubview(v)
}
@IBAction func hideOrShow(sender: AnyObject) {
print("placeholderVisible=\(self.placeholderVisible)")
if self.placeholderVisible {
self.placeholderVisible = false
// self.view.removePlaceholderWithAllSubviews()
self.view.hidePlaceholderWithAllSubviews()
}
else {
self.placeholderVisible = true
self.view.showPlaceholderWithAllSubviews()
}
}
}
|
mit
|
83424060578b91e5c90425c30cb32fc8
| 34.506849 | 118 | 0.637731 | 4.52356 | false | false | false | false |
TheDarkCode/Algorithms
|
Pod/Classes/BinarySearchUtils.swift
|
1
|
4679
|
//
// BinarySearchUtils.swift
// Ahtau
//
// Created by Mark Hamilton on 3/26/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import Foundation
public enum CalcError: ErrorType {
case InvalidAverage
case InvalidMiddleValue
}
public func binarySearch< T : Comparable >(collection: [T], query: T) throws -> Bool {
var leftCount: Int = 0
var rightCount: Int = collection.count - 1
while( leftCount <= rightCount ) {
guard let middleValue: Int = (( leftCount + rightCount ) / 2) else {
throw CalcError.InvalidAverage
}
guard let estimatedValue: T = collection[middleValue] else {
throw CalcError.InvalidMiddleValue
}
if (estimatedValue == query) {
return true
}
if (estimatedValue < query) {
leftCount = middleValue + 1
}
if (estimatedValue > query) {
rightCount = middleValue - 1
}
}
return false
}
public func binarySearchPrefix(collection: [String], query: String) throws -> Bool {
var leftCount: Int = 0
var rightCount: Int = collection.count - 1
while( leftCount <= rightCount ) {
guard let middleValue: Int = (( leftCount + rightCount ) / 2) else {
throw CalcError.InvalidAverage
}
guard let estimatedValue: String = collection[middleValue] else {
throw CalcError.InvalidMiddleValue
}
if (estimatedValue.hasPrefix(query)) {
return true
}
if (estimatedValue < query) {
leftCount = middleValue + 1
}
if (estimatedValue > query) {
rightCount = middleValue - 1
}
}
return false
}
public func binarySearchFirst(collection: [String], query: String) throws -> Int {
var leftCount: Int = 0
var rightCount: Int = collection.count - 1
while( leftCount <= rightCount ) {
guard let middleValue: Int = (( leftCount + rightCount ) / 2) else {
throw CalcError.InvalidAverage
}
guard let estimatedValue: String = collection[middleValue] else {
throw CalcError.InvalidMiddleValue
}
if (estimatedValue.hasPrefix(query) && leftCount == rightCount) {
return leftCount
}
if estimatedValue.hasPrefix(query) {
if middleValue > 0 && !collection[middleValue - 1].hasPrefix(query) {
return middleValue
}
rightCount = middleValue - 1
} else if (estimatedValue < query) {
leftCount = middleValue + 1
} else if (estimatedValue > query) {
rightCount = middleValue - 1
}
}
return -1
}
public func binarySearchLast(collection: [String], query: String) throws -> Int {
var leftCount: Int = 0
var rightCount: Int = collection.count - 1
while( leftCount <= rightCount ) {
guard let middleValue: Int = (( leftCount + rightCount ) / 2) else {
throw CalcError.InvalidAverage
}
guard let estimatedValue: String = collection[middleValue] else {
throw CalcError.InvalidMiddleValue
}
if (estimatedValue.hasPrefix(query) && leftCount == rightCount) {
return leftCount
}
if estimatedValue.hasPrefix(query) {
if middleValue < collection.count - 1 && !collection[middleValue + 1].hasPrefix(query) {
return middleValue
}
leftCount = middleValue + 1
} else if (estimatedValue < query) {
leftCount = middleValue + 1
} else if (estimatedValue > query) {
rightCount = middleValue - 1
}
}
return -1
}
|
mit
|
e18c62c0e6a8d019dc4079306e693401
| 21.936275 | 100 | 0.468363 | 5.775309 | false | false | false | false |
vishalvshekkar/realmDemo
|
RealmDemo/RealmDemo/ContactsManager.swift
|
1
|
1113
|
//
// ContactsManager.swift
// RealmDemo
//
// Created by Vishal V Shekkar on 16/08/16.
// Copyright © 2016 Vishal. All rights reserved.
//
import Foundation
import RealmSwift
private typealias ManagerConstants = ContactsManager
class ContactsManager {
let realm: Realm
var contacts: Results<Contact>
init?() {
do {
realm = try Realm()
} catch let error {
print(error)
return nil
}
contacts = realm.objects(Contact.self).sorted(ContactsManager.firstName, ascending: true)
}
func refreshContactsList(sortedByAttribute: String) {
contacts = realm.objects(Contact.self).sorted(sortedByAttribute, ascending: true)
}
func addContact(withContact: Contact) {
do {
try realm.write({
realm.add(withContact)
})
// try realm.commitWrite()
} catch let error {
print(error)
}
}
}
extension ManagerConstants {
static let firstName = "firstName"
static let lastName = "lastName"
}
|
mit
|
d0fa91119af6b01ea079643e0a9a16e2
| 20.823529 | 97 | 0.589928 | 4.465863 | false | false | false | false |
joerocca/GitHawk
|
Classes/Issues/Comments/Tables/IssueCommentTableCell.swift
|
1
|
3588
|
//
// IssueCommentTableCell.swift
// Freetime
//
// Created by Ryan Nystrom on 7/6/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
final class IssueCommentTableCell: DoubleTappableCell,
ListBindable,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout {
static let inset = UIEdgeInsets(top: 0, left: 4, bottom: Styles.Sizes.rowSpacing, right: 4)
weak var delegate: AttributedStringViewDelegate?
private let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = .zero
return UICollectionView(frame: .zero, collectionViewLayout: layout)
}()
private let identifier = "cell"
private var model: IssueCommentTableModel?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
collectionView.register(IssueCommentTableCollectionCell.self, forCellWithReuseIdentifier: identifier)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .white
collectionView.isPrefetchingEnabled = false
collectionView.contentInset = IssueCommentTableCell.inset
contentView.addSubview(collectionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutContentViewForSafeAreaInsets()
collectionView.frame = contentView.bounds
}
// MARK: ListBindable
func bindViewModel(_ viewModel: Any) {
guard let viewModel = viewModel as? IssueCommentTableModel else { return }
self.model = viewModel
collectionView.reloadData()
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return model?.columns.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return model?.columns[section].rows.count ?? 0
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
guard let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? IssueCommentTableCollectionCell,
let columns = model?.columns
else { fatalError("Cell is wrong type or missing model/item") }
let column = columns[indexPath.section]
let rows = column.rows
let row = rows[indexPath.item]
cell.configure(row.text)
cell.textView.delegate = delegate
cell.contentView.backgroundColor = row.fill ? Styles.Colors.Gray.lighter.color : .white
cell.setRightBorder(visible: columns.last === column)
cell.setBottomBorder(visible: rows.last === row)
return cell
}
// MARK: UICollectionViewDelegateFlowLayout
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
guard let model = model else { fatalError("Missing model") }
return CGSize(
width: model.columns[indexPath.section].width,
height: model.rowHeights[indexPath.item]
)
}
}
|
mit
|
9c11cb734ab8ba08e50e938c64d8c3b0
| 32.212963 | 118 | 0.684416 | 5.418429 | false | false | false | false |
oscarvgg/calorie-counter
|
Calorie Counter Tests/UserModelTests.swift
|
1
|
5446
|
//
// UserModelTests.swift
// CalorieCounter
//
// Created by Oscar Vicente González Greco on 25/5/15.
// Copyright (c) 2015 Oscarvgg. All rights reserved.
//
import Calorie_Counter
import UIKit
import XCTest
import RealmSwift
class UserModelTests: XCTestCase {
override func setUp() {
super.setUp()
// current calendar
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let components = calendar?.components(
NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond,
fromDate: NSDate())
// today at 10AM
components?.hour = 10
components?.minute = 0
components?.second = 0
let todayAt10AM = calendar?.dateByAddingComponents(
components!,
toDate: NSDate(),
options: NSCalendarOptions.allZeros)
// today at 12M
components?.hour = 12
components?.minute = 30
components?.second = 0
let todayAt12M = calendar?.dateByAddingComponents(
components!,
toDate: NSDate(),
options: NSCalendarOptions.allZeros)
// today at 4PM
components?.hour = 16
components?.minute = 5
components?.second = 0
let todayAt4PM = calendar?.dateByAddingComponents(
components!,
toDate: NSDate(),
options: NSCalendarOptions.allZeros)
// today at 6PM
components?.hour = 18
components?.minute = 45
components?.second = 0
let todayAt6PM = calendar?.dateByAddingComponents(
components!,
toDate: NSDate(),
options: NSCalendarOptions.allZeros)
// Yesterday at 8AM
components?.hour = 8 - 24
components?.minute = 0
components?.second = 0
let yesterdayAt8AM = calendar?.dateByAddingComponents(
components!,
toDate: NSDate(),
options: NSCalendarOptions.allZeros)
let entry1 = Calorie()
entry1.objectId = "10AM"
entry1.eatenOn = todayAt10AM!
let entry2 = Calorie()
entry2.objectId = "12AM"
entry2.eatenOn = todayAt12M!
let entry3 = Calorie()
entry3.objectId = "4PM"
entry3.eatenOn = todayAt4PM!
let entry4 = Calorie()
entry4.objectId = "6PM"
entry4.eatenOn = todayAt6PM!
let entry5 = Calorie()
entry5.objectId = "8AM"
entry5.eatenOn = yesterdayAt8AM!
let user = User()
user.objectId = "user"
user.calories.extend([entry1, entry2, entry3, entry4, entry5])
// Add to local databse
let realm = Realm()
realm.write { () -> Void in
realm.add(user, update: true)
}
}
override func tearDown() {
// remove from local database
let realm = Realm()
let entries = realm.objects(Calorie.self).filter("objectId IN %@",
["10AM", "12AM", "4PM", "6PM", "8AM"])
let user = realm.objects(User.self).filter("objectId == %@", "user")
realm.write { () -> Void in
realm.delete(user)
realm.delete(entries)
}
super.tearDown()
}
func testRetreavingTodaysEntries() {
let realm = Realm()
let user = realm.objects(User.self).filter("objectId == %@", "user")
let todaysEntries = user[0].todaysEntries()
XCTAssertEqual(todaysEntries.count, 4, "number of entries for today do not match")
}
func testRetreavingRangedEntries() {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
// build from date
let components = calendar?.components(
NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond,
fromDate: NSDate())
components?.hour = 6 - 24
components?.minute = 50
components?.second = 0
let from = calendar?.dateByAddingComponents(
components!,
toDate: NSDate(),
options: NSCalendarOptions.allZeros)
components?.hour = 16
components?.minute = 45
components?.second = 0
let to = calendar?.dateByAddingComponents(
components!,
toDate: NSDate(),
options: NSCalendarOptions.allZeros)
let realm = Realm()
let user = realm.objects(User.self).filter("objectId == %@", "user")
let todaysEntries = user[0].caloriesInRange(
(from: from!, to: to!),
timeRange: (fromHour: 11, fromMinute: 35, toHour: 18, toMinute: 30))
XCTAssertEqual(todaysEntries.count, 2, "number of entries for range do not match")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
|
mit
|
1dadb6debe8ee5204612176d9eef127c
| 26.923077 | 116 | 0.542332 | 5.084034 | false | false | false | false |
brentsimmons/Evergreen
|
Shared/SmartFeeds/SmartFeedsController.swift
|
1
|
1220
|
//
// SmartFeedsController.swift
// NetNewsWire
//
// Created by Brent Simmons on 12/16/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import RSCore
import Account
final class SmartFeedsController: DisplayNameProvider, ContainerIdentifiable {
var containerID: ContainerIdentifier? {
return ContainerIdentifier.smartFeedController
}
public static let shared = SmartFeedsController()
let nameForDisplay = NSLocalizedString("Smart Feeds", comment: "Smart Feeds group title")
var smartFeeds = [Feed]()
let todayFeed = SmartFeed(delegate: TodayFeedDelegate())
let unreadFeed = UnreadFeed()
let starredFeed = SmartFeed(delegate: StarredFeedDelegate())
private init() {
self.smartFeeds = [todayFeed, unreadFeed, starredFeed]
}
func find(by identifier: FeedIdentifier) -> PseudoFeed? {
switch identifier {
case .smartFeed(let stringIdentifer):
switch stringIdentifer {
case String(describing: TodayFeedDelegate.self):
return todayFeed
case String(describing: UnreadFeed.self):
return unreadFeed
case String(describing: StarredFeedDelegate.self):
return starredFeed
default:
return nil
}
default:
return nil
}
}
}
|
mit
|
41ee163fdcece6ad30a694db1222c914
| 23.877551 | 90 | 0.748154 | 3.857595 | false | false | false | false |
argent-os/argent-ios
|
app-ios/BitcoinUriViewController.swift
|
1
|
5449
|
//
// BitcoinUriViewController.swift
// app-ios
//
// Created by Sinan Ulkuatam on 5/5/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import UIKit
import MZFormSheetPresentationController
import QRCode
import EmitterKit
import CWStatusBarNotification
import Crashlytics
class BitcoinUriViewController: UIViewController {
var bitcoinId: String?
var bitcoinUri: String?
var bitcoinAmount: Float?
var bitcoinFilled: Bool?
let qrImageView = UIImageView()
let bitcoinAmountLabel = UILabel()
let bitcoinFilledSignal = Signal()
var bitcoinFilledListener: Listener?
var bitcoinPoller:NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
// This will set to only one instance
// screen width and height:
let screen = UIScreen.mainScreen().bounds
_ = screen.size.width
_ = screen.size.height
self.navigationController?.navigationBar.translucent = true
self.navigationController?.navigationBar.barTintColor = UIColor.lightGrayColor()
qrImageView.frame = CGRect(x: 25, y: 25, width: 200, height: 200)
qrImageView.image = {
var qrCode = QRCode(bitcoinUri!)
// print("got bitcoin uri", bitcoinUri)
qrCode?.image
qrCode!.errorCorrection = .High
qrCode!.color = CIColor(CGColor: UIColor.mediumBlue().CGColor)
return qrCode!.image
}();
self.view.addSubview(qrImageView)
bitcoinAmountLabel.frame = CGRect(x: 25, y: 230, width: 200, height: 50)
bitcoinAmountLabel.backgroundColor = UIColor.offWhite()
bitcoinAmountLabel.layer.borderColor = UIColor.lightBlue().colorWithAlphaComponent(0.2).CGColor
bitcoinAmountLabel.layer.cornerRadius = 10
bitcoinAmountLabel.layer.borderWidth = 1
// convert satoshi to bitcoin divide by 10^8
bitcoinAmountLabel.text = String(bitcoinAmount!/100000000) + " BTC"
bitcoinAmountLabel.textAlignment = .Center
bitcoinAmountLabel.textColor = UIColor.lightBlue()
bitcoinAmountLabel.font = UIFont(name: "HelveticaNeue-Light", size: 18)!
self.view.addSubview(bitcoinAmountLabel)
// Flow | Bitcoin
// Send request to get the bitcoin receiver by id
// This is essentially polling, but once the receiver is
// filled then emit event that the bitcoin receiver is filled
// thereby closing the bitcoin modal window
// and display a notification alert saying bitcoin was paid
// print("is bitcoin receiver for bitcoin id " + bitcoinId! + " filled? ", bitcoinFilled)
// make REST call to bitcoin receiver to retrieve bitcoin filled status
// if the status if filled, emit an event saying that the bitcoin receiver
// is filled and this will dismiss modal window
// Be careful with timers, they can cause memory leaks if not
// explicitly removed / destroyed
// poll bitcoin receiver every 30 seconds
bitcoinPoller = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: #selector(self.pollBitcoinReceiver(_:)), userInfo: nil, repeats: true)
}
func pollBitcoinReceiver(sender: AnyObject) {
// print("polling bitcoin")
Timeout(60) {
// invalidate timer after 1 minute
self.bitcoinPoller!.invalidate()
self.dismissViewControllerAnimated(true, completion: {
showGlobalNotification("Ƀitcoin was not received", duration: 5.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.NavigationBarNotification, color: UIColor.bitcoinOrange())
Answers.logCustomEventWithName("Ƀitcoin not received",
customAttributes: [
"amount": "No ɃTC received"
])
})
}
Bitcoin.getBitcoinReceiver(bitcoinId!) { (bitcoin, err) in
//print(bitcoin?.id)
//print("bitcoin filled status ", bitcoin!.filled)
if bitcoin?.filled == true {
// print("invalidating timer")
self.bitcoinPoller!.invalidate()
self.dismissViewControllerAnimated(true, completion: {
// print("bitcoin receiver for bitcoin id " + self.bitcoinId! + " filled!")
showGlobalNotification(String((bitcoin?.amount)!/100000000) + " BTC received!", duration: 5.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.NavigationBarNotification, color: UIColor.bitcoinOrange())
showAlert(.Bitcoin, title: "Received", msg: String((bitcoin?.amount)!/100000000) + " BTC received!")
Answers.logCustomEventWithName("Ƀitcoin received",
customAttributes: [
"amount": String((bitcoin?.amount)!/100000000) + " ɃTC received"
])
})
}
}
}
override func viewDidDisappear(animated: Bool) {
}
func close() -> Void {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
88b870a8d14836ac67d8ab9e181e98c8
| 39.626866 | 299 | 0.630351 | 5.208612 | false | false | false | false |
huangboju/Moots
|
Examples/uidatepicker/ExUIDatePicker/ExUIDatePicker/ViewController.swift
|
1
|
6599
|
//
// ViewController.swift
// ExUIDatePicker
//
// Created by joe feng on 2016/5/17.
// Copyright © 2016年 hsin. All rights reserved.
//
import UIKit
class DatePickerView: UIView {
private var datePicker: UIDatePicker!
override init(frame: CGRect) {
super.init(frame: frame)
datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 216))
// 設置 UIDatePicker 格式
datePicker.datePickerMode = .date
// 選取時間時的分鐘間隔 這邊以 15 分鐘為一個間隔
datePicker.minuteInterval = 15
// 設置預設時間為現在時間
datePicker.date = Date()
// 設置 Date 的格式
let formatter = DateFormatter()
// 設置時間顯示的格式
formatter.dateFormat = "yyyy-MM-dd"
// 可以選擇的最早日期時間
let fromDateTime = formatter.date(from: "1990-01-01")
// 設置可以選擇的最早日期時間
datePicker.minimumDate = fromDateTime
// 可以選擇的最晚日期時間
let endDateTime = formatter.date(from: "2027-12-31")
// 設置可以選擇的最晚日期時間
datePicker.maximumDate = endDateTime
// 設置顯示的語言環境
datePicker.locale = Locale(identifier: "zh_TW")
// 設置改變日期時間時會執行動作的方法
datePicker.addTarget(self, action: #selector(datePickerChanged), for: .valueChanged)
}
@objc func datePickerChanged(_ datePicker: UIDatePicker) {
print(datePicker.date, #function)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var canBecomeFirstResponder: Bool {
return datePicker.window == nil
}
override var inputView: UIView? {
return datePicker
}
override var inputAccessoryView: UIView? {
let accessoryView = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
accessoryView.backgroundColor = UIColor.white
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let right = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneAction))
accessoryView.items = [flexible, right]
return accessoryView
}
@objc func doneAction() {
resignFirstResponder()
}
}
class ClassPickerView: UIView, UIPickerViewDataSource, UIPickerViewDelegate {
var pickerView: UIPickerView!
var items: [[String]] = [
[
"一",
"二",
"三",
"四"
],
[
"1",
"2"
]
]
let dict: [String: [String]] = [
"一": ["1", "2"],
"二": [ "1", "2", "3"],
"三": [ "1", "2", "3", "4"],
"四": [ "1"]
]
let gradeTextLabel = UILabel()
let classTextLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
pickerView = UIPickerView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 216))
pickerView.delegate = self
pickerView.dataSource = self
// 23 = 9 * 2 + 5
let w = (pickerView.frame.width - 23) / 4
gradeTextLabel.frame = CGRect(x: w + 25, y: 0, width: 80, height: 30)
gradeTextLabel.text = "年级"
gradeTextLabel.font = UIFont.systemFont(ofSize: 23.5)
pickerView.addSubview(gradeTextLabel)
gradeTextLabel.center.y = pickerView.center.y
classTextLabel.frame = CGRect(x: pickerView.frame.width - w + 9, y: 0, width: 40, height: 30)
classTextLabel.text = "班"
classTextLabel.font = UIFont.systemFont(ofSize: 23.5)
pickerView.addSubview(classTextLabel)
classTextLabel.center.y = pickerView.center.y
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return items[component].count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return items[component][row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 1 { return }
items[1] = dict[items[0][row]]!
pickerView.reloadComponent(1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var canBecomeFirstResponder: Bool {
return pickerView.window == nil
}
override var inputView: UIView? {
return pickerView
}
override var inputAccessoryView: UIView? {
let accessoryView = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
accessoryView.backgroundColor = UIColor.white
let cancel = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(doneAction))
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let right = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(doneAction))
accessoryView.items = [cancel, fixedSpace, right]
return accessoryView
}
@objc func doneAction() {
resignFirstResponder()
}
}
class ViewController: UIViewController {
var classPickerView: ClassPickerView!
var datePickerView: DatePickerView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
classPickerView = ClassPickerView(frame: CGRect(x: 16, y: 100, width: view.frame.width - 32, height: 44))
classPickerView.backgroundColor = UIColor.red
view.addSubview(classPickerView)
datePickerView = DatePickerView(frame: CGRect(x: 16, y: 160, width: view.frame.width - 32, height: 44))
datePickerView.backgroundColor = UIColor.blue
view.addSubview(datePickerView)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// classPickerView.becomeFirstResponder()
datePickerView.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
6e0550541840d07add03079e289bb69b
| 28.952607 | 113 | 0.623892 | 4.261632 | false | false | false | false |
huangboju/Moots
|
UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/ViewModel/ImageVewModel.swift
|
2
|
1149
|
//
// ImageViewModel.swift
// SwiftNetworkImages
//
// Created by Arseniy Kuznetsov on 30/4/16.
// Copyright © 2016 Arseniy Kuznetsov. All rights reserved.
//
import UIKit
/// Image View Model
struct ImageViewModel {
let imageCaption: Observable<String>
let imageURLString: Observable<String>
let image: Observable<UIImage?>
init() {
imageCaption = Observable(EmptyString)
imageURLString = Observable(EmptyString)
image = Observable(nil)
}
var imageFetcher: ImageFetcher? {
didSet {
guard !self.imageURLString.value.isEqual(EmptyString),
let fetcher = imageFetcher else {return}
fetcher.fetchImage(urlString: self.imageURLString.value) { [s = self] img in
if let img = img {
s.image.value = img
}
}
}
}
private let EmptyString = ""
}
extension ImageViewModel {
init(imageInfo: ImageInfo) {
self.init()
imageCaption.value = imageInfo.imageCaption
imageURLString.value = imageInfo.imageURLString
}
}
|
mit
|
e23a8c474594f0c21218098e960676cc
| 25.090909 | 88 | 0.599303 | 4.763485 | false | false | false | false |
mightydeveloper/swift
|
test/Constraints/protocols.swift
|
10
|
2906
|
// RUN: %target-parse-verify-swift
protocol Fooable { func foo() }
protocol Barable { func bar() }
extension Int : Fooable, Barable {
func foo() {}
func bar() {}
}
extension Float32 : Barable {
func bar() {}
}
func f0(_: Barable) {}
func f1(x: protocol<Fooable, Barable>) {}
func f2(_: Float) {}
let nilFunc: Optional<(Barable) -> ()> = nil
func g(_: (protocol<Barable, Fooable>) -> ()) {}
protocol Classable : AnyObject {}
class SomeArbitraryClass {}
func fc0(_: Classable) {}
func fc1(_: protocol<Fooable, Classable>) {}
func fc2(_: AnyObject) {}
func fc3(_: SomeArbitraryClass) {}
func gc(_: (protocol<Classable, Fooable>) -> ()) {}
var i : Int
var f : Float
var b : Barable
//===--------------------------------------------------------------------===//
// Conversion to and among existential types
//===--------------------------------------------------------------------===//
f0(i)
f0(f)
f0(b)
f1(i)
f1(f) // expected-error{{argument type 'Float' does not conform to expected type 'protocol<Barable, Fooable>'}}
f1(b) // expected-error{{argument type 'Barable' does not conform to expected type 'protocol<Barable, Fooable>'}}
//===--------------------------------------------------------------------===//
// Subtyping
//===--------------------------------------------------------------------===//
g(f0) // okay (subtype)
g(f1) // okay (exact match)
g(f2) // expected-error{{cannot convert value of type '(Float) -> ()' to expected argument type '(protocol<Barable, Fooable>) -> ()'}}
// FIXME: Workaround for ?? not playing nice with function types.
infix operator ??* {}
func ??*<T>(lhs: T?, rhs: T) -> T { return lhs ?? rhs }
g(nilFunc ??* f0)
gc(fc0) // okay
gc(fc1) // okay
gc(fc2) // okay
gc(fc3) // expected-error{{cannot convert value of type '(SomeArbitraryClass) -> ()' to expected argument type '(protocol<Classable, Fooable>) -> ()'}}
// rdar://problem/19600325
func getAnyObject() -> AnyObject? {
return SomeArbitraryClass()
}
func castToClass(object: Any) -> SomeArbitraryClass? {
return object as? SomeArbitraryClass
}
_ = getAnyObject().map(castToClass)
_ = { (_: Any) -> Void in
return
} as ((Int) -> Void)
let _: (Int) -> Void = {
(_: Any) -> Void in
return
}
let _: () -> Any = {
() -> Int in
return 0
}
let _: () -> Int = {
() -> String in // expected-error {{declared closure result 'String' is incompatible with contextual type 'Int'}}
return ""
}
//===--------------------------------------------------------------------===//
// Dynamic self
//===--------------------------------------------------------------------===//
protocol Clonable {
func maybeClone() -> Self?
func badMaybeClone() -> Self??
}
func testClonable(v : Clonable) {
let v2 = v.maybeClone()
let v3 = v.badMaybeClone() // expected-error {{member 'badMaybeClone' cannot be used on value of protocol type 'Clonable'; use a generic constraint instead}}
}
|
apache-2.0
|
75fd87c50d4368d0e55c35d39e33cd16
| 25.907407 | 159 | 0.541638 | 3.959128 | false | false | false | false |
daniel-c/iSimulatorExplorer
|
iSimulatorExplorer/DCSimulatorTrustStoreViewController.swift
|
1
|
7323
|
//
// DCSimulatorTrustStoreViewController.swift
// iSimulatorExplorer
//
// Created by Daniel Cerutti on 10.10.14.
// Copyright (c) 2014 Daniel Cerutti. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
import Cocoa
import SecurityInterface
class DCSimulatorTrustStoreViewController: DCSimulatorViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var notavailableInfoTextField: NSTextField!
@IBOutlet weak var tableScrollView: NSScrollView!
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var importServerButton: NSButton!
@IBOutlet weak var importFileButton: NSButton!
@IBOutlet weak var removeButton: NSButton!
@IBOutlet weak var exportButton: NSButton!
var truststore : DCSimulatorTruststore?
override var simulator : Simulator? {
didSet {
truststore = nil
if let truststorePath = simulator?.trustStorePath {
if FileManager.default.fileExists(atPath: truststorePath) {
truststore = DCSimulatorTruststore(path : truststorePath)
truststore!.openTrustStore()
NSLog("Trustore has \(truststore!.items.count) items")
}
}
tableView.reloadData()
enableButtons()
if simulator != nil && truststore == nil {
// If we do not find the truststore.sqlite3 file it is usually because the simulator has not yet been run
// indicate it with an appropriate message and hide the tableview
notavailableInfoTextField.isHidden = false
tableScrollView!.isHidden = true
}
else {
notavailableInfoTextField.isHidden = true
tableScrollView!.isHidden = false
}
}
}
override func loadView() {
super.loadView()
enableButtons()
}
func enableButtons() {
let enableActionOnSelected = (tableView.selectedRow >= 0)
let enableActionOnTrustStore = (truststore != nil)
removeButton.isEnabled = enableActionOnSelected
exportButton.isEnabled = enableActionOnSelected
importServerButton.isEnabled = enableActionOnTrustStore
importFileButton.isEnabled = enableActionOnTrustStore
}
func numberOfRows(in tableView: NSTableView) -> Int {
return truststore?.items.count ?? 0
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let result = tableView.make(withIdentifier: "DataCell", owner: self) as? NSTableCellView {
if truststore != nil {
if let text = truststore?.items[row].subjectSummary {
result.textField!.stringValue = text
}
}
return result
}
return nil
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return nil;
}
@IBAction func viewCertificateButtonPressed(_ sender: NSButton) {
if let cellView = sender.superview as? NSTableCellView {
let row = tableView.row(for: cellView)
if row >= 0 {
tableView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false)
if let cert = truststore?.items[row].certificate {
showCertificate(cert)
}
}
}
return;
}
func showCertificate(_ cert : SecCertificate) {
SFCertificatePanel.shared().runModal(forCertificates: [cert], showGroup: false)
}
@IBAction func importCertificateFromServerButtonPressed(_ sender: AnyObject) {
let importPanel = DCImportCertificateWindowController(windowNibName: "DCImportCertificateWindowController")
let result = NSApplication.shared().runModal(for: importPanel.window!)
if result == 0 {
if importPanel.certificate != nil {
let item = DCSimulatorTruststoreItem(certificate: importPanel.certificate!)
if truststore!.addItem(item) {
tableView.reloadData()
enableButtons()
}
}
}
NSLog("Modal close: \(result)")
return;
}
@IBAction func importCertificateFromFile(_ sender: AnyObject) {
let openPanel = NSOpenPanel()
openPanel.canChooseFiles = true
openPanel.canChooseDirectories = false
openPanel.allowsMultipleSelection = false
if openPanel.runModal() == NSFileHandlingPanelOKButton {
for url in openPanel.urls {
if let data = try? Data(contentsOf: url) {
var format : SecExternalFormat = SecExternalFormat.formatUnknown
var itemType : SecExternalItemType = SecExternalItemType.itemTypeCertificate
//var outItems : Unmanaged<CFArray>?
var outItems : CFArray?
//var outItems : UnsafeMutablePointer<CFArray?>
SecItemImport(data as CFData, nil, &format, &itemType, SecItemImportExportFlags(rawValue: 0), nil, nil, &outItems)
//if let itemCFArray = outItems?.takeRetainedValue() {
if let itemCFArray = outItems {
let itemArray = itemCFArray as NSArray
if itemArray.count > 0 && itemType == SecExternalItemType.itemTypeCertificate {
// Here we must use an unconditional downcast (conditional downcast does not work here).
let item = DCSimulatorTruststoreItem(certificate: itemArray[0] as! SecCertificate)
if truststore!.addItem(item) {
tableView.reloadData()
}
}
}
}
}
}
}
@IBAction func removeCertificateButtonPressed(_ sender: AnyObject) {
if tableView.selectedRow >= 0 {
if truststore != nil {
if truststore!.removeItem(tableView.selectedRow) {
tableView.reloadData()
enableButtons()
}
}
}
}
@IBAction func exportButtonPressed(_ sender: AnyObject) {
if tableView.selectedRow >= 0 {
if truststore != nil {
let item = truststore!.items[tableView.selectedRow]
let savePanel = NSSavePanel()
if let text = item.subjectSummary {
savePanel.nameFieldStringValue = text
}
if savePanel.runModal() == NSFileHandlingPanelOKButton {
if let url = savePanel.url {
item.export(url)
}
}
}
}
}
func tableViewSelectionDidChange(_ notification: Notification) {
enableButtons()
}
}
|
mit
|
34bd8e3940eace70baf19eddc87d0cc3
| 37.952128 | 134 | 0.572853 | 5.743529 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift
|
Sources/Math/263_UglyNumber.swift
|
1
|
668
|
//
// 263_UglyNumber.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-09-05.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:263 Ugly Number
URL: https://leetcode.com/problems/ugly-number/
Space: O(1)
Time: O(1)
*/
class UglyNumber_Solution {
func isUgly(_ num: Int) -> Bool {
guard num > 0 else {
return false
}
var loopNum = num
while loopNum != 1 {
if loopNum % 2 == 0 {
loopNum /= 2
} else if loopNum % 3 == 0 {
loopNum /= 3
} else if loopNum % 5 == 0 {
loopNum /= 5
} else {
return false
}
}
return true
}
}
|
mit
|
90473c3c46ed92bf0cf9d4d5b9784ff5
| 17.027027 | 53 | 0.547226 | 3.146226 | false | false | false | false |
wesleysadler/CoreDataSelfReferencingTable
|
CoreDataSelfReferencingTable/AppDelegate.swift
|
1
|
14426
|
//
// AppDelegate.swift
// CoreDataSelfReferencingTable
//
// Created by Wesley Sadler on 5/22/15.
// Copyright (c) 2015 Digital Sadler. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let fileType: String = "plist"
let countryFile: String = "CountryAbbrCodes"
let usaFile: String = "USAStateAbbrCodes"
let canFile: String = "CANProvincesTerritoriesAbbrCodes"
var countryDict: NSDictionary?
var canDict: NSDictionary?
var usaDict: NSDictionary?
var rowsCount: Int?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.testDB()
// self.cleanDB()
// self.testDB()
// Create the managed object context
if rowsCount == 0 {
self.readPlistFiles()
self.loadCountryData()
self.loadCANData()
self.loadUSAData()
self.saveContext()
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Read rows in Location table
func testDB() {
var locations = [NSManagedObject]()
let fetchRequest = NSFetchRequest(entityName:"Location")
var error: NSError?
let fetchedResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]
if let results = fetchedResults {
locations = results
rowsCount = locations.count
println("Number of Location Rows: \(locations.count)");
if !locations.isEmpty {
for location in locations as! [Location] {
println("\(location.name) \(location.code)")
}
}
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}
func cleanDB() {
var locations = [NSManagedObject]()
var usaLocations = [NSManagedObject]()
var canLocations = [NSManagedObject]()
let fetchRequest = NSFetchRequest(entityName:"Location")
var error: NSError?
let fetchedResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]
let predicate = NSPredicate(format: "code IN %@", ["CAN", "USA"])
fetchRequest.predicate = predicate
if let results = fetchedResults {
locations = results
if !locations.isEmpty {
for location in locations as! [Location] {
println("\(location.name) \(location.code)")
// var relationshipLocations = location.hasStateProvince
// for relationshipLocation in relationshipLocations {
// var localRelationshipLocation = relationshipLocation as! NSManagedObject
// managedObjectContext?.deleteObject(localRelationshipLocation)
// }
managedObjectContext?.deleteObject(location)
}
var error: NSError?
if !managedObjectContext!.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
}
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}
// MARK: - Read plist Files
func readPlistFiles () {
let countryPath = NSBundle.mainBundle().pathForResource(countryFile, ofType: fileType)
if let countryPathLocal = countryPath {
countryDict = NSDictionary(contentsOfFile: countryPathLocal)
// println()
// println(countryDict)
}
let canPath = NSBundle.mainBundle().pathForResource(canFile, ofType: fileType)
if let canPathLocal = canPath {
canDict = NSDictionary(contentsOfFile: canPathLocal)
// println()
// println(canDict)
}
let usaPath = NSBundle.mainBundle().pathForResource(usaFile, ofType: fileType)
if let usaPathLocal = usaPath {
usaDict = NSDictionary(contentsOfFile: usaPathLocal)
// println()
// println(usaDict)
}
}
func loadCountryData() {
println()
let keysSorted = countryDict?.keysSortedByValueUsingComparator({ ($0 as! String).compare($1 as! String) }) as! [String]
for keyName in keysSorted {
let code = countryDict?.objectForKey(keyName) as! String
println("Key: " + keyName + " Code: " + code)
var location: Location = NSEntityDescription.insertNewObjectForEntityForName("Location", inManagedObjectContext: managedObjectContext!) as! Location
location.name = keyName
location.code = code
var error: NSError?
if !managedObjectContext!.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
}
}
func loadCANData() {
var indexSet = 0;
println()
// loop dictionary create location objects load into ordered set
var provincesSet: NSMutableOrderedSet = NSMutableOrderedSet()
let keysSorted = canDict?.keysSortedByValueUsingComparator({ ($0 as! String).compare($1 as! String) }) as! [String]
for keyName in keysSorted {
let code = canDict?.objectForKey(keyName) as! String
println("Key: " + keyName + " Code: " + code)
var location: Location = NSEntityDescription.insertNewObjectForEntityForName("Location", inManagedObjectContext: managedObjectContext!) as! Location
location.name = keyName
location.code = code
provincesSet.insertObject(location, atIndex: indexSet)
indexSet++
}
// save the provinces with country
let fetchRequest = NSFetchRequest(entityName:"Location")
let predicate = NSPredicate(format: "code == %@", "CAN")
fetchRequest.predicate = predicate
var error: NSError?
if let fetchResults = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) {
var locationCountry = fetchResults.first as! Location
locationCountry.hasStateProvince = provincesSet
if !managedObjectContext!.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
} else {
println("Could not fetch \(error), \(error?.userInfo)")
}
}
func loadUSAData() {
var indexSet = 0;
println()
// loop dictionary create location objects load into ordered set
var statesSet: NSMutableOrderedSet = NSMutableOrderedSet()
let keysSorted = usaDict?.keysSortedByValueUsingComparator({ ($0 as! String).compare($1 as! String) }) as! [String]
for keyName in keysSorted {
let code = usaDict?.objectForKey(keyName) as! String
println("Key: " + keyName + " Code: " + code)
var location: Location = NSEntityDescription.insertNewObjectForEntityForName("Location", inManagedObjectContext: managedObjectContext!) as! Location
location.name = keyName
location.code = code
statesSet.insertObject(location, atIndex: indexSet)
indexSet++
}
// save the provinces with country
let fetchRequest = NSFetchRequest(entityName:"Location")
let predicate = NSPredicate(format: "code == %@", "USA")
fetchRequest.predicate = predicate
var error: NSError?
if let fetchResults = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) {
var locationCountry = fetchResults.first as! Location
locationCountry.hasStateProvince = statesSet
if !managedObjectContext!.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
} else {
println("Could not fetch \(error), \(error?.userInfo)")
}
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.digitalsadler.CoreDataSelfReferencingTable" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CoreDataSelfReferencingTable", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDataSelfReferencingTable.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
mit
|
4c55034e941bb4bd87860580f5fe01ef
| 40.454023 | 290 | 0.625607 | 5.722332 | false | false | false | false |
tardieu/swift
|
test/SILGen/lifetime_unions.swift
|
4
|
3351
|
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -parse-as-library -emit-silgen %s | %FileCheck %s
enum TrivialUnion {
case Foo
case Bar(Int)
case Bas(Int, Int)
}
class C {
init() {}
}
enum NonTrivialUnion1 {
case Foo
case Bar(Int)
case Bas(Int, C)
}
enum NonTrivialUnion2 {
case Foo
case Bar(C)
case Bas(Int, C)
}
enum NonTrivialUnion3 {
case Bar(C)
case Bas(Int, C)
}
/* TODO: Address-only unions
enum AddressOnlyUnion<T> {
case Foo
case Bar(T)
case Bas(Int, T)
}
*/
func getTrivialUnion() -> TrivialUnion { return .Foo }
func getNonTrivialUnion1() -> NonTrivialUnion1 { return .Foo }
func getNonTrivialUnion2() -> NonTrivialUnion2 { return .Foo }
func getNonTrivialUnion3() -> NonTrivialUnion3 { return .Bar(C()) }
/* TODO: Address-only unions
func getAddressOnlyUnion<T>(_: T.Type) -> AddressOnlyUnion<T> { return .Foo }
*/
// CHECK-LABEL: sil hidden @_T015lifetime_unions19destroyUnionRValuesyyF : $@convention(thin) () -> () {
func destroyUnionRValues() {
// CHECK: [[GET_TRIVIAL_UNION:%.*]] = function_ref @_T015lifetime_unions15getTrivialUnionAA0dE0OyF : $@convention(thin) () -> TrivialUnion
// CHECK: [[TRIVIAL_UNION:%.*]] = apply [[GET_TRIVIAL_UNION]]() : $@convention(thin) () -> TrivialUnion
// CHECK-NOT: [[TRIVIAL_UNION]]
getTrivialUnion()
// CHECK: [[GET_NON_TRIVIAL_UNION_1:%.*]] = function_ref @_T015lifetime_unions19getNonTrivialUnion1AA0deF0OyF : $@convention(thin) () -> @owned NonTrivialUnion1
// CHECK: [[NON_TRIVIAL_UNION_1:%.*]] = apply [[GET_NON_TRIVIAL_UNION_1]]() : $@convention(thin) () -> @owned NonTrivialUnion1
// CHECK: destroy_value [[NON_TRIVIAL_UNION_1]] : $NonTrivialUnion1
getNonTrivialUnion1()
// CHECK: [[GET_NON_TRIVIAL_UNION_2:%.*]] = function_ref @_T015lifetime_unions19getNonTrivialUnion2AA0deF0OyF : $@convention(thin) () -> @owned NonTrivialUnion2
// CHECK: [[NON_TRIVIAL_UNION_2:%.*]] = apply [[GET_NON_TRIVIAL_UNION_2]]() : $@convention(thin) () -> @owned NonTrivialUnion2
// CHECK: destroy_value [[NON_TRIVIAL_UNION_2]] : $NonTrivialUnion2
getNonTrivialUnion2()
// CHECK: [[GET_NON_TRIVIAL_UNION_3:%.*]] = function_ref @_T015lifetime_unions19getNonTrivialUnion3AA0deF0OyF : $@convention(thin) () -> @owned NonTrivialUnion3
// CHECK: [[NON_TRIVIAL_UNION_3:%.*]] = apply [[GET_NON_TRIVIAL_UNION_3]]() : $@convention(thin) () -> @owned NonTrivialUnion3
// CHECK: destroy_value [[NON_TRIVIAL_UNION_3]] : $NonTrivialUnion3
getNonTrivialUnion3()
/* TODO: Address-only unions
// C/HECK: [[GET_ADDRESS_ONLY_UNION:%.*]] = function_ref @_TF15lifetime_unions19getAddressOnlyUnionU__FMQ_GOS_16AddressOnlyUnionQ__ : $@convention(thin) <T> T.Type -> AddressOnlyUnion<T>
// C/HECK: [[GET_ADDRESS_ONLY_UNION_SPEC:%.*]] = specialize [[GET_ADDRESS_ONLY_UNION]] : $@convention(thin) <T> T.Type -> AddressOnlyUnion<T>, $@thin Int64.Type -> AddressOnlyUnion<Int64>, T = Int
// C/HECK: [[ADDRESS_ONLY_UNION_ADDR:%.*]] = alloc_stack $AddressOnlyUnion<Int64>
// C/HECK: apply [[GET_ADDRESS_ONLY_UNION_SPEC]]([[ADDRESS_ONLY_UNION_ADDR]], {{%.*}}) : $@thin Int64.Type -> AddressOnlyUnion<Int64>
// C/HECK: destroy_addr [[ADDRESS_ONLY_UNION_ADDR]] : $*AddressOnlyUnion<Int64>
// C/HECK: dealloc_stack [[ADDRESS_ONLY_UNION_ADDR]] : $*AddressOnlyUnion<Int64>
getAddressOnlyUnion(Int)
*/
}
|
apache-2.0
|
95e94d22db026658968eec529a49663a
| 42.519481 | 200 | 0.676514 | 3.415902 | false | false | false | false |
imk2o/MK2Router
|
MK2Router-iOS/Router.swift
|
1
|
4302
|
//
// Router.swift
// MK2Router
//
// Created by k2o on 2016/05/12.
// Copyright © 2016年 Yuichi Kobayashi. All rights reserved.
//
import UIKit
/// ルータ.
open class Router {
public enum PerformBehavior {
case automatic
case push
case modal
}
public static let shared: Router = Router()
fileprivate init() {
}
/**
画面遷移を行う.
- parameter sourceViewController: 遷移元ビューコントローラ.
- parameter destinationViewController: 遷移先ビューコントローラ.
- parameter behavior: 遷移方法(pushまたはmodal).
- parameter contextForDestination: 遷移先へ渡すコンテキストを求めるブロック.
*/
open func perform<DestinationVC>(
_ sourceViewController: UIViewController,
destinationViewController: UIViewController,
behavior: PerformBehavior = .automatic,
contextForDestination: ((DestinationVC) -> DestinationVC.Context)
) where DestinationVC: DestinationType, DestinationVC: UIViewController {
ContextStore.shared.store(
for: destinationViewController,
contextForDestination: contextForDestination
)
self.perform(sourceViewController, destinationViewController: destinationViewController, behavior: behavior)
}
/**
画面遷移を行う.
- parameter sourceViewController: 遷移元ビューコントローラ.
- parameter storyboardName: 遷移先ストーリーボード名.
- parameter storyboardID: 遷移先ストーリーボードID. nilの場合はInitial View Controllerが遷移先となる.
- parameter behavior: 遷移方法(pushまたはmodal).
- parameter contextForDestination: 遷移先へ渡すコンテキストを求めるブロック.
*/
open func perform<DestinationVC>(
_ sourceViewController: UIViewController,
storyboardName: String,
storyboardID: String? = nil,
behavior: PerformBehavior = .automatic,
contextForDestination: ((DestinationVC) -> DestinationVC.Context)
) where DestinationVC: DestinationType, DestinationVC: UIViewController {
let destinationViewController = UIStoryboard(name: storyboardName, bundle: nil)
.mk2
.instantiateViewController(
withIdentifier: storyboardID,
contextForDestination: contextForDestination
)
return self.perform(sourceViewController, destinationViewController: destinationViewController, behavior: behavior)
}
func perform(
_ sourceViewController: UIViewController,
destinationViewController: UIViewController,
behavior: PerformBehavior = .automatic
) {
func performPush(_ sourceNavigationController: UINavigationController) {
sourceNavigationController.pushViewController(destinationViewController, animated: true)
}
func performModal() {
sourceViewController.present(destinationViewController, animated: true, completion: nil)
}
switch behavior {
case .automatic:
if
let sourceNavigationController = sourceViewController.navigationController
, !(destinationViewController is UINavigationController)
{
performPush(sourceNavigationController)
} else {
performModal()
}
case .push:
guard
let sourceNavigationController = sourceViewController.navigationController,
!(destinationViewController is UINavigationController)
else {
fatalError("Source view controller is not a child of navigation controller.")
}
performPush(sourceNavigationController)
case .modal:
performModal()
}
}
}
private extension UIViewController {
func contentViewController() -> UIViewController? {
if let navigationController = self as? UINavigationController {
return navigationController.topViewController
} else {
return self
}
}
}
|
mit
|
713db3df3a06d11a87eb46189f37b0fa
| 33.042373 | 123 | 0.64476 | 5.62605 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformKit/Services/SecureChannel/BrowserIdentityService.swift
|
1
|
5150
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import WalletPayloadKit
public enum IdentityError: LocalizedError, Equatable {
case identitySaveFailed
case identityEncodingFailed
case unknownPubKeyHash(String)
public var errorDescription: String? {
switch self {
case .identitySaveFailed:
return "BrowserIdentityService: Unable to save browser identity."
case .identityEncodingFailed:
return "BrowserIdentityService: Unable encode identity."
case .unknownPubKeyHash:
return "BrowserIdentityService: Browser not recognized."
}
}
}
final class BrowserIdentityService {
// MARK: Private Properties
private let appSettingsSecureChannel: AppSettingsSecureChannel
private let cryptoService: WalletCryptoServiceAPI
// MARK: Init
init(
appSettingsSecureChannel: AppSettingsSecureChannel = resolve(),
cryptoService: WalletCryptoServiceAPI = resolve()
) {
self.appSettingsSecureChannel = appSettingsSecureChannel
self.cryptoService = cryptoService
}
func saveIdentities(identities: [String: BrowserIdentity]) -> Result<Void, IdentityError> {
Result { try JSONEncoder().encode(identities) }
.replaceError(with: IdentityError.identityEncodingFailed)
.map { String(data: $0, encoding: .utf8) }
.onNil(error: .identitySaveFailed)
.map { string in
appSettingsSecureChannel.browserIdentities = string
}
}
func addBrowserIdentity(identity: BrowserIdentity) -> Result<Void, IdentityError> {
getIdentities()
.mapError(to: IdentityError.self)
.flatMap { list in
var newList = list
newList[identity.pubKeyHash] = identity
return saveIdentities(identities: newList)
}
}
func getBrowserIdentity(pubKeyHash: String) -> Result<BrowserIdentity, IdentityError> {
getIdentities()
.mapError(to: IdentityError.self)
.map(\.[pubKeyHash])
.onNil(error: .unknownPubKeyHash(pubKeyHash))
}
func deleteBrowserIdentity(pubKeyHash: String) -> Result<Void, IdentityError> {
getIdentities()
.mapError(to: IdentityError.self)
.flatMap { list in
var list = list
list[pubKeyHash] = nil
return saveIdentities(identities: list)
}
}
func updateBrowserIdentityUsedTimestamp(pubKeyHash: String) -> Result<Void, IdentityError> {
getIdentities()
.mapError(to: IdentityError.self)
.flatMap { list in
var list = list
var identity = list[pubKeyHash]
identity?.lastUsed = UInt64(Date().timeIntervalSince1970 * 1000)
list[pubKeyHash] = identity
return saveIdentities(identities: list)
}
}
/// Finds the `BrowserIdentity` with the given `pubKeyHash`and sets its `authorized`
func addBrowserIdentityAuthorization(pubKeyHash: String, authorized: Bool) -> Result<Void, IdentityError> {
getIdentities()
.mapError(to: IdentityError.self)
.flatMap { list in
var list = list
var identity = list[pubKeyHash]
identity?.authorized = authorized
list[pubKeyHash] = identity
return saveIdentities(identities: list)
}
}
/// Prunes entries that were never used and were create more than a cutoff date.
func pruneBrowserIdentities() -> Result<Void, IdentityError> {
let cutOffMinutes: Int = 5
let cutOffDate = Date().addingTimeInterval(-TimeInterval(cutOffMinutes * 60))
let cutOffPoint = UInt64(cutOffDate.timeIntervalSince1970 * 1000)
return getIdentities()
.mapError(to: IdentityError.self)
.flatMap { list in
let newList = list.filter { item in
item.value.lastUsed != 0 || item.value.creation > cutOffPoint
}
guard newList.count != list.count else {
return .success(())
}
return saveIdentities(identities: newList)
}
}
func getDeviceKey() -> Data {
var deviceKey = appSettingsSecureChannel.deviceKey
if deviceKey == nil {
deviceKey = Data.randomData(count: 32)?.hexValue
appSettingsSecureChannel.deviceKey = deviceKey
}
return Data(hex: deviceKey!)
}
private func getIdentities() -> Result<[String: BrowserIdentity], Never> {
guard let string = appSettingsSecureChannel.browserIdentities else {
return .success([:])
}
guard let data = string.data(using: .utf8) else {
return .success([:])
}
guard let decoded = try? JSONDecoder().decode([String: BrowserIdentity].self, from: data) else {
return .success([:])
}
return .success(decoded)
}
}
|
lgpl-3.0
|
19c369930888605d2e366917f6d44918
| 35.51773 | 111 | 0.611187 | 4.979691 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureKYC/Tests/FeatureKYCUITests/_New_KYC/EmailVerification/EmailVerificationReducerTests.swift
|
1
|
18289
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import AnalyticsKitMock
import ComposableArchitecture
@testable import FeatureKYCDomain
@testable import FeatureKYCDomainMock
@testable import FeatureKYCUI
@testable import FeatureKYCUIMock
import Localization
import TestKit
import XCTest
private typealias L10n = LocalizationConstants.NewKYC
// swiftlint:disable:next type_body_length
final class EmailVerificationReducerTests: XCTestCase {
fileprivate struct RecordedInvocations {
var flowCompletionCallback: [FlowResult] = []
}
fileprivate struct StubbedResults {
var canOpenMailApp: Bool = false
}
private var recordedInvocations: RecordedInvocations!
private var stubbedResults: StubbedResults!
private var testPollingQueue: TestSchedulerOf<DispatchQueue>!
private var testStore: TestStore<
EmailVerificationState,
EmailVerificationState,
EmailVerificationAction,
EmailVerificationAction,
EmailVerificationEnvironment
>!
override func setUpWithError() throws {
try super.setUpWithError()
recordedInvocations = RecordedInvocations()
stubbedResults = StubbedResults()
testPollingQueue = DispatchQueue.test
resetTestStore()
}
override func tearDownWithError() throws {
recordedInvocations = nil
stubbedResults = nil
testStore = nil
testPollingQueue = nil
try super.tearDownWithError()
}
// MARK: Root State Manipulation
func test_substates_init() throws {
let emailAddress = "[email protected]"
let state = EmailVerificationState(emailAddress: emailAddress)
XCTAssertEqual(state.verifyEmail.emailAddress, emailAddress)
XCTAssertEqual(state.editEmailAddress.emailAddress, emailAddress)
XCTAssertEqual(state.emailVerificationHelp.emailAddress, emailAddress)
}
func test_flowStep_startsAt_verifyEmail() throws {
let state = EmailVerificationState(emailAddress: "[email protected]")
XCTAssertEqual(state.flowStep, .verifyEmailPrompt)
}
func test_closes_flow_as_abandoned_when_closeButton_tapped() throws {
XCTAssertEqual(recordedInvocations.flowCompletionCallback, [])
testStore.assert(
.send(.closeButtonTapped),
.do {
XCTAssertEqual(self.recordedInvocations.flowCompletionCallback, [.abandoned])
}
)
}
func test_polls_verificationStatus_every_few_seconds_while_on_screen() throws {
// poll currently set to 5 seconds
testStore.assert(
.send(.didAppear),
.do {
// nothing should happen after 1 second
self.testPollingQueue.advance(by: 1)
},
.do {
// poll should happen after 4 more seconds (5 seconds in total)
self.testPollingQueue.advance(by: 4)
},
.receive(.loadVerificationState),
.receive(
.didReceiveEmailVerficationResponse(
.success(
.init(emailAddress: "[email protected]", status: .unverified)
)
)
),
.receive(.presentStep(.verifyEmailPrompt)),
.send(.didDisappear),
.do {
// no more actions should be received after view disappears
self.testPollingQueue.advance(by: 15)
}
)
}
func test_polling_verificationStatus_doesNot_redirectTo_anotherStep_when_editingEmail() throws {
// poll currently set to 5 seconds
testStore.assert(
.send(.didAppear),
.do {
// nothing should happen after 1 second
self.testPollingQueue.advance(by: 1)
},
.send(.presentStep(.editEmailAddress)) {
$0.flowStep = .editEmailAddress
},
.do {
// poll should happen after 4 more seconds (5 seconds in total)
self.testPollingQueue.advance(by: 4)
},
.receive(.loadVerificationState),
.receive(
.didReceiveEmailVerficationResponse(
.success(
.init(emailAddress: "[email protected]", status: .unverified)
)
)
),
.send(.didDisappear),
.do {
// no more actions should be received after view disappears
self.testPollingQueue.advance(by: 15)
}
)
}
func test_loads_verificationStatus_when_app_opened_unverified() throws {
testStore.assert(
.send(.didEnterForeground),
.receive(.presentStep(.loadingVerificationState)) {
$0.flowStep = .loadingVerificationState
},
.receive(.loadVerificationState),
.receive(
.didReceiveEmailVerficationResponse(
.success(
.init(emailAddress: "[email protected]", status: .unverified)
)
)
),
.receive(.presentStep(.verifyEmailPrompt)) {
$0.flowStep = .verifyEmailPrompt
}
)
}
func test_loads_verificationStatus_when_app_opened_verified() throws {
let mockService = testStore.environment.emailVerificationService as? MockEmailVerificationService
mockService?.stubbedResults.checkEmailVerificationStatus = .just(
.init(emailAddress: "[email protected]", status: .verified)
)
testStore.assert(
.send(.didEnterForeground),
.receive(.presentStep(.loadingVerificationState)) {
$0.flowStep = .loadingVerificationState
},
.receive(.loadVerificationState),
.receive(
.didReceiveEmailVerficationResponse(
.success(.init(emailAddress: "[email protected]", status: .verified))
)
),
.receive(.presentStep(.emailVerifiedPrompt)) {
$0.flowStep = .emailVerifiedPrompt
}
)
}
func test_loads_verificationStatus_when_app_opened_error() throws {
let mockService = testStore.environment.emailVerificationService as? MockEmailVerificationService
mockService?.stubbedResults.checkEmailVerificationStatus = .failure(.unknown(MockError.unknown))
testStore.assert(
.send(.didEnterForeground),
.receive(.presentStep(.loadingVerificationState)) {
$0.flowStep = .loadingVerificationState
},
.receive(.loadVerificationState),
.receive(.didReceiveEmailVerficationResponse(.failure(.unknown(MockError.unknown)))) {
$0.emailVerificationFailedAlert = AlertState(
title: TextState(L10n.GenericError.title),
message: TextState(L10n.EmailVerification.couldNotLoadVerificationStatusAlertMessage),
primaryButton: AlertState.Button.default(
TextState(L10n.GenericError.retryButtonTitle),
action: .send(.loadVerificationState)
),
secondaryButton: AlertState.Button.cancel(TextState(L10n.GenericError.cancelButtonTitle))
)
},
.receive(.presentStep(.verificationCheckFailed)) {
$0.flowStep = .verificationCheckFailed
}
)
}
func test_dismisses_verification_status_error() throws {
testStore.assert(
.send(.didReceiveEmailVerficationResponse(.failure(.unknown(MockError.unknown)))) {
$0.emailVerificationFailedAlert = AlertState(
title: TextState(L10n.GenericError.title),
message: TextState(L10n.EmailVerification.couldNotLoadVerificationStatusAlertMessage),
primaryButton: AlertState.Button.default(
TextState(L10n.GenericError.retryButtonTitle),
action: .send(.loadVerificationState)
),
secondaryButton: AlertState.Button.cancel(TextState(L10n.GenericError.cancelButtonTitle))
)
},
.receive(.presentStep(.verificationCheckFailed)) {
$0.flowStep = .verificationCheckFailed
},
.send(.dismissEmailVerificationFailedAlert) {
$0.emailVerificationFailedAlert = nil
},
.receive(.presentStep(.verifyEmailPrompt)) {
$0.flowStep = .verifyEmailPrompt
}
)
}
// MARK: Verify Email State Manipulation
func test_opens_inbox_failed() throws {
testStore.assert(
.send(.verifyEmail(.tapCheckInbox)),
.receive(.verifyEmail(.presentCannotOpenMailAppAlert)) {
$0.verifyEmail.cannotOpenMailAppAlert = AlertState(title: .init("Cannot Open Mail App"))
},
.send(.verifyEmail(.dismissCannotOpenMailAppAlert)) {
$0.verifyEmail.cannotOpenMailAppAlert = nil
}
)
}
func test_opens_inbox_success() throws {
stubbedResults.canOpenMailApp = true
testStore.assert(
.send(.verifyEmail(.tapCheckInbox)),
.receive(.verifyEmail(.dismissCannotOpenMailAppAlert))
)
}
func test_navigates_to_help() throws {
testStore.assert(
.send(.verifyEmail(.tapGetEmailNotReceivedHelp)),
.receive(.presentStep(.emailVerificationHelp)) {
$0.flowStep = .emailVerificationHelp
}
)
}
// MARK: Email Verified State Manipulation
func test_email_verified_continue_calls_flowCompletion_as_completed() throws {
XCTAssertEqual(recordedInvocations.flowCompletionCallback, [])
testStore.assert(
.send(.emailVerified(.acknowledgeEmailVerification)),
.do {
XCTAssertEqual(self.recordedInvocations.flowCompletionCallback, [.completed])
}
)
}
// MARK: Edit Email State Manipulation
func test_edit_email_validates_email_on_appear_validEmail() throws {
XCTAssertTrue(testStore.state.editEmailAddress.isEmailValid)
XCTAssertEqual(testStore.state.flowStep, .verifyEmailPrompt)
XCTAssertFalse(testStore.state.editEmailAddress.savingEmailAddress)
testStore.send(.editEmailAddress(.didAppear))
}
func test_edit_email_validates_email_on_appear_invalidEmail() throws {
resetTestStore(emailAddress: "test_example.com")
XCTAssertFalse(testStore.state.editEmailAddress.isEmailValid)
testStore.send(.editEmailAddress(.didAppear))
}
func test_edit_email_validates_email_on_appear_emptyEmail() throws {
resetTestStore(emailAddress: "")
XCTAssertFalse(testStore.state.editEmailAddress.isEmailValid)
testStore.send(.editEmailAddress(.didAppear))
}
func test_edit_email_updates_and_validates_email_when_changed_to_validEmail() throws {
testStore.assert(
.send(.editEmailAddress(.didChangeEmailAddress("[email protected]"))) {
$0.editEmailAddress.emailAddress = "[email protected]"
$0.editEmailAddress.isEmailValid = true
}
)
}
func test_edit_email_updates_and_validates_email_when_changed_to_invalidEmail() throws {
testStore.assert(
.send(.editEmailAddress(.didChangeEmailAddress("example_test.com"))) {
$0.editEmailAddress.emailAddress = "example_test.com"
$0.editEmailAddress.isEmailValid = false
}
)
}
func test_edit_email_updates_and_validates_email_when_changed_to_emptyEmail() throws {
testStore.assert(
.send(.editEmailAddress(.didChangeEmailAddress(""))) {
$0.editEmailAddress.emailAddress = ""
$0.editEmailAddress.isEmailValid = false
}
)
}
func test_edit_email_save_success() throws {
testStore.send(.editEmailAddress(.didAppear))
testStore.send(.editEmailAddress(.save)) {
$0.editEmailAddress.savingEmailAddress = true
}
testStore.receive(.editEmailAddress(.didReceiveSaveResponse(.success(0)))) {
$0.editEmailAddress.savingEmailAddress = false
}
testStore.receive(.presentStep(.verifyEmailPrompt))
}
func test_edit_email_edit_and_save_success() throws {
testStore.assert(
.send(.editEmailAddress(.didChangeEmailAddress("[email protected]"))) {
$0.editEmailAddress.emailAddress = "[email protected]"
$0.editEmailAddress.isEmailValid = true
},
.send(.editEmailAddress(.save)) {
$0.editEmailAddress.savingEmailAddress = true
},
.receive(.editEmailAddress(.didReceiveSaveResponse(.success(0)))) {
$0.editEmailAddress.savingEmailAddress = false
$0.verifyEmail.emailAddress = "[email protected]"
$0.emailVerificationHelp.emailAddress = "[email protected]"
},
.receive(.presentStep(.verifyEmailPrompt))
)
}
func test_edit_email_attemptingTo_save_invalidEmail_does_nothing() throws {
testStore.assert(
.send(.editEmailAddress(.didChangeEmailAddress("someone_example.com"))) {
$0.editEmailAddress.emailAddress = "someone_example.com"
$0.editEmailAddress.isEmailValid = false
},
.send(.editEmailAddress(.save))
)
}
func test_edit_email_save_failure() throws {
let mockService = testStore.environment.emailVerificationService as? MockEmailVerificationService
mockService?.stubbedResults.updateEmailAddress = .failure(.missingCredentials)
testStore.assert(
.send(.editEmailAddress(.didAppear)),
.send(.editEmailAddress(.save)) {
$0.editEmailAddress.savingEmailAddress = true
},
.receive(.editEmailAddress(.didReceiveSaveResponse(.failure(.missingCredentials)))) {
$0.editEmailAddress.savingEmailAddress = false
$0.editEmailAddress.saveEmailFailureAlert = AlertState(
title: TextState(L10n.GenericError.title),
message: TextState(L10n.EditEmail.couldNotUpdateEmailAlertMessage),
primaryButton: .default(
TextState(L10n.GenericError.retryButtonTitle),
action: .send(.save)
),
secondaryButton: .cancel(TextState(L10n.GenericError.cancelButtonTitle))
)
},
.send(.editEmailAddress(.dismissSaveEmailFailureAlert)) {
$0.editEmailAddress.saveEmailFailureAlert = nil
}
)
}
// MARK: Email Verification Help State Manipulation
func test_help_navigates_to_edit_email() throws {
testStore.assert(
.send(.emailVerificationHelp(.editEmailAddress)),
.receive(.presentStep(.editEmailAddress)) {
$0.flowStep = .editEmailAddress
}
)
}
func test_help_resend_verificationEmail_success() throws {
testStore.assert(
.send(.emailVerificationHelp(.sendVerificationEmail)) {
$0.emailVerificationHelp.sendingVerificationEmail = true
},
.receive(.emailVerificationHelp(.didReceiveEmailSendingResponse(.success(0)))) {
$0.emailVerificationHelp.sendingVerificationEmail = false
},
.receive(.presentStep(.verifyEmailPrompt))
)
}
func test_help_resend_verificationEmail_failure() throws {
let mockService = testStore.environment.emailVerificationService as? MockEmailVerificationService
mockService?.stubbedResults.sendVerificationEmail = .failure(.missingCredentials)
testStore.assert(
.send(.emailVerificationHelp(.sendVerificationEmail)) {
$0.emailVerificationHelp.sendingVerificationEmail = true
},
.receive(.emailVerificationHelp(.didReceiveEmailSendingResponse(.failure(.missingCredentials)))) {
$0.emailVerificationHelp.sendingVerificationEmail = false
$0.emailVerificationHelp.sentFailedAlert = AlertState(
title: TextState(L10n.GenericError.title),
message: TextState(L10n.EmailVerificationHelp.couldNotSendEmailAlertMessage),
primaryButton: .default(
TextState(L10n.GenericError.retryButtonTitle),
action: .send(.sendVerificationEmail)
),
secondaryButton: .cancel(TextState(L10n.GenericError.cancelButtonTitle))
)
},
.send(.emailVerificationHelp(.dismissEmailSendingFailureAlert)) {
$0.emailVerificationHelp.sentFailedAlert = nil
}
)
}
// MARK: - Helpers
private func resetTestStore(emailAddress: String = "[email protected]") {
testStore = TestStore(
initialState: EmailVerificationState(emailAddress: emailAddress),
reducer: emailVerificationReducer,
environment: EmailVerificationEnvironment(
analyticsRecorder: MockAnalyticsRecorder(),
emailVerificationService: MockEmailVerificationService(),
flowCompletionCallback: { [weak self] result in
self?.recordedInvocations.flowCompletionCallback.append(result)
},
openMailApp: { [unowned self] in
Effect(value: self.stubbedResults.canOpenMailApp)
},
mainQueue: .immediate,
pollingQueue: testPollingQueue.eraseToAnyScheduler()
)
)
}
}
|
lgpl-3.0
|
e81171e323125c58eb56e1a07076fcb6
| 39.105263 | 110 | 0.608322 | 5.208772 | false | true | false | false |
xiaolulwr/OpenDrcom-macOS-x86_64
|
OpenDrcom/LoginViewController.swift
|
1
|
7788
|
/**
* Copyright (c) 2017, 小路.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*/
import Cocoa
/// 登录界面
class LoginViewController: NSViewController,NSTextFieldDelegate,LoginDelegate {
var provider:LoginServiceProvider? = nil
/// 保存密码选项
@IBOutlet weak var buttonIsSavedPassword: NSButton!
/// 自动登录选项
@IBOutlet weak var buttonIsAutoLogin: NSButton!
/// 用户名输入框
@IBOutlet weak var textFieldUsername: NSTextField!
/// 密码输入框
@IBOutlet weak var textFieldPassword: NSSecureTextField!
/// 加载进度条
@IBOutlet weak var progress: NSProgressIndicator!
override func viewDidLoad() {
super.viewDidLoad()
// 设置文本框委托对象
self.textFieldUsername.delegate = self
self.textFieldPassword.delegate = self
// 初始化登录服务提供者
provider = LoginServiceProvider.init(loginDelegate: self, logoutDelegate: nil)
// 获得本地存储对象
let defaults = UserDefaults.standard
// 检查保存密码状态
if defaults.bool(forKey: "isSavePassword")==true {
buttonIsSavedPassword.state = NSControl.StateValue.on
textFieldUsername.stringValue = defaults.object(forKey: "savedUser") as! String
textFieldPassword.stringValue = defaults.object(forKey: "savedPassword") as! String
// 在保存密码的前提下才允许自动登录
buttonIsAutoLogin.isEnabled = true
}
// 检查自动登录状态
if defaults.bool(forKey: "isAutoLogin")==true {
buttonIsAutoLogin.state = NSControl.StateValue.on
// 如果不是刚刚从注销返回,则执行自动登录操作
if defaults.bool(forKey: "isLoadFromLogout")==false {
clickLoginButton(self)
}
}
}
/// 点按登录按钮调用的方法
///
/// - Parameter sender: 消息发送者
@IBAction func clickLoginButton(_ sender: Any) {
// 获得用户名和密码字符串
let username = textFieldUsername.stringValue
let password = textFieldPassword.stringValue
// 在登录之前,先使用回调方法通知保存现在输入的用户名和密码
// 因为用户不离开文本框直接点按登录按钮,该文本框不会触发回调
// 所以在这里为了保存的用户名和密码的正确,手动调用了回调方法
self.controlTextDidEndEditing(Notification.init(name: Notification.Name.init(rawValue: "Login")))
// 开始登录操作
self.progress.startAnimation(self)
// 开始登录
provider?.login(user: username, passwd: password)
}
/// 登录成功的回调方法
func didLoginSuccess() {
// 回到主线程继续操作
DispatchQueue.main.sync {
let defaults = UserDefaults.standard
defaults.set(false, forKey: "isLoadFromLogout")
// 加载条动画停止
self.progress.stopAnimation(self)
// 跳转到登录成功页面
self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "logInSuccessSegue"), sender: self)
// 关闭登录窗口
self.view.window?.performClose(self)
}
}
/// Segue跳转前调用的方法
///
/// - Parameters:
/// - segue: Segue对象
/// - sender: 消息发送者
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
// 登录成功跳转Segue
if segue.identifier?.rawValue == "logInSuccessSegue"{
let destWindow = segue.destinationController as! NSWindowController;
let viewController = destWindow.contentViewController as! SuccessInfoViewController
// 向登录成功页面传入账号和密码
viewController.getLoginParameter(account: self.textFieldUsername.stringValue, password: self.textFieldPassword.stringValue)
}
}
/// 登录失败的回调方法
///
/// - Parameter reason: 失败原因
func didLoginFailed(reason:String?) {
if Thread.isMainThread == true {
self.progress.stopAnimation(self)
let alert:NSAlert = NSAlert.init()
alert.addButton(withTitle: "好")
alert.alertStyle = NSAlert.Style.warning
alert.messageText = "出现错误:"
if reason != nil {
alert.messageText.append(" ")
alert.messageText.append(reason!)
}
alert.runModal()
return
}
// 回到主线程继续操作
DispatchQueue.main.sync {
// 加载条动画停止
self.progress.stopAnimation(self)
let alert:NSAlert = NSAlert.init()
alert.addButton(withTitle: "好")
alert.alertStyle = NSAlert.Style.warning
alert.messageText = "出现错误:"
if reason != nil {
alert.messageText.append(" ")
alert.messageText.append(reason!)
}
alert.runModal()
}
}
/// 保存密码按钮状态变化的方法
///
/// - Parameter sender: 消息发送者
@IBAction func savePasswordValueChanged(_ sender: NSButton) {
let defaults = UserDefaults.standard
defaults.set(sender.state, forKey: "isSavePassword")
if sender.state.rawValue == 1 {
defaults.set(textFieldUsername.stringValue, forKey: "savedUser")
defaults.set(textFieldPassword.stringValue, forKey: "savedPassword")
buttonIsAutoLogin.isEnabled = true
} else {
defaults.set("", forKey: "savedUser")
defaults.set("", forKey: "savedPassword")
buttonIsAutoLogin.state = NSControl.StateValue.off
let defaults = UserDefaults.standard
defaults.set(false, forKey: "isAutoLogin")
defaults.set(false, forKey: "isLoadFromLogout")
buttonIsAutoLogin.isEnabled = false
}
}
/// 自动登录按钮状态变化的方法
///
/// - Parameter sender: 消息发送者
@IBAction func autoLoginValueChanged(_ sender: NSButton) {
let defaults = UserDefaults.standard
defaults.set(sender.state, forKey: "isAutoLogin")
if sender.state == NSControl.StateValue.on {
defaults.set(false, forKey: "isLoadFromLogout")
}
}
/// 监听输入内容变化的回调方法
///
/// - Parameter obj: 通知对象
override func controlTextDidEndEditing(_ obj: Notification) {
if buttonIsSavedPassword.state.rawValue == 1 {
let defaults = UserDefaults.standard
defaults.set(textFieldUsername.stringValue, forKey: "savedUser")
defaults.set(textFieldPassword.stringValue, forKey: "savedPassword")
}
}
/// 获得注销状态参数,忽略自动登录参数,实现注销返回后不立即自动登录
func getLogoutParameter() {
let defaults = UserDefaults.standard
defaults.set(true, forKey: "isLoadFromLogout")
}
/// 退出应用
///
/// - Parameter sender: 消息发送者
@IBAction func exitApplication(_ sender: Any) {
self.view.window?.performClose(self)
}
}
|
gpl-3.0
|
55cb7edd703e25966628a5faf2819c09
| 34.927083 | 135 | 0.622644 | 4.413308 | false | false | false | false |
idea4good/GuiLiteSamples
|
Hello3D/BuildAppleWatch/Hello3D WatchKit Extension/InterfaceController.swift
|
1
|
1494
|
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
fileprivate let viewWidth = 240
fileprivate var viewHeight = 320
fileprivate var colorBytes = 4
@IBOutlet weak var image: WKInterfaceImage!
fileprivate var guiLiteImage : GuiLiteImage?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
guiLiteImage = GuiLiteImage(width: viewWidth, height: viewHeight, colorBytes: colorBytes)
Thread.detachNewThreadSelector(#selector(starUI), toTarget: self, with: nil)
sleep(2)// Wait for GuiLite App ready
Timer.scheduledTimer(withTimeInterval: 0.04, repeats: true, block: {_ in self.updateNativeView()})
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func updateNativeView() {
let cgGuiLiteImage = guiLiteImage?.getUiImage()
if(cgGuiLiteImage == nil){
return
}
image.setImage(UIImage(cgImage: cgGuiLiteImage!))
}
@objc func starUI(){
startHello3D(calloc(viewWidth * viewHeight, colorBytes), Int32(viewWidth), Int32(viewHeight), Int32(colorBytes), nil);
}
}
|
apache-2.0
|
9128e96c0242cbf772626e5c9e2e4c2e
| 32.2 | 126 | 0.670683 | 4.773163 | false | false | false | false |
abertelrud/swift-package-manager
|
Sources/SourceControl/RepositoryManager.swift
|
2
|
24724
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import Dispatch
import Foundation
import TSCBasic
import PackageModel
/// Manages a collection of bare repositories.
public class RepositoryManager: Cancellable {
public typealias Delegate = RepositoryManagerDelegate
/// The path under which repositories are stored.
public let path: AbsolutePath
/// The path to the directory where all cached git repositories are stored.
private let cachePath: AbsolutePath?
// used in tests to disable skipping of local packages.
private let cacheLocalPackages: Bool
/// The repository provider.
private let provider: RepositoryProvider
/// The delegate interface.
private let delegate: Delegate?
/// DispatchSemaphore to restrict concurrent operations on manager.
private let concurrencySemaphore: DispatchSemaphore
/// OperationQueue to park pending lookups
private let lookupQueue: OperationQueue
/// The filesystem to operate on.
private let fileSystem: FileSystem
// tracks outstanding lookups for de-duping requests
private var pendingLookups = [RepositorySpecifier: DispatchGroup]()
private var pendingLookupsLock = NSLock()
// tracks outstanding lookups for cancellation
private var outstandingLookups = ThreadSafeKeyValueStore<UUID, (repository: RepositorySpecifier, completion: (Result<RepositoryHandle, Error>) -> Void, queue: DispatchQueue)>()
private var emitNoConnectivityWarning = ThreadSafeBox<Bool>(true)
/// Create a new empty manager.
///
/// - Parameters:
/// - fileSystem: The filesystem to operate on.
/// - path: The path under which to store repositories. This should be a
/// directory in which the content can be completely managed by this
/// instance.
/// - provider: The repository provider.
/// - cachePath: The repository cache location.
/// - cacheLocalPackages: Should cache local packages as well. For testing purposes.
/// - maxConcurrentOperations: Max concurrent lookup operations
/// - initializationWarningHandler: Initialization warnings handler.
/// - delegate: The repository manager delegate.
public init(
fileSystem: FileSystem,
path: AbsolutePath,
provider: RepositoryProvider,
cachePath: AbsolutePath? = .none,
cacheLocalPackages: Bool = false,
maxConcurrentOperations: Int? = .none,
initializationWarningHandler: (String) -> Void,
delegate: Delegate? = .none
) {
self.fileSystem = fileSystem
self.path = path
self.cachePath = cachePath
self.cacheLocalPackages = cacheLocalPackages
self.provider = provider
self.delegate = delegate
// this queue and semaphore is used to limit the amount of concurrent git operations taking place
let maxConcurrentOperations = min(maxConcurrentOperations ?? 3, Concurrency.maxOperations)
self.lookupQueue = OperationQueue()
self.lookupQueue.name = "org.swift.swiftpm.repository-manager"
self.lookupQueue.maxConcurrentOperationCount = maxConcurrentOperations
self.concurrencySemaphore = DispatchSemaphore(value: maxConcurrentOperations)
}
/// Get a handle to a repository.
///
/// This will initiate a clone of the repository automatically, if necessary.
///
/// Note: Recursive lookups are not supported i.e. calling lookup inside
/// completion block of another lookup will block.
///
/// - Parameters:
/// - package: The package identity of the repository to fetch,
/// - repository: The repository to look up.
/// - skipUpdate: If a repository is available, skip updating it.
/// - observabilityScope: The observability scope
/// - delegateQueue: Dispatch queue for delegate events
/// - callbackQueue: Dispatch queue for callbacks
/// - completion: The completion block that should be called after lookup finishes.
public func lookup(
package: PackageIdentity,
repository: RepositorySpecifier,
skipUpdate: Bool,
observabilityScope: ObservabilityScope,
delegateQueue: DispatchQueue,
callbackQueue: DispatchQueue,
completion: @escaping (Result<RepositoryHandle, Error>) -> Void
) {
// records outstanding lookups for cancellation purposes
let lookupKey = UUID()
self.outstandingLookups[lookupKey] = (repository: repository, completion: completion, queue: callbackQueue)
// wrap the callback in the requested queue and cleanup operations
let completion: (Result<RepositoryHandle, Error>) -> Void = { result in
// free concurrency control semaphore
self.concurrencySemaphore.signal()
// remove any pending lookup
self.pendingLookupsLock.lock()
self.pendingLookups[repository]?.leave()
self.pendingLookups[repository] = nil
self.pendingLookupsLock.unlock()
// cancellation support
// if the callback is no longer on the pending lists it has been canceled already
// read + remove from outstanding requests atomically
if let (_, callback, queue) = self.outstandingLookups.removeValue(forKey: lookupKey) {
// call back on the request queue
queue.async { callback(result) }
}
}
// we must not block the calling thread (for concurrency control) so nesting this in a queue
self.lookupQueue.addOperation {
// park the lookup thread based on the max concurrency allowed
self.concurrencySemaphore.wait()
// check if there is a pending lookup
self.pendingLookupsLock.lock()
if let pendingLookup = self.pendingLookups[repository] {
self.pendingLookupsLock.unlock()
// chain onto the pending lookup
return pendingLookup.notify(queue: .sharedConcurrent) {
// at this point the previous lookup should be complete and we can re-lookup
completion(.init(catching: {
try self.lookup(
package: package,
repository: repository,
skipUpdate: skipUpdate,
observabilityScope: observabilityScope,
delegateQueue: delegateQueue
)
}))
}
} else {
// record the pending lookup
assert(self.pendingLookups[repository] == nil)
let group = DispatchGroup()
group.enter()
self.pendingLookups[repository] = group
self.pendingLookupsLock.unlock()
}
completion(.init(catching: {
try self.lookup(
package: package,
repository: repository,
skipUpdate: skipUpdate,
observabilityScope: observabilityScope,
delegateQueue: delegateQueue
)
}))
}
}
// sync version of the lookup,
// this is here because it simplifies reading & maintaining the logical flow
// while the underlying git client is sync
// once we move to an async git client we would need to get rid of this
// sync func and roll the logic into the async version above
private func lookup(
package: PackageIdentity,
repository: RepositorySpecifier,
skipUpdate: Bool,
observabilityScope: ObservabilityScope,
delegateQueue: DispatchQueue
) throws -> RepositoryHandle {
let relativePath = repository.storagePath()
let repositoryPath = self.path.appending(relativePath)
let handle = RepositoryHandle(manager: self, repository: repository, subpath: relativePath)
// check if a repository already exists
// errors when trying to check if a repository already exists are legitimate
// and recoverable, and as such can be ignored
if (try? self.provider.repositoryExists(at: repositoryPath)) ?? false {
// update if necessary and return early
// skip update if not needed
if skipUpdate {
return handle
}
// Update the repository when it is being looked up.
let start = DispatchTime.now()
delegateQueue.async {
self.delegate?.willUpdate(package: package, repository: handle.repository)
}
let repository = try handle.open()
try repository.fetch()
let duration = start.distance(to: .now())
delegateQueue.async {
self.delegate?.didUpdate(package: package, repository: handle.repository, duration: duration)
}
return handle
}
// inform delegate that we are starting to fetch
// calculate if cached (for delegate call) outside queue as it may change while queue is processing
let isCached = self.cachePath.map{ self.fileSystem.exists($0.appending(handle.subpath)) } ?? false
delegateQueue.async {
let details = FetchDetails(fromCache: isCached, updatedCache: false)
self.delegate?.willFetch(package: package, repository: handle.repository, details: details)
}
// perform the fetch
let start = DispatchTime.now()
let fetchResult = Result<FetchDetails, Error>(catching: {
// make sure destination is free.
try? self.fileSystem.removeFileTree(repositoryPath)
// fetch the repo and cache the results
return try self.fetchAndPopulateCache(
package: package,
handle: handle,
repositoryPath: repositoryPath,
observabilityScope: observabilityScope,
delegateQueue: delegateQueue
)
})
// inform delegate fetch is done
let duration = start.distance(to: .now())
delegateQueue.async {
self.delegate?.didFetch(package: package, repository: handle.repository, result: fetchResult, duration: duration)
}
// at this point we can throw, as we already notified the delegate above
_ = try fetchResult.get()
return handle
}
public func cancel(deadline: DispatchTime) throws {
// ask the provider to cancel
try self.provider.cancel(deadline: deadline)
// cancel any outstanding lookups
let outstanding = self.outstandingLookups.clear()
for (_, callback, queue) in outstanding.values {
queue.async {
callback(.failure(CancellationError()))
}
}
}
/// Fetches the repository into the cache. If no `cachePath` is set or an error occurred fall back to fetching the repository without populating the cache.
/// - Parameters:
/// - package: The package identity of the repository to fetch.
/// - handle: The specifier of the repository to fetch.
/// - repositoryPath: The path where the repository should be fetched to.
/// - observabilityScope: The observability scope
/// - delegateQueue: Dispatch queue for delegate events
@discardableResult
private func fetchAndPopulateCache(
package: PackageIdentity,
handle: RepositoryHandle,
repositoryPath: AbsolutePath,
observabilityScope: ObservabilityScope,
delegateQueue: DispatchQueue
) throws -> FetchDetails {
var cacheUsed = false
var cacheUpdated = false
// utility to update progress
func updateFetchProgress(progress: FetchProgress) -> Void {
if let total = progress.totalSteps {
delegateQueue.async {
self.delegate?.fetching(
package: package,
repository: handle.repository,
objectsFetched: progress.step,
totalObjectsToFetch: total
)
}
}
}
// We are expecting handle.repository.url to always be a resolved absolute path.
let shouldCacheLocalPackages = ProcessEnv.vars["SWIFTPM_TESTS_PACKAGECACHE"] == "1" || cacheLocalPackages
if let cachePath = self.cachePath, !(handle.repository.isLocal && !shouldCacheLocalPackages) {
let cachedRepositoryPath = cachePath.appending(handle.repository.storagePath())
do {
try self.initializeCacheIfNeeded(cachePath: cachePath)
try self.fileSystem.withLock(on: cachePath, type: .shared) {
try self.fileSystem.withLock(on: cachedRepositoryPath, type: .exclusive) {
// Fetch the repository into the cache.
if (self.fileSystem.exists(cachedRepositoryPath)) {
let repo = try self.provider.open(repository: handle.repository, at: cachedRepositoryPath)
try repo.fetch(progress: updateFetchProgress(progress:))
cacheUsed = true
} else {
try self.provider.fetch(repository: handle.repository, to: cachedRepositoryPath, progressHandler: updateFetchProgress(progress:))
}
cacheUpdated = true
// extra validation to defend from racy edge cases
if self.fileSystem.exists(repositoryPath) {
throw StringError("\(repositoryPath) already exists unexpectedly")
}
// Copy the repository from the cache into the repository path.
try self.fileSystem.createDirectory(repositoryPath.parentDirectory, recursive: true)
try self.provider.copy(from: cachedRepositoryPath, to: repositoryPath)
}
}
} catch {
// If we are offline and have a valid cached repository, use the cache anyway.
if isOffline(error) && self.provider.isValidDirectory(cachedRepositoryPath) {
// For the first offline use in the lifetime of this repository manager, emit a warning.
if self.emitNoConnectivityWarning.get(default: false) {
self.emitNoConnectivityWarning.put(false)
observabilityScope.emit(warning: "no connectivity, using previously cached repository state")
}
observabilityScope.emit(info: "using previously cached repository state for \(package)")
cacheUsed = true
// Copy the repository from the cache into the repository path.
try self.fileSystem.createDirectory(repositoryPath.parentDirectory, recursive: true)
try self.provider.copy(from: cachedRepositoryPath, to: repositoryPath)
} else {
cacheUsed = false
// Fetch without populating the cache in the case of an error.
observabilityScope.emit(warning: "skipping cache due to an error: \(error)")
// it is possible that we already created the directory from failed attempts, so clear leftover data if present.
try? self.fileSystem.removeFileTree(repositoryPath)
try self.provider.fetch(repository: handle.repository, to: repositoryPath, progressHandler: updateFetchProgress(progress:))
}
}
} else {
// it is possible that we already created the directory from failed attempts, so clear leftover data if present.
try? self.fileSystem.removeFileTree(repositoryPath)
// fetch without populating the cache when no `cachePath` is set.
try self.provider.fetch(repository: handle.repository, to: repositoryPath, progressHandler: updateFetchProgress(progress:))
}
return FetchDetails(fromCache: cacheUsed, updatedCache: cacheUpdated)
}
public func openWorkingCopy(at path: AbsolutePath) throws -> WorkingCheckout {
try self.provider.openWorkingCopy(at: path)
}
/// Open a repository from a handle.
private func open(_ handle: RepositoryHandle) throws -> Repository {
try self.provider.open(
repository: handle.repository,
at: self.path.appending(handle.subpath)
)
}
/// Create a working copy of the repository from a handle.
private func createWorkingCopy(
_ handle: RepositoryHandle,
at destinationPath: AbsolutePath,
editable: Bool
) throws -> WorkingCheckout {
try self.provider.createWorkingCopy(
repository: handle.repository,
sourcePath: self.path.appending(handle.subpath),
at: destinationPath,
editable: editable)
}
/// Removes the repository.
public func remove(repository: RepositorySpecifier) throws {
let relativePath = repository.storagePath()
let repositoryPath = self.path.appending(relativePath)
try self.fileSystem.removeFileTree(repositoryPath)
}
/// Returns true if the directory is valid git location.
public func isValidDirectory(_ directory: AbsolutePath) -> Bool {
self.provider.isValidDirectory(directory)
}
/// Returns true if the git reference name is well formed.
public func isValidRefFormat(_ ref: String) -> Bool {
self.provider.isValidRefFormat(ref)
}
/// Reset the repository manager.
///
/// Note: This also removes the cloned repositories from the disk.
public func reset() throws {
try self.fileSystem.removeFileTree(self.path)
}
/// Sets up the cache directories if they don't already exist.
public func initializeCacheIfNeeded(cachePath: AbsolutePath) throws {
// Create the supplied cache directory.
if !self.fileSystem.exists(cachePath) {
try self.fileSystem.createDirectory(cachePath, recursive: true)
}
}
/// Purges the cached repositories from the cache.
public func purgeCache() throws {
guard let cachePath = self.cachePath else { return }
try self.fileSystem.withLock(on: cachePath, type: .exclusive) {
let cachedRepositories = try self.fileSystem.getDirectoryContents(cachePath)
for repoPath in cachedRepositories {
try self.fileSystem.removeFileTree(cachePath.appending(component: repoPath))
}
}
}
}
extension RepositoryManager {
/// Handle to a managed repository.
public struct RepositoryHandle {
/// The manager this repository is owned by.
private unowned let manager: RepositoryManager
/// The repository specifier.
public let repository: RepositorySpecifier
/// The subpath of the repository within the manager.
///
/// This is intentionally hidden from the clients so that the manager is
/// allowed to move repositories transparently.
fileprivate let subpath: RelativePath
/// Create a handle.
fileprivate init(manager: RepositoryManager, repository: RepositorySpecifier, subpath: RelativePath) {
self.manager = manager
self.repository = repository
self.subpath = subpath
}
/// Open the given repository.
public func open() throws -> Repository {
return try self.manager.open(self)
}
/// Create a working copy at on the local file system.
///
/// - Parameters:
/// - path: The path at which to create the working copy; it is
/// expected to be non-existent when called.
///
/// - editable: The clone is expected to be edited by user.
public func createWorkingCopy(at path: AbsolutePath, editable: Bool) throws -> WorkingCheckout {
return try self.manager.createWorkingCopy(self, at: path, editable: editable)
}
}
}
extension RepositoryManager {
/// Additional information about a fetch
public struct FetchDetails: Equatable {
/// Indicates if the repository was fetched from the cache or from the remote.
public let fromCache: Bool
/// Indicates wether the wether the repository was already present in the cache and updated or if a clean fetch was performed.
public let updatedCache: Bool
}
}
/// Delegate to notify clients about actions being performed by RepositoryManager.
public protocol RepositoryManagerDelegate {
/// Called when a repository is about to be fetched.
func willFetch(package: PackageIdentity, repository: RepositorySpecifier, details: RepositoryManager.FetchDetails)
/// Called every time the progress of a repository fetch operation updates.
func fetching(package: PackageIdentity, repository: RepositorySpecifier, objectsFetched: Int, totalObjectsToFetch: Int)
/// Called when a repository has finished fetching.
func didFetch(package: PackageIdentity, repository: RepositorySpecifier, result: Result<RepositoryManager.FetchDetails, Error>, duration: DispatchTimeInterval)
/// Called when a repository has started updating from its remote.
func willUpdate(package: PackageIdentity, repository: RepositorySpecifier)
/// Called when a repository has finished updating from its remote.
func didUpdate(package: PackageIdentity, repository: RepositorySpecifier, duration: DispatchTimeInterval)
}
extension RepositoryManager.RepositoryHandle: CustomStringConvertible {
public var description: String {
return "<\(type(of: self)) subpath:\(subpath)>"
}
}
extension RepositorySpecifier {
// relative path where the repository should be stored
internal func storagePath() -> RelativePath {
return RelativePath(self.fileSystemIdentifier)
}
/// A unique identifier for this specifier.
///
/// This identifier is suitable for use in a file system path, and
/// unique for each repository.
private var fileSystemIdentifier: String {
// Use first 8 chars of a stable hash.
let suffix = self.location.description .sha256Checksum.prefix(8)
return "\(self.basename)-\(suffix)"
}
}
extension RepositorySpecifier {
fileprivate var isLocal: Bool {
switch self.location {
case .path:
return true
case .url:
return false
}
}
}
#if canImport(SystemConfiguration)
import SystemConfiguration
private struct Reachability {
let reachability: SCNetworkReachability
init?() {
var emptyAddress = sockaddr()
emptyAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
emptyAddress.sa_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &emptyAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
return nil
}
self.reachability = reachability
}
var connectionRequired: Bool {
var flags = SCNetworkReachabilityFlags()
let hasFlags = withUnsafeMutablePointer(to: &flags) {
SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0))
}
guard hasFlags else { return false }
guard flags.contains(.reachable) else {
return true
}
return flags.contains(.connectionRequired) || flags.contains(.transientConnection)
}
}
fileprivate func isOffline(_ error: Swift.Error) -> Bool {
return Reachability()?.connectionRequired == true
}
#else
fileprivate func isOffline(_ error: Swift.Error) -> Bool {
// TODO: Find a better way to determine reachability on non-Darwin platforms.
return "\(error)".contains("Could not resolve host")
}
#endif
|
apache-2.0
|
bd7fd4538fe09187d7103b844f3dc6fb
| 42.073171 | 180 | 0.63493 | 5.532334 | false | false | false | false |
cseduardorangel/Cantina
|
Cantina/Class/ViewController/PurchasesViewController.swift
|
1
|
4308
|
//
// PurchasesViewController.swift
// Cantina
//
// Created by Eduardo Rangel on 8/22/15.
// Copyright © 2015 Concrete Solutions. All rights reserved.
//
import UIKit
import Google
class PurchasesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//////////////////////////////////////////////////////////////////////
// MARK: - Variables
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var debitLabel: UILabel!
var sales: [Sale] = []
var debit = 0.0
//////////////////////////////////////////////////////////////////////
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
CredentialsService.getUser(CredentialStore().get(), completion : { (success, object) -> Void in
SaleService.getAllByCredential(object!, completion : { (objects, error) -> Void in
self.sales = objects as! [Sale]
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "pt_BR")
let totalDebit = self.sales.reduce(0) {$0 + CGFloat($1.product.price)}
self.debitLabel.text = formatter.stringFromNumber(totalDebit)
self.tableView.reloadData()
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//////////////////////////////////////////////////////////////////////
// MARK: - IBActions
@IBAction func logout(sender: AnyObject) {
let alertController = UIAlertController(title: "Logout", message: "Já vai?", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Não", style: .Cancel) { (action) in
}
let OKAction = UIAlertAction(title: "Sim", style: .Default) { (action) in
self.dismissViewControllerAnimated(true, completion: { () -> Void in
GIDSignIn.sharedInstance().signOut()
})
}
alertController.addAction(OKAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true) {
}
}
//////////////////////////////////////////////////////////////////////
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sales.count
}
//////////////////////////////////////////////////////////////////////
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let sale = self.sales[indexPath.row]
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "pt_BR")
if indexPath.row == self.sales.count - 1 {
let invoiceCell: InvoiceCell = tableView.dequeueReusableCellWithIdentifier("InvoiceCell", forIndexPath: indexPath) as! InvoiceCell
invoiceCell.invoiceTotal?.text = self.debitLabel.text
// invoiceCell.invoiceCloseDate?.text =
return invoiceCell
}
let purchaseCell: PurchaseCell = tableView.dequeueReusableCellWithIdentifier("PurchaseCell", forIndexPath: indexPath) as! PurchaseCell
purchaseCell.price?.text = formatter.stringFromNumber(sale.product.price)
purchaseCell.name?.text = sale.product.name
purchaseCell.purchaseTime?.text = NSDate.hourMinute(sale.createdAt!)
purchaseCell.purchaseDate?.text = NSDate.dayMonth(sale.createdAt!)
return purchaseCell
}
//////////////////////////////////////////////////////////////////////
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
|
mit
|
c44dbed7262880d804a13a6aa1623e15
| 31.134328 | 142 | 0.541928 | 5.913462 | false | false | false | false |
uasys/swift
|
validation-test/Reflection/functions.swift
|
11
|
21690
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/functions
// RUN: %target-run %target-swift-reflection-test %t/functions | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
// FIXME: Should not require objc_interop -- please put Objective-C-specific
// testcases in functions_objc.swift
// REQUIRES: objc_interop
// REQUIRES: executable_test
/*
This file pokes at the swift_reflection_infoForInstance() API
of the SwiftRemoteMirror library.
It tests introspection of function closure contexts.
- See also: SwiftReflectionTest.reflect(function:)
*/
import SwiftReflectionTest
@_semantics("optimize.sil.never")
func concrete(x: Int, y: Any) {
reflect(function: {print(x)})
// CHECK: Type reference:
// CHECK-NEXT: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32-NEXT: (closure_context size=16 alignment=4 stride=16
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
// CHECK-64: Type info:
// CHECK-64-NEXT: (closure_context size=24 alignment=8 stride=24
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))
// Here the context is a single boxed value
reflect(function: {print(y)})
// CHECK: Type reference:
// CHECK-NEXT: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32-NEXT: (closure_context size=28 alignment=4 stride=28
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096)))))
// CHECK-64: Type info:
// CHECK-64-NEXT: (closure_context size=48 alignment=8 stride=48
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647)))))
}
concrete(x: 10, y: true)
protocol P {}
extension Int : P {}
class C {
func captureWeakSelf() -> () -> () {
return { [weak self] in
print(self)
}
}
func captureUnownedSelf() -> () -> () {
return { [unowned self] in
print(self)
}
}
}
@_semantics("optimize.sil.never")
func generic<T : P, U, V : C>(x: T, y: U, z: V, i: Int) {
reflect(function: {print(i)})
// CHECK: Type reference:
// CHECK-NEXT: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32-NEXT: (closure_context size=16 alignment=4 stride=16
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
// CHECK-64: Type info:
// CHECK-64-NEXT: (closure_context size=24 alignment=8 stride=24
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))
reflect(function: {print(x); print(y); print(z)})
// CHECK: Type reference:
// CHECK-NEXT: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32-NEXT: (closure_context size=40 alignment=4 stride=40
// CHECK-32-NEXT: (field offset=28
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field offset=32
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field offset=36
// CHECK-32-NEXT: (reference kind=strong refcounting=native)))
// CHECK-64: Type info:
// CHECK-64-NEXT: (closure_context size=72 alignment=8 stride=72
// CHECK-64-NEXT: (field offset=48
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field offset=56
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field offset=64
// CHECK-64-NEXT: (reference kind=strong refcounting=native)))
}
generic(x: 10, y: "", z: C(), i: 101)
class GC<A, B, C> {}
@_semantics("optimize.sil.never")
func genericWithSources<A, B, C>(a: A, b: B, c: C, gc: GC<A, B, C>) {
reflect(function: {print(a); print(b); print(c); print(gc)})
// CHECK: Type reference:
// CHECK-NEXT: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32-NEXT: (closure_context size=28 alignment=4 stride=28
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field offset=16
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field offset=20
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field offset=24
// CHECK-32-NEXT: (reference kind=strong refcounting=native)))
// CHECK-64: Type info:
// CHECK-64-NEXT: (closure_context size=48 alignment=8 stride=48
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field offset=24
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field offset=32
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field offset=40
// CHECK-64-NEXT: (reference kind=strong refcounting=native)))
}
genericWithSources(a: (), b: ((), ()), c: ((), (), ()), gc: GC<(), ((), ()), ((), (), ())>())
class CapturingClass {
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (class functions.CapturingClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=16 alignment=1 stride=16
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (class functions.CapturingClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=12 alignment=1 stride=12
@_semantics("optimize.sil.never")
func arity0Capture1() -> () -> () {
let closure = {
// Captures a single retainable reference.
print(self)
}
reflect(function: closure)
return closure
}
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64: (closure_context size=32 alignment=8 stride=32
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32: (closure_context size=32 alignment=8 stride=32
// CHECK-32-NEXT: (field offset=16
// CHECK-32-NEXT: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=8
// CHECK-32-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
@_semantics("optimize.sil.never")
func arity1Capture1() -> (Int) -> () {
let pair = (2, 333.0)
let closure = { (i: Int) in
print(pair)
}
reflect(function: closure)
return closure
}
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64: (closure_context size=32 alignment=8 stride=32
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (reference kind=strong refcounting=native)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32: (closure_context size=20 alignment=4 stride=20
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (reference kind=strong refcounting=native)))))
@_semantics("optimize.sil.never")
func arity2Capture1() -> (Int, String) -> () {
let pair = (999, C())
let closure = { (i: Int, s: String) in
print(pair)
}
reflect(function: closure)
return closure
}
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64: (closure_context size=24 alignment=8 stride=24
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=2147483646
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (class_existential size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32: (closure_context size=16 alignment=4 stride=16
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (class_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown)))))
@_semantics("optimize.sil.never")
func arity3Capture1() -> (Int, String, AnyObject?) -> () {
let c: AnyObject? = C()
let closure = { (i: Int, s: String, a: AnyObject?) in
print(c)
}
reflect(function: closure)
return closure
}
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64: (closure_context size=40 alignment=8 stride=40
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field offset=24
// CHECK-64-NEXT: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32: (closure_context size=32 alignment=8 stride=32
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field offset=16
// CHECK-32-NEXT: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=8
// CHECK-32-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
@_semantics("optimize.sil.never")
func arity0Capture2() -> () -> () {
let pair = (999, 1010.2)
let closure = {
print(self)
print(pair)
}
reflect(function: closure)
return closure
}
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64: (closure_context size=32 alignment=8 stride=32
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field offset=24
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=2147483646
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32: (closure_context size=20 alignment=4 stride=20
// CHECK-32: (field offset=12
// CHECK-32: (reference kind=strong refcounting=native))
// CHECK-32: (field offset=16
// CHECK-32: (reference kind=strong refcounting=native)))
@_semantics("optimize.sil.never")
func arity1Capture2() -> (Int) -> () {
let x: C? = C()
let closure = { (i: Int) in
print(self)
print(x)
}
reflect(function: closure)
return closure
}
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64: (closure_context size=40 alignment=8 stride=40
// CHECK-64: (field offset=16
// CHECK-64: (reference kind=strong refcounting=native))
// CHECK-64: (field offset=24
// CHECK-64: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64: (field offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64: (field offset=8
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32: (closure_context size=32 alignment=8 stride=32
// CHECK-32: (field offset=12
// CHECK-32: (reference kind=strong refcounting=native))
// CHECK-32: (field offset=16
// CHECK-32: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-32: (field offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32: (field offset=8
// CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
@_semantics("optimize.sil.never")
func arity2Capture2() -> (Int, String) -> () {
let pair = (999, 1010.2)
let closure = { (i: Int, s: String) in
print(self)
print(pair)
}
reflect(function: closure)
return closure
}
// CHECK-64: Reflecting an object.
// CHECK-64: Type reference:
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64: (closure_context size=40 alignment=8 stride=40
// CHECK-64: (field offset=16
// CHECK-64: (reference kind=strong refcounting=native))
// CHECK-64: (field offset=24
// CHECK-64: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64: (field offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64: (field offset=8
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
// CHECK-32: Reflecting an object.
// CHECK-32: Type reference:
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32: (closure_context size=32 alignment=8 stride=32
// CHECK-32: (field offset=12
// CHECK-32: (reference kind=strong refcounting=native))
// CHECK-32: (field offset=16
// CHECK-32: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-32: (field offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32: (field offset=8
// CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))))))
@_semantics("optimize.sil.never")
func arity3Capture2() -> (Int, String, AnyObject?) -> () {
let pair = (999, 1010.2)
let closure = { (i: Int, s: String, a: AnyObject?) in
print(self)
print(pair)
}
reflect(function: closure)
return closure
}
}
let cc = CapturingClass()
_ = cc.arity0Capture1()
_ = cc.arity1Capture1()
_ = cc.arity2Capture1()
_ = cc.arity3Capture1()
_ = cc.arity0Capture2()
_ = cc.arity1Capture2()
_ = cc.arity2Capture2()
_ = cc.arity3Capture2()
reflect(function: C().captureWeakSelf())
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64: (closure_context size=24 alignment=8 stride=24
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (reference kind=weak refcounting=native)))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32: (closure_context size=16 alignment=4 stride=16
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (reference kind=weak refcounting=native)))
reflect(function: C().captureUnownedSelf())
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64: (closure_context size=24 alignment=8 stride=24
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (reference kind=unowned refcounting=native)))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32: (closure_context size=16 alignment=4 stride=16
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (reference kind=unowned refcounting=native)))
doneReflecting()
|
apache-2.0
|
6e67a4dbb42a9b1e4cbd0240264c932c
| 39.315985 | 136 | 0.639096 | 3.305898 | false | false | false | false |
mz2/AmazonS3RequestManager
|
Source/AmazonS3RequestManager/AmazonS3RequestSerializer.swift
|
1
|
10788
|
//
// AmazonS3RequestSerializer.swift
// AmazonS3RequestManager
//
// Created by Anthony Miller on 10/14/15.
// Copyright © 2015 Anthony Miller. All rights reserved.
//
import Foundation
#if os(iOS) || os(watchOS) || os(tvOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
import Alamofire
#if canImport(AmazonS3SignatureHelpers)
import AmazonS3SignatureHelpers
#endif
/**
MARK: - AmazonS3RequestSerializer
`AmazonS3RequestSerializer` serializes `NSURLRequest` objects for requests to the Amazon S3 service
*/
open class AmazonS3RequestSerializer {
// MARK: - Instance Properties
/**
The Amazon S3 Bucket for the client
*/
open var bucket: String?
/**
The Amazon S3 region for the client. `AmazonS3Region.USStandard` by default.
:note: Must not be `nil`.
:see: `AmazonS3Region` for defined regions.
*/
open var region: Region = .USStandard
/**
The Amazon S3 Access Key ID used to generate authorization headers and pre-signed queries
:dicussion: This can be found on the AWS control panel: http://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key
*/
open var accessKey: String
/**
The Amazon S3 Secret used to generate authorization headers and pre-signed queries
:dicussion: This can be found on the AWS control panel: http://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key
*/
open var secret: String
/**
Whether to connect over HTTPS. `true` by default.
*/
open var useSSL: Bool = true
/**
The AWS STS session token. `nil` by default.
*/
open var sessionToken: String?
// MARK: - Initialization
/**
Initalizes an `AmazonS3RequestSerializer` with the given Amazon S3 credentials.
- parameter bucket: The Amazon S3 bucket for the client
- parameter region: The Amazon S3 region for the client
- parameter accessKey: The Amazon S3 access key ID for the client
- parameter secret: The Amazon S3 secret for the client
- returns: An `AmazonS3RequestSerializer` with the given Amazon S3 credentials
*/
public init(accessKey: String, secret: String, region: Region, bucket: String? = nil) {
self.accessKey = accessKey
self.secret = secret
self.region = region
self.bucket = bucket
}
/**
MARK: - Amazon S3 Request Serialization
This method serializes a request for the Amazon S3 service with the given method and path.
:discussion: The `URLRequest`s returned from this method may be used with `Alamofire`, `NSURLSession` or any other network request manager.
- Parameters:
- method: The HTTP method for the request. For more information see `Alamofire.Method`.
- path: The desired path, including the file name and extension, in the Amazon S3 Bucket.
- subresource: The subresource to be added to the request's query. A subresource can be used to access
options or properties of a resource.
- acl: The optional access control list to set the acl headers for the request. For more
information see `ACL`.
- metaData: An optional dictionary of meta data that should be assigned to the object to be uploaded.
- storageClass: The optional storage class to use for the object to upload. If none is specified,
standard is used. For more information see `StorageClass`.
- customParameters: An optional dictionary of custom parameters to be added to the url's query string.
- returns: A `URLRequest`, serialized for use with the Amazon S3 service.
*/
open func amazonURLRequest(method: HTTPMethod,
path: String? = nil,
subresource: String? = nil,
acl: ACL? = nil,
metaData:[String : String]? = nil,
storageClass: StorageClass = .standard,
customParameters: [String : String]? = nil,
customHeaders: [String : String]? = nil) -> URLRequest {
let url = self.url(withPath: path, subresource: subresource, customParameters: customParameters)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
setContentType(on: &urlRequest)
acl?.setACLHeaders(on: &urlRequest)
setStorageClassHeaders(storageClass, on: &urlRequest)
setMetaDataHeaders(metaData, on: &urlRequest)
setCustomHeaders(customHeaders, on: &urlRequest)
setAuthorizationHeaders(on: &urlRequest)
return urlRequest as URLRequest
}
/// This method returns the `URL` for the given path.
///
/// - Note: This method only returns an unsigned `URL`. If the object at the generated `URL` requires authentication to access, the `amazonURLRequest(method:, path:)` function above should be used to create a signed `URLRequest`.
///
/// - Parameters:
/// - path: The desired path, including the file name and extension, in the Amazon S3 Bucket.
/// - subresource: The subresource to be added to the url's query. A subresource can be used to access
/// options or properties of a resource.
/// - customParameters: An optional dictionary of custom parameters to be added to the url's query string.
///
/// - Returns: A `URL` to access the given path on the Amazon S3 service.
open func url(withPath path: String?, subresource: String? = nil, customParameters:[String : String]? = nil) -> URL {
var url = endpointURL
if let path = path {
url = url.appendingPathComponent(path)
}
if let subresource = subresource {
url = url.URLByAppendingS3Subresource(subresource)
}
if let customParameters = customParameters {
for (key, value) in customParameters {
url = url.URLByAppendingRequestParameter(key, value: value)
}
}
return url
}
/**
A readonly endpoint URL created for the specified bucket, region, and SSL use preference. `AmazonS3RequestManager` uses this as the baseURL for all requests.
*/
open var endpointURL: URL {
var URLString = ""
let scheme = self.useSSL ? "https" : "http"
if bucket != nil {
URLString = "\(scheme)://\(region.endpoint)/\(bucket!)"
} else {
URLString = "\(scheme)://\(region.endpoint)"
}
return URL(string: URLString)!
}
fileprivate func setContentType(on request: inout URLRequest) {
let contentTypeString = MIMEType(for: request as URLRequest) ?? "application/octet-stream"
request.setValue(contentTypeString, forHTTPHeaderField: "Content-Type")
}
fileprivate func MIMEType(for request: URLRequest) -> String? {
if let fileExtension = request.url?.pathExtension , !fileExtension.isEmpty,
let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil),
let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTIRef.takeUnretainedValue(), kUTTagClassMIMEType) {
UTIRef.release()
let MIMEType = MIMETypeRef.takeUnretainedValue()
MIMETypeRef.release()
return MIMEType as String
}
return nil
}
fileprivate func setAuthorizationHeaders(on request: inout URLRequest) {
request.cachePolicy = .reloadIgnoringLocalCacheData
if sessionToken != nil {
request.setValue(sessionToken!, forHTTPHeaderField: "x-amz-security-token")
}
let timestamp = currentTimeStamp()
let requestSignature = try! signature(forRequest: request, timestamp: timestamp, secret: secret)
request.setValue(timestamp, forHTTPHeaderField: "Date")
request.setValue("AWS \(accessKey):\(requestSignature)", forHTTPHeaderField: "Authorization")
}
fileprivate func setStorageClassHeaders(_ storageClass: StorageClass, on request: inout URLRequest) {
request.setValue(storageClass.rawValue, forHTTPHeaderField: "x-amz-storage-class")
}
fileprivate func setMetaDataHeaders(_ metaData:[String : String]?, on request: inout URLRequest) {
guard let metaData = metaData else { return }
var metadataHeaders:[String:String] = [:]
for (key, value) in metaData {
metadataHeaders["x-amz-meta-" + key] = value
}
setCustomHeaders(metadataHeaders, on: &request)
}
fileprivate func setCustomHeaders(_ headerFields:[String : String]?, on request: inout URLRequest) {
guard let headerFields = headerFields else { return }
for (key, value) in headerFields {
request.setValue(value, forHTTPHeaderField: key)
}
}
fileprivate func currentTimeStamp() -> String {
return requestDateFormatter.string(from: Date())
}
fileprivate lazy var requestDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "GMT")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter
}()
}
private extension URL {
func URLByAppendingS3Subresource(_ subresource: String) -> URL {
if !subresource.isEmpty {
let URLString = self.absoluteString + "?\(subresource)"
return URL(string: URLString)!
}
return self
}
func URLByAppendingRequestParameter(_ key: String, value: String) -> URL {
if key.isEmpty || value.isEmpty {
return self
}
guard let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else {
return self
}
var URLString = self.absoluteString
URLString = URLString + (URLString.range(of: "?") == nil ? "?" : "&") + key + "=" + encodedValue
return URL(string: URLString)!
}
}
|
mit
|
71908d1ba4f3de5070aa85d5a914de16
| 37.116608 | 233 | 0.616761 | 5.117173 | false | false | false | false |
SanctionCo/pilot-ios
|
pilot/ValidationError.swift
|
1
|
1124
|
//
// ValidationError.swift
// pilot
//
// Created by Nick Eckert on 12/12/17.
// Copyright © 2017 sanction. All rights reserved.
//
import Foundation
struct ValidationError {
var errorCode: Int!
var errorString: String!
init(code: Int, message: String) {
self.errorCode = code
self.errorString = message
}
struct ErrorCode {
static let errorCodeEmptyText = 0
static let errorInvalidEmail = 1
static let errorInvalidPassword = 2
static let errorCodeinvalidMobilNumber = 3
static let errorCodeMaxLengthExceeded = 4
static let errorCodeMissMatchPasswords = 5
}
struct ErrorMessage {
static let messageEmptyEmail = "Email field cannot be empty"
static let messageEmptyPassword = "Password field cannot be empty"
static let messageInvalidEmail = "Email is invalid"
static let messageInvalidPassword = "Password is invalid"
static let messageMaxLengthExceeded = "Maximum length has been exceeded"
static let messageInvalidMobileNumber = "Invalid mobile number"
static let messageMissMatchPasswords = "The provided passwords do not match"
}
}
|
mit
|
048268e78d8bd22e32de1d90b68f8018
| 27.794872 | 80 | 0.73553 | 4.528226 | false | false | false | false |
venticake/RetricaImglyKit-iOS
|
RetricaImglyKit/Classes/Frontend/Extensions/AVCaptureVideoOrientationExtension.swift
|
1
|
1196
|
// This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import AVFoundation
@available(iOS 8, *)
extension AVCaptureVideoOrientation {
func toTransform(mirrored: Bool = false) -> CGAffineTransform {
let result: CGAffineTransform
switch self {
case .Portrait:
result = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
case .PortraitUpsideDown:
result = CGAffineTransformMakeRotation(CGFloat(3 * M_PI_2))
case .LandscapeRight:
result = mirrored ? CGAffineTransformMakeRotation(CGFloat(M_PI)) : CGAffineTransformIdentity
case .LandscapeLeft:
result = mirrored ? CGAffineTransformIdentity : CGAffineTransformMakeRotation(CGFloat(M_PI))
}
return result
}
}
|
mit
|
eb976bae013267f79aaf428be42135ce
| 38.866667 | 104 | 0.708194 | 5.004184 | false | false | false | false |
1yvT0s/XWebView
|
XWebViewTests/XWVInvocationTest.swift
|
1
|
4838
|
/*
Copyright 2015 XWebView
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 XCTest
import XWebView
class InvocationTarget: NSObject {
@objc class ObjectForLeakTest {
let expectation: XCTestExpectation
init(expectation: XCTestExpectation) {
self.expectation = expectation
}
deinit {
expectation.fulfill()
}
}
var integer: Int = 123
func dummy() {}
func echo(bool b: Bool) -> Bool { return b }
func echo(int i: Int) -> Int { return i }
func echo(int8 i8: Int8) -> Int8 { return i8 }
func echo(int16 i16: Int16) -> Int16 { return i16 }
func echo(int32 i32: Int32) -> Int32 { return i32 }
func echo(int64 i64: Int64) -> Int64 { return i64 }
func echo(uint u: UInt) -> UInt { return u }
func echo(uint8 u8: UInt8) -> UInt8 { return u8 }
func echo(uint16 u16: UInt16) -> UInt16 { return u16 }
func echo(uint32 u32: UInt32) -> UInt32 { return u32 }
func echo(uint64 u64: UInt64) -> UInt64 { return u64 }
func echo(float f: Float) -> Float { return f }
func echo(double d: Double) -> Double { return d }
func echo(unicode u: UnicodeScalar) -> UnicodeScalar { return u }
func echo(string s: String) -> String { return s }
func echo(selector s: Selector) -> Selector { return s }
func echo(`class` c: AnyClass) -> AnyClass { return c }
func add(a: Int, _ b: Int) -> Int { return a + b }
func concat(a: String, _ b: String) -> String { return a + b }
func convert(num: NSNumber) -> Int { return num.integerValue }
func leak(expectation: XCTestExpectation) -> AnyObject {
return ObjectForLeakTest(expectation: expectation)
}
}
class InvocationTests : XCTestCase {
var target: InvocationTarget!
var inv: XWVInvocation!
override func setUp() {
target = InvocationTarget()
inv = XWVInvocation(target: target)
}
override func tearDown() {
target = nil
inv = nil
}
func testMethods() {
XCTAssertTrue(inv[Selector("dummy")]() is Void)
XCTAssertTrue(inv[Selector("echoWithBool:")](Bool(true)) as? Bool == true)
XCTAssertTrue(inv[Selector("echoWithInt:")](Int(-11)) as? Int64 == -11)
XCTAssertTrue(inv[Selector("echoWithInt8:")](Int8(-22)) as? Int8 == -22)
XCTAssertTrue(inv[Selector("echoWithInt16:")](Int16(-33)) as? Int16 == -33)
XCTAssertTrue(inv[Selector("echoWithInt32:")](Int32(-44)) as? Int32 == -44)
XCTAssertTrue(inv[Selector("echoWithInt64:")](Int64(-55)) as? Int64 == -55)
XCTAssertTrue(inv[Selector("echoWithUint:")](UInt(11)) as? UInt64 == 11)
XCTAssertTrue(inv[Selector("echoWithUint8:")](UInt8(22)) as? UInt8 == 22)
XCTAssertTrue(inv[Selector("echoWithUint16:")](UInt16(33)) as? UInt16 == 33)
XCTAssertTrue(inv[Selector("echoWithUint32:")](UInt32(44)) as? UInt32 == 44)
XCTAssertTrue(inv[Selector("echoWithUint64:")](UInt64(55)) as? UInt64 == 55)
XCTAssertTrue(inv[Selector("echoWithFloat:")](Float(12.34)) as? Float == 12.34)
XCTAssertTrue(inv[Selector("echoWithDouble:")](Double(-56.78)) as? Double == -56.78)
XCTAssertTrue(inv[Selector("echoWithUnicode:")](UnicodeScalar(78)) as? Int32 == 78)
XCTAssertTrue(inv[Selector("echoWithString:")]("abc") as? String == "abc")
let selector = Selector("echoWithSelector:")
XCTAssertTrue(inv[selector](selector) as? Selector == selector)
let cls = self.dynamicType
XCTAssertTrue(inv[Selector("echoWithClass:")](cls) as? AnyClass === cls)
XCTAssertTrue(inv[Selector("convert:")](UInt8(12)) as? Int64 == 12)
XCTAssertTrue(inv[Selector("add::")](2, 3) as? Int64 == 5)
XCTAssertTrue(inv[Selector("concat::")]("ab", "cd") as? String == "abcd")
}
func testProperty() {
XCTAssertTrue(inv["integer"] as? Int64 == 123)
inv["integer"] = 321
XCTAssertTrue(inv["integer"] as? Int64 == 321)
}
func testLeak() {
autoreleasepool {
let expectation = expectationWithDescription("leak")
let obj = inv.call(Selector("leak:"), withArguments: expectation) as! InvocationTarget.ObjectForLeakTest
XCTAssertEqual(expectation, obj.expectation)
}
waitForExpectationsWithTimeout(2, handler: nil)
}
}
|
apache-2.0
|
139b51d50ffb31fc94bbabfc88fee2de
| 41.438596 | 116 | 0.642001 | 3.889068 | false | true | false | false |
lukaszwas/mcommerce-api
|
Sources/App/Controllers/AuthController.swift
|
1
|
1224
|
import Vapor
import HTTP
import Foundation
// /auth
final class AuthController {
// POST /login
// Login
func login(req: Request) throws -> ResponseRepresentable {
let credentials = try req.credentials()
guard let user = try User.makeQuery()
.filter(User.emailKey, .equals, credentials.email)
.filter(User.passwordKey, .equals, credentials.password)
.first()
else { throw Abort.badRequest }
let token = Token(token: NSUUID().uuidString, userId: user.id!)
try token.save()
return token
}
// POST /logout
// Logout
func logout(req: Request) throws -> ResponseRepresentable {
let token = req.auth.header?.bearer?.string
let tokenRow = try Token.makeQuery()
.filter(Token.tokenKey, .equals, token)
.first()
try tokenRow?.delete()
return ""
}
}
// Deserialize JSON
extension Request {
func credentials() throws -> Credentials {
guard let json = json else { throw Abort.badRequest }
return try Credentials(json: json)
}
}
extension AuthController: EmptyInitializable { }
|
mit
|
75b2006955a2ae164cb76ba243bcb9b8
| 24.5 | 71 | 0.589869 | 4.762646 | false | false | false | false |
takebayashi/SwallowIO
|
Sources/FileReader.swift
|
1
|
949
|
#if os(OSX) || os(tvOS) || os(watchOS) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
import C7
public class FileReader: Reader {
public typealias Entry = C7.Byte
let fileDescriptor: FileDescriptor
public init(fileDescriptor: FileDescriptor) {
self.fileDescriptor = fileDescriptor
}
public func read() throws -> Entry? {
return try read(maxLength: 1).first
}
public func read(maxLength: Int) throws -> [Entry] {
let buffer = UnsafeMutablePointer<Entry>.allocate(capacity: maxLength)
memset(buffer, 0, maxLength)
let size = recv(fileDescriptor.rawDescriptor, buffer, maxLength, 0)
if size < 0 {
throw ReaderError.GenericError(error: errno)
}
var bytes = [Entry]()
for i in 0..<size {
bytes.append(buffer[i])
}
buffer.deallocate(capacity: maxLength)
return bytes
}
}
|
mit
|
3d06aa26bf06c80d9b956f2591c4af69
| 23.973684 | 78 | 0.617492 | 4.294118 | false | false | false | false |
a2/ParksAndRecreation
|
Localize.playground/Sources/Localize.swift
|
1
|
1368
|
import Foundation
private typealias LocalizationSegment = (String, [NSString])
private func +(lhs: LocalizationSegment, rhs: LocalizationSegment) -> LocalizationSegment {
return (lhs.0 + rhs.0, lhs.1 + rhs.1)
}
private func +(lhs: LocalizationSegment, rhs: LocalizableText) -> LocalizationSegment {
return lhs + rhs.localizationSegments
}
private extension LocalizableText {
private var localizationSegments: LocalizationSegment {
switch self {
case .Tree(let segments):
return segments.reduce(("", []), combine: +)
case .Segment(let element):
return (element, [])
case .Expression(let value):
return ("%@", [ value ])
}
}
}
public func localize(text: LocalizableText, tableName: String? = nil, bundle: NSBundle = NSBundle.mainBundle(), value: String = "", comment: String) -> String {
let (key, strings) = text.localizationSegments
let format = bundle.localizedStringForKey(key, value: value, table: tableName)
guard !strings.isEmpty else { return format }
let args = strings.map {
Unmanaged.passRetained($0).toOpaque()
} as [CVarArgType]
let formatted = String(format: format, arguments: args)
for ptr in args {
Unmanaged<NSString>.fromOpaque(ptr as! COpaquePointer).release()
}
return formatted
}
|
mit
|
0627340f58837fbd6d552f7767ccc67a
| 32.365854 | 160 | 0.658626 | 4.5 | false | false | false | false |
koher/EasyImagy
|
Tests/EasyImagyTests/UIKitTests.swift
|
1
|
5508
|
#if canImport(UIKit)
import XCTest
import EasyImagy
import CoreGraphics
import UIKit
class UIKitTests: XCTestCase {
func testInitWithUIImage() {
do {
let uiImage = UIImage(data: try! Data(contentsOf: URL(fileURLWithPath: (#file as NSString).deletingLastPathComponent).appendingPathComponent("Test2x2.png")))!
let image = Image<RGBA<UInt8>>(uiImage: uiImage)
XCTAssertEqual(image.width, 2)
XCTAssertEqual(image.height, 2)
XCTAssertEqual(image[0, 0].red, 255)
XCTAssertEqual(image[0, 0].green, 0)
XCTAssertEqual(image[0, 0].blue, 0)
XCTAssertEqual(image[0, 0].alpha, 64)
XCTAssertEqual(image[1, 0].red, 0)
XCTAssertEqual(image[1, 0].green, 255)
XCTAssertEqual(image[1, 0].blue, 0)
XCTAssertEqual(image[1, 0].alpha, 127)
XCTAssertEqual(image[0, 1].red, 0)
XCTAssertEqual(image[0, 1].green, 0)
XCTAssertEqual(image[0, 1].blue, 255)
XCTAssertEqual(image[0, 1].alpha, 191)
XCTAssertEqual(image[1, 1].red, 255)
XCTAssertEqual(image[1, 1].green, 255)
XCTAssertEqual(image[1, 1].blue, 0)
XCTAssertEqual(image[1, 1].alpha, 255)
}
do {
let uiImage = UIImage(data: try! Data(contentsOf: URL(fileURLWithPath: (#file as NSString).deletingLastPathComponent).appendingPathComponent("Test2x2.png")))!
let image = Image<PremultipliedRGBA<UInt8>>(uiImage: uiImage)
XCTAssertEqual(image.width, 2)
XCTAssertEqual(image.height, 2)
XCTAssertEqual(image[0, 0].red, 64)
XCTAssertEqual(image[0, 0].green, 0)
XCTAssertEqual(image[0, 0].blue, 0)
XCTAssertEqual(image[0, 0].alpha, 64)
XCTAssertEqual(image[1, 0].red, 0)
XCTAssertEqual(image[1, 0].green, 127)
XCTAssertEqual(image[1, 0].blue, 0)
XCTAssertEqual(image[1, 0].alpha, 127)
XCTAssertEqual(image[0, 1].red, 0)
XCTAssertEqual(image[0, 1].green, 0)
XCTAssertEqual(image[0, 1].blue, 191)
XCTAssertEqual(image[0, 1].alpha, 191)
XCTAssertEqual(image[1, 1].red, 255)
XCTAssertEqual(image[1, 1].green, 255)
XCTAssertEqual(image[1, 1].blue, 0)
XCTAssertEqual(image[1, 1].alpha, 255)
}
do { // With `UIImage` from `CGImage`
let dataProvider = CGDataProvider.init(data: try! Data(contentsOf: URL(fileURLWithPath: (#file as NSString).deletingLastPathComponent).appendingPathComponent("Test2x2.png")) as CFData)!
let cgImage = CGImage(pngDataProviderSource: dataProvider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)!
let uiImage = UIImage(cgImage: cgImage)
let image = Image<RGBA<UInt8>>(uiImage: uiImage)
XCTAssertEqual(image.width, 2)
XCTAssertEqual(image.height, 2)
XCTAssertEqual(255, image[0, 0].red)
XCTAssertEqual( 0, image[0, 0].green)
XCTAssertEqual( 0, image[0, 0].blue)
XCTAssertEqual( 64, image[0, 0].alpha)
XCTAssertEqual( 0, image[1, 0].red)
XCTAssertEqual(255, image[1, 0].green)
XCTAssertEqual( 0, image[1, 0].blue)
XCTAssertEqual(127, image[1, 0].alpha)
XCTAssertEqual( 0, image[0, 1].red)
XCTAssertEqual( 0, image[0, 1].green)
XCTAssertEqual(255, image[0, 1].blue)
XCTAssertEqual(191, image[0, 1].alpha)
XCTAssertEqual(255, image[1, 1].red)
XCTAssertEqual(255, image[1, 1].green)
XCTAssertEqual( 0, image[1, 1].blue)
XCTAssertEqual(255, image[1, 1].alpha)
}
#if os(iOS) || os(tvOS)
do { // With `UIImage` from `CIImage`
let ciImage = CIImage(color: CIColor.red).cropped(to: CGRect(x: 0, y: 0, width: 1, height: 1))
let uiImage = UIImage(ciImage: ciImage)
let image = Image<RGBA<UInt8>>(uiImage: uiImage)
XCTAssertEqual(image.width, 1)
XCTAssertEqual(image.height, 1)
XCTAssertEqual(255, image[0, 0].red)
XCTAssertEqual( 0, image[0, 0].green)
XCTAssertEqual( 0, image[0, 0].blue)
XCTAssertEqual(255, image[0, 0].alpha)
}
#endif
do { // With `UIImage` whose `cgImage` and `ciImage` are `nil`
let uiImage = UIImage()
let image = Image<RGBA<UInt8>>(uiImage: uiImage)
XCTAssertEqual(image.width, 0)
XCTAssertEqual(image.height, 0)
}
}
}
#endif
|
mit
|
9297694fd12578e9e27ac13b244e1d3b
| 45.285714 | 201 | 0.499455 | 4.652027 | false | true | false | false |
AcroMace/receptionkit
|
ReceptionKit/View Controllers/Visitor/VisitorSearchViewController.swift
|
1
|
4091
|
//
// VisitorSearchViewController.swift
// ReceptionKit
//
// Created by Andy Cho on 2015-04-23.
// Copyright (c) 2015 Andy Cho. All rights reserved.
//
import UIKit
struct VisitorSearchViewModel {
var visitorName: String?
var searchResults = [Contact]()
init(visitorName: String?) {
self.visitorName = visitorName
}
}
class VisitorSearchViewController: ReturnToHomeViewController, UITextFieldDelegate {
private var viewModel: VisitorSearchViewModel?
@IBOutlet weak var lookingForLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
static let lookingForLabelAccessibilityLabel = "Looking for label"
static let nameTextFieldAccessibilityLabel = "Name text field"
func configure(_ viewModel: VisitorSearchViewModel) {
self.viewModel = viewModel
}
override func viewDidLoad() {
super.viewDidLoad()
lookingForLabel.text = Text.lookingFor.get()
lookingForLabel.accessibilityLabel = VisitorSearchViewController.lookingForLabelAccessibilityLabel
nameTextField.delegate = self
nameTextField.borderStyle = UITextBorderStyle.roundedRect
nameTextField.placeholder = Text.wizardOfOz.get()
nameTextField.accessibilityLabel = VisitorSearchViewController.nameTextFieldAccessibilityLabel
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
nameTextField.becomeFirstResponder()
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let nameText = nameTextField.text else {
return false
}
Contact.search(nameText, completion: receiveSearchResults)
return false
}
func receiveSearchResults(contacts: [Contact]) {
DispatchQueue.main.async { [weak self] in
guard let `self` = self else { return }
self.viewModel?.searchResults = contacts
guard let numberOfSearchResults = self.viewModel?.searchResults.count else {
return
}
// Check if the person the visitor is searching for exists
if numberOfSearchResults > 0 {
self.performSegue(withIdentifier: "VisitorNameSearchSegue", sender: self)
} else {
self.performSegue(withIdentifier: "VisitorNameInvalidSearchSegue", sender: self)
}
}
}
// MARK: - Navigation
// Post a message if the person the visitor is looking for does not exist
// Otherwise show the result of the search
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let visitorSearchResultsTableViewController = segue.destination as? VisitorSearchResultsTableViewController {
// There is a result
let searchResultsViewModel = VisitorSearchResultsViewModel(
visitorName: viewModel?.visitorName,
searchQuery: nameTextField.text,
searchResults: viewModel?.searchResults)
visitorSearchResultsTableViewController.configure(searchResultsViewModel)
} else if let waitingViewController = segue.destination as? WaitingViewController {
// Don't do anything if the visitor hasn't specified who they are looking for
guard let lookingForName = nameTextField.text else { return }
// Configure the view model
let waitingViewModel = WaitingViewModel(shouldAskToWait: true)
waitingViewController.configure(waitingViewModel)
// The visitor's name is unknown
guard let visitorName = viewModel?.visitorName, !visitorName.isEmpty else {
messageSender.send(message: .unknownVisitorKnownVisitee(visiteeName: lookingForName))
doorbell.play()
return
}
// The visitor's name is known
messageSender.send(message: .knownVisitorKnownVisitee(visitorName: visitorName, visiteeName: lookingForName))
doorbell.play()
}
}
}
|
mit
|
fbb3161d5464b43bc9cf20d08d52191a
| 35.526786 | 121 | 0.675141 | 5.461949 | false | false | false | false |
lucasharding/antenna
|
tvOS/Controllers/GuideCollectionViewController.swift
|
1
|
11549
|
//
// GuideCollectionViewController.swift
// ustvnow-tvos
//
// Created by Lucas Harding on 2015-09-11.
// Copyright © 2015 Lucas Harding. All rights reserved.
//
import UIKit
import Alamofire
class GuideCollectionViewController: UIViewController, UICollectionViewDataSource, GuideCollectionViewDelegate {
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var activityIndicator: UIActivityIndicatorView!
var guide : TVGuide?
var focusedTime: Date?
var focusedIndexPath: IndexPath = IndexPath(item: 0, section: 0)
var timer: Timer? { didSet { oldValue?.invalidate() } }
//MARK: View
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.register(GuideChannelCollectionViewHeader.self, forSupplementaryViewOfKind: "ChannelHeader", withReuseIdentifier: "ChannelHeader")
self.collectionView.register(GuideChannelCollectionViewBackground.self, forSupplementaryViewOfKind: "ChannelBackground", withReuseIdentifier: "ChannelBackground")
self.collectionView.register(GuideTimeCollectionViewHeader.self, forSupplementaryViewOfKind: "TimeHeader", withReuseIdentifier: "TimeHeader")
self.collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: "TimeIndicator", withReuseIdentifier: "TimeIndicator")
NotificationCenter.default.addObserver(self, selector: #selector(GuideCollectionViewController.didRefreshGuide(_:)), name: NSNotification.Name(rawValue: TVService.didRefreshGuideNotification), object: nil)
self.didRefreshGuide(nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(GuideCollectionViewController.timerFire), userInfo: nil, repeats: true)
self.timer?.fire()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.timer = nil
}
func timerFire() {
self.collectionView.reloadData()
}
//MARK: Notifications
func didRefreshGuide(_ n: Notification?) {
if n != nil {
self.activityIndicator.stopAnimating()
}
//Find previous focused channel and time
var previousChannel: TVChannel?
if (self.guide?.channels.count ?? 0) > self.focusedIndexPath.section {
previousChannel = self.guide?.channels[self.focusedIndexPath.section]
}
//Update guide var
self.guide = TVService.sharedInstance.guide
self.guide?.channelsFilter = {
return TVPreferences.sharedInstance.channelsFilterForGuide
}
//Update focused time if guide has shifted startdate
if let startDate = self.guide?.startDate.addingTimeInterval(15 * 60) {
self.focusedTime = (self.focusedTime as NSDate?)?.laterDate(startDate as Date)
}
//Try and focus new cell based on old focus
if (previousChannel != nil) {
let section = self.guide?.channels.index(of: previousChannel!)
let item = self.focusedTime == nil ? 0 : self.guide?.programsForChannel(previousChannel!)?.index {
return $0.containsDate(self.focusedTime!)
}
self.focusedIndexPath = IndexPath(item: item ?? 0, section: section ?? 0)
}
else {
self.focusedIndexPath = IndexPath(item: 0, section: 0)
}
self.collectionView.reloadData()
self.setNeedsFocusUpdate()
}
//MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.guide?.channels.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let channel = self.guide?.channels[section] else { return 0 }
return self.guide?.programsForChannel(channel)?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GuideProgramCollectionViewCell", for: indexPath) as! GuideProgramCollectionViewCell
if let (_, program) = self.channelAndProgramForIndexPath(indexPath) {
cell.titleLabel.text = program.title
cell.subtitleLabel.text = program.episodeTitle
cell.recordingBadge.isHidden = !program.isDVRScheduled
cell.isAiring = program.isAiring
}
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kind, for: indexPath)
if kind == "ChannelHeader" {
let header = view as! GuideChannelCollectionViewHeader
if let channel = self.guide?.channels[indexPath.section] {
header.imageView?.image = UIImage(named: channel.guideImageString)
}
}
else if kind == "TimeHeader" {
let header = view as! GuideTimeCollectionViewHeader
if let date = self.guide?.startDate.addingTimeInterval(Double(1800 * indexPath.item)) {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.short
header.titleLabel?.text = ((Calendar.current as NSCalendar).component(.minute, from: date as Date) == 0 || indexPath.item == 0) ? dateFormatter.string(from: date as Date) : ""
}
else {
header.titleLabel?.text = ""
}
}
else if kind == "TimeIndicator" {
view.backgroundColor = UIColor(white: 1.0, alpha: 0.1)
}
return view
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let channel = self.guide?.channels[indexPath.section]
let program = self.programForIndexPath(indexPath)
if program?.isAiring == true && channel != nil {
performSegue(withIdentifier: "PlayChannel", sender: channel)
}
else {
performSegue(withIdentifier: "ShowProgramDetails", sender: program)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let controller = segue.destination as? PlayerViewController {
controller.channel = sender as? TVChannel
}
else if let controller = segue.destination as? ProgramDetailsViewController {
controller.program = sender as? TVProgram
}
}
//MARK: GuideCollectionViewLayout Delegate
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, runtimeForProgramAtIndexPath indexPath: IndexPath) -> Double {
guard let guide = self.guide, let (_, program) = self.channelAndProgramForIndexPath(indexPath) else { return 0 }
return program.endDate.timeIntervalSince((guide.startDate as NSDate).laterDate(program.startDate as Date))
}
func timeIntervalForTimeIndicatorForCollectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout) -> Double {
return self.guide?.startDate != nil ? Date().timeIntervalSince((self.guide?.startDate)! as Date) : 0
}
//MARK: Focus
override var preferredFocusedView: UIView? {
get {
return self.collectionView.cellForItem(at: self.focusedIndexPath)
}
}
func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? {
return self.focusedIndexPath
}
func collectionView(_ collectionView: UICollectionView, shouldUpdateFocusIn context: UICollectionViewFocusUpdateContext) -> Bool {
if let indexPath = context.nextFocusedIndexPath {
self.focusedIndexPath = indexPath
}
return true
}
func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
if (context.focusHeading == .left || context.focusHeading == .right) || self.focusedTime == nil {
//Keep track of approximate time of the focused cell, to make vertical scrolling smoother
guard let indexPath = context.nextFocusedIndexPath, let (_, program) = self.channelAndProgramForIndexPath(indexPath) else { return }
self.focusedTime = ((program.startDate.addingTimeInterval(60 * 15) as NSDate).earlierDate(program.endDate as Date) as NSDate).laterDate(self.guide!.startDate.addingTimeInterval(60 * 15) as Date)
}
}
func collectionView(_ collectionView: UICollectionView, canFocusItemAt indexPath: IndexPath) -> Bool {
if indexPath.section == self.focusedIndexPath.section {
return true
}
else if indexPath.section == self.focusedIndexPath.section + 1 || indexPath.section == self.focusedIndexPath.section - 1 {
//When vertical scrolling, try and find proper cell based on airtimes, instead of cell frames
if let focusedTime = self.focusedTime {
if let nextProgram = self.programForIndexPath(indexPath) {
if indexPath.item == 0 && self.focusedIndexPath.item == 0 {
return true
}
else if nextProgram.containsDate(focusedTime) {
return true
}
else {
return false
}
}
}
else {
return true
}
}
return false
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
//Ensure the leftmost program cell is not cut off when focused
guard let cell = UIScreen.main.focusedView as? UICollectionViewCell,
let layout = self.collectionView.collectionViewLayout as? GuideCollectionViewLayout
else { return }
let point = targetContentOffset.pointee
let leftPadding = CGFloat(layout.channelWidth + layout.padding)
if point.x + leftPadding > cell.frame.minX {
targetContentOffset.pointee = CGPoint(x: cell.frame.minX - leftPadding, y: point.y)
}
}
//MARK: Helpers
func channelAndProgramForIndexPath(_ indexPath: IndexPath?) -> (TVChannel, TVProgram)? {
guard let indexPath = indexPath,
let channel = self.guide?.channels[indexPath.section],
let program = self.guide?.programsForChannel(channel)?[indexPath.item] else { return nil }
return (channel, program)
}
func programForIndexPath(_ indexPath: IndexPath?) -> TVProgram? {
guard let indexPath = indexPath, let channel = self.guide?.channels[indexPath.section] else { return nil }
return self.guide?.programsForChannel(channel)?[indexPath.item]
}
}
|
gpl-3.0
|
00cdf8735f3fc83bfacf4d93af4d9a8c
| 42.742424 | 213 | 0.652581 | 5.419052 | false | false | false | false |
UnsignedInt8/LightSwordX
|
LightSwordX/Socket/ytcpsocket.swift
|
2
|
6594
|
/*
Copyright (c) <2014>, skysent
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by skysent.
4. Neither the name of the skysent nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY skysent ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL skysent BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
@asmname("ytcpsocket_connect") func c_ytcpsocket_connect(host:UnsafePointer<Int8>,port:Int32,timeout:Int32) -> Int32
@asmname("ytcpsocket_close") func c_ytcpsocket_close(fd:Int32) -> Int32
@asmname("ytcpsocket_send") func c_ytcpsocket_send(fd:Int32,buff:UnsafePointer<UInt8>,len:Int32) -> Int32
@asmname("ytcpsocket_pull") func c_ytcpsocket_pull(fd:Int32,buff:UnsafePointer<UInt8>,len:Int32,timeout:Int32) -> Int32
@asmname("ytcpsocket_listen") func c_ytcpsocket_listen(addr:UnsafePointer<Int8>,port:Int32)->Int32
@asmname("ytcpsocket_accept") func c_ytcpsocket_accept(onsocketfd:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>) -> Int32
public class TCPClient:YSocket{
/*
* connect to server
* return success or fail with message
*/
public func connect(timeout t:Int)->(Bool,String){
let rs:Int32=c_ytcpsocket_connect(self.addr, port: Int32(self.port), timeout: Int32(t))
if rs>0{
self.fd=rs
return (true,"connect success")
}else{
switch rs{
case -1:
return (false,"query server fail")
case -2:
return (false,"connection closed")
case -3:
return (false,"connect timeout")
default:
return (false,"unknow err.")
}
}
}
/*
* close socket
* return success or fail with message
*/
public func close()->(Bool,String){
if let fd:Int32=self.fd{
c_ytcpsocket_close(fd)
self.fd=nil
return (true,"close success")
}else{
return (false,"socket not open")
}
}
/*
* send data
* return success or fail with message
*/
public func send(data d:[UInt8])->(Bool,String){
if let fd:Int32=self.fd{
let sendsize:Int32=c_ytcpsocket_send(fd, buff: d, len: Int32(d.count))
if Int(sendsize)==d.count{
return (true,"send success")
}else{
return (false,"send error")
}
}else{
return (false,"socket not open")
}
}
/*
* send string
* return success or fail with message
*/
public func send(str s:String)->(Bool,String){
if let fd:Int32=self.fd{
let sendsize:Int32=c_ytcpsocket_send(fd, buff: s, len: Int32(strlen(s)))
if sendsize==Int32(strlen(s)){
return (true,"send success")
}else{
return (false,"send error")
}
}else{
return (false,"socket not open")
}
}
/*
*
* send nsdata
*/
public func send(data d:NSData)->(Bool,String){
if let fd:Int32=self.fd{
var buff:[UInt8] = [UInt8](count:d.length,repeatedValue:0x0)
d.getBytes(&buff, length: d.length)
let sendsize:Int32=c_ytcpsocket_send(fd, buff: buff, len: Int32(d.length))
if sendsize==Int32(d.length){
return (true,"send success")
}else{
return (false,"send error")
}
}else{
return (false,"socket not open")
}
}
/*
* read data with expect length
* return success or fail with message
*/
public func read(expectlen:Int, timeout:Int = -1)->[UInt8]?{
if let fd:Int32 = self.fd{
var buff:[UInt8] = [UInt8](count:expectlen,repeatedValue:0x0)
let readLen:Int32=c_ytcpsocket_pull(fd, buff: &buff, len: Int32(expectlen), timeout: Int32(timeout))
if readLen<=0{
return nil
}
let rs=buff[0...Int(readLen-1)]
let data:[UInt8] = Array(rs)
return data
}
return nil
}
}
public class TCPServer:YSocket{
public func listen()->(Bool,String){
let fd:Int32=c_ytcpsocket_listen(self.addr, port: Int32(self.port))
if fd>0{
self.fd=fd
return (true,"listen success")
}else{
return (false,"listen fail")
}
}
public func accept()->TCPClient?{
if let serferfd=self.fd{
var buff:[Int8] = [Int8](count:16,repeatedValue:0x0)
var port:Int32=0
let clientfd:Int32=c_ytcpsocket_accept(serferfd, ip: &buff,port: &port)
if clientfd<0{
return nil
}
let tcpClient:TCPClient=TCPClient()
tcpClient.fd=clientfd
tcpClient.port=Int(port)
if let addr=String(CString: buff, encoding: NSUTF8StringEncoding){
tcpClient.addr=addr
}
return tcpClient
}
return nil
}
public func close()->(Bool,String){
if let fd:Int32=self.fd{
c_ytcpsocket_close(fd)
self.fd=nil
return (true,"close success")
}else{
return (false,"socket not open")
}
}
}
|
gpl-2.0
|
05ee0d9bb1d1e24158c1beabf33ec8ee
| 34.643243 | 130 | 0.608887 | 3.98429 | false | false | false | false |
honghaoz/RRNCollapsableSectionTableViewSwift
|
Example-Swift/Example-Swift/FakeModelBuilder.swift
|
1
|
1573
|
//
// FakeModelBuilder.swift
// Example-Swift
//
// Created by Robert Nash on 22/09/2015.
// Copyright © 2015 Robert Nash. All rights reserved.
//
import Foundation
class MenuSection: RRNCollapsableSectionItemProtocol {
var title: String
var isVisible: Bool
var items: [AnyObject]
init() {
title = ""
isVisible = false
items = []
}
}
class ModelBuilder {
class func buildMenu() -> [RRNCollapsableSectionItemProtocol] {
var collector = [RRNCollapsableSectionItemProtocol]()
for var i = 0; i < 5; i++ {
let section = MenuSection()
switch i {
case 0:
section.title = "Option 1"
section.isVisible = true
section.items = [NSNull(), NSNull(), NSNull()]
case 1:
section.title = "Option 2"
section.items = [NSNull(), NSNull(), NSNull(), NSNull(), NSNull(), NSNull()]
case 2:
section.title = "Option 3"
section.items = [NSNull(), NSNull(), NSNull()]
case 3:
section.title = "Option 4"
section.items = [NSNull(), NSNull()]
case 4:
section.title = "Option 5"
section.items = [NSNull(), NSNull(), NSNull(), NSNull()]
default:
break
}
collector.append(section)
}
return collector
}
}
|
mit
|
d0f98b198ea15ee366bd4ebd889f8667
| 24.786885 | 92 | 0.477735 | 4.9125 | false | false | false | false |
mownier/photostream
|
Photostream/UI/Home/HomeViewController.swift
|
1
|
2047
|
//
// HomeViewController.swift
// Photostream
//
// Created by Mounir Ybanez on 15/08/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
@objc protocol HomeViewControllerAction: class {
func showPostComposer()
}
class HomeViewController: UITabBarController, HomeViewControllerAction {
lazy var specialButton = UIButton()
var specialIndex: Int? {
didSet {
guard let index = specialIndex else {
specialButton.removeFromSuperview()
return
}
guard tabBar.subviews.isValid(index) else {
return
}
if specialButton.superview == nil {
specialButton.backgroundColor = UIColor.clear
specialButton.addTarget(self, action: #selector(self.showPostComposer), for: .touchUpInside)
view.addSubview(specialButton)
}
let tabBarButtons = tabBar.subviews.filter { subview -> Bool in
return subview.isUserInteractionEnabled
}
let subviews = tabBarButtons.sorted { (button1, button2) -> Bool in
return button1.frame.origin.x < button2.frame.origin.x
}
let subview = subviews[index]
let point = subview.superview!.convert(subview.frame.origin, to: view)
let size = subview.frame.size
let frame = CGRect(origin: point, size: size)
specialButton.frame = frame
view.bringSubview(toFront: specialButton)
}
}
var presenter: HomePresenterInterface!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
specialIndex = 2
}
func showPostComposer() {
presenter.presentPostComposer()
}
}
extension HomeViewController: HomeViewInterface {
var controller: UIViewController? {
return self
}
}
|
mit
|
95e7028664d09a450444d2d3615e149c
| 27.027397 | 108 | 0.580645 | 5.328125 | false | false | false | false |
swift102016team5/mefocus
|
MeFocus/MeFocus/UserLoginViewController.swift
|
1
|
2569
|
//
// UserLoginViewController.swift
// MeFocus
//
// Created by Hao on 11/19/16.
// Copyright © 2016 Group5. All rights reserved.
//
import UIKit
import Lock
import SimpleKeychain
class UserLoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Auth.shared.check{
(auth:Auth) in
// Dont have profile
if auth.profile == nil {
let controller = A0Lock.shared().newLockViewController()
controller?.onAuthenticationBlock = { maybeProfile, maybeToken in
// Do something with token profile. e.g.: save them.
// Lock will not save these objects for you.
// Don't forget to dismiss the Lock controller
guard let token = maybeToken else {
print("cannot get token")
return
}
guard let profile = maybeProfile else {
print("cannot get profile")
return
}
auth.token = token
auth.profile = profile
controller?.dismiss(animated: true, completion: nil)
self.toProfile()
}
A0Lock.shared().present(controller, from: self)
return
}
// Already have profile
// Do some navigations ...
self.toProfile()
}
}
func toProfile(){
App.shared.present(
presenter: self,
storyboard: "User",
controller: "UserProfileViewController",
modifier: nil,
completion: nil
)
}
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
|
7d1689fb8f22a7f9cc7b74d2528fad94
| 28.860465 | 106 | 0.520249 | 5.744966 | false | false | false | false |
xxxAIRINxxx/VHUD
|
Sources/VHUD.swift
|
1
|
5039
|
//
// VHUD.swift
// VHUD
//
// Created by xxxAIRINxxx on 2016/07/19.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
public enum Mode {
case loop(TimeInterval)
case duration(TimeInterval, dismissDeley: TimeInterval?)
case percentComplete
public static func ==(lhs: Mode, rhs: Mode) -> Bool {
switch (lhs, rhs) {
case (.loop(_), .loop(_)): return true
case (.duration(_), .duration(_)): return true
case (.percentComplete, .percentComplete): return true
default: return false
}
}
}
public enum Shape {
case round
case circle
case custom((UIView) -> Void)
}
public enum Style {
case light
case dark
case blur(UIBlurEffect.Style)
}
public enum Background {
case none
case color(UIColor)
case blur(UIBlurEffect.Style)
}
public struct VHUDContent {
public static var defaultShape: Shape = .circle
public static var defaultStyle: Style = .blur(.light)
public static var defaultBackground: Background = .none
public static var defaultLoadingText: String? = nil
public static var defaultCompletionText: String? = nil
public static var defaultIsUserInteractionEnabled: Bool = true
public var mode: Mode
public var shape: Shape
public var style: Style
public var background: Background
public var loadingText: String? = nil
public var completionText: String? = nil
public var isUserInteractionEnabled: Bool = true
public var labelFont: UIFont? = nil
public var lineDefaultColor: UIColor? = nil
public var lineElapsedColor: UIColor? = nil
public init(_ mode: Mode, _ style: Shape? = nil, _ theme: Style? = nil, _ background: Background? = nil) {
self.mode = mode
self.shape = style ?? VHUDContent.defaultShape
self.style = theme ?? VHUDContent.defaultStyle
self.background = background ?? VHUDContent.defaultBackground
self.loadingText = VHUDContent.defaultLoadingText
self.completionText = VHUDContent.defaultCompletionText
self.isUserInteractionEnabled = VHUDContent.defaultIsUserInteractionEnabled
}
}
public struct VHUD {
private static let window: VHUDWindow = VHUDWindow(frame: CGRect.zero)
fileprivate(set) var content: VHUDContent
fileprivate var hudView: VHUDView?
public init (_ mode: Mode) {
self.content = VHUDContent(mode)
}
public static func show(loopInterval: TimeInterval) {
self.show(VHUDContent(.loop(loopInterval)))
}
public static func show(duration: TimeInterval, _ dismissDeley: TimeInterval? = nil) {
self.show(VHUDContent(.duration(duration, dismissDeley: dismissDeley)))
}
public static func show(_ content: VHUDContent) {
self.window.show(content: content)
}
public static func updateProgress(_ percentComplete: CGFloat) {
self.window.updateProgress(Double(percentComplete))
}
public static func dismiss(_ duration: TimeInterval, _ deley: TimeInterval? = nil, _ text: String? = nil, _ completion: (() -> Void)? = nil) {
self.window.dismiss(duration, deley, text, completion)
}
}
extension VHUD {
public mutating func setShapeStyle(_ shape: Shape) -> VHUD {
self.content.shape = shape
return self
}
public mutating func setThemeStyle(_ theme: Style) -> VHUD {
self.content.style = theme
return self
}
public mutating func setBackgroundStyle(_ background: Background) -> VHUD {
self.content.background = background
return self
}
public mutating func setLoadingText(_ text: String) -> VHUD {
self.content.loadingText = text
return self
}
public mutating func setCompletionText(_ text: String) -> VHUD {
self.content.completionText = text
return self
}
public mutating func setLabelFont(_ font: UIFont) -> VHUD {
self.content.labelFont = font
return self
}
public mutating func setUserInteractionEnabled(_ isUserInteractionEnabled: Bool) -> VHUD {
self.content.isUserInteractionEnabled = isUserInteractionEnabled
return self
}
public mutating func setLineDefaultColor(_ color: UIColor) -> VHUD {
self.content.lineDefaultColor = color
return self
}
public mutating func setLineElapsedColor(_ color: UIColor) -> VHUD {
self.content.lineElapsedColor = color
return self
}
public mutating func show(_ inView: UIView) -> VHUD {
let view = VHUDView(inView: inView)
self.hudView = view
self.hudView?.setContent(content)
return self
}
public func dismiss(_ duration: TimeInterval, _ deley: TimeInterval? = nil, _ text: String? = nil, _ completion: (() -> Void)? = nil) {
self.hudView?.dismiss(duration, deley, text, completion)
}
}
|
mit
|
4aedb7b8744c7a2c6a82c6bed2278cc8
| 28.461988 | 146 | 0.650457 | 4.551039 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/UserInterface/MainController/ZClientViewController.swift
|
1
|
30140
|
//
// Wire
// Copyright (C) 2018 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 UIKit
import WireSyncEngine
import avs
import WireCommonComponents
final class ZClientViewController: UIViewController {
private(set) var conversationRootViewController: UIViewController?
private(set) var currentConversation: ZMConversation?
// TODO: This must be removed from here once we introduce VIPER
weak var router: AuthenticatedRouterProtocol?
var isComingFromRegistration = false
var needToShowDataUsagePermissionDialog = false
let wireSplitViewController: SplitViewController = SplitViewController()
private(set) var mediaPlaybackManager: MediaPlaybackManager?
let conversationListViewController: ConversationListViewController
var proximityMonitorManager: ProximityMonitorManager?
var legalHoldDisclosureController: LegalHoldDisclosureController?
var userObserverToken: Any?
var conferenceCallingUnavailableObserverToken: Any?
private let topOverlayContainer: UIView = UIView()
private var topOverlayViewController: UIViewController?
private var contentTopRegularConstraint: NSLayoutConstraint!
private var contentTopCompactConstraint: NSLayoutConstraint!
// init value = false which set to true, set to false after data usage permission dialog is displayed
var dataUsagePermissionDialogDisplayed = false
let backgroundViewController: BackgroundViewController
private let colorSchemeController: ColorSchemeController = ColorSchemeController()
private var incomingApnsObserver: Any?
private var networkAvailabilityObserverToken: Any?
private var pendingInitialStateRestore = false
var _userSession: UserSessionInterface?
/// init method for testing allows injecting an Account object and self user
///
/// - Parameters:
/// - account: an Account object
/// - selfUser: a SelfUserType object
required init(account: Account,
selfUser: SelfUserType,
userSession: UserSessionInterface? = ZMUserSession.shared()) {
_userSession = userSession
backgroundViewController = BackgroundViewController(user: selfUser, userSession: userSession as? ZMUserSession)
conversationListViewController = ConversationListViewController(account: account, selfUser: selfUser)
super.init(nibName: nil, bundle: nil)
proximityMonitorManager = ProximityMonitorManager()
mediaPlaybackManager = MediaPlaybackManager(name: "conversationMedia")
dataUsagePermissionDialogDisplayed = false
needToShowDataUsagePermissionDialog = false
AVSMediaManager.sharedInstance().register(mediaPlaybackManager, withOptions: [
"media": "external "
])
if let appGroupIdentifier = Bundle.main.appGroupIdentifier,
let remoteIdentifier = ZMUser.selfUser().remoteIdentifier {
let sharedContainerURL = FileManager.sharedContainerDirectory(for: appGroupIdentifier)
_ = sharedContainerURL.appendingPathComponent("AccountData", isDirectory: true).appendingPathComponent(remoteIdentifier.uuidString, isDirectory: true)
}
NotificationCenter.default.post(name: NSNotification.Name.ZMUserSessionDidBecomeAvailable, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil)
NotificationCenter.default.addObserver(forName: .featureDidChangeNotification, object: nil, queue: .main) { [weak self] (note) in
guard let change = note.object as? FeatureService.FeatureChange else { return }
switch change {
case .conferenceCallingIsAvailable:
guard let session = SessionManager.shared,
session.usePackagingFeatureConfig else { break }
self?.presentConferenceCallingAvailableAlert()
default:
break
}
}
setupAppearance()
createLegalHoldDisclosureController()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
AVSMediaManager.sharedInstance().unregisterMedia(mediaPlaybackManager)
}
private func restoreStartupState() {
pendingInitialStateRestore = false
attemptToPresentInitialConversation()
}
@discardableResult
private func attemptToPresentInitialConversation() -> Bool {
var stateRestored = false
let lastViewedScreen: SettingsLastScreen? = Settings.shared[.lastViewedScreen]
switch lastViewedScreen {
case .list?:
transitionToList(animated: false, completion: nil)
// only attempt to show content vc if it would be visible
if isConversationViewVisible {
stateRestored = attemptToLoadLastViewedConversation(withFocus: false, animated: false)
}
case .conversation?:
stateRestored = attemptToLoadLastViewedConversation(withFocus: true, animated: false)
default:
break
}
return stateRestored
}
// MARK: - Overloaded methods
override func viewDidLoad() {
super.viewDidLoad()
pendingInitialStateRestore = true
view.backgroundColor = .black
wireSplitViewController.delegate = self
addToSelf(wireSplitViewController)
wireSplitViewController.view.translatesAutoresizingMaskIntoConstraints = false
createTopViewConstraints()
updateSplitViewTopConstraint()
wireSplitViewController.view.backgroundColor = .clear
createBackgroundViewController()
if pendingInitialStateRestore {
restoreStartupState()
}
NotificationCenter.default.addObserver(self, selector: #selector(colorSchemeControllerDidApplyChanges(_:)), name: NSNotification.colorSchemeControllerDidApplyColorSchemeChange, object: nil)
if Bundle.developerModeEnabled {
// better way of dealing with this?
NotificationCenter.default.addObserver(self, selector: #selector(requestLoopNotification(_:)), name: NSNotification.Name(rawValue: ZMLoggingRequestLoopNotificationName), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(inconsistentStateNotification(_:)), name: NSNotification.Name(rawValue: ZMLoggingInconsistentStateNotificationName), object: nil)
}
setupUserChangeInfoObserver()
setUpConferenceCallingUnavailableObserver()
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return wr_supportedInterfaceOrientations
}
override var shouldAutorotate: Bool {
return presentedViewController?.shouldAutorotate ?? true
}
// MARK: keyboard shortcut
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(action: #selector(openStartUI(_:)),
input: "n", modifierFlags: [.command],
discoverabilityTitle: L10n.Localizable.Keyboardshortcut.openPeople)]
}
@objc
private func openStartUI(_ sender: Any?) {
conversationListViewController.bottomBarController.startUIViewTapped()
}
private func createBackgroundViewController() {
backgroundViewController.addToSelf(conversationListViewController)
conversationListViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
conversationListViewController.view.frame = backgroundViewController.view.bounds
wireSplitViewController.leftViewController = backgroundViewController
}
// MARK: Status bar
private var child: UIViewController? {
return topOverlayViewController ?? wireSplitViewController
}
private var childForStatusBar: UIViewController? {
// For iPad regular mode, there is a black bar area and we always use light style and non hidden status bar
return isIPadRegular() ? nil : child
}
override var childForStatusBarStyle: UIViewController? {
return childForStatusBar
}
override var childForStatusBarHidden: UIViewController? {
return childForStatusBar
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: trait
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// if changing from compact width to regular width, make sure current conversation is loaded
if previousTraitCollection?.horizontalSizeClass == .compact && traitCollection.horizontalSizeClass == .regular {
if let currentConversation = currentConversation {
select(conversation: currentConversation)
} else {
attemptToLoadLastViewedConversation(withFocus: false, animated: false)
}
}
updateSplitViewTopConstraint()
view.setNeedsLayout()
}
// MARK: - Singleton
static var shared: ZClientViewController? {
return AppDelegate.shared.appRootRouter?.rootViewController.children.first(where: {$0 is ZClientViewController}) as? ZClientViewController
}
/// Select the connection inbox and optionally move focus to it.
///
/// - Parameter focus: focus or not
func selectIncomingContactRequestsAndFocus(onView focus: Bool) {
conversationListViewController.selectInboxAndFocusOnView(focus: focus)
}
/// Exit the connection inbox. This contains special logic for reselecting another conversation etc when you
/// have no more connection requests.
///
/// - Parameter completion: completion handler
func hideIncomingContactRequests(completion: Completion? = nil) {
guard let userSession = ZMUserSession.shared() else { return }
let conversationsList = ZMConversationList.conversations(inUserSession: userSession)
if let conversation = (conversationsList as? [ZMConversation])?.first {
select(conversation: conversation)
}
wireSplitViewController.setLeftViewControllerRevealed(true, animated: true, completion: completion)
}
@discardableResult
private func pushContentViewController(_ viewController: UIViewController? = nil,
focusOnView focus: Bool = false,
animated: Bool = false,
completion: Completion? = nil) -> Bool {
conversationRootViewController = viewController
wireSplitViewController.setRightViewController(conversationRootViewController, animated: animated, completion: completion)
if focus {
wireSplitViewController.setLeftViewControllerRevealed(false, animated: animated)
}
return true
}
func loadPlaceholderConversationController(animated: Bool) {
loadPlaceholderConversationController(animated: animated) { }
}
func loadPlaceholderConversationController(animated: Bool, completion: @escaping Completion) {
currentConversation = nil
pushContentViewController(animated: animated, completion: completion)
}
/// Load and optionally show a conversation, but don't change the list selection. This is the place to put
/// stuff if you definitely need it to happen when a conversation is selected and/or presented
///
/// This method should only be called when the list selection changes, or internally by other zclientviewcontroller
///
/// - Parameters:
/// - conversation: conversation to load
/// - message: scroll to a specific message
/// - focus: focus on view or not
/// - animated: animated or not
/// - completion: optional completion handler
func load(_ conversation: ZMConversation,
scrollTo message: ZMConversationMessage?,
focusOnView focus: Bool,
animated: Bool,
completion: Completion? = nil) {
var conversationRootController: ConversationRootViewController?
if conversation === currentConversation,
conversationRootController != nil {
if let message = message {
conversationRootController?.scroll(to: message)
}
} else {
conversationRootController = ConversationRootViewController(conversation: conversation, message: message, clientViewController: self)
}
currentConversation = conversation
conversationRootController?.conversationViewController?.isFocused = focus
conversationListViewController.hideArchivedConversations()
pushContentViewController(conversationRootController, focusOnView: focus, animated: animated, completion: completion)
}
func loadIncomingContactRequestsAndFocus(onView focus: Bool, animated: Bool) {
currentConversation = nil
let inbox = ConnectRequestsViewController()
pushContentViewController(inbox.wrapInNavigationController(setBackgroundColor: true), focusOnView: focus, animated: animated)
}
/// Open the user clients detail screen
///
/// - Parameter conversation: conversation to open
func openDetailScreen(for conversation: ZMConversation) {
let controller = GroupDetailsViewController(conversation: conversation)
let navController = controller.wrapInNavigationController()
navController.modalPresentationStyle = .formSheet
present(navController, animated: true)
}
@objc
private func dismissClientListController(_ sender: Any?) {
dismiss(animated: true)
}
// MARK: - Animated conversation switch
func dismissAllModalControllers(callback: Completion?) {
let dismissAction = {
if let rightViewController = self.wireSplitViewController.rightViewController,
rightViewController.presentedViewController != nil {
rightViewController.dismiss(animated: false, completion: callback)
} else if let presentedViewController = self.conversationListViewController.presentedViewController {
// This is a workaround around the fact that the transitioningDelegate of the settings
// view controller is not called when the transition is not being performed animated.
// This sounds like a bug in UIKit (Radar incoming) as I would expect the custom animator
// being called with `transitionContext.isAnimated == false`. As this is not the case
// we have to restore the proper pre-presentation state here.
let conversationView = self.conversationListViewController.view
if let transform = conversationView?.layer.transform {
if !CATransform3DIsIdentity(transform) || 1 != conversationView?.alpha {
conversationView?.layer.transform = CATransform3DIdentity
conversationView?.alpha = 1
}
}
presentedViewController.dismiss(animated: false, completion: callback)
} else if self.presentedViewController != nil {
self.dismiss(animated: false, completion: callback)
} else {
callback?()
}
}
let ringingCallConversation = ZMUserSession.shared()?.ringingCallConversation
if ringingCallConversation != nil {
dismissAction()
} else {
minimizeCallOverlay(animated: true, withCompletion: dismissAction)
}
}
// MARK: - Getters/Setters
var context: ZMUserSession? {
return ZMUserSession.shared()
}
// MARK: - ColorSchemeControllerDidApplyChangesNotification
private func reloadCurrentConversation() {
guard let currentConversation = currentConversation else { return }
let currentConversationViewController = ConversationRootViewController(conversation: currentConversation, message: nil, clientViewController: self)
// Need to reload conversation to apply color scheme changes
pushContentViewController(currentConversationViewController)
}
@objc
private func colorSchemeControllerDidApplyChanges(_ notification: Notification?) {
reloadCurrentConversation()
}
// MARK: - Debug logging notifications
@objc
private func requestLoopNotification(_ notification: Notification?) {
guard let path = notification?.userInfo?["path"] as? String else { return }
DebugAlert.showSendLogsMessage(message: "A request loop is going on at \(path)")
}
@objc
private func inconsistentStateNotification(_ notification: Notification?) {
if let userInfo = notification?.userInfo?[ZMLoggingDescriptionKey] {
DebugAlert.showSendLogsMessage(message: "We detected an inconsistent state: \(userInfo)")
}
}
/// Attempt to load the last viewed conversation associated with the current account.
/// If no info is available, we attempt to load the first conversation in the list.
///
///
/// - Parameters:
/// - focus: <#focus description#>
/// - animated: <#animated description#>
/// - Returns: In the first case, YES is returned, otherwise NO.
@discardableResult
private func attemptToLoadLastViewedConversation(withFocus focus: Bool, animated: Bool) -> Bool {
if let currentAccount = SessionManager.shared?.accountManager.selectedAccount {
if let conversation = Settings.shared.lastViewedConversation(for: currentAccount) {
select(conversation: conversation, focusOnView: focus, animated: animated)
}
// dispatch async here because it has to happen after the collection view has finished
// laying out for the first time
DispatchQueue.main.async(execute: {
self.conversationListViewController.scrollToCurrentSelection(animated: false)
})
return true
} else {
selectListItemWhenNoPreviousItemSelected()
return false
}
}
/**
* This handles the case where we have to select a list item on startup but there is no previous item saved
*/
func selectListItemWhenNoPreviousItemSelected() {
guard let userSession = ZMUserSession.shared() else { return }
// check for conversations and pick the first one.. this can be tricky if there are pending updates and
// we haven't synced yet, but for now we just pick the current first item
let list = ZMConversationList.conversations(inUserSession: userSession) as? [ZMConversation]
if let conversation = list?.first {
// select the first conversation and don't focus on it
select(conversation: conversation)
} else {
loadPlaceholderConversationController(animated: true)
}
}
@objc
func contentSizeCategoryDidChange(_ notification: Notification?) {
reloadCurrentConversation()
}
private func setupAppearance() {
let labelColor: UIColor
labelColor = .label
UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = labelColor
}
// MARK: - Setup methods
func transitionToList(animated: Bool, completion: Completion?) {
transitionToList(animated: animated,
leftViewControllerRevealed: true,
completion: completion)
}
func transitionToList(animated: Bool,
leftViewControllerRevealed: Bool = true,
completion: Completion?) {
let action: Completion = { [weak self] in
self?.wireSplitViewController.setLeftViewControllerRevealed(leftViewControllerRevealed, animated: animated, completion: completion)
}
if let presentedViewController = wireSplitViewController.rightViewController?.presentedViewController {
presentedViewController.dismiss(animated: animated, completion: action)
} else {
action()
}
}
func setTopOverlay(to viewController: UIViewController?, animated: Bool = true) {
topOverlayViewController?.willMove(toParent: nil)
if let previousViewController = topOverlayViewController, let viewController = viewController {
addChild(viewController)
viewController.view.frame = topOverlayContainer.bounds
viewController.view.translatesAutoresizingMaskIntoConstraints = false
if animated {
transition(from: previousViewController,
to: viewController,
duration: 0.5,
options: .transitionCrossDissolve,
animations: { viewController.view.fitIn(view: self.view) },
completion: { _ in
viewController.didMove(toParent: self)
previousViewController.removeFromParent()
self.topOverlayViewController = viewController
self.updateSplitViewTopConstraint()
})
} else {
topOverlayContainer.addSubview(viewController.view)
viewController.view.fitIn(view: topOverlayContainer)
viewController.didMove(toParent: self)
topOverlayViewController = viewController
updateSplitViewTopConstraint()
}
} else if let previousViewController = topOverlayViewController {
if animated {
let heightConstraint = topOverlayContainer.heightAnchor.constraint(equalToConstant: 0)
UIView.animate(withDuration: 0.35, delay: 0, options: [.curveEaseIn, .beginFromCurrentState], animations: {
heightConstraint.isActive = true
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}, completion: { _ in
heightConstraint.isActive = false
self.topOverlayViewController?.removeFromParent()
previousViewController.view.removeFromSuperview()
self.topOverlayViewController = nil
self.updateSplitViewTopConstraint()
})
} else {
self.topOverlayViewController?.removeFromParent()
previousViewController.view.removeFromSuperview()
self.topOverlayViewController = nil
self.updateSplitViewTopConstraint()
}
} else if let viewController = viewController {
addChild(viewController)
viewController.view.frame = topOverlayContainer.bounds
viewController.view.translatesAutoresizingMaskIntoConstraints = false
topOverlayContainer.addSubview(viewController.view)
viewController.view.fitIn(view: topOverlayContainer)
viewController.didMove(toParent: self)
let isRegularContainer = traitCollection.horizontalSizeClass == .regular
if animated && !isRegularContainer {
let heightConstraint = viewController.view.heightAnchor.constraint(equalToConstant: 0)
heightConstraint.isActive = true
self.topOverlayViewController = viewController
self.updateSplitViewTopConstraint()
UIView.animate(withDuration: 0.35, delay: 0, options: [.curveEaseOut, .beginFromCurrentState], animations: {
heightConstraint.isActive = false
self.view.layoutIfNeeded()
})
} else {
topOverlayViewController = viewController
updateSplitViewTopConstraint()
}
}
}
private func createLegalHoldDisclosureController() {
legalHoldDisclosureController = LegalHoldDisclosureController(selfUser: ZMUser.selfUser(), userSession: ZMUserSession.shared(), presenter: { viewController, animated, completion in
viewController.presentTopmost(animated: animated, completion: completion)
})
}
private func createTopViewConstraints() {
topOverlayContainer.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(topOverlayContainer)
contentTopRegularConstraint = topOverlayContainer.topAnchor.constraint(equalTo: safeTopAnchor)
contentTopCompactConstraint = topOverlayContainer.topAnchor.constraint(equalTo: view.topAnchor)
NSLayoutConstraint.activate([
topOverlayContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
topOverlayContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
topOverlayContainer.bottomAnchor.constraint(equalTo: wireSplitViewController.view.topAnchor),
wireSplitViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
wireSplitViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
wireSplitViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
let heightConstraint = topOverlayContainer.heightAnchor.constraint(equalToConstant: 0)
heightConstraint.priority = UILayoutPriority.defaultLow
heightConstraint.isActive = true
}
private func updateSplitViewTopConstraint() {
let isRegularContainer = traitCollection.horizontalSizeClass == .regular
if isRegularContainer && nil == topOverlayViewController {
contentTopCompactConstraint.isActive = false
contentTopRegularConstraint.isActive = true
} else {
contentTopRegularConstraint.isActive = false
contentTopCompactConstraint.isActive = true
}
}
/// Open the user client list screen
///
/// - Parameter user: the UserType with client list to show
func openClientListScreen(for user: UserType) {
var viewController: UIViewController?
if user.isSelfUser, let clients = user.allClients as? [UserClient] {
let clientListViewController = ClientListViewController(clientsList: clients, credentials: nil, detailedView: true, showTemporary: true, variant: ColorScheme.default.variant)
clientListViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissClientListController(_:)))
viewController = clientListViewController
} else {
let profileViewController = ProfileViewController(user: user, viewer: ZMUser.selfUser(), context: .deviceList)
if let conversationViewController = (conversationRootViewController as? ConversationRootViewController)?.conversationViewController {
profileViewController.delegate = conversationViewController
profileViewController.viewControllerDismisser = conversationViewController
}
viewController = profileViewController
}
let navWrapperController: UINavigationController? = viewController?.wrapInNavigationController()
navWrapperController?.modalPresentationStyle = .formSheet
if let aController = navWrapperController {
present(aController, animated: true)
}
}
// MARK: - Select conversation
/// Select a conversation and move the focus to the conversation view.
///
/// - Parameters:
/// - conversation: the conversation to select
/// - message: scroll to this message
/// - focus: focus on the view or not
/// - animated: perform animation or not
/// - completion: the completion block
func select(conversation: ZMConversation,
scrollTo message: ZMConversationMessage? = nil,
focusOnView focus: Bool,
animated: Bool,
completion: Completion? = nil) {
dismissAllModalControllers(callback: { [weak self] in
guard
!conversation.isDeleted,
conversation.managedObjectContext != nil
else {
return
}
self?.conversationListViewController.viewModel.select(conversation: conversation, scrollTo: message, focusOnView: focus, animated: animated, completion: completion)
})
}
func select(conversation: ZMConversation) {
conversationListViewController.viewModel.select(conversation: conversation)
}
var isConversationViewVisible: Bool {
return wireSplitViewController.isConversationViewVisible
}
var isConversationListVisible: Bool {
return (wireSplitViewController.layoutSize == .regularLandscape) ||
(wireSplitViewController.isLeftViewControllerRevealed && conversationListViewController.presentedViewController == nil)
}
func minimizeCallOverlay(animated: Bool,
withCompletion completion: Completion?) {
router?.minimizeCallOverlay(animated: animated, withCompletion: completion)
}
}
|
gpl-3.0
|
28b11a8d46d6e1587dfcb4b837b923c2
| 41.450704 | 206 | 0.681188 | 6.035242 | false | false | false | false |
loganSims/wsdot-ios-app
|
wsdot/RestAreaViewController.swift
|
1
|
3681
|
//
// RestAreaViewController.swift
// WSDOT
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// 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 UIKit
class RestAreaViewController: UIViewController, MapMarkerDelegate, GMSMapViewDelegate {
var restAreaItem: RestAreaItem?
fileprivate let restAreaMarker = GMSMarker(position: CLLocationCoordinate2D(latitude: 0, longitude: 0))
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var directionLabel: UILabel!
@IBOutlet weak var milepostLabel: UILabel!
@IBOutlet weak var amenities: UILabel!
weak fileprivate var embeddedMapViewController: SimpleMapViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Rest Area"
embeddedMapViewController.view.isHidden = true
locationLabel.text = restAreaItem!.route + " - " + restAreaItem!.location
directionLabel.text = restAreaItem!.direction
milepostLabel.text = String(restAreaItem!.milepost)
amenities.text? = ""
restAreaMarker.position = CLLocationCoordinate2D(latitude: restAreaItem!.latitude, longitude: restAreaItem!.longitude)
for amenity in restAreaItem!.amenities {
amenities.text?.append("• " + amenity + "\n")
}
scrollView.contentMode = .scaleAspectFit
if let mapView = embeddedMapViewController.view as? GMSMapView{
restAreaMarker.map = mapView
mapView.settings.setAllGesturesEnabled(false)
if let restArea = restAreaItem {
mapView.moveCamera(GMSCameraUpdate.setTarget(CLLocationCoordinate2D(latitude: restArea.latitude, longitude: restArea.longitude), zoom: 14))
embeddedMapViewController.view.isHidden = false
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MyAnalytics.screenView(screenName: "RestArea")
}
func mapReady() {
if let mapView = embeddedMapViewController.view as? GMSMapView{
restAreaMarker.map = mapView
mapView.settings.setAllGesturesEnabled(false)
if let restArea = restAreaItem {
mapView.moveCamera(GMSCameraUpdate.setTarget(CLLocationCoordinate2D(latitude: restArea.latitude, longitude: restArea.longitude), zoom: 14))
embeddedMapViewController.view.isHidden = false
}
}
}
// MARK: Naviagtion
// Get refrence to child VC
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("here 1")
if let vc = segue.destination as? SimpleMapViewController, segue.identifier == "EmbedMapSegue" {
print("here 2")
vc.markerDelegate = self
vc.mapDelegate = self
self.embeddedMapViewController = vc
}
}
}
|
gpl-3.0
|
6637b9daeb44c796210bb5d34ac1d64a
| 35.425743 | 155 | 0.665126 | 4.802872 | false | false | false | false |
Ashok28/Kingfisher
|
Sources/Networking/SessionDelegate.swift
|
4
|
9283
|
//
// SessionDelegate.swift
// Kingfisher
//
// Created by Wei Wang on 2018/11/1.
//
// Copyright (c) 2019 Wei Wang <[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 Foundation
// Represents the delegate object of downloader session. It also behave like a task manager for downloading.
@objc(KFSessionDelegate) // Fix for ObjC header name conflicting. https://github.com/onevcat/Kingfisher/issues/1530
open class SessionDelegate: NSObject {
typealias SessionChallengeFunc = (
URLSession,
URLAuthenticationChallenge,
(URLSession.AuthChallengeDisposition, URLCredential?) -> Void
)
typealias SessionTaskChallengeFunc = (
URLSession,
URLSessionTask,
URLAuthenticationChallenge,
(URLSession.AuthChallengeDisposition, URLCredential?) -> Void
)
private var tasks: [URL: SessionDataTask] = [:]
private let lock = NSLock()
let onValidStatusCode = Delegate<Int, Bool>()
let onDownloadingFinished = Delegate<(URL, Result<URLResponse, KingfisherError>), Void>()
let onDidDownloadData = Delegate<SessionDataTask, Data?>()
let onReceiveSessionChallenge = Delegate<SessionChallengeFunc, Void>()
let onReceiveSessionTaskChallenge = Delegate<SessionTaskChallengeFunc, Void>()
func add(
_ dataTask: URLSessionDataTask,
url: URL,
callback: SessionDataTask.TaskCallback) -> DownloadTask
{
lock.lock()
defer { lock.unlock() }
// Create a new task if necessary.
let task = SessionDataTask(task: dataTask)
task.onCallbackCancelled.delegate(on: self) { [weak task] (self, value) in
guard let task = task else { return }
let (token, callback) = value
let error = KingfisherError.requestError(reason: .taskCancelled(task: task, token: token))
task.onTaskDone.call((.failure(error), [callback]))
// No other callbacks waiting, we can clear the task now.
if !task.containsCallbacks {
let dataTask = task.task
self.cancelTask(dataTask)
self.remove(task)
}
}
let token = task.addCallback(callback)
tasks[url] = task
return DownloadTask(sessionTask: task, cancelToken: token)
}
private func cancelTask(_ dataTask: URLSessionDataTask) {
lock.lock()
defer { lock.unlock() }
dataTask.cancel()
}
func append(
_ task: SessionDataTask,
url: URL,
callback: SessionDataTask.TaskCallback) -> DownloadTask
{
let token = task.addCallback(callback)
return DownloadTask(sessionTask: task, cancelToken: token)
}
private func remove(_ task: SessionDataTask) {
lock.lock()
defer { lock.unlock() }
guard let url = task.originalURL else {
return
}
tasks[url] = nil
}
private func task(for task: URLSessionTask) -> SessionDataTask? {
lock.lock()
defer { lock.unlock() }
guard let url = task.originalRequest?.url else {
return nil
}
guard let sessionTask = tasks[url] else {
return nil
}
guard sessionTask.task.taskIdentifier == task.taskIdentifier else {
return nil
}
return sessionTask
}
func task(for url: URL) -> SessionDataTask? {
lock.lock()
defer { lock.unlock() }
return tasks[url]
}
func cancelAll() {
lock.lock()
let taskValues = tasks.values
lock.unlock()
for task in taskValues {
task.forceCancel()
}
}
func cancel(url: URL) {
lock.lock()
let task = tasks[url]
lock.unlock()
task?.forceCancel()
}
}
extension SessionDelegate: URLSessionDataDelegate {
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
guard let httpResponse = response as? HTTPURLResponse else {
let error = KingfisherError.responseError(reason: .invalidURLResponse(response: response))
onCompleted(task: dataTask, result: .failure(error))
completionHandler(.cancel)
return
}
let httpStatusCode = httpResponse.statusCode
guard onValidStatusCode.call(httpStatusCode) == true else {
let error = KingfisherError.responseError(reason: .invalidHTTPStatusCode(response: httpResponse))
onCompleted(task: dataTask, result: .failure(error))
completionHandler(.cancel)
return
}
completionHandler(.allow)
}
open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let task = self.task(for: dataTask) else {
return
}
task.didReceiveData(data)
task.callbacks.forEach { callback in
callback.options.onDataReceived?.forEach { sideEffect in
sideEffect.onDataReceived(session, task: task, data: data)
}
}
}
open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let sessionTask = self.task(for: task) else { return }
if let url = sessionTask.originalURL {
let result: Result<URLResponse, KingfisherError>
if let error = error {
result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
} else if let response = task.response {
result = .success(response)
} else {
result = .failure(KingfisherError.responseError(reason: .noURLResponse(task: sessionTask)))
}
onDownloadingFinished.call((url, result))
}
let result: Result<(Data, URLResponse?), KingfisherError>
if let error = error {
result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
} else {
if let data = onDidDownloadData.call(sessionTask) {
result = .success((data, task.response))
} else {
result = .failure(KingfisherError.responseError(reason: .dataModifyingFailed(task: sessionTask)))
}
}
onCompleted(task: task, result: result)
}
open func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
onReceiveSessionChallenge.call((session, challenge, completionHandler))
}
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
onReceiveSessionTaskChallenge.call((session, task, challenge, completionHandler))
}
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
guard let sessionDataTask = self.task(for: task),
let redirectHandler = Array(sessionDataTask.callbacks).last?.options.redirectHandler else
{
completionHandler(request)
return
}
redirectHandler.handleHTTPRedirection(
for: sessionDataTask,
response: response,
newRequest: request,
completionHandler: completionHandler)
}
private func onCompleted(task: URLSessionTask, result: Result<(Data, URLResponse?), KingfisherError>) {
guard let sessionTask = self.task(for: task) else {
return
}
remove(sessionTask)
sessionTask.onTaskDone.call((result, sessionTask.callbacks))
}
}
|
mit
|
fd27b798b8b42a2ec57705f6182ef814
| 34.431298 | 115 | 0.637509 | 5.075451 | false | false | false | false |
LDlalala/LDZBLiving
|
LDZBLiving/LDZBLiving/Classes/Home/LDAnchorViewController.swift
|
1
|
3371
|
//
// LDAnchorViewController.swift
// LDZBLiving
//
// Created by 李丹 on 17/8/7.
// Copyright © 2017年 LD. All rights reserved.
//
import UIKit
private let homeColCellID = "homeColCellID"
class LDAnchorViewController: UIViewController {
lazy var homeVM : LDHomeViewModel = LDHomeViewModel()
// MARK:- 外界传值
var homeType : LDHomeType!
fileprivate lazy var collectionView : UICollectionView = {
let frame = CGRect(x: 0, y: 0, width: Int(self.view.frame.width), height: Int(self.view.frame.height) - KNavgationBarH - 2 * KTabBarH)
let layout = LDWaterFallFlowLayout()
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
layout.dateSource = self
let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.randomColor()
// 添加collectionView
view.addSubview(collectionView)
// 注册cell
collectionView.register(UINib(nibName: "LDHomeColCell", bundle: nil), forCellWithReuseIdentifier: homeColCellID)
// 请求数据
loadData(index: 0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK:- 请求数据
extension LDAnchorViewController {
func loadData(index : Int){
homeVM.loadHomeData(type: homeType, index: index, finishedCallback: {
self.collectionView.reloadData()
})
}
}
// MARK:- 流水布局的数据源设置
extension LDAnchorViewController : LDWaterFallFlowLayoutDateSource{
func numOfSection(_ waterFall: LDWaterFallFlowLayout) -> Int {
return 2
}
func waterFall(_ waterFall: LDWaterFallFlowLayout, indexpath indexPath: IndexPath) -> CGFloat {
return indexPath.item % 2 == 0 ? KScreenW * 2 / 3 : KScreenW * 0.5
}
}
// MARK:- UICollectionViewDataSource
extension LDAnchorViewController : UICollectionViewDataSource ,UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(homeVM.anchorModels.count)
return homeVM.anchorModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: homeColCellID, for: indexPath) as! LDHomeColCell
cell.backgroundColor = UIColor.randomColor()
cell.anchorModel = homeVM.anchorModels[indexPath.item]
// 加载更多数据
if indexPath.item == homeVM.anchorModels.count - 1 {
loadData(index: homeVM.anchorModels.count)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let RoomVC = RoomViewController()
RoomVC.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(RoomVC, animated: true)
}
}
|
mit
|
5081358e1ada6797fcded53bbb152908
| 31.352941 | 142 | 0.678485 | 4.992436 | false | false | false | false |
JohnEstropia/CoreStore
|
Sources/DataStack+Migration.swift
|
1
|
30258
|
//
// DataStack+Migration.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - DataStack
extension DataStack {
/**
Asynchronously adds a `StorageInterface` to the stack. Migrations are also initiated by default.
```
dataStack.addStorage(
InMemoryStore(configuration: "Config1"),
completion: { result in
switch result {
case .success(let storage): // ...
case .failure(let error): // ...
}
}
)
```
- parameter storage: the storage
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `StorageInterface` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `StorageInterface` was already added at the same URL and with the same configuration.
*/
public func addStorage<T>(_ storage: T, completion: @escaping (SetupResult<T>) -> Void) {
self.coordinator.performAsynchronously {
if let _ = self.persistentStoreForStorage(storage) {
DispatchQueue.main.async {
completion(.success(storage))
}
return
}
do {
_ = try self.createPersistentStoreFromStorage(
storage,
finalURL: nil,
finalStoreOptions: storage.storeOptions
)
DispatchQueue.main.async {
completion(.success(storage))
}
}
catch {
let storeError = CoreStoreError(error)
Internals.log(
storeError,
"Failed to add \(Internals.typeName(storage)) to the stack."
)
DispatchQueue.main.async {
completion(.failure(storeError))
}
}
}
}
/**
Asynchronously adds a `LocalStorage` to the stack. Migrations are also initiated by default.
```
let migrationProgress = dataStack.addStorage(
SQLiteStore(fileName: "core_data.sqlite", configuration: "Config1"),
completion: { result in
switch result {
case .success(let storage): // ...
case .failure(let error): // ...
}
}
)
```
- parameter storage: the local storage
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `SetupResult` argument indicates the result. Note that the `LocalStorage` associated to the `SetupResult.success` may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration.
- returns: a `Progress` instance if a migration has started, or `nil` if either no migrations are required or if a failure occured.
*/
public func addStorage<T: LocalStorage>(_ storage: T, completion: @escaping (SetupResult<T>) -> Void) -> Progress? {
let fileURL = storage.fileURL
Internals.assert(
fileURL.isFileURL,
"The specified URL for the \(Internals.typeName(storage)) is invalid: \"\(fileURL)\""
)
return self.coordinator.performSynchronously {
if let _ = self.persistentStoreForStorage(storage) {
DispatchQueue.main.async {
completion(.success(storage))
}
return nil
}
if let persistentStore = self.coordinator.persistentStore(for: fileURL as URL) {
if let existingStorage = persistentStore.storageInterface as? T,
storage.matchesPersistentStore(persistentStore) {
DispatchQueue.main.async {
completion(.success(existingStorage))
}
return nil
}
let error = CoreStoreError.differentStorageExistsAtURL(existingPersistentStoreURL: fileURL)
Internals.log(
error,
"Failed to add \(Internals.typeName(storage)) at \"\(fileURL)\" because a different \(Internals.typeName(NSPersistentStore.self)) at that URL already exists."
)
DispatchQueue.main.async {
completion(.failure(error))
}
return nil
}
do {
try FileManager.default.createDirectory(
at: fileURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: type(of: storage).storeType,
at: fileURL as URL,
options: storage.storeOptions
)
return self.upgradeStorageIfNeeded(
storage,
metadata: metadata,
completion: { (result) -> Void in
if case .failure(.internalError(let error)) = result {
if storage.localStorageOptions.contains(.recreateStoreOnModelMismatch) && error.isCoreDataMigrationError {
do {
try storage.cs_eraseStorageAndWait(
metadata: metadata,
soureModelHint: self.schemaHistory.schema(for: metadata)?.rawModel()
)
_ = try self.addStorageAndWait(storage)
DispatchQueue.main.async {
completion(.success(storage))
}
}
catch {
completion(.failure(CoreStoreError(error)))
}
return
}
completion(.failure(CoreStoreError(error)))
return
}
do {
_ = try self.addStorageAndWait(storage)
DispatchQueue.main.async {
completion(.success(storage))
}
}
catch {
completion(.failure(CoreStoreError(error)))
}
}
)
}
catch let error as NSError
where error.code == NSFileReadNoSuchFileError && error.domain == NSCocoaErrorDomain {
do {
_ = try self.addStorageAndWait(storage)
DispatchQueue.main.async {
completion(.success(storage))
}
}
catch {
DispatchQueue.main.async {
completion(.failure(CoreStoreError(error)))
}
}
return nil
}
catch {
let storeError = CoreStoreError(error)
Internals.log(
storeError,
"Failed to load SQLite \(Internals.typeName(NSPersistentStore.self)) metadata."
)
DispatchQueue.main.async {
completion(.failure(storeError))
}
return nil
}
}
}
/**
Migrates a local storage to match the `DataStack`'s managed object model version. This method does NOT add the migrated store to the data stack.
- parameter storage: the local storage
- parameter completion: the closure to be executed on the main queue when the migration completes, either due to success or failure. The closure's `MigrationResult` argument indicates the result.
- throws: a `CoreStoreError` value indicating the failure
- returns: a `Progress` instance if a migration has started, or `nil` is no migrations are required
*/
public func upgradeStorageIfNeeded<T: LocalStorage>(_ storage: T, completion: @escaping (MigrationResult) -> Void) throws -> Progress? {
return try self.coordinator.performSynchronously {
let fileURL = storage.fileURL
do {
Internals.assert(
self.persistentStoreForStorage(storage) == nil,
"Attempted to migrate an already added \(Internals.typeName(storage)) at URL \"\(fileURL)\""
)
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: type(of: storage).storeType,
at: fileURL as URL,
options: storage.storeOptions
)
return self.upgradeStorageIfNeeded(
storage,
metadata: metadata,
completion: completion
)
}
catch {
let metadataError = CoreStoreError(error)
Internals.log(
metadataError,
"Failed to load \(Internals.typeName(storage)) metadata from URL \"\(fileURL)\"."
)
throw metadataError
}
}
}
/**
Checks the migration steps required for the storage to match the `DataStack`'s managed object model version.
- parameter storage: the local storage
- throws: a `CoreStoreError` value indicating the failure
- returns: a `MigrationType` array indicating the migration steps required for the store, or an empty array if the file does not exist yet. Otherwise, an error is thrown if either inspection of the store failed, or if no mapping model was found/inferred.
*/
public func requiredMigrationsForStorage<T: LocalStorage>(_ storage: T) throws -> [MigrationType] {
return try self.coordinator.performSynchronously {
let fileURL = storage.fileURL
Internals.assert(
self.persistentStoreForStorage(storage) == nil,
"Attempted to query required migrations for an already added \(Internals.typeName(storage)) at URL \"\(fileURL)\""
)
do {
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: type(of: storage).storeType,
at: fileURL as URL,
options: storage.storeOptions
)
guard let migrationSteps = self.computeMigrationFromStorage(storage, metadata: metadata) else {
let error = CoreStoreError.mappingModelNotFound(
localStoreURL: fileURL,
targetModel: self.schemaHistory.rawModel,
targetModelVersion: self.modelVersion
)
Internals.log(
error,
"Failed to find migration steps from the \(Internals.typeName(storage)) at URL \"\(fileURL)\" to version model \"\(self.modelVersion)\"."
)
throw error
}
if migrationSteps.count > 1 && storage.localStorageOptions.contains(.preventProgressiveMigration) {
let error = CoreStoreError.progressiveMigrationRequired(localStoreURL: fileURL)
Internals.log(
error,
"Failed to find migration mapping from the \(Internals.typeName(storage)) at URL \"\(fileURL)\" to version model \"\(self.modelVersion)\" without requiring progessive migrations."
)
throw error
}
return migrationSteps.map { $0.migrationType }
}
catch let error as NSError
where error.code == NSFileReadNoSuchFileError && error.domain == NSCocoaErrorDomain {
return []
}
catch {
let metadataError = CoreStoreError(error)
Internals.log(
metadataError,
"Failed to load \(Internals.typeName(storage)) metadata from URL \"\(fileURL)\"."
)
throw metadataError
}
}
}
// MARK: Private
private func upgradeStorageIfNeeded<T: LocalStorage>(_ storage: T, metadata: [String: Any], completion: @escaping (MigrationResult) -> Void) -> Progress? {
guard let migrationSteps = self.computeMigrationFromStorage(storage, metadata: metadata) else {
let error = CoreStoreError.mappingModelNotFound(
localStoreURL: storage.fileURL,
targetModel: self.schemaHistory.rawModel,
targetModelVersion: self.modelVersion
)
Internals.log(
error,
"Failed to find migration steps from \(Internals.typeName(storage)) at URL \"\(storage.fileURL)\" to version model \"\(self.schemaHistory.rawModel)\"."
)
DispatchQueue.main.async {
completion(.failure(error))
}
return nil
}
let numberOfMigrations: Int64 = Int64(migrationSteps.count)
if numberOfMigrations == 0 {
DispatchQueue.main.async {
completion(.success([]))
return
}
return nil
}
else if numberOfMigrations > 1 && storage.localStorageOptions.contains(.preventProgressiveMigration) {
let error = CoreStoreError.progressiveMigrationRequired(localStoreURL: storage.fileURL)
Internals.log(
error,
"Failed to find migration mapping from the \(Internals.typeName(storage)) at URL \"\(storage.fileURL)\" to version model \"\(self.modelVersion)\" without requiring progessive migrations."
)
DispatchQueue.main.async {
completion(.failure(error))
}
return nil
}
let migrationTypes = migrationSteps.map { $0.migrationType }
var migrationResult: MigrationResult?
var operations = [Operation]()
var cancelled = false
let progress = Progress(parent: nil, userInfo: nil)
progress.totalUnitCount = numberOfMigrations
for (sourceModel, destinationModel, mappingModel, migrationType) in migrationSteps {
progress.becomeCurrent(withPendingUnitCount: 1)
let childProgress = Progress(parent: progress, userInfo: nil)
childProgress.totalUnitCount = 100
operations.append(
BlockOperation { [weak self] in
guard let self = self, !cancelled else {
return
}
autoreleasepool {
do {
try self.startMigrationForStorage(
storage,
sourceModel: sourceModel,
destinationModel: destinationModel,
mappingModel: mappingModel,
migrationType: migrationType,
progress: childProgress
)
}
catch {
let migrationError = CoreStoreError(error)
Internals.log(
migrationError,
"Failed to migrate version model \"\(migrationType.sourceVersion)\" to version \"\(migrationType.destinationVersion)\"."
)
migrationResult = .failure(migrationError)
cancelled = true
}
}
DispatchQueue.main.async {
withExtendedLifetime(childProgress) { (_: Progress) -> Void in }
}
}
)
progress.resignCurrent()
}
let migrationOperation = BlockOperation()
migrationOperation.qualityOfService = .utility
operations.forEach { migrationOperation.addDependency($0) }
migrationOperation.addExecutionBlock { () -> Void in
DispatchQueue.main.async {
progress.setProgressHandler(nil)
completion(migrationResult ?? .success(migrationTypes))
return
}
}
operations.append(migrationOperation)
self.migrationQueue.addOperations(operations, waitUntilFinished: false)
return progress
}
private func computeMigrationFromStorage<T: LocalStorage>(_ storage: T, metadata: [String: Any]) -> [(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType)]? {
let schemaHistory = self.schemaHistory
if schemaHistory.rawModel.isConfiguration(withName: storage.configuration, compatibleWithStoreMetadata: metadata) {
return []
}
guard let initialSchema = schemaHistory.schema(for: metadata) else {
return nil
}
var currentVersion = initialSchema.modelVersion
let migrationChain: MigrationChain = schemaHistory.migrationChain.isEmpty
? [currentVersion: schemaHistory.currentModelVersion]
: schemaHistory.migrationChain
var migrationSteps = [(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType)]()
while let nextVersion = migrationChain.nextVersionFrom(currentVersion),
let sourceSchema = schemaHistory.schema(for: currentVersion),
sourceSchema.modelVersion != schemaHistory.currentModelVersion,
let destinationSchema = schemaHistory.schema(for: nextVersion) {
let mappingProviders = storage.migrationMappingProviders
do {
try withExtendedLifetime((sourceSchema.rawModel(), destinationSchema.rawModel())) {
let (sourceModel, destinationModel) = $0
let mapping = try mappingProviders.findMapping(
sourceSchema: sourceSchema,
destinationSchema: destinationSchema,
storage: storage
)
migrationSteps.append(
(
sourceModel: sourceModel,
destinationModel: destinationModel,
mappingModel: mapping.mappingModel,
migrationType: mapping.migrationType
)
)
}
}
catch {
return nil
}
currentVersion = nextVersion
}
if migrationSteps.last?.destinationModel == schemaHistory.rawModel {
return migrationSteps
}
return nil
}
private func startMigrationForStorage<T: LocalStorage>(_ storage: T, sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType, progress: Progress) throws {
do {
try storage.cs_finalizeStorageAndWait(soureModelHint: sourceModel)
}
catch {
throw CoreStoreError(error)
}
let fileURL = storage.fileURL
if case .lightweight = migrationType {
do {
let timerQueue = DispatchQueue(
label: "DataStack.lightweightMigration.timerQueue",
qos: .utility,
attributes: []
)
let estimatedTime: TimeInterval = 60 * 3 // 3 mins
let interval: TimeInterval = 1
let fakeTotalUnitCount: Float = 0.9 * Float(progress.totalUnitCount)
var fakeProgress: Float = 0
var recursiveCheck: () -> Void = {}
recursiveCheck = { [weak timerQueue] in
guard let timerQueue = timerQueue, fakeProgress < 1 else {
return
}
progress.completedUnitCount = Int64(fakeTotalUnitCount * fakeProgress)
fakeProgress += Float(interval / estimatedTime)
timerQueue.asyncAfter(
deadline: .now() + interval,
execute: recursiveCheck
)
}
timerQueue.async(execute: recursiveCheck)
_ = try withExtendedLifetime(NSPersistentStoreCoordinator(managedObjectModel: destinationModel)) { (coordinator: NSPersistentStoreCoordinator) in
try coordinator.addPersistentStoreSynchronously(
type(of: storage).storeType,
configuration: storage.configuration,
URL: fileURL,
options: storage.dictionary(
forOptions: storage.localStorageOptions.union(.allowSynchronousLightweightMigration)
)
)
}
timerQueue.sync {
fakeProgress = 1
}
_ = try? storage.cs_finalizeStorageAndWait(soureModelHint: destinationModel)
progress.completedUnitCount = progress.totalUnitCount
return
}
catch {
// Lightweight migration failed somehow. Proceed using InferedMappingModel below
}
}
let fileManager = FileManager.default
let temporaryDirectoryURL = fileManager.temporaryDirectory
.appendingPathComponent(Bundle.main.bundleIdentifier ?? "com.CoreStore.DataStack")
.appendingPathComponent(ProcessInfo().globallyUniqueString)
try! fileManager.createDirectory(
at: temporaryDirectoryURL,
withIntermediateDirectories: true,
attributes: nil
)
let externalStorageFolderName = ".\(fileURL.deletingPathExtension().lastPathComponent)_SUPPORT"
let temporaryExternalStorageURL = temporaryDirectoryURL.appendingPathComponent(
externalStorageFolderName,
isDirectory: true
)
let temporaryFileURL = temporaryDirectoryURL.appendingPathComponent(
fileURL.lastPathComponent,
isDirectory: false
)
let migrationManager = Internals.MigrationManager(
sourceModel: sourceModel,
destinationModel: destinationModel,
progress: progress
)
do {
try migrationManager.migrateStore(
from: fileURL,
sourceType: type(of: storage).storeType,
options: nil,
with: mappingModel,
toDestinationURL: temporaryFileURL,
destinationType: type(of: storage).storeType,
destinationOptions: nil
)
let temporaryStorage = SQLiteStore(
fileURL: temporaryFileURL,
configuration: storage.configuration,
migrationMappingProviders: storage.migrationMappingProviders,
localStorageOptions: storage.localStorageOptions
)
try temporaryStorage.cs_finalizeStorageAndWait(soureModelHint: destinationModel)
}
catch {
_ = try? fileManager.removeItem(at: temporaryFileURL)
throw CoreStoreError(error)
}
do {
try fileManager.replaceItem(
at: fileURL,
withItemAt: temporaryFileURL,
backupItemName: nil,
options: [],
resultingItemURL: nil
)
if fileManager.fileExists(atPath: temporaryExternalStorageURL.path) {
let externalStorageURL = fileURL
.deletingLastPathComponent()
.appendingPathComponent(externalStorageFolderName, isDirectory: true)
try fileManager.replaceItem(
at: externalStorageURL,
withItemAt: temporaryExternalStorageURL,
backupItemName: nil,
options: [],
resultingItemURL: nil
)
}
progress.completedUnitCount = progress.totalUnitCount
}
catch {
_ = try? fileManager.removeItem(at: temporaryFileURL)
_ = try? fileManager.removeItem(at: temporaryExternalStorageURL)
throw CoreStoreError(error)
}
}
}
// MARK: - FilePrivate
extension Array where Element == SchemaMappingProvider {
func findMapping(sourceSchema: DynamicSchema, destinationSchema: DynamicSchema, storage: LocalStorage) throws -> (mappingModel: NSMappingModel, migrationType: MigrationType) {
for element in self {
switch element {
case let element as CustomSchemaMappingProvider
where element.sourceVersion == sourceSchema.modelVersion && element.destinationVersion == destinationSchema.modelVersion:
return try element.cs_createMappingModel(from: sourceSchema, to: destinationSchema, storage: storage)
case let element as XcodeSchemaMappingProvider
where element.sourceVersion == sourceSchema.modelVersion && element.destinationVersion == destinationSchema.modelVersion:
return try element.cs_createMappingModel(from: sourceSchema, to: destinationSchema, storage: storage)
default:
continue
}
}
return try InferredSchemaMappingProvider()
.cs_createMappingModel(from: sourceSchema, to: destinationSchema, storage: storage)
}
}
|
mit
|
297689a7a9a210babfcceb070f008cbf
| 40.618982 | 429 | 0.512245 | 6.811571 | false | false | false | false |
SwiftOnTheServer/DrinkChooser
|
lib/Redis/Redis+SortedSet.swift
|
1
|
35663
|
/**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/// Extend Redis by adding the Sorted Set operations
extension Redis {
//
// MARK: Sorted set API functions
//
/// Add elements to a sorted set.
///
/// - Parameter key: The key.
/// - Parameter tuples: A list of tuples containing a score and value to be added to the sorted set.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements added to the sorted set.
/// NSError will be non-nil if an error occurred.
public func zadd(_ key: String, tuples: (Int, String)..., callback: (Int?, NSError?) -> Void) {
zaddArrayOfScoreMembers(key, tuples: tuples, callback: callback)
}
/// Add elements to a sorted set.
///
/// - Parameter key: The key.
/// - Parameter tuples: A list of tuples containing a score and value to be added to the sorted set.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements added to the sorted set.
/// NSError will be non-nil if an error occurred.
public func zadd(_ key: String, tuples: (Int, RedisString)..., callback: (Int?, NSError?) -> Void) {
zaddArrayOfScoreMembers(key, tuples: tuples, callback: callback)
}
/// Add elements to a sorted set.
///
/// - Parameter key: The key.
/// - Parameter tuples: An array of tuples containing a score and value to be added to the sorted set.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements added to the sorted set.
/// NSError will be non-nil if an error occurred.
public func zaddArrayOfScoreMembers(_ key: String, tuples: [(Int, String)], callback: (Int?, NSError?) -> Void) {
var command = ["ZADD"]
command.append(key)
for tuple in tuples {
command.append(String(tuple.0))
command.append(tuple.1)
}
issueCommandInArray(command) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Add elements to a sorted set.
///
/// - Parameter key: The key.
/// - Parameter tuples: An array of tuples containing a score and value to be added to the sorted set.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements added to the sorted set.
/// NSError will be non-nil if an error occurred.
public func zaddArrayOfScoreMembers(_ key: String, tuples: [(Int, RedisString)], callback: (Int?, NSError?) -> Void) {
var command = [RedisString("ZADD")]
command.append(RedisString(key))
for tuple in tuples {
command.append(RedisString(tuple.0))
command.append(tuple.1)
}
issueCommandInArray(command) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Get the sorted set's cardinality (number of elements).
///
/// - Parameter key: The key.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements in the sorted set.
/// NSError will be non-nil if an error occurred.
public func zcard(_ key: String, callback: (Int?, NSError?) -> Void) {
issueCommand("ZCARD", key) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Count the members in a sorted set with scores within the given values.
///
/// - Parameter key: The key.
/// - Parameter min: The minimum score to count from the set.
/// - Parameter max: The maximum score to count from the set.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the specified score range.
/// NSError will be non-nil if an error occurred.
public func zcount(_ key: String, min: String, max: String, callback: (Int?, NSError?) -> Void) {
issueCommand("ZCOUNT", key, min, max) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Count the members in a sorted set with scores within the given values.
///
/// - Parameter key: The key.
/// - Parameter min: The minimum score to count from the set.
/// - Parameter max: The maximum score to count from the set.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the specified score range.
/// NSError will be non-nil if an error occurred.
public func zcount(_ key: RedisString, min: RedisString, max: RedisString, callback: (Int?, NSError?) -> Void) {
issueCommand(RedisString("ZCOUNT"), key, min, max) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Increment the score of a member in a sorted set.
///
/// - Parameter key: The key.
/// - Parameter increment: The amount to increment the member by.
/// - Parameter member: The member to increment.
/// - Parameter callback: The callback function, the String will contain
/// the new score of member.
/// NSError will be non-nil if an error occurred.
public func zincrby(_ key: String, increment: Int, member: String, callback: (RedisString?, NSError?) -> Void) {
issueCommand("ZINCRBY", key, String(increment), member) { (response: RedisResponse) in
self.redisStringResponseHandler(response, callback: callback)
}
}
/// Increment the score of a member in a sorted set.
///
/// - Parameter key: The key.
/// - Parameter increment: The amount to increment the member by.
/// - Parameter member: The member to increment.
/// - Parameter callback: The callback function, the String will contain
/// the new score of member.
/// NSError will be non-nil if an error occurred.
public func zincrby(_ key: String, increment: Int, member: RedisString, callback: (RedisString?, NSError?) -> Void) {
issueCommand(RedisString("ZINCRBY"), RedisString(key), RedisString(increment), member) { (response: RedisResponse) in
self.redisStringResponseHandler(response, callback: callback)
}
}
/// Intersect multiple sorted sets and store the resulting sorted set in a new key.
///
/// - Parameter destination: The stored set where the results will be saved to.
/// If destination exists, it will be overwritten.
/// - Parameter numkeys: The number of keys to be sorted.
/// - Parameter keys: The keys to be intersected.
/// - Parameter weights: A multiplication factor for each input sorted set.
/// - Parameter aggregate: Specify how the results of the union are aggregated.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the resulting sorted set at destination.
/// NSError will be non-nil if an error occurred.
public func zinterstore(_ destination: String, numkeys: Int, keys: String..., weights: [Int] = [], aggregate: String = "", callback: (Int?, NSError?) -> Void) {
zinterstoreInArray(destination, numkeys: numkeys, keys: keys, weights: weights, aggregate: aggregate, callback: callback)
}
/// Intersect multiple sorted sets and store the resulting sorted set in a new key.
///
/// - Parameter destination: The stored set where the results will be saved to.
/// If destination exists, it will be overwritten.
/// - Parameter numkeys: The number of keys to be sorted.
/// - Parameter keys: The keys to be intersected.
/// - Parameter weights: A multiplication factor for each input sorted set.
/// - Parameter aggregate: Specify how the results of the union are aggregated.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the resulting sorted set at destination.
/// NSError will be non-nil if an error occurred.
public func zinterstoreInArray(_ destination: String, numkeys: Int, keys: [String], weights: [Int], aggregate: String, callback: (Int?, NSError?) -> Void) {
let command = appendValues(operation: "ZINTERSTORE", destination, numkeys: numkeys, keys: keys, weights: weights, aggregate: aggregate)
issueCommandInArray(command) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Intersect multiple sorted sets and store the resulting sorted set in a new key.
///
/// - Parameter destination: The stored set where the results will be saved to.
/// If destination exists, it will be overwritten.
/// - Parameter numkeys: The number of keys to be sorted.
/// - Parameter keys: The keys to be intersected.
/// - Parameter weights: A multiplication factor for each input sorted set.
/// - Parameter aggregate: Specify how the results of the union are aggregated.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the resulting sorted set at destination.
/// NSError will be non-nil if an error occurred.
public func zinterstore(_ destination: String, numkeys: Int, keys: RedisString..., weights: [Int] = [], aggregate: RedisString = RedisString(""), callback: (Int?, NSError?) -> Void) {
zinterstoreInArray(destination, numkeys: numkeys, keys: keys, weights: weights, aggregate: aggregate, callback: callback)
}
/// Intersect multiple sorted sets and store the resulting sorted set in a new key.
///
/// - Parameter destination: The stored set where the results will be saved to.
/// If destination exists, it will be overwritten.
/// - Parameter numkeys: The number of keys to be sorted.
/// - Parameter keys: The keys to be intersected.
/// - Parameter weights: A multiplication factor for each input sorted set.
/// - Parameter aggregate: Specify how the results of the union are aggregated.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the resulting sorted set at destination.
/// NSError will be non-nil if an error occurred.
public func zinterstoreInArray(_ destination: String, numkeys: Int, keys: [RedisString], weights: [Int], aggregate: RedisString, callback: (Int?, NSError?) -> Void) {
let command = appendValues(operation: "ZINTERSTORE", destination, numkeys: numkeys, keys: keys, weights: weights, aggregate: aggregate)
issueCommandInArray(command) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Count the number of members in a sorted set between a given lexicographical range.
///
/// - Parameter key: The key.
/// - Parameter min: The minimum score to count from the set.
/// - Parameter max: The maximum score to count from the set.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the specified score range.
/// NSError will be non-nil if an error occurred.
public func zlexcount(_ key: String, min: String, max: String, callback: (Int?, NSError?) -> Void) {
issueCommand("ZLEXCOUNT", key, min, max) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Get the specified range of elements in a sorted set.
///
/// - Parameter key: The key.
/// - Parameter start: The starting index of the elements of the sorted set to fetch.
/// - Parameter stop: The ending index of the elements of the sorted set to fetch.
/// - Parameter callback: The callback function, the Array<RedisString> will contain the
/// elements fetched from the sorted set.
/// NSError will be non-nil if an error occurred.
public func zrange(_ key: String, start: Int, stop: Int, callback: ([RedisString?]?, NSError?) -> Void) {
issueCommand("ZRANGE", key, String(start), String(stop)) { (response: RedisResponse) in
self.redisStringArrayResponseHandler(response, callback: callback)
}
}
/// Return a range of members in a sorted set, by lexicographical range.
///
/// - Parameter key: The key.
/// - Parameter min: The minimum score to return from the set.
/// - Parameter max: The maximum score to return from the set.
/// - Parameter callback: The callback function, the Array will contain the list of elements
/// in the specified score range.
/// NSError will be non-nil if an error occurred.
public func zrangebylex(_ key: String, min: String, max: String, callback: ([RedisString?]?, NSError?) -> Void) {
issueCommand("ZRANGEBYLEX", key, min, max) { (response: RedisResponse) in
self.redisStringArrayResponseHandler(response, callback: callback)
}
}
/// Return a range of members in a sorted set, by score.
///
/// - Parameter key: The key.
/// - Parameter min: The minimum score to return from the set.
/// - Parameter max: The maximum score to return from the set.
/// - Parameter callback: The callback function, list of elements in the specified score range
/// (optionally their scores)
/// NSError will be non-nil if an error occurred.
public func zrangebyscore(_ key: String, min: String, max: String, callback: ([RedisString?]?, NSError?) -> Void) {
issueCommand("ZRANGEBYSCORE", min, max) { (response: RedisResponse) in
self.redisStringArrayResponseHandler(response, callback: callback)
}
}
/// Determine the index of a member in a sorted set.
///
/// - Parameter key: The key.
/// - Parameter member: The member to get the rank of.
/// - Parameter callback: The callback function, the Int will conatain the rank of the member,
/// If member or key does not exist returns nil.
/// NSError will be non-nil if an error occurred.
public func zrank(_ key: String, member: String, callback: (Int?, NSError?) -> Void) {
issueCommand("ZRANK", key, member) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Determine the index of a member in a sorted set.
///
/// - Parameter key: The key.
/// - Parameter member: The member to get the rank of.
/// - Parameter callback: The callback function, the Int will conatain the rank of the member,
/// If member or key does not exist returns nil.
/// NSError will be non-nil if an error occurred.
public func zrank(_ key: String, member: RedisString, callback: (Int?, NSError?) -> Void) {
issueCommand(RedisString("ZRANK"), RedisString(key), member) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Removes the specified members from the sorted set stored at key. Non existing members are ignored.
/// An error is returned when key exists and does not hold a sorted set.
///
/// - Parameter key: The key.
/// - Parameter members: The list of the member(s) to remove.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements removed from the sorted set.
/// NSError will be non-nil if an error occurred.
public func zrem(_ key: String, members: String..., callback: (Int?, NSError?) -> Void) {
zremArrayOfMembers(key, members: members, callback: callback)
}
/// Removes the specified members from the sorted set stored at key. Non existing members are ignored.
/// An error is returned when key exists and does not hold a sorted set.
///
/// - Parameter key: The key.
/// - Parameter members: An array of the member(s) to remove.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements removed from the sorted set.
/// NSError will be non-nil if an error occurred.
public func zremArrayOfMembers(_ key: String, members: [String], callback: (Int?, NSError?) -> Void) {
var command = ["ZREM"]
command.append(key)
for element in members {
command.append(element)
}
issueCommandInArray(command) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Remove all members in a sorted set between the given lexicographical range.
///
/// - Parameter key: The key.
/// - Parameter min: The minimum score to remove from the set.
/// - Parameter max: The maximum score to remove from the set.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements removed from the sorted set.
/// NSError will be non-nil if an error occurred.
public func zremrangebylex(_ key: String, min: String, max: String, callback: (Int?, NSError?) -> Void) {
issueCommand("ZREMRANGEBYLEX", key, min, max) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Remove all members in a sorted set within the given indexes.
///
/// - Parameter key: The key.
/// - Parameter start: The starting index to remove from the set.
/// - Parameter stop: The ending index to remove from the set.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements removed from the sorted set.
/// NSError will be non-nil if an error occurred.
public func zremrangebyrank(_ key: String, start: Int, stop: Int, callback: (Int?, NSError?) -> Void) {
issueCommand("ZREMRANGEBYRANK", key, String(start), String(stop)) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Removes all elements in the sorted set stored at key with a score between a minimum and a maximum (inclusive).
///
/// - Parameter key: The key.
/// - Parameter min: The minimum score to remove from the set.
/// - Parameter max: The maximum score to remove from the set.
/// - Parameter callback: The callback function, the Int will contain the
/// number of elements removed from the sorted set.
/// NSError will be non-nil if an error occurred.
public func zremrangebyscore(_ key: String, min: String, max: String, callback: (_ nElements: Int?, _ error: NSError?) -> Void) {
issueCommand("ZREMRANGEBYSCORE", key, min, max) { (response) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Return a range of members in a sorted set, by index, with scores ordered from high to low
///
/// - Parameter key: The key.
/// - Parameter start: The starting index to return from the set.
/// - Parameter stop: The stoping index to return from the set.
/// - Parameter withscores: Whether or not to return scores as well.
/// - Parameter callback: The callback function, the Array will conatian the list of elements
/// in the specified range (optionally with their scores).
/// NSError will be non-nil if an error occurred.
public func zrevrange(_ key: String, start: Int, stop: Int, withscores: Bool = false, callback: ([RedisString?]?, NSError?) -> Void) {
if !withscores {
issueCommand("ZREVRANGE", key, String(start), String(stop)) { (response: RedisResponse) in
self.redisStringArrayResponseHandler(response, callback: callback)
}
} else {
issueCommand("ZREVRANGE", key, String(start), String(stop), "WITHSCORES") { (response: RedisResponse) in
self.redisStringArrayResponseHandler(response, callback: callback)
}
}
}
/// Return a range of members in a sorted set, by lexicographical range,
/// ordered from higher to lower strings.
///
/// - Parameter key: The key.
/// - Parameter min: The minimum score to return from the set.
/// - Parameter max: The maximum score to return from the set.
/// - Parameter callback: The callback function, the Array will conatian the list of elements
/// in the specified lexicographical range.
/// NSError will be non-nil if an error occurred.
public func zrevrangebylex(_ key: String, min: String, max: String, callback: ([RedisString?]?, NSError?) -> Void) {
issueCommand("ZREVRANGEBYLEX", key, min, max) { (response: RedisResponse) in
self.redisStringArrayResponseHandler(response, callback: callback)
}
}
/// Return a range of members in a sorted set, by score, with scores ordered from high to low.
///
/// - Parameter key: The key.
/// - Parameter max: The minimum score to return from the set.
/// - Parameter min: The maximum score to return from the set.
/// - Parameter withscores: The bool whether to return the scores as well
/// - Parameter callback: The callback function, the Array will conatian the list of elements
/// in the specified score range (optionally with their scores)
/// NSError will be non-nil if an error occurred.
public func zrevrangebyscore(_ key: String, min: String, max: String, withscores: Bool = false, callback: ([RedisString?]?, NSError?) -> Void) {
if !withscores {
issueCommand("ZREVRANGEBYSCORE", key, max, min) { (response: RedisResponse) in
self.redisStringArrayResponseHandler(response, callback: callback)
}
} else {
issueCommand("ZREVRANGEBYSCORE", key, max, min, "WITHSCORES") { (response: RedisResponse) in
self.redisStringArrayResponseHandler(response, callback: callback)
}
}
}
/// Determine the index of a member in a sorted set, with scores ordered from high to low.
///
/// - Parameter key: The key.
/// - Parameter member: The member to get the rank of.
/// - Parameter callback: The callback function, the Int will contain the rank of the member
/// when the set is in reverse order.
/// If member does not exist in the sorted set or key does not exist
/// returns nil.
/// NSError will be non-nil if an error occurred.
public func zrevrank(_ key: String, member: String, callback: (Int?, NSError?) -> Void) {
issueCommand("ZREVRANK", key, member) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Incrementally iterate sorted sets elements and associated scores.
///
/// - Parameter key: The key.
/// - Parameter cursor: iterator
/// - Parameter match: glob-style pattern
/// - parameter count: The amount of work that should be done at every call in order
/// to retrieve elements from the collection.
/// - Parameter callback: The callback function, the `RedisString` will contain
/// the cursor to use to continue the scan, the Array<RedisString>
/// will contain the found elements.
/// NSError will be non-nil if an error occurred.
public func zscan(_ key: String, cursor: Int, match: String? = nil, count: Int? = nil,
callback: (RedisString?, [RedisString?]?, NSError?) -> Void) {
let ZSCAN = "ZSCAN"
let MATCH = "MATCH"
let COUNT = "COUNT"
if let match = match, let count = count {
issueCommand(ZSCAN, key, String(cursor), MATCH, match, COUNT, String(count)) {(response: RedisResponse) in
self.redisScanResponseHandler(response, callback: callback)
}
} else if let match = match {
issueCommand(ZSCAN, key, String(cursor), MATCH, match) {(response: RedisResponse) in
self.redisScanResponseHandler(response, callback: callback)
}
} else if let count = count {
issueCommand(ZSCAN, key, String(cursor), COUNT, String(count)) {(response: RedisResponse) in
self.redisScanResponseHandler(response, callback: callback)
}
} else {
issueCommand(ZSCAN, key, String(cursor)) {(response: RedisResponse) in
self.redisScanResponseHandler(response, callback: callback)
}
}
}
/// Incrementally iterate sorted sets elements and associated scores.
///
/// - Parameter key: The key.
/// - Parameter cursor: iterator
/// - Parameter match: glob-style pattern
/// - parameter count: The amount of work that should be done at every call in order
/// to retrieve elements from the collection.
/// - Parameter callback: The callback function, the `RedisString` will contain
/// the cursor to use to continue the scan, the Array<RedisString>
/// will contain the found elements.
/// NSError will be non-nil if an error occurred.
public func zscan(_ key: RedisString, cursor: Int, match: RedisString? = nil, count: Int? = nil,
callback: (RedisString?, [RedisString?]?, NSError?) -> Void) {
let ZSCAN = RedisString("ZSCAN")
let MATCH = RedisString("MATCH")
let COUNT = RedisString("COUNT")
if let match = match, let count = count {
issueCommand(ZSCAN, key, RedisString(cursor), MATCH, match, COUNT, RedisString(count)) {(response: RedisResponse) in
self.redisScanResponseHandler(response, callback: callback)
}
} else if let match = match {
issueCommand(ZSCAN, key, RedisString(cursor), MATCH, match) {(response: RedisResponse) in
self.redisScanResponseHandler(response, callback: callback)
}
} else if let count = count {
issueCommand(ZSCAN, key, RedisString(cursor), COUNT, RedisString(count)) {(response: RedisResponse) in
self.redisScanResponseHandler(response, callback: callback)
}
} else {
issueCommand(ZSCAN, key, RedisString(cursor)) {(response: RedisResponse) in
self.redisScanResponseHandler(response, callback: callback)
}
}
}
/// Get the score associated with the given member in a sorted set.
///
/// - Parameter key: The key.
/// - Parameter member: The member to get the score from.
/// - Parameter callback: The callback function, the RedisString will contain
/// the score of member.
/// NSError will be non-nil if an error occurred.
public func zscore(_ key: String, member: String, callback: (RedisString?, NSError?) -> Void) {
issueCommand("ZSCORE", key, member) { (response: RedisResponse) in
self.redisStringResponseHandler(response, callback: callback)
}
}
/// Get the score associated with the given member in a sorted set.
///
/// - Parameter key: The key.
/// - Parameter member: The member to get the score from.
/// - Parameter callback: The callback function, the RedisString will contain
/// the score of member.
/// NSError will be non-nil if an error occurred.
public func zscore(_ key: String, member: RedisString, callback: (RedisString?, NSError?) -> Void) {
issueCommand(RedisString("ZSCORE"), RedisString(key), member) { (response: RedisResponse) in
self.redisStringResponseHandler(response, callback: callback)
}
}
/// Add multiple sorted sets and store the resulting sorted set in a new key
///
/// - Parameter destination: The destination where the result will be stored.
/// - Parameter numkeys: The number of keys to union.
/// - Parameter keys: The keys.
/// - Parameter weights: A multiplication factor for each input sorted set.
/// - Parameter aggregate: Specify how the results of the union are aggregated.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the resulting sorted set at destination.
/// NSError will be non-nil if an error occured.
public func zunionstore(_ destination: String, numkeys: Int, keys: String..., weights: [Int] = [], aggregate: String = "", callback: (Int?, NSError?) -> Void) {
zunionstoreWithArray(destination, numkeys: numkeys, keys: keys, weights: weights, aggregate: aggregate, callback: callback)
}
/// Add multiple sorted sets and store the resulting sorted set in a new key
///
/// - Parameter destination: The destination where the result will be stored.
/// - Parameter numkeys: The number of keys to union.
/// - Parameter keys: The keys.
/// - Parameter weights: A multiplication factor for each input sorted set.
/// - Parameter aggregate: Specify how the results of the union are aggregated.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the resulting sorted set at destination.
/// NSError will be non-nil if an error occured.
public func zunionstoreWithArray(_ destination: String, numkeys: Int, keys: [String], weights: [Int], aggregate: String, callback: (Int?, NSError?) -> Void) {
let command = appendValues(operation: "ZUNIONSTORE", destination, numkeys: numkeys, keys: keys, weights: weights, aggregate: aggregate)
issueCommandInArray(command) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
/// Add multiple sorted sets and store the resulting sorted set in a new key
///
/// - Parameter destination: The destination where the result will be stored.
/// - Parameter numkeys: The number of keys to union.
/// - Parameter keys: The keys.
/// - Parameter weights: A multiplication factor for each input sorted set.
/// - Parameter aggregate: Specify how the results of the union are aggregated.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the resulting sorted set at destination.
/// NSError will be non-nil if an error occured.
public func zunionstore(_ destination: String, numkeys: Int, keys: RedisString..., weights: [Int] = [], aggregate: RedisString = RedisString(""), callback: (Int?, NSError?) -> Void) {
zunionstoreWithArray(destination, numkeys: numkeys, keys: keys, weights: weights, aggregate: aggregate, callback: callback)
}
/// Add multiple sorted sets and store the resulting sorted set in a new key
///
/// - Parameter destination: The destination where the result will be stored.
/// - Parameter numkeys: The number of keys to union.
/// - Parameter keys: The keys.
/// - Parameter weights: A multiplication factor for each input sorted set.
/// - Parameter aggregate: Specify how the results of the union are aggregated.
/// - Parameter callback: The callback function, the Int will contain the number of elements
/// in the resulting sorted set at destination.
/// NSError will be non-nil if an error occured.
public func zunionstoreWithArray(_ destination: String, numkeys: Int, keys: [RedisString], weights: [Int], aggregate: RedisString, callback: (Int?, NSError?) -> Void) {
let command = appendValues(operation: "ZUNIONSTORE", destination, numkeys: numkeys, keys: keys, weights: weights, aggregate: aggregate)
issueCommandInArray(command) { (response: RedisResponse) in
self.redisIntegerResponseHandler(response, callback: callback)
}
}
//Appends all the values into a String array ready to be used for issueCommandInArray()
private func appendValues(operation: String, _ destination: String, numkeys: Int, keys: [String], weights: [Int], aggregate: String) -> [String] {
var command = [operation]
command.append(destination)
command.append(String(numkeys))
for key in keys {
command.append(key)
}
if weights.count > 0 {
command.append("WEIGHTS")
for weight in weights {
command.append(String(weight))
}
}
if aggregate != "" {
command.append("AGGREGATE")
command.append(aggregate)
}
return command
}
//Appends all the values into a RedisString array ready to be used for issueCommandInArray()
private func appendValues(operation: String, _ destination: String, numkeys: Int, keys: [RedisString], weights: [Int], aggregate: RedisString) -> [RedisString] {
var command = [RedisString(operation)]
command.append(RedisString(destination))
command.append(RedisString(numkeys))
for key in keys {
command.append(key)
}
if weights.count > 0 {
command.append(RedisString("WEIGHTS"))
for weight in weights {
command.append(RedisString(weight))
}
}
if aggregate != RedisString("") {
command.append(RedisString("AGGREGATE"))
command.append(aggregate)
}
return command
}
}
|
mit
|
750d782507dfa3d41fc406256343bcef
| 53.697853 | 187 | 0.625158 | 4.66183 | false | false | false | false |
petester42/Natalie
|
natalie.swift
|
1
|
46131
|
#!/usr/bin/env xcrun -sdk macosx swift
//
// Natalie - Storyboard Generator Script
//
// Generate swift file based on storyboard files
//
// Usage:
// natalie.swift Main.storyboard > Storyboards.swift
// natalie.swift path/toproject/with/storyboards > Storyboards.swift
//
// Licence: MIT
// Author: Marcin Krzyżanowski http://blog.krzyzanowskim.com
//
//MARK: SWXMLHash
//
// SWXMLHash.swift
//
// Copyright (c) 2014 David Mohundro
//
// 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
//MARK: Extensions
public extension String {
var trimAllWhitespacesAndSpecialCharacters: String {
let invalidCharacters = NSCharacterSet.alphanumericCharacterSet().invertedSet
let x = self.componentsSeparatedByCharactersInSet(invalidCharacters)
return "".join(x)
}
}
//MARK: Parser
let rootElementName = "SWXMLHash_Root_Element"
/// Simple XML parser.
public class SWXMLHash {
/**
Method to parse XML passed in as a string.
:param: xml The XML to be parsed
:returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(xml: String) -> XMLIndexer {
return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
/**
Method to parse XML passed in as an NSData instance.
:param: xml The XML to be parsed
:returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(data: NSData) -> XMLIndexer {
var parser = XMLParser()
return parser.parse(data)
}
class public func lazy(xml: String) -> XMLIndexer {
return lazy((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
class public func lazy(data: NSData) -> XMLIndexer {
var parser = LazyXMLParser()
return parser.parse(data)
}
}
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
mutating func removeAll() {
items.removeAll(keepCapacity: false)
}
func top() -> T {
return items[items.count - 1]
}
}
class LazyXMLParser : NSObject, NSXMLParserDelegate {
override init() {
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
var elementStack = Stack<String>()
var data: NSData?
var ops: [IndexOp] = []
func parse(data: NSData) -> XMLIndexer {
self.data = data
return XMLIndexer(self)
}
func startParsing(ops: [IndexOp]) {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
root = XMLElement(name: rootElementName)
parentStack.push(root)
self.ops = ops
let parser = NSXMLParser(data: data!)
parser.delegate = self
parser.parse()
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
elementStack.push(elementName)
if !onMatch() {
return
}
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String?) {
if !onMatch() {
return
}
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string!
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
let match = onMatch()
elementStack.pop()
if match {
parentStack.pop()
}
}
func onMatch() -> Bool {
// we typically want to compare against the elementStack to see if it matches ops, *but*
// if we're on the first element, we'll instead compare the other direction.
if elementStack.items.count > ops.count {
return startsWith(elementStack.items, ops.map { $0.key })
}
else {
return startsWith(ops.map { $0.key }, elementStack.items)
}
}
}
/// The implementation of NSXMLParserDelegate and where the parsing actually happens.
class XMLParser : NSObject, NSXMLParserDelegate {
override init() {
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
func parse(data: NSData) -> XMLIndexer {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
parentStack.push(root)
let parser = NSXMLParser(data: data)
parser.delegate = self
parser.parse()
return XMLIndexer(root)
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String?) {
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string!
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
parentStack.pop()
}
}
public class IndexOp {
var index: Int
let key: String
init(_ key: String) {
self.key = key
self.index = -1
}
func toString() -> String {
if index >= 0 {
return key + " " + index.description
}
return key
}
}
public class IndexOps {
var ops: [IndexOp] = []
let parser: LazyXMLParser
init(parser: LazyXMLParser) {
self.parser = parser
}
func findElements() -> XMLIndexer {
parser.startParsing(ops)
let indexer = XMLIndexer(parser.root)
var childIndex = indexer
for op in ops {
childIndex = childIndex[op.key]
if op.index >= 0 {
childIndex = childIndex[op.index]
}
}
ops.removeAll(keepCapacity: false)
return childIndex
}
func stringify() -> String {
var s = ""
for op in ops {
s += "[" + op.toString() + "]"
}
return s
}
}
/// Returned from SWXMLHash, allows easy element lookup into XML data.
public enum XMLIndexer : SequenceType {
case Element(XMLElement)
case List([XMLElement])
case Stream(IndexOps)
case Error(NSError)
/// The underlying XMLElement at the currently indexed level of XML.
public var element: XMLElement? {
get {
switch self {
case .Element(let elem):
return elem
case .Stream(let ops):
let list = ops.findElements()
return list.element
default:
return nil
}
}
}
/// All elements at the currently indexed level
public var all: [XMLIndexer] {
get {
switch self {
case .List(let list):
var xmlList = [XMLIndexer]()
for elem in list {
xmlList.append(XMLIndexer(elem))
}
return xmlList
case .Element(let elem):
return [XMLIndexer(elem)]
case .Stream(let ops):
let list = ops.findElements()
return list.all
default:
return []
}
}
}
/// All child elements from the currently indexed level
public var children: [XMLIndexer] {
get {
var list = [XMLIndexer]()
for elem in all.map({ $0.element! }) {
for elem in elem.children {
list.append(XMLIndexer(elem))
}
}
return list
}
}
/**
Allows for element lookup by matching attribute values.
:param: attr should the name of the attribute to match on
:param: _ should be the value of the attribute to match on
:returns: instance of XMLIndexer
*/
public func withAttr(attr: String, _ value: String) -> XMLIndexer {
let attrUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"]"]
let valueUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"]
switch self {
case .Stream(let opStream):
opStream.stringify()
let match = opStream.findElements()
return match.withAttr(attr, value)
case .List(let list):
if let elem = list.filter({$0.attributes[attr] == value}).first {
return .Element(elem)
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo))
case .Element(let elem):
if let attr = elem.attributes[attr] {
if attr == value {
return .Element(elem)
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo))
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo))
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo))
}
}
/**
Initializes the XMLIndexer
:param: _ should be an instance of XMLElement, but supports other values for error handling
:returns: instance of XMLIndexer
*/
public init(_ rawObject: AnyObject) {
switch rawObject {
case let value as XMLElement:
self = .Element(value)
case let value as LazyXMLParser:
self = .Stream(IndexOps(parser: value))
default:
self = .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: nil))
}
}
/**
Find an XML element at the current level by element name
:param: key The element name to index by
:returns: instance of XMLIndexer to match the element (or elements) found by key
*/
public subscript(key: String) -> XMLIndexer {
get {
let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect key [\"\(key)\"]"]
switch self {
case .Stream(let opStream):
let op = IndexOp(key)
opStream.ops.append(op)
return .Stream(opStream)
case .Element(let elem):
let match = elem.children.filter({ $0.name == key })
if match.count > 0 {
if match.count == 1 {
return .Element(match[0])
}
else {
return .List(match)
}
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
}
}
/**
Find an XML element by index within a list of XML Elements at the current level
:param: index The 0-based index to index by
:returns: instance of XMLIndexer to match the element (or elements) found by key
*/
public subscript(index: Int) -> XMLIndexer {
get {
let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect index [\"\(index)\"]"]
switch self {
case .Stream(let opStream):
opStream.ops[opStream.ops.count - 1].index = index
return .Stream(opStream)
case .List(let list):
if index <= list.count {
return .Element(list[index])
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
case .Element(let elem):
if index == 0 {
return .Element(elem)
}
else {
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
}
}
typealias GeneratorType = XMLIndexer
public func generate() -> IndexingGenerator<[XMLIndexer]> {
return all.generate()
}
}
/// XMLIndexer extensions
extension XMLIndexer: BooleanType {
/// True if a valid XMLIndexer, false if an error type
public var boolValue: Bool {
get {
switch self {
case .Error:
return false
default:
return true
}
}
}
}
extension XMLIndexer: Printable {
public var description: String {
get {
switch self {
case .List(let list):
return "\n".join(list.map { $0.description })
case .Element(let elem):
if elem.name == rootElementName {
return "\n".join(elem.children.map { $0.description })
}
return elem.description
default:
return ""
}
}
}
}
/// Models an XML element, including name, text and attributes
public class XMLElement {
/// The name of the element
public let name: String
/// The inner text of the element, if it exists
public var text: String?
/// The attributes of the element
public var attributes = [String:String]()
var children = [XMLElement]()
var count: Int = 0
var index: Int
/**
Initialize an XMLElement instance
:param: name The name of the element to be initialized
:returns: a new instance of XMLElement
*/
init(name: String, index: Int = 0) {
self.name = name
self.index = index
}
/**
Adds a new XMLElement underneath this instance of XMLElement
:param: name The name of the new element to be added
:param: withAttributes The attributes dictionary for the element being added
:returns: The XMLElement that has now been added
*/
func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement {
let element = XMLElement(name: name, index: count)
count++
children.append(element)
for (keyAny,valueAny) in attributes {
let key = keyAny as! String
let value = valueAny as! String
element.attributes[key] = value
}
return element
}
}
extension XMLElement: Printable {
public var description:String {
get {
var attributesStringList = [String]()
if !attributes.isEmpty {
for (key, val) in attributes {
attributesStringList.append("\(key)=\"\(val)\"")
}
}
var attributesString = " ".join(attributesStringList)
if (!attributesString.isEmpty) {
attributesString = " " + attributesString
}
if children.count > 0 {
var xmlReturn = [String]()
xmlReturn.append("<\(name)\(attributesString)>")
for child in children {
xmlReturn.append(child.description)
}
xmlReturn.append("</\(name)>")
return "\n".join(xmlReturn)
}
if text != nil {
return "<\(name)\(attributesString)>\(text!)</\(name)>"
}
else {
return "<\(name)\(attributesString)/>"
}
}
}
}
//MARK: - Natalie
//MARK: Objects
enum OS: String, Printable {
case iOS = "iOS"
case OSX = "OSX"
static let allValues = [iOS, OSX]
enum Runtime: String {
case iOSCocoaTouch = "iOS.CocoaTouch"
case MacOSXCocoa = "MacOSX.Cocoa"
init(os: OS) {
switch os {
case iOS:
self = .iOSCocoaTouch
case OSX:
self = .MacOSXCocoa
}
}
}
enum Framework: String {
case UIKit = "UIKit"
case Cocoa = "Cocoa"
init(os: OS) {
switch os {
case iOS:
self = .UIKit
case OSX:
self = .Cocoa
}
}
}
init(targetRuntime: String) {
switch (targetRuntime) {
case Runtime.iOSCocoaTouch.rawValue:
self = .iOS
case Runtime.MacOSXCocoa.rawValue:
self = .OSX
case "iOS.CocoaTouch.iPad":
self = iOS
default:
fatalError("Unsupported")
}
}
var description: String {
return self.rawValue
}
var framework: String {
return Framework(os: self).rawValue
}
var targetRuntime: String {
return Runtime(os: self).rawValue
}
var storyboardType: String {
switch self {
case iOS:
return "UIStoryboard"
case OSX:
return "NSStoryboard"
}
}
var storyboardSegueType: String {
switch self {
case iOS:
return "UIStoryboardSegue"
case OSX:
return "NSStoryboardSegue"
}
}
var storyboardTypeUnwrap: String {
switch self {
case iOS:
return ""
case OSX:
return "!"
}
}
var storyboardSegueUnwrap: String {
switch self {
case iOS:
return ""
case OSX:
return "!"
}
}
var storyboardControllerTypes: [String] {
switch self {
case iOS:
return ["UIViewController"]
case OSX:
return ["NSViewController", "NSWindowController"]
}
}
var storyboardControllerSignatureType: String {
switch self {
case iOS:
return "ViewController"
case OSX:
return "Controller" // NSViewController or NSWindowController
}
}
var viewType: String {
switch self {
case iOS:
return "UIView"
case OSX:
return "NSView"
}
}
var resuableViews: [String]? {
switch self {
case iOS:
return ["UICollectionReusableView","UITableViewCell"]
case OSX:
return nil
}
}
var storyboardControllerReturnType: String {
switch self {
case iOS:
return "UIViewController"
case OSX:
return "AnyObject" // NSViewController or NSWindowController
}
}
var storyboardControllerInitialReturnTypeCast: String {
switch self {
case iOS:
return "as? \(self.storyboardControllerReturnType)"
case OSX:
return ""
}
}
var storyboardControllerReturnTypeCast: String {
switch self {
case iOS:
return " as! \(self.storyboardControllerReturnType)"
case OSX:
return "!"
}
}
func storyboardControllerInitialReturnTypeCast(initialClass: String) -> String {
switch self {
case iOS:
return "as! \(initialClass)"
case OSX:
return ""
}
}
func controllerTypeForElementName(name: String) -> String? {
switch self {
case iOS:
switch name {
case "navigationController":
return "UINavigationController"
case "tableViewController":
return "UITableViewController"
case "tabBarController":
return "UITabBarController"
case "splitViewController":
return "UISplitViewController"
case "pageViewController":
return "UIPageViewController"
default:
return nil
}
case OSX:
switch name {
case "pagecontroller":
return "NSPageController"
case "tabViewController":
return "NSTabViewController"
case "splitViewController":
return "NSSplitViewController"
default:
return nil
}
}
}
}
class XMLObject {
var xml: XMLIndexer
lazy var name: String? = self.xml.element?.name
init(xml: XMLIndexer) {
self.xml = xml
}
func searchAll(attributeKey: String, attributeValue: String? = nil) -> [XMLIndexer]? {
return searchAll(self.xml, attributeKey: attributeKey, attributeValue: attributeValue)
}
func searchAll(root: XMLIndexer, attributeKey: String, attributeValue: String? = nil) -> [XMLIndexer]? {
var result = Array<XMLIndexer>()
for child in root.children {
for childAtLevel in child.all {
if let attributeValue = attributeValue {
if let element = childAtLevel.element where element.attributes[attributeKey] == attributeValue {
result += [childAtLevel]
}
} else if let element = childAtLevel.element where element.attributes[attributeKey] != nil {
result += [childAtLevel]
}
if let found = searchAll(childAtLevel, attributeKey: attributeKey, attributeValue: attributeValue) {
result += found
}
}
}
return result.count > 0 ? result : nil
}
func searchNamed(name: String) -> [XMLIndexer]? {
return self.searchNamed(self.xml, name: name)
}
func searchNamed(root: XMLIndexer, name: String) -> [XMLIndexer]? {
var result = Array<XMLIndexer>()
for child in root.children {
for childAtLevel in child.all {
if let elementName = childAtLevel.element?.name where elementName == name {
result += [child]
}
if let found = searchNamed(childAtLevel, name: name) {
result += found
}
}
}
return result.count > 0 ? result : nil
}
func searchById(id: String) -> XMLIndexer? {
return searchAll("id", attributeValue: id)?.first
}
}
class Scene: XMLObject {
lazy var viewController: ViewController? = {
if let vcs = self.searchAll("sceneMemberID", attributeValue: "viewController"), vc = vcs.first {
return ViewController(xml: vc)
}
return nil
}()
lazy var segues: [Segue]? = {
return self.searchNamed("segue")?.map { Segue(xml: $0) }
}()
lazy var customModule: String? = self.viewController?.customModule
lazy var customModuleProvider: String? = self.viewController?.customModuleProvider
}
class ViewController: XMLObject {
lazy var customClass: String? = self.xml.element?.attributes["customClass"]
lazy var customModuleProvider: String? = self.xml.element?.attributes["customModuleProvider"]
lazy var storyboardIdentifier: String? = self.xml.element?.attributes["storyboardIdentifier"]
lazy var customModule: String? = self.xml.element?.attributes["customModule"]
lazy var reusables: [Reusable]? = {
if let reusables = self.searchAll(self.xml, attributeKey: "reuseIdentifier"){
return reusables.map { Reusable(xml: $0) }
}
return nil
}()
}
class Segue: XMLObject {
lazy var identifier: String? = self.xml.element?.attributes["identifier"]
lazy var kind: String? = self.xml.element?.attributes["kind"]
lazy var destination: String? = self.xml.element?.attributes["destination"]
}
class Reusable: XMLObject {
lazy var reuseIdentifier: String? = self.xml.element?.attributes["reuseIdentifier"]
lazy var customClass: String? = self.xml.element?.attributes["customClass"]
lazy var kind: String? = self.xml.element?.name
}
class Storyboard: XMLObject {
lazy var os:OS = self.initOS() ?? OS.iOS
private func initOS() -> OS? {
if let targetRuntime = self.xml["document"].element?.attributes["targetRuntime"] {
return OS(targetRuntime: targetRuntime)
}
return nil
}
lazy var initialViewControllerClass: String? = self.initInitialViewControllerClass()
private func initInitialViewControllerClass() -> String? {
if let initialViewControllerId = xml["document"].element?.attributes["initialViewController"],
xmlVC = searchById(initialViewControllerId)
{
let vc = ViewController(xml: xmlVC)
if let customClassName = vc.customClass {
return customClassName
}
if let name = vc.name, controllerType = os.controllerTypeForElementName(name) {
return controllerType
}
}
return nil
}
lazy var version: String? = self.xml["document"].element?.attributes["version"]
lazy var scenes: [Scene] = {
if let scenes = self.searchAll(self.xml, attributeKey: "sceneID"){
return scenes.map { Scene(xml: $0) }
}
return []
}()
lazy var customModules: [String] = self.scenes.filter{ $0.customModule != nil && $0.customModuleProvider == nil }.map{ $0.customModule! }
func processStoryboard(storyboardName: String, os: OS) {
println()
println(" struct \(storyboardName) {")
println()
println(" static let identifier = \"\(storyboardName)\"")
println()
println(" static var storyboard: \(os.storyboardType) {")
println(" return \(os.storyboardType)(name: self.identifier, bundle: nil)\(os.storyboardTypeUnwrap)")
println(" }")
if let initialViewControllerClass = self.initialViewControllerClass {
println()
println(" static func instantiateInitial\(os.storyboardControllerSignatureType)() -> \(initialViewControllerClass)! {")
println(" return self.storyboard.instantiateInitial\(os.storyboardControllerSignatureType)() \(os.storyboardControllerInitialReturnTypeCast(initialViewControllerClass))")
println(" }")
}
println()
println(" static func instantiate\(os.storyboardControllerSignatureType)WithIdentifier(identifier: String) -> \(os.storyboardControllerReturnType) {")
println(" return self.storyboard.instantiate\(os.storyboardControllerSignatureType)WithIdentifier(identifier)\(os.storyboardControllerReturnTypeCast)")
println(" }")
for scene in self.scenes {
if let viewController = scene.viewController, customClass = viewController.customClass, storyboardIdentifier = viewController.storyboardIdentifier {
println()
println(" static func instantiate\(storyboardIdentifier.trimAllWhitespacesAndSpecialCharacters)() -> \(customClass)! {")
println(" return self.storyboard.instantiate\(os.storyboardControllerSignatureType)WithIdentifier(\"\(storyboardIdentifier)\") as! \(customClass)")
println(" }")
}
}
println(" }")
}
func processViewControllers() {
for scene in self.scenes {
if let viewController = scene.viewController {
if let customClass = viewController.customClass {
println()
println("//MARK: - \(customClass)")
if let segues = scene.segues?.filter({ return $0.identifier != nil })
where segues.count > 0 {
println("extension \(os.storyboardSegueType) {")
println(" func selection() -> \(customClass).Segue? {")
println(" if let identifier = self.identifier {")
println(" return \(customClass).Segue(rawValue: identifier)")
println(" }")
println(" return nil")
println(" }")
println("}")
println()
}
if let segues = scene.segues?.filter({ return $0.identifier != nil })
where segues.count > 0 {
println("extension \(customClass) { ")
println()
println(" enum Segue: String, Printable, SegueProtocol {")
for segue in segues {
if let identifier = segue.identifier
{
println(" case \(identifier.trimAllWhitespacesAndSpecialCharacters) = \"\(identifier)\"")
}
}
println()
println(" var kind: SegueKind? {")
println(" switch (self) {")
for segue in segues {
if let identifier = segue.identifier, kind = segue.kind {
println(" case \(identifier.trimAllWhitespacesAndSpecialCharacters):")
println(" return SegueKind(rawValue: \"\(kind)\")")
}
}
println(" default:")
println(" preconditionFailure(\"Invalid value\")")
println(" break")
println(" }")
println(" }")
println()
println(" var destination: \(self.os.storyboardControllerReturnType).Type? {")
println(" switch (self) {")
for segue in segues {
if let identifier = segue.identifier, destination = segue.destination,
destinationCustomClass = searchById(destination)?.element?.attributes["customClass"]
{
println(" case \(identifier.trimAllWhitespacesAndSpecialCharacters):")
println(" return \(destinationCustomClass).self")
}
}
println(" default:")
println(" assertionFailure(\"Unknown destination\")")
println(" return nil")
println(" }")
println(" }")
println()
println(" var identifier: String? { return self.description } ")
println(" var description: String { return self.rawValue }")
println(" }")
println()
println("}")
}
if let reusables = viewController.reusables?.filter({ return $0.reuseIdentifier != nil })
where reusables.count > 0 {
println("extension \(customClass) { ")
println()
println(" enum Reusable: String, Printable, ReusableViewProtocol {")
for reusable in reusables {
if let identifier = reusable.reuseIdentifier
{
println(" case \(identifier) = \"\(identifier)\"")
}
}
println()
println(" var kind: ReusableKind? {")
println(" switch (self) {")
for reusable in reusables {
if let identifier = reusable.reuseIdentifier, kind = reusable.kind {
println(" case \(identifier):")
println(" return ReusableKind(rawValue: \"\(kind)\")")
}
}
println(" default:")
println(" preconditionFailure(\"Invalid value\")")
println(" break")
println(" }")
println(" }")
println()
println(" var viewType: \(self.os.viewType).Type? {")
println(" switch (self) {")
for reusable in reusables {
if let identifier = reusable.reuseIdentifier, customClass = reusable.customClass
{
println(" case \(identifier):")
println(" return \(customClass).self")
}
}
println(" default:")
println(" return nil")
println(" }")
println(" }")
println()
println(" var identifier: String? { return self.description } ")
println(" var description: String { return self.rawValue }")
println(" }")
println()
println("}\n")
}
}
}
}
}
}
class StoryboardFile {
let filePath: String
init(filePath: String){
self.filePath = filePath
}
lazy var storyboardName: String = self.filePath.lastPathComponent.stringByDeletingPathExtension
lazy var data: NSData? = NSData(contentsOfFile: self.filePath)
lazy var xml: XMLIndexer? = {
if let d = self.data {
return SWXMLHash.parse(d)
}
return nil
}()
lazy var storyboard: Storyboard? = {
if let xml = self.xml {
return Storyboard(xml:xml)
}
return nil
}()
}
//MARK: Functions
func findStoryboards(rootPath: String, suffix: String) -> [String]? {
var result = Array<String>()
let fm = NSFileManager.defaultManager()
var error:NSError?
if let paths = fm.subpathsAtPath(rootPath) as? [String] {
let storyboardPaths = paths.filter({ return $0.hasSuffix(suffix)})
// result = storyboardPaths
for p in storyboardPaths {
result.append(rootPath.stringByAppendingPathComponent(p))
}
}
return result.count > 0 ? result : nil
}
func processStoryboards(storyboards: [StoryboardFile], os: OS) {
println("//")
println("// Autogenerated by Natalie - Storyboard Generator Script.")
println("// http://blog.krzyzanowskim.com")
println("//")
println()
println("import \(os.framework)")
let modules = storyboards.filter{ $0.storyboard != nil }.flatMap{ $0.storyboard!.customModules }
for module in Set<String>(modules) {
println("import \(module)")
}
println()
println("//MARK: - Storyboards")
println("struct Storyboards {")
for file in storyboards {
file.storyboard?.processStoryboard(file.storyboardName, os: os)
}
println("}")
println()
println("//MARK: - ReusableKind")
println("enum ReusableKind: String, Printable {")
println(" case TableViewCell = \"tableViewCell\"")
println(" case CollectionViewCell = \"collectionViewCell\"")
println()
println(" var description: String { return self.rawValue }")
println("}")
println()
println("//MARK: - SegueKind")
println("enum SegueKind: String, Printable { ")
println(" case Relationship = \"relationship\" ")
println(" case Show = \"show\" ")
println(" case Presentation = \"presentation\" ")
println(" case Embed = \"embed\" ")
println(" case Unwind = \"unwind\" ")
println()
println(" var description: String { return self.rawValue } ")
println("}")
println()
println("//MARK: - SegueProtocol")
println("public protocol IdentifiableProtocol: Equatable {")
println(" var identifier: String? { get }")
println("}")
println()
println("public protocol SegueProtocol: IdentifiableProtocol {")
println("}")
println()
println("public func ==<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {")
println(" return lhs.identifier == rhs.identifier")
println("}")
println()
println("public func ~=<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {")
println(" return lhs.identifier == rhs.identifier")
println("}")
println()
println("public func ==<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {")
println(" return lhs.identifier == rhs")
println("}")
println()
println("public func ~=<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {")
println(" return lhs.identifier == rhs")
println("}")
println()
println("//MARK: - ReusableViewProtocol")
println("public protocol ReusableViewProtocol: IdentifiableProtocol {")
println(" var viewType: \(os.viewType).Type? {get}")
println("}")
println()
println("public func ==<T: ReusableViewProtocol, U: ReusableViewProtocol>(lhs: T, rhs: U) -> Bool {")
println(" return lhs.identifier == rhs.identifier")
println("}")
println()
println("//MARK: - Protocol Implementation")
println("extension \(os.storyboardSegueType): SegueProtocol {")
println("}")
println()
if let reusableViews = os.resuableViews {
for reusableView in reusableViews {
println("extension \(reusableView): ReusableViewProtocol {")
println(" public var viewType: UIView.Type? { return self.dynamicType}")
println(" public var identifier: String? { return self.reuseIdentifier}")
println("}")
println()
}
}
for controllerType in os.storyboardControllerTypes {
println("//MARK: - \(controllerType) extension")
println("extension \(controllerType) {")
println(" func performSegue<T: SegueProtocol>(segue: T, sender: AnyObject?) {")
println(" performSegueWithIdentifier(segue.identifier\(os.storyboardSegueUnwrap), sender: sender)")
println(" }")
println()
println(" func performSegue<T: SegueProtocol>(segue: T) {")
println(" performSegue(segue, sender: nil)")
println(" }")
println("}")
println()
}
if os == OS.iOS {
println("//MARK: - UICollectionView")
println()
println("extension UICollectionView {")
println()
println(" func dequeueReusableCell<T: ReusableViewProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> UICollectionViewCell? {")
println(" if let identifier = reusable.identifier {")
println(" return dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: forIndexPath) as? UICollectionViewCell")
println(" }")
println(" return nil")
println(" }")
println()
println(" func registerReusableCell<T: ReusableViewProtocol>(reusable: T) {")
println(" if let type = reusable.viewType, identifier = reusable.identifier {")
println(" registerClass(type, forCellWithReuseIdentifier: identifier)")
println(" }")
println(" }")
println()
println(" func dequeueReusableSupplementaryViewOfKind<T: ReusableViewProtocol>(elementKind: String, withReusable reusable: T, forIndexPath: NSIndexPath!) -> UICollectionReusableView? {")
println(" if let identifier = reusable.identifier {")
println(" return dequeueReusableSupplementaryViewOfKind(elementKind, withReuseIdentifier: identifier, forIndexPath: forIndexPath) as? UICollectionReusableView")
println(" }")
println(" return nil")
println(" }")
println()
println(" func registerReusable<T: ReusableViewProtocol>(reusable: T, forSupplementaryViewOfKind elementKind: String) {")
println(" if let type = reusable.viewType, identifier = reusable.identifier {")
println(" registerClass(type, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)")
println(" }")
println(" }")
println("}")
println("//MARK: - UITableView")
println()
println("extension UITableView {")
println()
println(" func dequeueReusableCell<T: ReusableViewProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> UITableViewCell? {")
println(" if let identifier = reusable.identifier {")
println(" return dequeueReusableCellWithIdentifier(identifier, forIndexPath: forIndexPath) as? UITableViewCell")
println(" }")
println(" return nil")
println(" }")
println()
println(" func registerReusableCell<T: ReusableViewProtocol>(reusable: T) {")
println(" if let type = reusable.viewType, identifier = reusable.identifier {")
println(" registerClass(type, forCellReuseIdentifier: identifier)")
println(" }")
println(" }")
println()
println(" func dequeueReusableHeaderFooter<T: ReusableViewProtocol>(reusable: T) -> UITableViewHeaderFooterView? {")
println(" if let identifier = reusable.identifier {")
println(" return dequeueReusableHeaderFooterViewWithIdentifier(identifier) as? UITableViewHeaderFooterView")
println(" }")
println(" return nil")
println(" }")
println()
println(" func registerReusableHeaderFooter<T: ReusableViewProtocol>(reusable: T) {")
println(" if let type = reusable.viewType, identifier = reusable.identifier {")
println(" registerClass(type, forHeaderFooterViewReuseIdentifier: identifier)")
println(" }")
println(" }")
println("}")
println()
}
for file in storyboards {
file.storyboard?.processViewControllers()
}
}
//MARK: MAIN()
if Process.arguments.count == 1 {
println("Invalid usage. Missing path to storyboard.")
exit(0)
}
let argument = Process.arguments[1]
var storyboards:[String] = []
let storyboardSuffix = ".storyboard"
if argument.hasSuffix(storyboardSuffix) {
storyboards = [argument]
} else if let s = findStoryboards(argument, storyboardSuffix) {
storyboards = s
}
let storyboardFiles: [StoryboardFile] = storyboards.map { StoryboardFile(filePath: $0) }
for os in OS.allValues {
var storyboardsForOS = storyboardFiles.filter { $0.storyboard?.os == os }
if !storyboardsForOS.isEmpty {
if storyboardsForOS.count != storyboardFiles.count {
println("#if os(\(os.rawValue))")
}
processStoryboards(storyboardsForOS, os)
if storyboardsForOS.count != storyboardFiles.count {
println("#endif")
}
}
}
|
mit
|
29aca84a9d0108266ccdf23e17586124
| 33.815094 | 197 | 0.543941 | 5.411779 | false | false | false | false |
joeytat/Gorge
|
Gorge/AddContainerView.swift
|
1
|
725
|
//
// AddContainerView.swift
// Gorge
//
// Created by Joey on 06/02/2017.
// Copyright © 2017 Joey. All rights reserved.
//
import UIKit
class AddContainerView: UIView {
@IBOutlet weak var urlLabel: UILabel!
@IBOutlet weak var addButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
layer.masksToBounds = false
layer.borderColor = Color.divider.color(alpha: 0.7).cgColor
layer.borderWidth = 0.5
layer.shadowColor = Color.darkPrimary.color(alpha: 0.5).cgColor
layer.shadowOffset = CGSize(width: 0, height: -0.5)
layer.shadowOpacity = 1.0
}
func populate(url: String) {
urlLabel.text = url
}
}
|
mit
|
22880d722e3941a0b0a3181396487097
| 23.133333 | 71 | 0.629834 | 3.978022 | false | false | false | false |
jasnig/DouYuTVMutate
|
DouYuTVMutate/DouYuTV/Main/Controller/WelcomeController.swift
|
1
|
2994
|
//
// WelcomeController.swift
// DouYuTVMutate
//
// Created by ZeroJ on 16/7/19.
// Copyright © 2016年 ZeroJ. All rights reserved.
//
import UIKit
//import IJKMediaFramework
import MediaPlayer
class WelcomeController: UIViewController {
// var player: IJKMediaPlayback!
var mediaPlayer: MPMoviePlayerController!
override func viewDidLoad() {
super.viewDidLoad()
do {
let path = NSBundle.mainBundle().pathForResource("movie.mp4", ofType: nil)
// player = IJKAVMoviePlayerController(contentURL: NSURL.fileURLWithPath(path!))
// player.view.frame = view.bounds
// view.addSubview(player.view)
// player.scalingMode = .AspectFill
// player.shouldAutoplay = true
// player.prepareToPlay()
mediaPlayer = MPMoviePlayerController(contentURL: NSURL.fileURLWithPath(path!))
mediaPlayer.shouldAutoplay = true
/// 不显示播放进度条
mediaPlayer.controlStyle = .None
mediaPlayer.scalingMode = .AspectFill
mediaPlayer.view.frame = view.bounds
view.addSubview(mediaPlayer.view)
mediaPlayer.prepareToPlay()
}
do {
let btn = UIButton(frame: CGRect(x: 0.0, y: Constant.screenHeight - 60, width: 80, height: 44))
btn.center.x = view.center.x
btn.setTitle("点击进入", forState: .Normal)
btn.addTarget(self, action: #selector(self.loginIn), forControlEvents: .TouchUpInside)
btn.backgroundColor = UIColor.blueColor()
btn.layer.cornerRadius = 20
btn.layer.masksToBounds = true
view.addSubview(btn)
}
NSNotificationCenter.defaultCenter().addObserver(self
, selector: #selector(self.didPlaybackFinish), name: MPMoviePlayerPlaybackDidFinishNotification, object: mediaPlayer)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if mediaPlayer.playbackState != .Playing {
mediaPlayer.play()
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self
, name: MPMoviePlayerPlaybackDidFinishNotification, object: mediaPlayer)
// player.shutdown()
// player = nil
mediaPlayer.stop()
mediaPlayer = nil
}
func didPlaybackFinish() {
// 重播
mediaPlayer.play()
}
func loginIn() {
let rootVc = MainTabBarController()
if let window = UIApplication.sharedApplication().keyWindow {
window.rootViewController = rootVc
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
d3afc90e4cd86d404e8b511ff64a7e78
| 31.922222 | 129 | 0.61323 | 5.108621 | false | false | false | false |
kfarst/alarm
|
alarm/ScheduleViewController.swift
|
1
|
3988
|
//
// ScheduleViewController.swift
// alarm
//
// Created by Michael Lewis on 3/10/15.
// Copyright (c) 2015 Kevin Farst. All rights reserved.
//
import UIKit
class ScheduleViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, TimePickerDelegate, DayOfWeekAlarmDelegate {
@IBOutlet weak var scheduleTableView: UITableView!
// An array of 7 TimeEntities
// One for each day of the week (Sun-Sat)
var alarmEntityArray: Array<AlarmEntity>!
// If the time picker is up, we're modifying a cell
var cellBeingChanged: ScheduleTableViewCell?
// The home view controls display of the time picker
var timePickerManagerDelegate: TimePickerManagerDelegate!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
scheduleTableView.registerNib(
UINib(
nibName: "ScheduleTableViewCell",
bundle: nil
),
forCellReuseIdentifier: "ScheduleTableViewCell"
)
scheduleTableView.delegate = self
scheduleTableView.dataSource = self
// Load in the alarms for presentation
alarmEntityArray = AlarmManager.loadAlarmsOrdered()
scheduleTableView.alwaysBounceVertical = false
scheduleTableView.separatorColor = UIColor.clearColor()
self.view.backgroundColor = UIColor.whiteColor()
scheduleTableView.backgroundColor = UIColor.whiteColor()
scheduleTableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
scheduleTableView.reloadData()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let cell = scheduleTableView.dequeueReusableCellWithIdentifier("ScheduleTableViewCell") as! ScheduleTableViewCell
let containerHeight = cell.frame.height * 7
parentViewController?.viewDidLayoutSubviews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* Table functions */
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return alarmEntityArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(
"ScheduleTableViewCell",
forIndexPath: indexPath
) as! ScheduleTableViewCell
cell.alarmEntity = alarmEntityArray[indexPath.row]
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.contentView.autoresizingMask = .FlexibleHeight
cell.delegate = self
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
NSLog("\(indexPath.row)")
}
/* Alarm cell time updating */
// Delegate of DayOfWeekAlarmDelegate
func updateTimeSelected(cell: ScheduleTableViewCell) {
// Stash the cell under change
cellBeingChanged = cell
// Get the cell's underlying alarm and trigger a picker for it
if let indexPath = scheduleTableView.indexPathForCell(cell) {
let alarmEntity = alarmEntityArray[indexPath.row]
timePickerManagerDelegate.showTimePicker(
self,
time: TimePresenter(alarmEntity: alarmEntity)
)
}
}
// Delegate callback from the time picker
func timeSelected(time: TimePresenter) {
updateCellBeingChanged(time)
timePickerManagerDelegate.dismissTimePicker()
}
/* Private */
// Update the displayed time
private func updateCellBeingChanged(time: TimePresenter) {
if let cell = cellBeingChanged {
AlarmManager.updateAlarmEntity(cell.alarmEntity, timePresenter: time)
// Update the display for the cell
cell.updateDisplay()
// Clear out our stashed cell reference
cellBeingChanged = nil
}
}
}
|
mit
|
18ef9125cebef4b60c539d7a776b998e
| 29.676923 | 136 | 0.737212 | 5.213072 | false | false | false | false |
fengxinsen/ReadX
|
ReadX/BookRoomViewController.swift
|
1
|
3568
|
//
// XViewController.swift
// ReadX
//
// Created by video on 2017/2/21.
// Copyright © 2017年 Von. All rights reserved.
//
import Cocoa
import Kanna
class BookRoomViewController: BaseViewController {
deinit {
NotificationCenter.default.removeObserver(self, name: Book_RoomRefresh_Notification, object: nil)
NotificationCenter.default.removeObserver(self, name: Book_RoomChaptersRefresh_Notification, object: nil)
}
lazy var readWC: BaseWindowController = {
return BaseWindowController()
}()
internal var datas = [Book]()
@IBOutlet weak var mTableView: NSTableView!
override func viewDidLoad() {
super.viewDidLoad()
// addBook(bookUrl: "http://baishuzhai.com/ibook/30/30144/")
// addBook(bookUrl: "http://www.qu.la/book/24868/")
NotificationCenter.default.addObserver(self, selector: #selector(notification(notification:)), name: Book_RoomRefresh_Notification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(notification(notification:)), name: Book_RoomChaptersRefresh_Notification, object: nil)
}
override func viewWillAppear() {
super.viewWillAppear()
loadData()
}
func notification(notification: Notification) {
if notification.name == Book_RoomRefresh_Notification {
loadData()
} else if notification.name == Book_RoomChaptersRefresh_Notification {
loadData()
}
}
@IBAction func tableViewAction(_ sender: NSTableView) {
let row = sender.selectedRow
print(row)
if row >= 0 && row < datas.count {
let data = self.datas[row]
openBook(book: data)
}
}
}
extension BookRoomViewController: NSTableViewDataSource {
func loadData() {
datas.removeAll()
let books = sqlite.readData()
books.forEach { (book) in
getBook(book: book, callBack: { (book) in
self.datas.append(book)
self.mTableView.reloadData()
})
}
}
func refreshData() {
datas.removeAll()
let books = sqlite.readData()
books.forEach { (book) in
BookChapters(book: book, callBack: { (chapters) in
var temp = book
temp.bookChapters = chapters
self.datas.append(book)
self.mTableView.reloadData()
})
}
}
func numberOfRows(in tableView: NSTableView) -> Int {
return self.datas.count
}
func tableViewSelectionDidChange(_ notification: Notification) {
// let tableView = notification.object as! NSTableView
// let row = tableView.selectedRow
// let data = self.datas[row]
// print(row)
//
// openBook(book: data)
}
}
extension BookRoomViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let data = self.datas[row]
let view = tableView.make(withIdentifier: "BookRoomCell", owner: self) as! BookRoomCell
view.mBook = data;
return view
}
func tableView(_ tableView: NSTableView, didClick tableColumn: NSTableColumn) {
print(tableColumn.identifier)
}
func tableView(_ tableView: NSTableView, mouseDownInHeaderOf tableColumn: NSTableColumn) {
print(tableView.selectedRow)
}
}
|
mit
|
d6f637d77ee0d03b454075d51c4dd311
| 29.470085 | 160 | 0.611501 | 4.684625 | false | false | false | false |
steveholt55/Football-College-Trivia-iOS
|
FootballCollegeTriviaTests/TitlePresenterTests.swift
|
1
|
2529
|
//
// Copyright © 2016 Brandon Jenniges. All rights reserved.
//
import XCTest
@testable import FootballCollegeTrivia
class TitlePresenterTests: XCTestCase {
var viewController: TitleViewController!
var presenter:TitlePresenter!
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
viewController = storyboard.instantiateViewControllerWithIdentifier(TitleViewController.storyboardId) as! TitleViewController
presenter = TitlePresenter(view: viewController)
viewController.presenter = presenter
}
override func tearDown() {
super.tearDown()
}
func test_init() {
XCTAssertNotNil(viewController)
XCTAssertNotNil(presenter)
}
// MARK: - GameType selection
func test_PracticeSelected() {
presenter.gameTypeSelected(.Practice, view: UIView())
XCTAssert(presenter.gameType == .Practice)
}
func test_StandardSelected() {
presenter.gameTypeSelected(.Standard, view: UIView())
XCTAssert(presenter.gameType == .Standard)
}
func test_SurvivalSelected() {
presenter.gameTypeSelected(.Survival, view: UIView())
XCTAssert(presenter.gameType == .Survival)
}
// MARK: - Difficuly selection
func test_RookieSelected() {
presenter.gameTypeSelected(.Practice, view: UIView())
self.viewController.dismissViewControllerAnimated(true, completion: nil)
self.presenter.difficultySelected(.Rookie)
XCTAssert(self.presenter.difficulty == .Rookie)
}
func test_StarterSelected() {
presenter.gameTypeSelected(.Practice, view: UIView())
self.viewController.dismissViewControllerAnimated(true, completion: nil)
presenter.difficultySelected(.Starter)
XCTAssert(presenter.difficulty == .Starter)
}
func test_VeteranSelected() {
presenter.gameTypeSelected(.Practice, view: UIView())
self.viewController.dismissViewControllerAnimated(true, completion: nil)
presenter.difficultySelected(.Veteran)
XCTAssert(presenter.difficulty == .Veteran)
}
func test_AllProSelected() {
presenter.gameTypeSelected(.Practice, view: UIView())
self.viewController.dismissViewControllerAnimated(true, completion: nil)
presenter.difficultySelected(.AllPro)
XCTAssert(presenter.difficulty == .AllPro)
}
}
|
mit
|
72e9a1e3a2f58bd74f240935c95e3d52
| 30.6125 | 133 | 0.667326 | 5.096774 | false | true | false | false |
Liangxue/DY-
|
DYZB/DYZB/Classes/Tools/Commen.swift
|
1
|
320
|
//
// Commen.swift
// DYZB
//
// Created by xue on 2017/4/10.
// Copyright © 2017年 liangxue. All rights reserved.
//
import UIKit
let kStatusBarH:CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabBarH : CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
|
mit
|
1b5aafa7064b525f16d5b6e9daabd1cb
| 15.684211 | 52 | 0.709779 | 3.336842 | false | false | false | false |
josve05a/wikipedia-ios
|
Wikipedia/Code/WKWebView+WMFWebViewControllerJavascript.swift
|
2
|
12868
|
import WebKit
import WMF
fileprivate extension Bool{
func toString() -> String {
return self ? "true" : "false"
}
}
@objc enum WMFArticleFooterMenuItem: Int {
case languages, lastEdited, pageIssues, disambiguation, coordinate, talkPage
// Reminder: These are the strings used by the footerMenu JS transform:
private var menuItemTypeString: String {
switch self {
case .languages: return "languages"
case .lastEdited: return "lastEdited"
case .pageIssues: return "pageIssues"
case .disambiguation: return "disambiguation"
case .coordinate: return "coordinate"
case .talkPage: return "talkPage"
}
}
public var menuItemTypeJSPath: String {
return "window.wmf.footerMenu.MenuItemType.\(menuItemTypeString)"
}
public func shouldAddItem(with article: MWKArticle) -> Bool {
switch self {
case .languages where !article.hasMultipleLanguages:
return false
case .pageIssues:
// Always try to add - footer menu JS will hide this if no page issues found.
return true
case .disambiguation:
// Always try to add - footer menu JS will hide this if no disambiguation titles found.
return true
case .coordinate where !CLLocationCoordinate2DIsValid(article.coordinate):
return false
default:
break
}
return true
}
}
fileprivate protocol JSONEncodable: Encodable {
}
fileprivate extension JSONEncodable {
func toJSON() -> String {
guard
let jsonData = try? JSONEncoder().encode(self),
let jsonString = String(data: jsonData, encoding: .utf8)
else {
assertionFailure("Expected JSON string")
return "{}"
}
return jsonString
}
}
fileprivate struct FooterLocalizedStrings: JSONEncodable {
var readMoreHeading: String = ""
var licenseString: String = ""
var licenseSubstitutionString: String = ""
var viewInBrowserString: String = ""
var menuHeading: String = ""
var menuLanguagesTitle: String = ""
var menuLastEditedTitle: String = ""
var menuLastEditedSubtitle: String = ""
var menuTalkPageTitle: String = ""
var menuPageIssuesTitle: String = ""
var menuDisambiguationTitle: String = ""
var menuCoordinateTitle: String = ""
init(for article: MWKArticle) {
let lang = (article.url as NSURL).wmf_language
readMoreHeading = WMFLocalizedString("article-read-more-title", language: lang, value: "Read more", comment: "The text that is displayed before the read more section at the bottom of an article {{Identical|Read more}}").uppercased(with: Locale.current)
licenseString = String.localizedStringWithFormat(WMFLocalizedString("license-footer-text", language: lang, value: "Content is available under %1$@ unless otherwise noted.", comment: "Marker at page end for who last modified the page when anonymous. %1$@ is a relative date such as '2 months ago' or 'today'."), "$1")
licenseSubstitutionString = WMFLocalizedString("license-footer-name", language: lang, value: "CC BY-SA 3.0", comment: "License short name; usually leave untranslated as CC-BY-SA 3.0 {{Identical|CC BY-SA}}")
viewInBrowserString = WMFLocalizedString("view-in-browser-footer-link", language: lang, value: "View article in browser", comment: "Link to view article in browser")
menuHeading = WMFLocalizedString("article-about-title", language: lang, value: "About this article", comment: "The text that is displayed before the 'about' section at the bottom of an article").uppercased(with: Locale.current)
menuLanguagesTitle = String.localizedStringWithFormat(WMFLocalizedString("page-read-in-other-languages", language: lang, value: "Available in {{PLURAL:%1$d|%1$d other language|%1$d other languages}}", comment: "Label for button showing number of languages an article is available in. %1$@ will be replaced with the number of languages"), article.languagecount)
let lastModified = article.lastmodified ?? Date()
let days = NSCalendar.wmf_gregorian().wmf_days(from: lastModified, to: Date())
menuLastEditedTitle = String.localizedStringWithFormat(WMFLocalizedString("page-last-edited", language: lang, value: "{{PLURAL:%1$d|0=Edited today|1=Edited yesterday|Edited %1$d days ago}}", comment: "Relative days since an article was last edited. 0 = today, singular = yesterday. %1$d will be replaced with the number of days ago."), days)
menuLastEditedSubtitle = WMFLocalizedString("page-edit-history", language: lang, value: "Full edit history", comment: "Label for button used to show an article's complete edit history")
menuTalkPageTitle = WMFLocalizedString("page-talk-page", language: lang, value: "View talk page", comment: "Label for button linking out to an article's talk page")
menuPageIssuesTitle = WMFLocalizedString("page-issues", language: lang, value: "Page issues", comment: "Label for the button that shows the \"Page issues\" dialog, where information about the imperfections of the current page is provided (by displaying the warning/cleanup templates). {{Identical|Page issue}}")
menuDisambiguationTitle = WMFLocalizedString("page-similar-titles", language: lang, value: "Similar pages", comment: "Label for button that shows a list of similar titles (disambiguation) for the current page")
menuCoordinateTitle = WMFLocalizedString("page-location", language: lang, value: "View on a map", comment: "Label for button used to show an article on the map")
}
}
fileprivate struct CollapseTablesLocalizedStrings: JSONEncodable {
var tableInfoboxTitle: String = ""
var tableOtherTitle: String = ""
var tableFooterTitle: String = ""
init(for lang: String?) {
tableInfoboxTitle = WMFLocalizedString("info-box-title", language: lang, value: "Quick Facts", comment: "The title of infoboxes – in collapsed and expanded form")
tableOtherTitle = WMFLocalizedString("table-title-other", language: lang, value: "More information", comment: "The title of non-info box tables - in collapsed and expanded form {{Identical|More information}}")
tableFooterTitle = WMFLocalizedString("info-box-close-text", language: lang, value: "Close", comment: "The text for telling users they can tap the bottom of the info box to close it {{Identical|Close}}")
}
}
extension WKWebView {
@objc static public func wmf_themeApplicationJavascript(with theme: Theme?) -> String {
var jsThemeConstant = "DEFAULT"
guard let theme = theme else {
return jsThemeConstant
}
var isDim = false
switch theme.name {
case Theme.sepia.name:
jsThemeConstant = "SEPIA"
case Theme.blackDimmed.name:
isDim = true
fallthrough
case Theme.black.name:
jsThemeConstant = "BLACK"
case Theme.darkDimmed.name:
isDim = true
fallthrough
case Theme.dark.name:
jsThemeConstant = "DARK"
default:
break
}
return """
window.wmf.themes.setTheme(document, window.wmf.themes.THEME.\(jsThemeConstant))
window.wmf.imageDimming.dim(window, \(isDim.toString()))
"""
}
@objc public func wmf_applyTheme(_ theme: Theme){
let themeJS = WKWebView.wmf_themeApplicationJavascript(with: theme)
evaluateJavaScript(themeJS, completionHandler: nil)
}
private func languageJS(for article: MWKArticle) -> String {
let lang = (article.url as NSURL).wmf_language ?? MWKLanguageLinkController.sharedInstance().appLanguage?.languageCode ?? "en"
let langInfo = MWLanguageInfo(forCode: lang)
let langCode = langInfo.code
let langDir = langInfo.dir
return """
new window.wmf.sections.Language(
'\(langCode.wmf_stringBySanitizingForJavaScript())',
'\(langDir.wmf_stringBySanitizingForJavaScript())',
\((langDir == "rtl").toString())
)
"""
}
private func articleJS(for article: MWKArticle, title: String) -> String {
let articleDisplayTitle = article.displaytitle ?? ""
let articleEntityDescription = (article.entityDescription ?? "").wmf_stringByCapitalizingFirstCharacter(usingWikipediaLanguage: article.url.wmf_language)
let addTitleDescriptionLocalizedString = WMFLocalizedString("description-add-link-title", language: (article.url as NSURL).wmf_language, value: "Add title description", comment: "Text for link for adding a title description")
return """
new window.wmf.sections.Article(
\(article.isMain.toString()),
'\(title.wmf_stringBySanitizingForJavaScript())',
'\(articleDisplayTitle.wmf_stringBySanitizingForJavaScript())',
'\(articleEntityDescription.wmf_stringBySanitizingForJavaScript())',
\(article.editable.toString()),
\(languageJS(for: article)),
'\(addTitleDescriptionLocalizedString.wmf_stringBySanitizingForJavaScript())',
\(article.isWikidataDescriptionEditable.toString())
)
"""
}
private func menuItemsJS(for article: MWKArticle) -> String {
let menuItemTypeJSPaths = [
WMFArticleFooterMenuItem.languages,
WMFArticleFooterMenuItem.coordinate,
WMFArticleFooterMenuItem.lastEdited,
WMFArticleFooterMenuItem.pageIssues,
WMFArticleFooterMenuItem.disambiguation,
WMFArticleFooterMenuItem.talkPage
]
.filter{$0.shouldAddItem(with: article)}
.map{$0.menuItemTypeJSPath}
return "[\(menuItemTypeJSPaths.joined(separator: ", "))]"
}
@objc public func wmf_fetchTransformAndAppendSectionsToDocument(_ article: MWKArticle, collapseTables: Bool, scrolledTo fragment: String?){
guard
let url = article.url,
let host = url.host,
let appSchemeURL = SchemeHandler.APIHandler.appSchemeURL(for: host, fragment: nil),
let apiURL = SchemeHandler.ArticleSectionHandler.appSchemeURL(for: url, targetImageWidth: self.traitCollection.wmf_articleImageWidth)
else {
assertionFailure("Expected url, appSchemeURL and encodedTitle")
return
}
// https://github.com/wikimedia/wikipedia-ios/pull/1334/commits/f2b2228e2c0fd852479464ec84e38183d1cf2922
let appSchemeURLString = appSchemeURL.absoluteString
let apiURLString = apiURL.absoluteString
let title = (article.url as NSURL).wmf_title ?? ""
let articleContentLoadedCallbackJS = """
() => {
const footer = new window.wmf.footers.Footer(
'\(title.wmf_stringBySanitizingForJavaScript())',
\(menuItemsJS(for: article)),
\(article.hasReadMore.toString()),
3,
\(FooterLocalizedStrings.init(for: article).toJSON()),
'\(appSchemeURLString.wmf_stringBySanitizingForJavaScript())'
)
footer.add()
window.requestAnimationFrame(() => {
window.webkit.messageHandlers.articleState.postMessage('articleContentLoaded')
})
}
"""
let sectionErrorMessageLocalizedString = WMFLocalizedString("article-unable-to-load-section", language: (article.url as NSURL).wmf_language, value: "Unable to load this section. Try refreshing the article to see if it fixes the problem.", comment: "Displayed within the article content when a section fails to render for some reason.")
evaluateJavaScript("""
window.wmf.sections.sectionErrorMessageLocalizedString = '\(sectionErrorMessageLocalizedString.wmf_stringBySanitizingForJavaScript())'
window.wmf.sections.collapseTablesLocalizedStrings = \(CollapseTablesLocalizedStrings.init(for: (article.url as NSURL).wmf_language).toJSON())
window.wmf.sections.collapseTablesInitially = \(collapseTables ? "true" : "false")
window.wmf.sections.fetchTransformAndAppendSectionsToDocument(
\(articleJS(for: article, title: title)),
'\(apiURLString.wmf_stringBySanitizingForJavaScript())',
'\((fragment ?? "").wmf_stringBySanitizingForJavaScript())',
\(articleContentLoadedCallbackJS)
)
""") { (result, error) in
guard let error = error else {
return
}
DDLogError("Error when evaluating javascript on fetch and transform: \(error)")
}
}
}
|
mit
|
58459470905db0b668ff31b84d66d830
| 51.514286 | 368 | 0.665786 | 4.716276 | false | false | false | false |
monisun/warble
|
Warble/TweetsViewController.swift
|
1
|
12317
|
//
// TweetsViewController.swift
// Warble
//
// Created by Monica Sun on 5/21/15.
// Copyright (c) 2015 Monica Sun. All rights reserved.
//
import UIKit
import Social
class TweetsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, TweetTableViewCellDelegate, UISearchBarDelegate, UISearchDisplayDelegate {
let pageIndexOffset = 199 // max allowed per Twitter API is 200
var minId: Int? // min tweet id of currently fetched tweets
let maxNumTweetsToKeepInMemory = 1000
var tweets = [Tweet]()
var refreshControl = UIRefreshControl()
var currentlySelectedTweet: Tweet?
@IBOutlet weak var searchBar: UISearchBar!
var searchActive = false
var lastSearchedTerm = String()
var searchResultTweets = [Tweet]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.titleView = searchBar
searchBar.delegate = self
searchBar.translucent = true
self.tableView.dataSource = self
self.tableView.delegate = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
// initial request for landing page
SVProgressHUD.showProgress(1, status: "Loading...")
TwitterClient.sharedInstance.homeTimelineWithParams(nil, maxId: nil, completion: { (tweets, minId, error) -> () in
if error != nil {
SVProgressHUD.dismiss()
NSLog("ERROR: TwitterClient.sharedInstance.homeTimelineWithParams: \(error)")
} else {
self.tweets = tweets!
self.tableView.reloadData()
self.minId = minId
SVProgressHUD.showSuccessWithStatus("Success")
}
})
refreshControl.addTarget(self, action: "onRefresh", forControlEvents: UIControlEvents.ValueChanged)
tableView.insertSubview(refreshControl, atIndex: 0)
}
override func viewWillAppear(animated: Bool) {
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
if tweets.count > maxNumTweetsToKeepInMemory {
tweets.removeRange(Range(start: 0, end: maxNumTweetsToKeepInMemory))
}
}
@IBAction func onLogout(sender: AnyObject) {
User.currentUser?.logout()
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false
tableView.reloadData()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = true
let searchTerms = searchBar.text
lastSearchedTerm = searchTerms
TwitterClient.sharedInstance.searchTweets(searchTerms, completion: { (tweets, minId, error) -> () in
if error != nil {
SVProgressHUD.dismiss()
NSLog("ERROR: Searching tweets with TwitterClient.sharedInstance.searchTweets: \(error)")
} else {
self.searchResultTweets = tweets!
self.tableView.reloadData()
SVProgressHUD.showSuccessWithStatus("Success")
}
})
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchActive {
return searchResultTweets.count
} else {
return tweets.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = TweetTableViewCell()
if searchActive {
if searchResultTweets.count > indexPath.row {
cell = tableView.dequeueReusableCellWithIdentifier("tweetCell", forIndexPath: indexPath) as! TweetTableViewCell
cell.tweet = searchResultTweets[indexPath.row]
cell.delegate = self
} else {
NSLog("ERROR: searchResultTweets[] does not contain index: \(indexPath.row)")
}
} else {
if tweets.count > indexPath.row {
cell = tableView.dequeueReusableCellWithIdentifier("tweetCell", forIndexPath: indexPath) as! TweetTableViewCell
cell.tweet = tweets[indexPath.row]
cell.delegate = self
} else {
NSLog("ERROR: tweets[] does not contain index: \(indexPath.row)")
}
if (indexPath.row == tweets.count - 1) || ((indexPath.row > 0) && (indexPath.row % pageIndexOffset == 0)) {
// fetch more results
let maxIdForRequest = minId! - 1
SVProgressHUD.showProgress(1, status: "Loading...")
TwitterClient.sharedInstance.homeTimelineWithParams(nil, maxId: maxIdForRequest, completion: { (tweets, minId, error) -> () in
if error != nil {
SVProgressHUD.dismiss()
NSLog("ERROR: Fetching more results with TwitterClient.sharedInstance.homeTimelineWithParams: \(error)")
} else {
// extend for scrolling
self.tweets.extend(tweets!)
self.tableView.reloadData()
self.minId = minId
SVProgressHUD.showSuccessWithStatus("Success")
}
})
}
}
if let tweetForCell = cell.tweet as Tweet! {
if let mediaUrl = tweetForCell.mediaUrl as String? {
cell.mediaImageView.hidden = false
}
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if searchActive {
if searchResultTweets.count > indexPath.row {
currentlySelectedTweet = searchResultTweets[indexPath.row]
performSegueWithIdentifier("showTweetSegue", sender: self)
} else {
NSLog("ERROR: In didSelectRowAtIndexPath, searchResultTweets.count: \(searchResultTweets.count) is less than or equal to indexPath.row: \(indexPath.row). Cannot segue to show tweet.")
}
} else {
if tweets.count > indexPath.row {
currentlySelectedTweet = tweets[indexPath.row]
performSegueWithIdentifier("showTweetSegue", sender: self)
} else {
NSLog("ERROR: In didSelectRowAtIndexPath, tweets.count: \(tweets.count) is less than or equal to indexPath.row: \(indexPath.row). Cannot segue to show tweet.")
}
}
}
func onRefresh() {
SVProgressHUD.showProgress(1, status: "Loading...")
TwitterClient.sharedInstance.homeTimelineWithParams(nil, maxId: nil, completion: { (tweets, minId, error) -> () in
if error != nil {
SVProgressHUD.dismiss()
NSLog("ERROR: onRefresh TwitterClient.sharedInstance.homeTimelineWithParams: \(error)")
} else {
// set searchActive to false for pull to refresh (always refresh home timeline)
self.searchActive = false
self.tweets = tweets!
self.tableView.reloadData()
self.minId = minId
self.refreshControl.endRefreshing()
SVProgressHUD.showSuccessWithStatus("Success")
}
})
}
@IBAction func composeButtonClicked(sender: AnyObject) {
performSegueWithIdentifier("composeSegue", sender: self)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "composeSegue" {
let composeViewController = segue.destinationViewController as! ComposeTweetViewController
composeViewController.user = User.currentUser!
}
if segue.identifier == "showTweetSegue" {
let showTweetViewController = segue.destinationViewController as! ShowTweetViewController
showTweetViewController.tweet = currentlySelectedTweet
}
if segue.identifier == "replyToTweetFromHomeTimelineSegue" {
let composeViewController = segue.destinationViewController as! ComposeTweetViewController
composeViewController.user = User.currentUser!
composeViewController.replyToTweetId = currentlySelectedTweet?.tweetId
composeViewController.tweetTextPrefix = "@" + (currentlySelectedTweet?.user?.username as String!)
}
}
// delegate functions
func tweetTableViewCell(tweetTableViewCell: TweetTableViewCell, replyButtonClicked value: Bool) {
NSLog("replyButtonClicked event")
currentlySelectedTweet = tweetTableViewCell.tweet
performSegueWithIdentifier("replyToTweetFromHomeTimelineSegue", sender: self)
}
func tweetTableViewCell(tweetTableViewCell: TweetTableViewCell, deleteButtonClicked value: Bool) {
NSLog("deleteButtonClicked event")
currentlySelectedTweet = tweetTableViewCell.tweet
let indexPathCellToDelete = tableView.indexPathForCell(tweetTableViewCell)
TwitterClient.sharedInstance.destroy(currentlySelectedTweet!.tweetId!, completion: { (result, error) -> () in
if error != nil {
NSLog("ERROR: TwitterClient.sharedInstance.destroy: \(error)")
} else {
NSLog("Successfully destroyed/removed tweet.")
if self.tweets.count > indexPathCellToDelete!.row {
self.tweets.removeAtIndex(indexPathCellToDelete!.row)
} else {
NSLog("UNEXPECTED: self.tweets.count is less than/equal to indexPathCellToDelete.row. Cannot delete tweet!")
}
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPathCellToDelete!], withRowAnimation: UITableViewRowAnimation.Fade)
self.tableView.endUpdates()
}
})
}
func tweetTableViewCell(tweetTableViewCell: TweetTableViewCell, fbShareButtonClicked value: Bool) {
NSLog("fbShareButtonClicked event")
var referenceText = String()
if let authorUsername = tweetTableViewCell.tweet?.user?.username as String? {
if let tweetText = tweetTableViewCell.tweet?.text as String? {
referenceText = "@\(authorUsername): \(tweetText)"
}
}
if !referenceText.isEmpty {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) {
var fbSharePost: SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbSharePost.setInitialText(referenceText)
if let mediaUrl = tweetTableViewCell.tweet?.mediaUrl {
var success = fbSharePost.addURL(NSURL(string: mediaUrl))
if !success {
NSLog("ERROR: Could not add image URL to fb post")
}
}
self.presentViewController(fbSharePost, animated: true, completion: nil)
} else {
var alert = UIAlertController(title: "Sign Into Facebook", message: "Sign into your facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Got it.", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
}
|
mit
|
383a21260702a2a23bfff2fe829bfba2
| 40.894558 | 199 | 0.610863 | 5.779916 | false | false | false | false |
TheDarkCode/Example-Swift-Apps
|
Exercises and Basic Principles/search-controller-basics/search-controller-basics/SearchTableVC.swift
|
1
|
6059
|
//
// SearchTableVC.swift
// search-controller-basics
//
// Created by Mark Hamilton on 3/7/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import UIKit
import CoreData
class SearchTableVC: UITableViewController, UISearchResultsUpdating {
var movies = [Movie]()
var filteredMovies = [Movie]()
var searchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
self.loadSearchController()
// Register Custom Cell
var nib = UINib(nibName: "MovieCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "movieCell")
// 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.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
fetchAndRefresh()
}
// MARK: - Update Data in Table
func fetchAndRefresh() {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Movie")
do {
let results = try context.executeFetchRequest(fetchRequest)
self.movies = results as! [Movie]
} catch let err as NSError {
NSLog(err.debugDescription)
}
tableView.reloadData()
}
// MARK: - Search Controller Configuration
func loadSearchController() {
self.searchController = UISearchController(searchResultsController: nil)
self.searchController.searchResultsUpdater = self
self.searchController.dimsBackgroundDuringPresentation = false
self.searchController.searchBar.sizeToFit()
self.tableView.tableHeaderView = self.searchController.searchBar
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return filteredMovies.count
if self.searchController.active {
return filteredMovies.count
} else {
return movies.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("movieCell", forIndexPath: indexPath) as? MovieCell
if self.searchController.active {
if let filteredMovie: Movie = filteredMovies[indexPath.row] {
cell!.configureCell(filteredMovie)
}
} else {
if let aMovie: Movie = movies[indexPath.row] {
cell!.configureCell(aMovie)
}
}
// Configure the cell...
return cell!
}
func updateSearchResultsForSearchController(searchCtrl: UISearchController) {
self.filteredMovies.removeAll(keepCapacity: false)
// Contains only works on Strings, if you put "SELF" instead of movieTitle it will return an error
let searchPredicate = NSPredicate(format: "movieTitle contains[c] %@", searchCtrl.searchBar.text!)
let array = (self.movies as NSArray).filteredArrayUsingPredicate(searchPredicate)
self.filteredMovies = array as! [Movie]
self.tableView.reloadData()
}
/*
// 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.
}
*/
}
|
mit
|
2208c9a357dfd20d09e518f5ad092d2f
| 28.990099 | 157 | 0.617696 | 5.974359 | false | false | false | false |
google/JacquardSDKiOS
|
Example/JacquardSDK/MusicalThreads/NoteHelper.swift
|
1
|
2253
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Starling
enum Note: String {
case b2 = "B2"
case b3 = "B3"
case b4 = "B4"
case d3 = "D3"
case d4 = "D4"
case g2 = "G2"
case g3 = "G3"
case g4 = "G4"
}
class NoteHelper {
private let starling = Starling()
private var currentlyPlaying: [Int] = []
/// 12 notes played in the following sequence:
/// G2 G3 B2 B3 D3 D4 G3 G4 D4 D4 G4 G4
private let lookupTable: [Note] = [
.g2, .g3, .b2, .b3, .d3, .d4, .g3, .g4, .d4, .d4, .g4, .g4,
]
private enum Constants {
static let velocityThreshold = 15
}
init() {
for note in lookupTable {
starling.load(resource: note.rawValue, type: "mp3", for: note.rawValue)
}
}
private func lookUp(item: Int) -> String {
precondition(item >= 0 && item < lookupTable.count)
return lookupTable[item].rawValue
}
public func playLine(_ line: Int, _ velocity: UInt8) {
if currentlyPlaying.contains(line) {
onPlaying(line, velocity)
} else {
onNotPlaying(line, velocity)
}
}
// The note it currently playing.
private func onPlaying(_ line: Int, _ velocity: UInt8) {
if velocity > 0 {
return
}
if let index = currentlyPlaying.firstIndex(of: line) {
currentlyPlaying.remove(at: index)
}
}
// The note is not currently playing
private func onNotPlaying(_ line: Int, _ velocity: UInt8) {
if velocity < Constants.velocityThreshold {
// The note's velocity is below threshold. Ignore.
return
}
if !currentlyPlaying.contains(line) {
currentlyPlaying.append(line)
let itemToPlay = lookUp(item: line)
starling.play(itemToPlay, allowOverlap: true)
}
}
}
|
apache-2.0
|
0c7d5952eb90c82db736c1d940bc6138
| 26.144578 | 77 | 0.653351 | 3.444954 | false | false | false | false |
dashboardearth/rewardsplatform
|
src/Halo-iOS-App/Halo/User Interface/MapCardView.swift
|
1
|
3579
|
//
// MapCardView.swift
// Halo
//
// Created by Sattawat Suppalertporn on 25/7/17.
// Copyright © 2017 dashboardearth. All rights reserved.
//
import UIKit
import GoogleMaps
class MapCardView: UIView {
private var containerView:UIView?
private var mapView:GMSMapView?
private var currentMarker:GMSMarker?
private var currentCamera:GMSCameraPosition?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
// add round corner and shadow
containerView.backgroundColor = UIColor.white
containerView.layer.cornerRadius = 12
containerView.layer.masksToBounds = true
self.addSubview(containerView)
self.containerView = containerView
let camera = GMSCameraPosition.camera(withLatitude: 47.642, longitude: -122.128, zoom: 15.0)
self.currentCamera = camera
let mapWidth = UIScreen.main.bounds.size.width
let frame = CGRect(x: 0, y: 0, width: mapWidth, height: mapWidth)
let mapView = GMSMapView.map(withFrame: frame, camera: camera)
mapView?.translatesAutoresizingMaskIntoConstraints = false
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 47.642, longitude: -122.128)
marker.icon = GMSMarker.markerImage(with: .blue)
marker.title = "Current Location"
marker.snippet = "Current Location"
marker.map = mapView
self.currentMarker = marker
containerView.addSubview(mapView!)
self.mapView = mapView
self.setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupConstraints() {
let views = ["containerView": self.containerView!,
"mapView": self.mapView!] as [String : Any]
var allConstraints = [NSLayoutConstraint]()
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "V:|-8-[containerView]-8-|",
options: [],
metrics: nil,
views: views))
allConstraints.append(contentsOf: NSLayoutConstraint.constraints(
withVisualFormat: "H:|-8-[containerView]-8-|",
options: [],
metrics: nil,
views: views))
allConstraints.append(contentsOf: NSLayoutConstraint.fillSuperview(view: self.mapView!))
NSLayoutConstraint.activate(allConstraints)
}
func addMarker(latitude: Double, longitue: Double) {
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitue)
marker.title = "Redmond, WA"
marker.snippet = "Redmond"
marker.map = self.mapView
}
func moveCurrentMarker(latitude: Double, longitue: Double) {
self.currentMarker?.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitue)
}
func updateCameraPosition(latitude: Double, longitue: Double) {
let cameraUpdate = GMSCameraUpdate.setTarget(CLLocationCoordinate2D(latitude: latitude, longitude: longitue))
self.mapView?.animate(with: cameraUpdate)
}
}
|
apache-2.0
|
6ef25aa69e5919659f15a38ef26a4c4b
| 33.737864 | 117 | 0.636669 | 4.854817 | false | false | false | false |
lenglengiOS/BuDeJie
|
百思不得姐/Pods/Charts/Charts/Classes/Data/CombinedChartData.swift
|
34
|
4861
|
//
// CombinedChartData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class CombinedChartData: BarLineScatterCandleBubbleChartData
{
private var _lineData: LineChartData!
private var _barData: BarChartData!
private var _scatterData: ScatterChartData!
private var _candleData: CandleChartData!
private var _bubbleData: BubbleChartData!
public override init()
{
super.init()
}
public override init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public override init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public var lineData: LineChartData!
{
get
{
return _lineData
}
set
{
_lineData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
public var barData: BarChartData!
{
get
{
return _barData
}
set
{
_barData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
public var scatterData: ScatterChartData!
{
get
{
return _scatterData
}
set
{
_scatterData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
public var candleData: CandleChartData!
{
get
{
return _candleData
}
set
{
_candleData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
public var bubbleData: BubbleChartData!
{
get
{
return _bubbleData
}
set
{
_bubbleData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
/// - returns: all data objects in row: line-bar-scatter-candle-bubble if not null.
public var allData: [ChartData]
{
var data = [ChartData]()
if lineData !== nil
{
data.append(lineData)
}
if barData !== nil
{
data.append(barData)
}
if scatterData !== nil
{
data.append(scatterData)
}
if candleData !== nil
{
data.append(candleData)
}
if bubbleData !== nil
{
data.append(bubbleData)
}
return data;
}
public override func notifyDataChanged()
{
if (_lineData !== nil)
{
_lineData.notifyDataChanged()
}
if (_barData !== nil)
{
_barData.notifyDataChanged()
}
if (_scatterData !== nil)
{
_scatterData.notifyDataChanged()
}
if (_candleData !== nil)
{
_candleData.notifyDataChanged()
}
if (_bubbleData !== nil)
{
_bubbleData.notifyDataChanged()
}
super.notifyDataChanged() // recalculate everything
}
}
|
apache-2.0
|
20429e50320d312597208f8583ecc343
| 21.821596 | 87 | 0.482822 | 5.672112 | false | false | false | false |
Allow2CEO/browser-ios
|
Client/Frontend/Settings/SearchEnginePicker.swift
|
1
|
2282
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
protocol SearchEnginePickerDelegate {
func searchEnginePicker(_ searchEnginePicker: SearchEnginePicker, didSelectSearchEngine engine: OpenSearchEngine?) -> Void
}
class SearchEnginePicker: UITableViewController {
var delegate: SearchEnginePickerDelegate?
var engines: [OpenSearchEngine]!
var selectedSearchEngineName: String?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = Strings.DefaultSearchEngine
navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.Cancel, style: .plain, target: self, action: #selector(SearchEnginePicker.SELcancel))
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return engines.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let engine = engines[indexPath.item]
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image?.createScaled(CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize))
if engine.shortName == selectedSearchEngineName {
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let engine = engines[indexPath.item]
delegate?.searchEnginePicker(self, didSelectSearchEngine: engine)
guard let cell = tableView.cellForRow(at: indexPath) else { return }
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none
}
func SELcancel() {
delegate?.searchEnginePicker(self, didSelectSearchEngine: nil)
}
}
|
mpl-2.0
|
cdf5aef3af60be6e31925827e883cad5
| 41.259259 | 159 | 0.735758 | 5.485577 | false | false | false | false |
openhab/openhab.ios
|
OpenHABCore/Sources/OpenHABCore/Model/OpenHABItem.swift
|
1
|
6033
|
// Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import CoreLocation
import Fuzi
import os.log
import UIKit
public final class OpenHABItem: NSObject, CommItem {
public enum ItemType: String {
case color = "Color"
case contact = "Contact"
case dateTime = "DateTime"
case dimmer = "Dimmer"
case group = "Group"
case image = "Image"
case location = "Location"
case number = "Number"
case numberWithDimension = "NumberWithDimension"
case player = "Player"
case rollershutter = "Rollershutter"
case stringItem = "String"
case switchItem = "Switch"
}
public var type: ItemType?
public var groupType: ItemType?
public var name = ""
public var state: String?
public var link = ""
public var label = ""
public var stateDescription: OpenHABStateDescription?
public var readOnly = false
public var members: [OpenHABItem] = []
public var category = ""
public var options: [OpenHABOptions] = []
var canBeToggled: Bool {
isOfTypeOrGroupType(ItemType.color) ||
isOfTypeOrGroupType(ItemType.contact) ||
isOfTypeOrGroupType(ItemType.dimmer) ||
isOfTypeOrGroupType(ItemType.rollershutter) ||
isOfTypeOrGroupType(ItemType.switchItem) ||
isOfTypeOrGroupType(ItemType.player)
}
public init(name: String, type: String, state: String?, link: String, label: String?, groupType: String?, stateDescription: OpenHABStateDescription?, members: [OpenHABItem], category: String?, options: [OpenHABOptions]?) {
self.name = name
self.type = type.toItemType()
if let state = state, (state == "NULL" || state == "UNDEF" || state.caseInsensitiveCompare("undefined") == .orderedSame) {
self.state = nil
} else {
self.state = state
}
self.link = link
self.label = label.orEmpty
self.groupType = groupType?.toItemType()
self.stateDescription = stateDescription
readOnly = stateDescription?.readOnly ?? false
self.members = members
self.category = category.orEmpty
self.options = options ?? []
}
public init(xml xmlElement: XMLElement) {
super.init()
for child in xmlElement.children {
switch child.tag {
case "name": name = child.stringValue
case "type": type = child.stringValue.toItemType()
case "groupType": groupType = child.stringValue.toItemType()
case "state": state = child.stringValue
case "link": link = child.stringValue
default:
break
}
}
}
public func isOfTypeOrGroupType(_ type: ItemType) -> Bool {
self.type == type || groupType == type
}
}
extension OpenHABItem.ItemType: Decodable {}
public extension OpenHABItem {
func stateAsDouble() -> Double {
state?.numberValue?.doubleValue ?? 0
}
func stateAsInt() -> Int {
state?.numberValue?.intValue ?? 0
}
func stateAsUIColor() -> UIColor {
if let state = state {
let values = state.components(separatedBy: ",")
if values.count == 3 {
let hue = CGFloat(state: values[0], divisor: 360)
let saturation = CGFloat(state: values[1], divisor: 100)
let brightness = CGFloat(state: values[2], divisor: 100)
os_log("hue saturation brightness: %g %g %g", log: .default, type: .info, hue, saturation, brightness)
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
} else {
return .black
}
} else {
return .black
}
}
func stateAsLocation() -> CLLocation? {
if type == .location {
// Example of `state` string for location: '0.000000,0.000000,0.0' ('<latitude>,<longitude>,<altitude>')
if let state = state {
let locationComponents = state.components(separatedBy: ",")
if locationComponents.count >= 2 {
let latitude = CLLocationDegrees(Double(locationComponents[0]) ?? 0.0)
let longitude = CLLocationDegrees(Double(locationComponents[1]) ?? 0.0)
return CLLocation(latitude: latitude, longitude: longitude)
}
} else {
return nil
}
}
return nil
}
}
public extension OpenHABItem {
struct CodingData: Decodable {
let type: String
let groupType: String?
let name: String
let link: String
let state: String?
let label: String?
let stateDescription: OpenHABStateDescription.CodingData?
let members: [OpenHABItem.CodingData]?
let category: String?
let options: [OpenHABOptions]?
}
}
public extension OpenHABItem.CodingData {
var openHABItem: OpenHABItem {
let mappedMembers = members?.map(\.openHABItem) ?? []
return OpenHABItem(name: name, type: type, state: state, link: link, label: label, groupType: groupType, stateDescription: stateDescription?.openHABStateDescription, members: mappedMembers, category: category, options: options)
}
}
extension CGFloat {
init(state string: String, divisor: Float) {
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "US")
if let number = numberFormatter.number(from: string) {
self.init(number.floatValue / divisor)
} else {
self.init(0)
}
}
}
|
epl-1.0
|
186a360673132e15a4d7e9c9039f468d
| 33.872832 | 235 | 0.605669 | 4.532682 | false | false | false | false |
synergistic-fantasy/wakeonlan-osx
|
WakeOnLAN-OSX/Controllers/EditComputerViewController.swift
|
1
|
2752
|
//
// EditComputerViewController.swift
// WakeOnLAN-OSX
//
// Created by Mario Estrella on 12/22/15.
// Copyright © 2015 Synergistic Fantasy LLC. All rights reserved.
//
import Cocoa
class EditComputerViewController: InputDialogViewController {
// MARK: - Variables
@IBOutlet weak var editCompName: NSTextField!
@IBOutlet weak var editMacAddr: NSTextField!
@IBOutlet weak var editIpAddr: NSTextField!
@IBOutlet weak var editSubnet: NSComboBox!
@IBOutlet weak var editButtonState: NSButton!
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
editButtonState.enabled = false
editSubnet.addItemsWithObjectValues(listOfSubnets)
loadComputer()
// Do view setup here.
}
override func controlTextDidChange(obj: NSNotification) {
validateFields()
}
// MARK: - Button Actions
@IBAction func cancel(sender: AnyObject) {
dismissViewController(self)
}
@IBAction func edit(sender: AnyObject) {
if currentComputer.compName! == editCompName.stringValue.uppercaseString {
editComputer()
saveItem()
dismissViewController(self)
} else if currentComputer.macAddress! == editMacAddr.stringValue.uppercaseString {
editComputer()
saveItem()
dismissViewController(self)
} else if isDuplicate(editCompName.stringValue.uppercaseString, currentMac: editMacAddr.stringValue.uppercaseString) {
editButtonState.enabled = false
} else {
editComputer()
saveItem()
dismissViewController(self)
}
}
func editComputer() {
currentComputer.compName = editCompName.stringValue.uppercaseString
currentComputer.macAddress = editMacAddr.stringValue.uppercaseString
currentComputer.ipAddress = editIpAddr.stringValue
if editIpAddr.stringValue == "" {
currentComputer.subnet = ""
} else {
currentComputer.subnet = editSubnet.stringValue
}
}
// MARK: - Functions
func loadComputer() {
editCompName.stringValue = currentComputer.compName!
editMacAddr.stringValue = currentComputer.macAddress!
editIpAddr.stringValue = currentComputer.ipAddress!
editSubnet.stringValue = currentComputer.subnet!
validateFields()
}
func validateFields() {
textFieldValidation(editCompName, type: .name)
textFieldValidation(editMacAddr, type: .mac)
textFieldValidation(editIpAddr, type: .ip)
buttonState(editButtonState)
}
}
|
gpl-3.0
|
bedce70534a0f9569ec0713665eb0faa
| 27.957895 | 126 | 0.640131 | 5.075646 | false | false | false | false |
nwjs/chromium.src
|
ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_destination_list.swift
|
1
|
7533
|
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import SwiftUI
/// A view displaying a list of destinations.
@available(iOS 15, *)
struct OverflowMenuDestinationList: View {
enum Constants {
/// Padding breakpoints for each width. The ranges should be inclusive of
/// the larger number. That is, a width of 320 should fall in the
/// `(230, 320]` bucket.
static let widthBreakpoints: [CGFloat] = [
180, 230, 320, 400, 470, 560, 650,
]
/// Array of the lower end of each breakpoint range.
static let lowerWidthBreakpoints = [nil] + widthBreakpoints
/// Array of the higher end of each breakpoint range.
static let upperWidthBreakpoints = widthBreakpoints + [nil]
/// Leading space on the first icon.
static let iconInitialSpace: CGFloat = 16
/// Range of spacing around icons; varies based on view width.
static let iconSpacingRange: ClosedRange<CGFloat> = 9...13
/// Range of icon paddings; varies based on view width.
static let iconPaddingRange: ClosedRange<CGFloat> = 0...3
/// When the dynamic text size is large, the width of each item is the
/// screen width minus a fixed space.
static let largeTextSizeSpace: CGFloat = 120
/// Space above the list pushing them down from the grabber.
static let topMargin: CGFloat = 20
/// The name for the coordinate space of the scroll view, so children can
/// find their positioning in the scroll view.
static let coordinateSpaceName = "destinations"
}
/// `PreferenceKey` to track the leading offset of the scroll view.
struct ScrollViewLeadingOffset: PreferenceKey {
static var defaultValue: CGFloat = .greatestFiniteMagnitude
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = min(value, nextValue())
}
}
/// The current dynamic type size.
@Environment(\.sizeCategory) var sizeCategory
/// The current environment layout direction.
@Environment(\.layoutDirection) var layoutDirection: LayoutDirection
/// The destinations for this view.
var destinations: [OverflowMenuDestination]
weak var metricsHandler: PopupMenuMetricsHandler?
@ObservedObject var uiConfiguration: OverflowMenuUIConfiguration
/// Tracks the list's current offset, to see when it scrolls.
@State var listOffset: CGFloat = 0
var body: some View {
GeometryReader { geometry in
ScrollViewReader { proxy in
ScrollView(.horizontal, showsIndicators: false) {
let spacing = destinationSpacing(forScreenWidth: geometry.size.width)
let layoutParameters: OverflowMenuDestinationView.LayoutParameters =
sizeCategory >= .accessibilityMedium
? .horizontal(itemWidth: geometry.size.width - Constants.largeTextSizeSpace)
: .vertical(
iconSpacing: spacing.iconSpacing,
iconPadding: spacing.iconPadding)
let alignment: VerticalAlignment = sizeCategory >= .accessibilityMedium ? .center : .top
ZStack {
VStack {
Spacer(minLength: Constants.topMargin)
LazyHStack(alignment: alignment, spacing: 0) {
// Make sure the space to the first icon is constant, so add extra
// spacing before the first item.
Spacer().frame(width: Constants.iconInitialSpace - spacing.iconSpacing)
ForEach(destinations) { destination in
OverflowMenuDestinationView(
destination: destination, layoutParameters: layoutParameters,
metricsHandler: metricsHandler
).id(destination.destinationName)
}
}
}
GeometryReader { innerGeometry in
let offset = innerGeometry.frame(in: .named(Constants.coordinateSpaceName)).minX
Color.clear
.preference(key: ScrollViewLeadingOffset.self, value: offset)
}
}
}
.animation(nil)
.background(
uiConfiguration.highlightDestinationsRow
? Color("destination_highlight_color") : Color.clear
)
.animation(.linear(duration: kMaterialDuration3))
.coordinateSpace(name: Constants.coordinateSpaceName)
.accessibilityIdentifier(kPopupMenuToolsMenuTableViewId)
.onAppear {
if layoutDirection == .rightToLeft {
proxy.scrollTo(destinations.last?.destinationName)
}
uiConfiguration.destinationListScreenFrame = geometry.frame(in: .global)
}
}
.onPreferenceChange(ScrollViewLeadingOffset.self) { value in
if value != listOffset {
metricsHandler?.popupMenuScrolledHorizontally()
}
listOffset = value
}
}
}
/// Finds the lower and upper breakpoint above and below `width`.
///
/// Returns `nil` for either end if `width` is above or below the largest or
/// smallest breakpoint.
private func findBreakpoints(forScreenWidth width: CGFloat) -> (CGFloat?, CGFloat?) {
// Add extra sentinel values to either end of the breakpoint array.
let x = zip(
Constants.lowerWidthBreakpoints, Constants.upperWidthBreakpoints
)
// There should only be one item where the provided width is both greater
// than the lower end and less than the upper end.
.filter {
(low, high) in
// Check if width is above the low value, or default to true if low is
// nil.
let aboveLow = low.map { value in width > value } ?? true
let belowHigh = high.map { value in width <= value } ?? true
return aboveLow && belowHigh
}.first
return x ?? (nil, nil)
}
/// Calculates the icon spacing and padding for the given `width`.
private func destinationSpacing(forScreenWidth width: CGFloat) -> (
iconSpacing: CGFloat, iconPadding: CGFloat
) {
let (lowerBreakpoint, upperBreakpoint) = findBreakpoints(
forScreenWidth: width)
// If there's no lower breakpoint, `width` is lower than the lowest, so
// default to the lower bound of the ranges.
guard let lowerBreakpoint = lowerBreakpoint else {
return (
iconSpacing: Constants.iconSpacingRange.lowerBound,
iconPadding: Constants.iconPaddingRange.lowerBound
)
}
// If there's no upper breakpoint, `width` is higher than the highest, so
// default to the higher bound of the ranges.
guard let upperBreakpoint = upperBreakpoint else {
return (
iconSpacing: Constants.iconSpacingRange.upperBound,
iconPadding: Constants.iconPaddingRange.upperBound
)
}
let breakpointRange = lowerBreakpoint...upperBreakpoint
let iconSpacing = mapNumber(
width, from: breakpointRange, to: Constants.iconSpacingRange)
let iconPadding = mapNumber(
width, from: breakpointRange, to: Constants.iconPaddingRange)
return (iconSpacing: iconSpacing, iconPadding: iconPadding)
}
/// Maps the given `number` from its relative position in `inRange` to its
/// relative position in `outRange`.
private func mapNumber<F: FloatingPoint>(
_ number: F, from inRange: ClosedRange<F>, to outRange: ClosedRange<F>
) -> F {
let scalingFactor =
(outRange.upperBound - outRange.lowerBound)
/ (inRange.upperBound - inRange.lowerBound)
return (number - inRange.lowerBound) * scalingFactor + outRange.lowerBound
}
}
|
bsd-3-clause
|
913eaaf6a8fb8a51cb2ed2daaca92f7c
| 37.829897 | 98 | 0.670649 | 4.813419 | false | false | false | false |
appsandwich/ppt2rk
|
ppt2rk/RunkeeperGPXUploadParser.swift
|
1
|
2748
|
//
// RunkeeperGPXUploadParser.swift
// ppt2rk
//
// Created by Vinny Coyne on 18/05/2017.
// Copyright © 2017 App Sandwich Limited. All rights reserved.
//
import Foundation
class RunkeeperGPXUploadParser {
var data: Data? = nil
init(_ data: Data) {
self.data = data
}
public func parseWithHandler(_ handler: @escaping (RunkeeperActivity?) -> Void) {
guard let data = self.data else {
handler(nil)
return
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else {
handler(nil)
return
}
guard let dictionary = json as? Dictionary<String, Any> else {
handler(nil)
return
}
if let error = dictionary["error"] as? String, error.characters.count > 0 {
handler(nil)
return
}
guard let trackImportData = dictionary["trackImportData"] as? Dictionary<String, Any> else {
handler(nil)
return
}
guard let duration = trackImportData["duration"] as? Double, let startTime = trackImportData["startTime"] as? Int, let trackPoints = trackImportData["trackPoints"] as? Array< Dictionary<String, Any> >, trackPoints.count > 0 else {
handler(nil)
return
}
// Thanks to https://medium.com/@ndcrandall/automating-gpx-file-imports-in-runkeeper-f446917f8a19
//str << "#{point['type']},#{point['latitude']},#{point['longitude']},#{point['deltaTime']},0,#{point['deltaDistance']};"
var totalDistance = 0.0
let runkeeperString = trackPoints.reduce("") { (string, trackPoint) -> String in
guard let type = trackPoint["type"] as? String, let latitude = trackPoint["latitude"] as? Double, let longitude = trackPoint["longitude"] as? Double, let deltaTime = trackPoint["deltaTime"] as? Double, let deltaDistance = trackPoint["deltaDistance"] as? Double else {
return string
}
let trackPointString = "\(type),\(latitude),\(longitude),\(Int(deltaTime)),0,\(deltaDistance);"
totalDistance += deltaDistance
return string + trackPointString
}
let date = Date(timeIntervalSince1970: Double(startTime) / 1000.0)
let runkeeperActivity = RunkeeperActivity(id: -1, timestamp: date, distance: "\(totalDistance)", duration: "\(duration / 1000.0)", day: "")
runkeeperActivity.convertedFromGPXString = runkeeperString
handler(runkeeperActivity)
}
}
|
mit
|
9c99105a12c040f14986c02e991b3756
| 34.217949 | 279 | 0.573353 | 4.540496 | false | false | false | false |
scarlettwu93/test
|
Example/Pods/SwiftSVG/SwiftSVG/CrossPlatform.swift
|
1
|
4643
|
//
// CrossPlatform.swift
// SwiftSVG
//
// Copyright (c) 2015 Michael Choe
// http://www.straussmade.com/
// http://www.twitter.com/_mchoe
// http://www.github.com/mchoe
//
// 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
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
public typealias UIView = NSView
public typealias UIBezierPath = NSBezierPath
public typealias UIColor = NSColor
#endif
extension UIView {
var nonOptionalLayer:CALayer {
#if os(iOS)
return self.layer
#elseif os(OSX)
if let l = self.layer {
return l
} else {
self.layer = CALayer()
self.layer?.frame = self.bounds
let flip = CATransform3DMakeScale(1.0, -1.0, 1.0)
let translate = CATransform3DMakeTranslation(0.0, self.bounds.size.height, 1.0)
self.layer?.sublayerTransform = CATransform3DConcat(flip, translate)
self.wantsLayer = true
return self.layer!
}
#endif
}
}
#if os(OSX)
extension NSBezierPath {
var addLineToPoint:((NSPoint)->Void) {
return lineToPoint
}
var addCurveToPoint:((NSPoint, controlPoint1:NSPoint, controlPoint2:NSPoint)->Void) {
return curveToPoint
}
func addQuadCurveToPoint(endPoint: NSPoint, controlPoint: NSPoint) {
self.addCurveToPoint(endPoint,
controlPoint1: CGPointMake(
(controlPoint.x - currentPoint.x) * (2.0 / 3.0) + currentPoint.x,
(controlPoint.y - currentPoint.y) * (2.0 / 3.0) + currentPoint.y
),
controlPoint2: CGPointMake(
(controlPoint.x - endPoint.x) * (2.0 / 3.0) + endPoint.x,
(controlPoint.y - endPoint.y) * (2.0 / 3.0) + endPoint.y
))
}
var CGPath:CGPathRef? {
var immutablePath:CGPathRef? = nil
let numElements = self.elementCount
if numElements > 0 {
let path = CGPathCreateMutable()
let points = NSPointArray.alloc(3)
var didClosePath = true
for i in 0..<numElements {
switch(self.elementAtIndex(i, associatedPoints: points)) {
case .MoveToBezierPathElement:
CGPathMoveToPoint(path, nil, points[0].x, points[0].y)
case .LineToBezierPathElement:
CGPathAddLineToPoint(path, nil, points[0].x, points[0].y);
didClosePath = false;
case .CurveToBezierPathElement:
CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y,
points[1].x, points[1].y,
points[2].x, points[2].y);
didClosePath = false;
case .ClosePathBezierPathElement:
CGPathCloseSubpath(path);
didClosePath = true;
}
}
if !didClosePath {
CGPathCloseSubpath(path)
}
immutablePath = CGPathCreateCopy(path)
points.dealloc(3)
}
return immutablePath
}
}
#endif
|
mit
|
ecdfb2dbb196a3c2a946b05b49125ccc
| 39.034483 | 102 | 0.550937 | 4.887368 | false | false | false | false |
johnno1962b/swift-corelibs-foundation
|
Foundation/NSCFString.swift
|
5
|
8958
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
internal class _NSCFString : NSMutableString {
required init(characters: UnsafePointer<unichar>, length: Int) {
fatalError()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
required init(extendedGraphemeClusterLiteral value: StaticString) {
fatalError()
}
required init(stringLiteral value: StaticString) {
fatalError()
}
required init(capacity: Int) {
fatalError()
}
required init(string aString: String) {
fatalError()
}
deinit {
_CFDeinit(self)
_CFZeroUnsafeIvars(&_storage)
}
override var length: Int {
return CFStringGetLength(unsafeBitCast(self, to: CFString.self))
}
override func character(at index: Int) -> unichar {
return CFStringGetCharacterAtIndex(unsafeBitCast(self, to: CFString.self), index)
}
override func replaceCharacters(in range: NSRange, with aString: String) {
CFStringReplace(unsafeBitCast(self, to: CFMutableString.self), CFRangeMake(range.location, range.length), aString._cfObject)
}
override var classForCoder: AnyClass {
return NSMutableString.self
}
}
internal final class _NSCFConstantString : _NSCFString {
internal var _ptr : UnsafePointer<UInt8> {
// FIXME: Split expression as a work-around for slow type
// checking (tracked by SR-5322).
let offTemp1 = MemoryLayout<OpaquePointer>.size + MemoryLayout<Int32>.size
let offTemp2 = MemoryLayout<Int32>.size + MemoryLayout<_CFInfo>.size
let offset = offTemp1 + offTemp2
let ptr = Unmanaged.passUnretained(self).toOpaque()
return ptr.load(fromByteOffset: offset, as: UnsafePointer<UInt8>.self)
}
private var _lenOffset : Int {
// FIXME: Split expression as a work-around for slow type
// checking (tracked by SR-5322).
let offTemp1 = MemoryLayout<OpaquePointer>.size + MemoryLayout<Int32>.size
let offTemp2 = MemoryLayout<Int32>.size + MemoryLayout<_CFInfo>.size
return offTemp1 + offTemp2 + MemoryLayout<UnsafePointer<UInt8>>.size
}
private var _lenPtr : UnsafeMutableRawPointer {
return Unmanaged.passUnretained(self).toOpaque()
}
#if arch(s390x)
internal var _length : UInt64 {
return _lenPtr.load(fromByteOffset: _lenOffset, as: UInt64.self)
}
#else
internal var _length : UInt32 {
return _lenPtr.load(fromByteOffset: _lenOffset, as: UInt32.self)
}
#endif
required init(characters: UnsafePointer<unichar>, length: Int) {
fatalError()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
required init(extendedGraphemeClusterLiteral value: StaticString) {
fatalError()
}
required init(stringLiteral value: StaticString) {
fatalError()
}
required init(capacity: Int) {
fatalError()
}
required init(string aString: String) {
fatalError("Constant strings cannot be constructed in code")
}
deinit {
fatalError("Constant strings cannot be deallocated")
}
override var length: Int {
return Int(_length)
}
override func character(at index: Int) -> unichar {
return unichar(_ptr[index])
}
override func replaceCharacters(in range: NSRange, with aString: String) {
fatalError()
}
override var classForCoder: AnyClass {
return NSString.self
}
}
internal func _CFSwiftStringGetLength(_ string: AnyObject) -> CFIndex {
return (string as! NSString).length
}
internal func _CFSwiftStringGetCharacterAtIndex(_ str: AnyObject, index: CFIndex) -> UniChar {
return (str as! NSString).character(at: index)
}
internal func _CFSwiftStringGetCharacters(_ str: AnyObject, range: CFRange, buffer: UnsafeMutablePointer<UniChar>) {
(str as! NSString).getCharacters(buffer, range: NSMakeRange(range.location, range.length))
}
internal func _CFSwiftStringGetBytes(_ str: AnyObject, encoding: CFStringEncoding, range: CFRange, buffer: UnsafeMutablePointer<UInt8>?, maxBufLen: CFIndex, usedBufLen: UnsafeMutablePointer<CFIndex>?) -> CFIndex {
let convertedLength: CFIndex
switch encoding {
// TODO: Don't treat many encodings like they are UTF8
case CFStringEncoding(kCFStringEncodingUTF8), CFStringEncoding(kCFStringEncodingISOLatin1), CFStringEncoding(kCFStringEncodingMacRoman), CFStringEncoding(kCFStringEncodingASCII), CFStringEncoding(kCFStringEncodingNonLossyASCII):
let encodingView = (str as! NSString).substring(with: NSRange(range)).utf8
if let buffer = buffer {
for (idx, character) in encodingView.enumerated() {
buffer.advanced(by: idx).initialize(to: character)
}
}
usedBufLen?.pointee = encodingView.count
convertedLength = encodingView.count
case CFStringEncoding(kCFStringEncodingUTF16):
let encodingView = (str as! NSString)._swiftObject.utf16
let start = encodingView.startIndex
if let buffer = buffer {
for idx in 0..<range.length {
// Since character is 2 bytes but the buffer is in term of 1 byte values, we have to split it up
let character = encodingView[start.advanced(by: idx + range.location)]
let byte0 = UInt8(character & 0x00ff)
let byte1 = UInt8((character >> 8) & 0x00ff)
buffer.advanced(by: idx * 2).initialize(to: byte0)
buffer.advanced(by: (idx * 2) + 1).initialize(to: byte1)
}
}
// Every character was 2 bytes
usedBufLen?.pointee = range.length * 2
convertedLength = range.length
default:
fatalError("Attempted to get bytes of a Swift string using an unsupported encoding")
}
return convertedLength
}
internal func _CFSwiftStringCreateWithSubstring(_ str: AnyObject, range: CFRange) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((str as! NSString).substring(with: NSMakeRange(range.location, range.length))._nsObject)
}
internal func _CFSwiftStringCreateCopy(_ str: AnyObject) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((str as! NSString).copy() as! NSObject)
}
internal func _CFSwiftStringCreateMutableCopy(_ str: AnyObject) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((str as! NSString).mutableCopy() as! NSObject)
}
internal func _CFSwiftStringFastCStringContents(_ str: AnyObject, _ nullTerminated: Bool) -> UnsafePointer<Int8>? {
return (str as! NSString)._fastCStringContents(nullTerminated)
}
internal func _CFSwiftStringFastContents(_ str: AnyObject) -> UnsafePointer<UniChar>? {
return (str as! NSString)._fastContents
}
internal func _CFSwiftStringGetCString(_ str: AnyObject, buffer: UnsafeMutablePointer<Int8>, maxLength: Int, encoding: CFStringEncoding) -> Bool {
return (str as! NSString).getCString(buffer, maxLength: maxLength, encoding: CFStringConvertEncodingToNSStringEncoding(encoding))
}
internal func _CFSwiftStringIsUnicode(_ str: AnyObject) -> Bool {
return (str as! NSString)._encodingCantBeStoredInEightBitCFString
}
internal func _CFSwiftStringInsert(_ str: AnyObject, index: CFIndex, inserted: AnyObject) {
(str as! NSMutableString).insert((inserted as! NSString)._swiftObject, at: index)
}
internal func _CFSwiftStringDelete(_ str: AnyObject, range: CFRange) {
(str as! NSMutableString).deleteCharacters(in: NSMakeRange(range.location, range.length))
}
internal func _CFSwiftStringReplace(_ str: AnyObject, range: CFRange, replacement: AnyObject) {
(str as! NSMutableString).replaceCharacters(in: NSMakeRange(range.location, range.length), with: (replacement as! NSString)._swiftObject)
}
internal func _CFSwiftStringReplaceAll(_ str: AnyObject, replacement: AnyObject) {
(str as! NSMutableString).setString((replacement as! NSString)._swiftObject)
}
internal func _CFSwiftStringAppend(_ str: AnyObject, appended: AnyObject) {
(str as! NSMutableString).append((appended as! NSString)._swiftObject)
}
internal func _CFSwiftStringAppendCharacters(_ str: AnyObject, chars: UnsafePointer<UniChar>, length: CFIndex) {
(str as! NSMutableString).appendCharacters(chars, length: length)
}
internal func _CFSwiftStringAppendCString(_ str: AnyObject, chars: UnsafePointer<Int8>, length: CFIndex) {
(str as! NSMutableString)._cfAppendCString(chars, length: length)
}
|
apache-2.0
|
9fea0d339e54fad4b9a7ae110b7f40e7
| 35.713115 | 232 | 0.691337 | 4.624677 | false | false | false | false |
algolia/algoliasearch-client-swift
|
Sources/AlgoliaSearchClient/Models/Synonym/SynonymSearchResponse+Hit.swift
|
1
|
874
|
//
// SynonymSearchResponse+Hit.swift
//
//
// Created by Vladislav Fitc on 20/05/2020.
//
import Foundation
extension SynonymSearchResponse {
public struct Hit {
public let synonym: Synonym
public let highlightResult: TreeModel<HighlightResult>
}
}
extension SynonymSearchResponse.Hit: Codable {
enum CodingKeys: String, CodingKey {
case highlightResult = "_highlightResult"
}
public init(from decoder: Decoder) throws {
self.synonym = try .init(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.highlightResult = try container.decode(forKey: .highlightResult)
}
public func encode(to encoder: Encoder) throws {
try synonym.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(highlightResult, forKey: .highlightResult)
}
}
|
mit
|
2e66ab4f604dc4a24b0c6180cf27c548
| 21.410256 | 73 | 0.726545 | 4.065116 | false | false | false | false |
samodom/TestSwagger
|
TestSwagger/Spying/SpyController.swift
|
1
|
3542
|
//
// SpyController.swift
// TestSwagger
//
// Created by Sam Odom on 2/2/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import FoundationSwagger
/// A static group of values that provide information used in the construction of a spy.
public protocol SpyController {
/// The original class defining a test subject's spyable method.
static var rootSpyableClass: AnyClass { get }
/// The type of spy mechanism being used: direct-invocation or indirect-invocation.
static var vector: SpyVector { get }
/// All selector pairs of original and spy methods along with their method types.
static var coselectors: Set<SpyCoselectors> { get }
/// A set of evidence reference items used in cleaning up evidence after spying.
static var evidence: Set<SpyEvidenceReference> { get }
/// Method-forwarding behavior to be used by spy methods.
static var forwardsInvocations: Bool { get }
}
public extension SpyController {
/// Common spy-creation method
/// - parameter subject: The subject on which one intends to spy.
/// - returns: A new spy on the subject or nil if the subject is invalid.
public static func createSpy(on subject: Any) -> Spy? {
guard let owningClass = spyTarget(for: subject, vector: vector) else {
return nil
}
let surrogates = coselectors.map { coselector in
MethodSurrogate(
forClass: owningClass,
ofType: coselector.methodType,
originalSelector: coselector.original,
alternateSelector: coselector.spy
)
}
return Spy(subject: subject, surrogates: surrogates, evidence: evidence)
}
}
fileprivate extension SpyController {
static func spyTarget(for subject: Any, vector: SpyVector) -> AnyClass? {
switch vector {
case .direct:
return directInvocationSpyTarget(for: subject, rootClass: rootSpyableClass)
case .indirect:
return indirectInvocationSpyTarget(for: subject, rootClass: rootSpyableClass)
}
}
private static func directInvocationSpyTarget(for subject: Any, rootClass: AnyClass) -> AnyClass? {
if let subjectAsClass = subject as? AnyClass {
return subjectAsClass.isSubclass(of: rootClass) ? subjectAsClass : nil
}
else {
return object_getClass(subject)
}
}
private static func indirectInvocationSpyTarget(for subject: Any, rootClass: AnyClass) -> AnyClass? {
if let subjectAsClass = subject as? AnyClass {
return indirectInvocationClassSpyTarget(for: subjectAsClass, rootClass: rootClass)
}
else {
return indirectInvocationObjectSpyTarget(for: subject, rootClass: rootClass)
}
}
private static func indirectInvocationClassSpyTarget(for subject: AnyClass, rootClass: AnyClass) -> AnyClass? {
guard subject != rootClass,
let target = class_getSuperclass(subject),
target.isSubclass(of: rootClass)
else {
return nil
}
return target
}
private static func indirectInvocationObjectSpyTarget(for subject: Any, rootClass: AnyClass) -> AnyClass? {
guard let subjectClass: AnyClass = object_getClass(subject),
subjectClass != rootClass,
let target = class_getSuperclass(subjectClass)
else {
return nil
}
return target
}
}
|
mit
|
c4f43d570ac02ae5bc3d24c52c181d17
| 29.525862 | 115 | 0.649252 | 4.884138 | false | false | false | false |
raulriera/Bike-Compass
|
App/Carthage/Checkouts/Decodable/Tests/DecodableExtensionTests.swift
|
1
|
2478
|
//
// DecodableExtensionTests.swift
// Decodable
//
// Created by FJBelchi on 13/07/15.
// Copyright © 2015 anviking. All rights reserved.
//
import XCTest
@testable import Decodable
class DecodableExtensionTests: XCTestCase {
// MARK: String
func testStringDecodableSuccess() {
//given
let anyObject = "hello"
//when
let string = try! String.decode(anyObject)
//then
XCTAssertEqual(string, anyObject)
}
func testStringDecodableFail() {
//given
let anyObject = 0
//when
do {
_ = try String.decode(anyObject)
} catch is TypeMismatchError {
//then
XCTAssertTrue(true)
} catch {
XCTFail("should not throw this exception")
}
}
// MARK: Int
func testIntDecodable() {
//given
let anyObject = 0
//when
let int = try! Int.decode(anyObject)
//then
XCTAssertEqual(int, anyObject)
}
func testIntDecodableFail() {
//given
let anyObject = ""
//when
do {
_ = try Int.decode(anyObject)
} catch is TypeMismatchError {
//then
XCTAssertTrue(true)
} catch {
XCTFail("should not throw this exception")
}
}
// MARK: Double
func testDoubleDecodable() {
//given
let anyObject = 0.5
//when
let double = try! Double.decode(anyObject)
//then
XCTAssertEqual(double, anyObject)
}
func testDoubleDecodableFail() {
//given
let anyObject = ""
//when
do {
_ = try Double.decode(anyObject)
} catch is TypeMismatchError {
//then
XCTAssertTrue(true)
} catch {
XCTFail("should not throw this exception")
}
}
// MARK: Bool
func testBoolDecodable() {
//given
let anyObject = true
//when
let bool = try! Bool.decode(anyObject)
//then
XCTAssertEqual(bool, anyObject)
}
func testBoolDecodableFail() {
//given
let anyObject = ""
//when
do {
_ = try Bool.decode(anyObject)
} catch is TypeMismatchError {
//then
XCTAssertTrue(true)
} catch {
XCTFail("should not throw this exception")
}
}
}
|
mit
|
c282eaad9e3f01e017eecf26475fc6f1
| 21.724771 | 54 | 0.512717 | 4.944112 | false | true | false | false |
EaglesoftZJ/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Compose/AAGroupCreateViewController.swift
|
1
|
7770
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
open class AAGroupCreateViewController: AAViewController, UITextFieldDelegate {
fileprivate let isChannel: Bool
fileprivate var addPhotoButton = UIButton()
fileprivate var avatarImageView = UIImageView()
fileprivate var hint = UILabel()
fileprivate var groupName = UITextField()
fileprivate var groupNameFieldSeparator = UIView()
fileprivate var image: UIImage?
public init(isChannel: Bool) {
self.isChannel = isChannel
super.init(nibName: nil, bundle: nil)
if isChannel {
self.navigationItem.title = AALocalized("CreateChannelTitle")
} else {
self.navigationItem.title = AALocalized("CreateGroupTitle")
}
if AADevice.isiPad {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: AALocalized("NavigationCancel"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.dismissController))
}
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: AALocalized("NavigationNext"), style: UIBarButtonItemStyle.done, target: self, action: #selector(AAGroupCreateViewController.doNext))
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = appStyle.vcBgColor
view.addSubview(addPhotoButton)
view.addSubview(avatarImageView)
view.addSubview(hint)
view.addSubview(groupName)
view.addSubview(groupNameFieldSeparator)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 110, height: 110), false, 0.0);
let context = UIGraphicsGetCurrentContext();
context?.setFillColor(appStyle.composeAvatarBgColor.cgColor);
context?.fillEllipse(in: CGRect(x: 0.0, y: 0.0, width: 110.0, height: 110.0));
context?.setStrokeColor(appStyle.composeAvatarBorderColor.cgColor);
context?.setLineWidth(1.0);
context?.strokeEllipse(in: CGRect(x: 0.5, y: 0.5, width: 109.0, height: 109.0));
let buttonImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
addPhotoButton.isExclusiveTouch = true
addPhotoButton.setBackgroundImage(buttonImage, for: UIControlState())
addPhotoButton.addTarget(self, action: #selector(AAGroupCreateViewController.photoTap), for: UIControlEvents.touchUpInside)
let addPhotoLabelFirst = UILabel()
addPhotoLabelFirst.text = AALocalized("ActionAddPhoto1")
addPhotoLabelFirst.font = UIFont.systemFont(ofSize: 15.0)
addPhotoLabelFirst.backgroundColor = UIColor.clear
addPhotoLabelFirst.textColor = appStyle.composeAvatarTextColor
addPhotoLabelFirst.sizeToFit()
let addPhotoLabelSecond = UILabel()
addPhotoLabelSecond.text = AALocalized("ActionAddPhoto2")
addPhotoLabelSecond.font = UIFont.systemFont(ofSize: 15.0)
addPhotoLabelSecond.backgroundColor = UIColor.clear
addPhotoLabelSecond.textColor = appStyle.composeAvatarTextColor
addPhotoLabelSecond.sizeToFit()
addPhotoButton.addSubview(addPhotoLabelFirst)
addPhotoButton.addSubview(addPhotoLabelSecond)
addPhotoLabelFirst.frame = CGRect(x: (80 - addPhotoLabelFirst.frame.size.width) / 2, y: 22, width: addPhotoLabelFirst.frame.size.width, height: addPhotoLabelFirst.frame.size.height).integral;
addPhotoLabelSecond.frame = CGRect(x: (80 - addPhotoLabelSecond.frame.size.width) / 2, y: 22 + 22, width: addPhotoLabelSecond.frame.size.width, height: addPhotoLabelSecond.frame.size.height).integral;
groupName.backgroundColor = appStyle.vcBgColor
groupName.textColor = ActorSDK.sharedActor().style.cellTextColor
groupName.font = UIFont.systemFont(ofSize: 20)
groupName.keyboardType = UIKeyboardType.default
groupName.returnKeyType = UIReturnKeyType.next
if isChannel {
groupName.attributedPlaceholder = NSAttributedString(string: AALocalized("CreateChannelNamePlaceholder"), attributes: [NSForegroundColorAttributeName: ActorSDK.sharedActor().style.vcHintColor])
} else {
groupName.attributedPlaceholder = NSAttributedString(string: AALocalized("CreateGroupNamePlaceholder"), attributes: [NSForegroundColorAttributeName: ActorSDK.sharedActor().style.vcHintColor])
}
groupName.delegate = self
groupName.contentVerticalAlignment = UIControlContentVerticalAlignment.center
groupName.autocapitalizationType = UITextAutocapitalizationType.words
groupName.keyboardAppearance = appStyle.isDarkApp ? .dark : .light
groupNameFieldSeparator.backgroundColor = appStyle.vcSeparatorColor
if isChannel {
hint.text = AALocalized("CreateChannelHint")
} else {
hint.text = AALocalized("CreateGroupHint")
}
hint.font = UIFont.systemFont(ofSize: 15)
hint.lineBreakMode = .byWordWrapping
hint.numberOfLines = 0
hint.textColor = ActorSDK.sharedActor().style.vcHintColor
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
avatarImageView.frame = CGRect(x: 20, y: 20 + 66, width: 80, height: 80)
addPhotoButton.frame = avatarImageView.frame
hint.frame = CGRect(x: 120, y: 20 + 66, width: view.width - 140, height: 80)
groupName.frame = CGRect(x: 20, y: 106 + 66, width: view.width - 20, height: 56.0)
groupNameFieldSeparator.frame = CGRect(x: 20, y: 156 + 66, width: view.width - 20, height: 0.5)
}
open func photoTap() {
let hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.avatarImageView.image != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if index == -2 {
self.avatarImageView.image = nil
self.image = nil
} else if index >= 0 {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
self.image = image
self.avatarImageView.image = image.roundImage(80)
})
}
})
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
groupName.becomeFirstResponder()
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
doNext()
return false
}
open func doNext() {
let title = groupName.text!.trim()
if (title.length == 0) {
shakeView(groupName, originalX: groupName.frame.origin.x)
return
}
groupName.resignFirstResponder()
if isChannel {
_ = executePromise(Actor.createChannel(withTitle: title, withAvatar: nil)).then({ (gid: JavaLangInteger!) in
self.navigateNext(AAGroupTypeViewController(gid: Int(gid.intValue()), isCreation: true), removeCurrent: true)
})
} else {
navigateNext(GroupMembersController(title: title, image: image), removeCurrent: true)
}
}
}
|
agpl-3.0
|
2e618d512d0b4fd8c2e685d19541411d
| 44.976331 | 208 | 0.660875 | 5.246455 | false | false | false | false |
awsdocs/aws-doc-sdk-examples
|
swift/example_code/iam/ListRolePolicies/Sources/ServiceHandler/ServiceHandler.swift
|
1
|
2580
|
/*
A class containing functions that interact with AWS services.
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// snippet-start:[iam.swift.listrolepolicies.handler]
// snippet-start:[iam.swift.listrolepolicies.handler.imports]
import Foundation
import AWSIAM
import ClientRuntime
import AWSClientRuntime
// snippet-end:[iam.swift.listrolepolicies.handler.imports]
/// Errors returned by `ServiceHandler` functions.
enum ServiceHandlerError: Error {
case noSuchGroup
case noSuchRole
case noSuchPolicy
case noSuchUser
}
/// A class containing all the code that interacts with the AWS SDK for Swift.
public class ServiceHandler {
public let client: IamClient
/// Initialize and return a new ``ServiceHandler`` object, which is used
/// to drive the AWS calls used for the example. The Region string
/// `AWS_GLOBAL` is used because users are shared across all Regions.
///
/// - Returns: A new ``ServiceHandler`` object, ready to be called to
/// execute AWS operations.
// snippet-start:[iam.swift.listrolepolicies.handler.init]
public init() async {
do {
client = try IamClient(region: "AWS_GLOBAL")
} catch {
print("ERROR: ", dump(error, name: "Initializing Amazon IAM client"))
exit(1)
}
}
// snippet-end:[iam.swift.listrolepolicies.handler.init]
/// Returns a list of all AWS Identity and Access Management (IAM) policy
/// names.
///
/// - Returns: An array of the available policy names.
// snippet-start:[iam.swift.listrolepolicies.handler.listrolepolicies]
public func listRolePolicies(role: String) async throws -> [String] {
var policyList: [String] = []
var marker: String? = nil
var isTruncated: Bool
repeat {
let input = ListRolePoliciesInput(
marker: marker,
roleName: role
)
let output = try await client.listRolePolicies(input: input)
guard let policies = output.policyNames else {
return policyList
}
for policy in policies {
policyList.append(policy)
}
marker = output.marker
isTruncated = output.isTruncated
} while isTruncated == true
return policyList
}
// snippet-end:[iam.swift.listrolepolicies.handler.listrolepolicies]
}
// snippet-end:[iam.swift.listrolepolicies.handler]
|
apache-2.0
|
293e2769d00f0540d693edc742e883c4
| 32.947368 | 81 | 0.641085 | 4.455959 | false | false | false | false |
Blackjacx/SwiftTrace
|
Sources/main.swift
|
1
|
946
|
import Foundation
print("Welcome to SwiftTrace - The cross platform ray tracer!")
func usage() {
print("Usage: swifttrace <filename.json>")
}
if CommandLine.argc != 2 {
print("No file path provided!")
usage()
exit(0)
}
let filePath = CommandLine.arguments[1]
let startDate = Date()
print("Starting trace")
do {
let destinationName = filePath.components(separatedBy: "/").last?.components(separatedBy: ".").first ?? "test"
let raytracer = try Raytracer(filePath: filePath)
let image = raytracer.trace()
try image.write(to: destinationName + ".ppm")
print("Trace finished \(Float(Date().timeIntervalSince(startDate))) seconds")
} catch JSONError.decodingError(let className, let json) {
print("Failed initializing scene: \(className) - \(json)")
} catch FileIOError.writeError(let filePath) {
print("File not written at path: \(filePath)")
} catch {
print("File not found at: \(filePath)")
}
|
mit
|
b8500833e16b2f34d1a915a48838a968
| 27.666667 | 114 | 0.687104 | 3.925311 | false | false | false | false |
to4iki/conference-app-2017-ios
|
conference-app-2017/data/storage/LocalFile.swift
|
1
|
2126
|
import Cache
import Himotoki
import Result
struct LocalFile: Storage {
static let shared = LocalFile()
private init() {}
func read<T: Decodable>(key: String, completion: @escaping (Result<T, StorageError>) -> Void) {
guard let path = Resource.JSON(rawValue: key) else {
completion(.failure(.notFound))
return
}
guard let fileHandle = FileHandle(forReadingAtPath: path.filePath) else {
completion(.failure(.notFound))
return
}
DispatchQueue.global().async {
do {
let data = fileHandle.readDataToEndOfFile()
let json = try JSONSerialization.jsonObject(with: data, options: [])
let result = try T.decodeValue(json)
completion(.success(result))
} catch {
completion(.failure(.read(error)))
}
}
}
func read<T: Decodable>(key: String, completion: @escaping (Result<[T], StorageError>) -> Void) {
guard let path = Resource.JSON(rawValue: key) else {
completion(.failure(.notFound))
return
}
guard let fileHandle = FileHandle(forReadingAtPath: path.filePath) else {
completion(.failure(.notFound))
return
}
DispatchQueue.global().async {
do {
let data = fileHandle.readDataToEndOfFile()
let json = try JSONSerialization.jsonObject(with: data, options: [])
let result: [T] = try decodeArray(json)
completion(.success(result))
} catch {
completion(.failure(.read(error)))
}
}
}
func write(_ value: JSON, key: String, completion: @escaping (Result<Void, StorageError>) -> Void) {
log.debug("non implement")
}
func remove(key: String, completion: @escaping (Result<Void, StorageError>) -> Void) {
log.debug("non implement")
}
func removeAll(completion: @escaping (Result<Void, StorageError>) -> Void) {
log.debug("non implement")
}
}
|
apache-2.0
|
743088a4f7004d884c9b31ddbcf57dfc
| 32.21875 | 104 | 0.562088 | 4.932715 | false | false | false | false |
brunophilipe/tune
|
tune/Search/SearchEngine.swift
|
1
|
2243
|
//
// SearchEngine.swift
// tune
//
// Created by Bruno Philipe on 1/5/17.
// Copyright © 2017 Bruno Philipe. All rights reserved.
//
import Foundation
class SearchEngine
{
private var searchQueue = DispatchQueue(label: "Search Queue", qos: .background)
var delegate: SearchEngineDelegate? = nil
var mediaPlayer: MediaPlayer? = nil
func search(forTracks text: String)
{
if let delegate = self.delegate
{
// This forces one search to be executed at a time, without blocking the main queue (thread(s))
searchQueue.sync
{
if let result = mediaPlayer?.search(forTracks: text)
{
delegate.searchEngine(self, gotSearchResult: result)
}
else
{
delegate.searchEngine(self, gotErrorForSearchWithQuery: text)
}
}
}
}
func search(forAlbums text: String)
{
if let delegate = self.delegate
{
// This forces one search to be executed at a time, without blocking the main queue (thread(s))
searchQueue.sync
{
if let result = self.mediaPlayer?.search(forAlbums: text)
{
delegate.searchEngine(self, gotSearchResult: result)
}
else
{
delegate.searchEngine(self, gotErrorForSearchWithQuery: text)
}
}
}
}
func search(forPlaylists text: String)
{
if let delegate = self.delegate
{
// This forces one search to be executed at a time, without blocking the main queue (thread(s))
searchQueue.sync
{
if let result = mediaPlayer?.search(forPlaylists: text)
{
delegate.searchEngine(self, gotSearchResult: result)
}
else
{
delegate.searchEngine(self, gotErrorForSearchWithQuery: text)
}
}
}
}
}
protocol MediaSearchable
{
func search(forTracks text: String) -> SearchResult
func search(forAlbums text: String) -> SearchResult
func search(forPlaylists text: String) -> SearchResult
}
protocol SearchEngineDelegate
{
func searchEngine(_ searchEngine: SearchEngine, gotSearchResult: SearchResult)
func searchEngine(_ searchEngine: SearchEngine, gotErrorForSearchWithQuery text: String)
}
class SearchResult
{
let resultItems: [MediaPlayerItem]
let query: String
init(withItems items: [MediaPlayerItem], forQuery query: String)
{
self.resultItems = items
self.query = query
}
}
|
gpl-3.0
|
d39ee57ca8254a5c32ac2b26e0c29bab
| 21.646465 | 98 | 0.704282 | 3.58147 | false | false | false | false |
arvedviehweger/swift
|
test/decl/protocol/req/recursion.swift
|
1
|
3374
|
// RUN: %target-typecheck-verify-swift
protocol SomeProtocol {
associatedtype T
}
extension SomeProtocol where T == Optional<T> { } // expected-error{{same-type constraint 'Self.T' == 'Optional<Self.T>' is recursive}}
// rdar://problem/19840527
class X<T> where T == X { // expected-error{{same-type constraint 'T' == 'X<T>' is recursive}}
// expected-error@-1{{same-type requirement makes generic parameter 'T' non-generic}}
var type: T { return type(of: self) }
}
// FIXME: The "associated type 'Foo' is not a member type of 'Self'" diagnostic
// should also become "associated type 'Foo' references itself"
protocol CircularAssocTypeDefault {
associatedtype Z = Z // expected-error{{associated type 'Z' references itself}}
// expected-note@-1{{type declared here}}
// expected-note@-2{{protocol requires nested type 'Z'; do you want to add it?}}
associatedtype Z2 = Z3
// expected-note@-1{{protocol requires nested type 'Z2'; do you want to add it?}}
associatedtype Z3 = Z2
// expected-note@-1{{protocol requires nested type 'Z3'; do you want to add it?}}
associatedtype Z4 = Self.Z4 // expected-error{{associated type 'Z4' references itself}}
// expected-note@-1{{type declared here}}
// expected-note@-2{{protocol requires nested type 'Z4'; do you want to add it?}}
associatedtype Z5 = Self.Z6
// expected-note@-1{{protocol requires nested type 'Z5'; do you want to add it?}}
associatedtype Z6 = Self.Z5
// expected-note@-1{{protocol requires nested type 'Z6'; do you want to add it?}}
}
struct ConformsToCircularAssocTypeDefault : CircularAssocTypeDefault { }
// expected-error@-1 {{type 'ConformsToCircularAssocTypeDefault' does not conform to protocol 'CircularAssocTypeDefault'}}
// rdar://problem/20000145
public protocol P {
associatedtype T
}
public struct S<A: P> where A.T == S<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'S' references itself}}
func f(a: A.T) {
g(a: id(t: a))
// expected-error@-1 {{cannot convert value of type 'A.T' to expected argument type 'S<_>'}}
_ = A.T.self
}
func g(a: S<A>) {
f(a: id(t: a))
// expected-note@-1 {{expected an argument list of type '(a: A.T)'}}
// expected-error@-2 {{cannot invoke 'f' with an argument list of type '(a: S<A>)'}}
_ = S<A>.self
}
func id<T>(t: T) -> T {
return t
}
}
protocol I {
init()
}
protocol PI {
associatedtype T : I
}
struct SI<A: PI> : I where A : I, A.T == SI<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'SI' references itself}}
func ggg<T : I>(t: T.Type) -> T {
return T()
}
func foo() {
_ = A()
_ = A.T()
_ = SI<A>()
_ = ggg(t: A.self)
_ = ggg(t: A.T.self)
_ = self.ggg(t: A.self)
_ = self.ggg(t: A.T.self)
}
}
// Used to hit infinite recursion
struct S4<A: PI> : I where A : I {
}
struct S5<A: PI> : I where A : I, A.T == S4<A> {
// expected-warning@-1{{redundant conformance constraint 'A': 'I'}}
// expected-warning@-2{{redundant conformance constraint 'A': 'PI'}}
// expected-note@-3{{conformance constraint 'A': 'PI' inferred from type here}}
// expected-note@-4{{conformance constraint 'A': 'I' inferred from type here}}
}
// Used to hit ArchetypeBuilder assertions
struct SU<A: P> where A.T == SU {
}
struct SIU<A: PI> : I where A : I, A.T == SIU {
}
|
apache-2.0
|
9fc574ce46eb9723bd16a9e1690bebb2
| 29.125 | 135 | 0.644932 | 3.213333 | false | false | false | false |
jjatie/Charts
|
Source/Charts/Components/Legend.swift
|
1
|
12495
|
//
// Legend.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 CoreGraphics
import Foundation
open class Legend: Component {
public enum Form {
/// Avoid drawing a form
case none
/// Do not draw the a form, but leave space for it
case empty
/// Use default (default dataset's form to the legend's form)
case `default`
/// Draw a square
case square
/// Draw a circle
case circle
/// Draw a horizontal line
case line
}
public enum HorizontalAlignment {
case left
case center
case right
}
public enum VerticalAlignment {
case top
case center
case bottom
}
public enum Orientation {
case horizontal
case vertical
}
public enum Direction {
case leftToRight
case rightToLeft
}
public var isEnabled = true
public var xOffset: CGFloat = 5
public var yOffset: CGFloat = 3
/// The legend entries array
open var entries = [LegendEntry]()
/// Entries that will be appended to the end of the auto calculated entries after calculating the legend.
/// (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect)
open var extraEntries = [LegendEntry]()
/// Are the legend labels/colors a custom value or auto calculated? If false, then it's auto, if true, then custom.
///
/// **default**: false (automatic legend)
private var _isLegendCustom = false
/// The horizontal alignment of the legend
open var horizontalAlignment = HorizontalAlignment.left
/// The vertical alignment of the legend
open var verticalAlignment = VerticalAlignment.bottom
/// The orientation of the legend
open var orientation = Orientation.horizontal
/// Flag indicating whether the legend will draw inside the chart or outside
open var drawInside: Bool = false
/// Flag indicating whether the legend will draw inside the chart or outside
open var isDrawInsideEnabled: Bool { return drawInside }
/// The text direction of the legend
open var direction = Direction.leftToRight
open var font = NSUIFont.systemFont(ofSize: 10.0)
open var textColor = NSUIColor.labelOrBlack
/// The form/shape of the legend forms
open var form = Form.square
/// The size of the legend forms
open var formSize = CGFloat(8.0)
/// The line width for forms that consist of lines
open var formLineWidth = CGFloat(3.0)
/// Line dash configuration for shapes that consist of lines.
///
/// This is how much (in pixels) into the dash pattern are we starting from.
open var formLineDashPhase: CGFloat = 0.0
/// Line dash configuration for shapes that consist of lines.
///
/// This is the actual dash pattern.
/// I.e. [2, 3] will paint [-- -- ]
/// [1, 3, 4, 2] will paint [- ---- - ---- ]
open var formLineDashLengths: [CGFloat]?
open var xEntrySpace = CGFloat(6.0)
open var yEntrySpace = CGFloat(0.0)
open var formToTextSpace = CGFloat(5.0)
open var stackSpace = CGFloat(3.0)
open var calculatedLabelSizes = [CGSize]()
open var calculatedLabelBreakPoints = [Bool]()
open var calculatedLineSizes = [CGSize]()
public init(entries: [LegendEntry] = []) {
self.entries = entries
}
open func getMaximumEntrySize(withFont font: NSUIFont) -> CGSize {
var maxW = CGFloat(0.0)
var maxH = CGFloat(0.0)
var maxFormSize: CGFloat = 0.0
for entry in entries {
let formSize = entry.formSize.isNaN ? self.formSize : entry.formSize
if formSize > maxFormSize {
maxFormSize = formSize
}
guard let label = entry.label
else { continue }
let size = (label as NSString).size(withAttributes: [.font: font])
if size.width > maxW {
maxW = size.width
}
if size.height > maxH {
maxH = size.height
}
}
return CGSize(
width: maxW + maxFormSize + formToTextSpace,
height: maxH
)
}
open var neededWidth = CGFloat(0.0)
open var neededHeight = CGFloat(0.0)
open var textWidthMax = CGFloat(0.0)
open var textHeightMax = CGFloat(0.0)
/// flag that indicates if word wrapping is enabled
/// this is currently supported only for `orientation == Horizontal`.
/// you may want to set maxSizePercent when word wrapping, to set the point where the text wraps.
///
/// **default**: true
open var wordWrapEnabled = true
/// if this is set, then word wrapping the legend is enabled.
open var isWordWrapEnabled: Bool { return wordWrapEnabled }
/// The maximum relative size out of the whole chart view in percent.
/// If the legend is to the right/left of the chart, then this affects the width of the legend.
/// If the legend is to the top/bottom of the chart, then this affects the height of the legend.
///
/// **default**: 0.95 (95%)
open var maxSizePercent: CGFloat = 0.95
open func calculateDimensions(labelFont: NSUIFont, viewPortHandler: ViewPortHandler) {
let maxEntrySize = getMaximumEntrySize(withFont: labelFont)
let defaultFormSize = formSize
let stackSpace = self.stackSpace
let formToTextSpace = self.formToTextSpace
let xEntrySpace = self.xEntrySpace
let yEntrySpace = self.yEntrySpace
let wordWrapEnabled = self.wordWrapEnabled
let entries = self.entries
let entryCount = entries.count
textWidthMax = maxEntrySize.width
textHeightMax = maxEntrySize.height
switch orientation {
case .vertical:
var maxWidth = CGFloat(0.0)
var width = CGFloat(0.0)
var maxHeight = CGFloat(0.0)
let labelLineHeight = labelFont.lineHeight
var wasStacked = false
for i in entries.indices {
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
if !wasStacked {
width = 0.0
}
if drawingForm {
if wasStacked {
width += stackSpace
}
width += formSize
}
if let label = e.label {
let size = (label as NSString).size(withAttributes: [.font: labelFont])
if drawingForm, !wasStacked {
width += formToTextSpace
} else if wasStacked {
maxWidth = max(maxWidth, width)
maxHeight += labelLineHeight + yEntrySpace
width = 0.0
wasStacked = false
}
width += size.width
maxHeight += labelLineHeight + yEntrySpace
} else {
wasStacked = true
width += formSize
if i < entryCount - 1 {
width += stackSpace
}
}
maxWidth = max(maxWidth, width)
}
neededWidth = maxWidth
neededHeight = maxHeight
case .horizontal:
let labelLineHeight = labelFont.lineHeight
let contentWidth: CGFloat = viewPortHandler.contentWidth * maxSizePercent
// Prepare arrays for calculated layout
if calculatedLabelSizes.count != entryCount {
calculatedLabelSizes = [CGSize](repeating: CGSize(), count: entryCount)
}
if calculatedLabelBreakPoints.count != entryCount {
calculatedLabelBreakPoints = [Bool](repeating: false, count: entryCount)
}
calculatedLineSizes.removeAll(keepingCapacity: true)
// Start calculating layout
var maxLineWidth: CGFloat = 0.0
var currentLineWidth: CGFloat = 0.0
var requiredWidth: CGFloat = 0.0
var stackedStartIndex: Int = -1
for i in entries.indices {
let e = entries[i]
let drawingForm = e.form != .none
let label = e.label
calculatedLabelBreakPoints[i] = false
if stackedStartIndex == -1 {
// we are not stacking, so required width is for this label only
requiredWidth = 0.0
} else {
// add the spacing appropriate for stacked labels/forms
requiredWidth += stackSpace
}
// grouped forms have null labels
if let label = label {
calculatedLabelSizes[i] = (label as NSString).size(withAttributes: [.font: labelFont])
requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0
requiredWidth += calculatedLabelSizes[i].width
} else {
calculatedLabelSizes[i] = CGSize()
requiredWidth += drawingForm ? formSize : 0.0
if stackedStartIndex == -1 {
// mark this index as we might want to break here later
stackedStartIndex = i
}
}
if label != nil || i == entryCount - 1 {
let requiredSpacing = currentLineWidth == 0.0 ? 0.0 : xEntrySpace
if !wordWrapEnabled || // No word wrapping, it must fit.
currentLineWidth == 0.0 || // The line is empty, it must fit.
(contentWidth - currentLineWidth >= requiredSpacing + requiredWidth) // It simply fits
{
// Expand current line
currentLineWidth += requiredSpacing + requiredWidth
} else { // It doesn't fit, we need to wrap a line
// Add current line size to array
calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight))
maxLineWidth = max(maxLineWidth, currentLineWidth)
// Start a new line
calculatedLabelBreakPoints[stackedStartIndex > -1 ? stackedStartIndex : i] = true
currentLineWidth = requiredWidth
}
if i == entryCount - 1 { // Add last line size to array
calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight))
maxLineWidth = max(maxLineWidth, currentLineWidth)
}
}
stackedStartIndex = label != nil ? -1 : stackedStartIndex
}
neededWidth = maxLineWidth
neededHeight = labelLineHeight * CGFloat(calculatedLineSizes.count) +
yEntrySpace * CGFloat(calculatedLineSizes.isEmpty ? 0 : (calculatedLineSizes.count - 1))
}
neededWidth += xOffset
neededHeight += yOffset
}
// MARK: - Custom legend
/// Sets a custom legend's entries array.
/// * A nil label will start a group.
/// This will disable the feature that automatically calculates the legend entries from the datasets.
/// Call `resetCustom(...)` to re-enable automatic calculation (and then `notifyDataSetChanged()` is needed).
open func setCustom(entries: [LegendEntry]) {
self.entries = entries
_isLegendCustom = true
}
/// Calling this will disable the custom legend entries (set by `setLegend(...)`). Instead, the entries will again be calculated automatically (after `notifyDataSetChanged()` is called).
open func resetCustom() {
_isLegendCustom = false
}
/// **default**: false (automatic legend)
/// `true` if a custom legend entries has been set
open var isLegendCustom: Bool {
return _isLegendCustom
}
}
|
apache-2.0
|
16bfe8572dcbe494a8135405cae417ce
| 33.232877 | 190 | 0.573189 | 5.437337 | false | false | false | false |
zhangzichen/Pontus
|
Pontus/Swift+Pontus/Alert.swift
|
1
|
1588
|
import UIKit
open class Alert {
var title: String?
var message: String?
var style = UIAlertControllerStyle.alert
var actions = [UIAlertAction]()
weak var alertController: UIAlertController?
open class func showIn(_ vc: UIViewController) -> Alert {
let alert = Alert()
DispatchQueue.main.async {
let alertController = UIAlertController(title: alert.title, message: alert.message, preferredStyle: alert.style)
alert.alertController = alertController
for action in alert.actions {
alertController.addAction(action)
}
vc.present(alertController, animated: true, completion: nil)
}
return alert
}
/// Set title
open func title(_ title: String?) -> Self {
self.title = title
return self
}
/// Set message
open func message(_ message: String?) -> Self {
self.message = message
return self
}
/// Set style
open func preferredStyle(_ style: UIAlertControllerStyle) -> Self {
self.style = style
return self
}
/// Add a button
open func addAction(_ title: String?, style: UIAlertActionStyle, handler: ((UIAlertAction) -> Void)?) -> Self {
let action = UIAlertAction(title: title, style: style) { [weak self] in
handler?($0)
self?.alertController?.dismiss(animated: true, completion: nil)
}
actions.append(action)
return self
}
}
|
mit
|
5b01b3f177781b2884b8c28ac951965c
| 26.37931 | 124 | 0.575567 | 5.206557 | false | false | false | false |
kmalkic/LazyKit
|
LazyKit/Classes/Theming/Sets/LazyStyleSet.swift
|
1
|
1240
|
//
// StyleSet.swift
// LazyKit
//
// Created by Kevin Malkic on 22/04/2015.
// Copyright (c) 2015 Malkic Kevin. All rights reserved.
//
import UIKit
internal class LazyStyleSet : NSObject {
var patterns = [String]()
var basicSet: LazyBasicSet?
var textSet: LazyTextSet?
var placeholderSet: LazyTextSet?
var decorationSet: LazyDecorationSet?
var optionSet: LazyOptionSet?
override init() {
}
init(elementName: String!, content: [String]!, variables: [String: String]?) {
let separatedPatterns = elementName.components(separatedBy: ",")
for (pattern) in separatedPatterns {
patterns.append(pattern.trimmingCharacters(in: CharacterSet.whitespaces))
}
basicSet = LazyBasicSet(content: content, variables: variables)
textSet = LazyTextSet(content: content, variables: variables)
placeholderSet = LazyTextSet(content: content, variables: variables, textSearchMode: .Placeholder)
decorationSet = LazyDecorationSet(content: content, variables: variables)
optionSet = LazyOptionSet(content: content, variables: variables)
}
}
|
mit
|
814f1b4bc23ccc902a7439e9b76d804e
| 30 | 107 | 0.641129 | 4.609665 | false | false | false | false |
SwiftGen/SwiftGen
|
Sources/SwiftGenKit/Parsers/Files/FilesFile.swift
|
1
|
1096
|
//
// SwiftGenKit
// Copyright © 2022 SwiftGen
// MIT Licence
//
import Foundation
import PathKit
extension Files {
struct File {
let name: String
let ext: String?
let path: [String]
let mimeType: String
init(path: Path, relativeTo parent: Path? = nil) throws {
guard path.exists else {
throw ParserError.invalidFile(path: path, reason: "Unable to read file")
}
self.ext = path.extension
self.name = path.lastComponentWithoutExtension
if let relative = parent.flatMap({ path.relative(to: $0) })?.parent(),
relative != "." {
self.path = relative.components
} else {
self.path = []
}
if let ext = self.ext,
let uti = UTTypeCreatePreferredIdentifierForTag(
kUTTagClassFilenameExtension, ext as NSString, nil
)?.takeRetainedValue(),
let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
self.mimeType = mimetype as String
} else {
self.mimeType = "application/octet-stream"
}
}
}
}
|
mit
|
a0b503c842ec22a874c1ff4deb5b8854
| 25.071429 | 103 | 0.627397 | 4.639831 | false | false | false | false |
mumbler/PReVo-iOS
|
PoshReVo/Motoroj/Iloj.swift
|
1
|
12529
|
//
// Iloj.swift
// PoshReVo
//
// Created by Robin Hill on 3/11/16.
// Copyright © 2016 Robin Hill. All rights reserved.
//
import Foundation
import UIKit
import ReVoModeloj
let markoLigoKlavo = "ligo"
let markoAkcentoKlavo = "akcento"
let markoFortoKlavo = "forto"
let markoSuperKlavo = "super"
let markoSubKlavo = "sub"
public struct AtentigoNomoj {
static let elektisTradukLingvojn = "elektisTradukLingvoj"
}
/*
Diversaj iloj
*/
class Iloj {
// Aldoni chapelon al litero, se tio taugas
static func chapeli(_ litero: Character) -> Character? {
let unua = "chgjsuCGHJSU"
let dua = "ĉĥĝĵŝŭĈĜĤĴŜŬ"
for i in 0 ..< unua.count {
if unua[unua.index(unua.startIndex, offsetBy: i)] == litero {
return dua[dua.index(dua.startIndex, offsetBy: i)]
}
}
return nil
}
static func chapeliFinon(_ teksto: String) -> String {
if let lasta = teksto.last, let chapelita = Iloj.chapeli(lasta) {
return teksto.prefix(teksto.count - 1) + String(chapelita)
}
return teksto
}
static func majuskligiUnuan(_ teksto: String) -> String {
return teksto.prefix(1).uppercased() + teksto.lowercased().dropFirst()
}
// Trovi la X-an literon de la alfabeto (por listado)
static func alLitero(nombro: Int, _ granda: Bool) -> String {
let alfabeto = "abcdefghijklmnoprstuvz"
if nombro >= alfabeto.count {
return ""
}
let litero = alfabeto[alfabeto.index(alfabeto.startIndex, offsetBy: nombro)]
if !granda {
return String(litero)
} else {
return String(litero).uppercased()
}
}
// Trovi Romian version de nombro (por listado)
static func alRomia(nombro: Int) -> String {
let romiajLiteroj = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabajLiteroj = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romia = ""
var komenca = nombro
for (index, romiaLitero) in romiajLiteroj.enumerated() {
let arabaSumo = arabajLiteroj[index]
let div = komenca / arabaSumo
if (div > 0)
{
for _ in 0 ..< div
{
romia += romiaLitero
}
komenca -= arabaSumo * div
}
}
return romia
}
// Funkcioj pri TTTAttributedLabel uzado ===================
/*
Legi la tekston kaj trovi markojn reprezentata de HTML kodoj.
Tiu trovos:
<i>...</i> por akcentaj tekstoj
<b>...</b> por fortaj tekstoj
<a href="...">...</a> por ligoj
La rezulto estas aro de listo de trovajhoj, en la form do (komenca loko, fina loko, ligo-teksto)
*/
static func troviMarkojn(teksto: String) -> [String : [(Int, Int, String)]] {
var rez = [String : [(Int, Int, String)]]()
rez[markoAkcentoKlavo] = [(Int, Int, String)]()
rez[markoFortoKlavo] = [(Int, Int, String)]()
rez[markoLigoKlavo] = [(Int, Int, String)]()
rez[markoSuperKlavo] = [(Int, Int, String)]()
rez[markoSubKlavo] = [(Int, Int, String)]()
let regesp = try! NSRegularExpression(pattern: "<(/?([ikbga]|sup|sub|frm))( (href|am)=\"(.*?)\")?>")
let matches = regesp.matches(in: teksto, range: NSRange(teksto.startIndex..., in: teksto))
var rubo = 0
var ligoStako = [(Int, String)]()
var akcentoStako = [Int]()
var fortoStako = [Int]()
var superStako = [Int]()
var subStako = [Int]()
for match in matches {
let range = match.range
let klavo = String(teksto[Range(match.range(at: 1), in: teksto)!])
let loko = range.location - rubo
if klavo == "i" || klavo == "k" {
akcentoStako.append(loko)
}
else if klavo == "/i" || klavo == "/k" {
if let nombro = akcentoStako.popLast() {
rez[markoAkcentoKlavo]?.append((nombro, loko, ""))
}
}
else if klavo == "b" || klavo == "g" {
fortoStako.append(loko)
}
else if klavo == "/b" || klavo == "/g" {
if let nombro = fortoStako.popLast() {
rez[markoFortoKlavo]?.append((nombro, loko, ""))
}
}
else if klavo == "sup" {
superStako.append(loko)
}
else if klavo == "/sup" {
if let nombro = superStako.popLast() {
rez[markoSuperKlavo]?.append((nombro, loko, ""))
}
}
else if klavo == "sub" {
subStako.append(loko)
}
else if klavo == "/sub" {
if let nombro = subStako.popLast() {
rez[markoSubKlavo]?.append((nombro, loko, ""))
}
}
else if klavo == "/a" {
if let ligo = ligoStako.popLast() {
let nombro = ligo.0, celo = ligo.1
rez[markoLigoKlavo]?.append((nombro, loko, celo))
}
}
else if klavo == "a" && match.numberOfRanges >= 4 {
let ligLoko = match.range(at: 5)
if ligLoko.location != NSNotFound {
let ligCelo = String(teksto[Range(ligLoko, in: teksto)!])
ligoStako.append((loko, ligCelo))
}
} else {
}
rubo += range.length
}
return rez
}
// Forigi la HTML kodojn el la teksto, por ke ghi povu montriĝi nude
static func forigiAngulojn(teksto: String) -> String {
var rez: String = ""
var en: Bool = false
var enhavoj: String = ""
for literoScalar in teksto.unicodeScalars {
let litero = String(literoScalar)
if litero == "<" {
en = true
enhavoj.append(litero)
} else if litero == ">" {
en = false
enhavoj.append(litero)
do {
let regesp = try NSRegularExpression(pattern: "(<a href=\"(.*?)\">)|(<frm am=\".*?\">)", options: NSRegularExpression.Options())
let trovoj = regesp.matches(in: enhavoj, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, enhavoj.count))
if trovoj.count > 0 {
// Fari nenion
} else if enhavoj == "<i>" ||
enhavoj == "</i>" ||
enhavoj == "<k>" ||
enhavoj == "</k>" ||
enhavoj == "<b>" ||
enhavoj == "</b>" ||
enhavoj == "<g>" ||
enhavoj == "</g>" ||
enhavoj == "<sup>" ||
enhavoj == "</sup>" ||
enhavoj == "<sub>" ||
enhavoj == "</sub>" ||
enhavoj == "</a>" ||
enhavoj == "<frm>" ||
enhavoj == "</frm>" {
// Fari nenion
} else {
rez += enhavoj
}
enhavoj = ""
} catch { }
} else if en {
enhavoj.append(litero)
} else {
rez.append(litero)
}
}
return rez
}
// Pretigi NSAttributedString kun la akcentoj, fortaj regionoj, kaj ligoj kiujn uzas artikoloj ktp.
// Chi tiu funkciono uzas la rezultojn de la troviMarkojn funkcio
static func pretigiTekston(_ teksto: String, kunMarkoj markoj: [String : [(Int, Int, String)]] ) -> NSMutableAttributedString {
let mutaciaTeksto: NSMutableAttributedString = NSMutableAttributedString(string: forigiAngulojn(teksto: teksto))
let tekstGrandeco = UIFont.preferredFont(forTextStyle: .body).pointSize
let tekstStilo = UIFont.systemFont(ofSize: tekstGrandeco)
let fortaTeksto = UIFont.boldSystemFont(ofSize: tekstGrandeco)
let akcentaTeksto = UIFont.italicSystemFont(ofSize: tekstGrandeco)
let fortaAkcentaDescriptor = fortaTeksto.fontDescriptor.withSymbolicTraits([.traitItalic, .traitBold])!
let fortaAkcentaTeksto = UIFont(descriptor: fortaAkcentaDescriptor, size: tekstGrandeco)
mutaciaTeksto.addAttribute(.font, value: tekstStilo, range: NSMakeRange(0, mutaciaTeksto.length))
mutaciaTeksto.addAttribute(.foregroundColor, value: UzantDatumaro.stilo.tekstKoloro, range: NSMakeRange(0, mutaciaTeksto.length))
for akcentMarko in markoj[markoAkcentoKlavo]! {
guard akcentMarko.0 >= 0 && akcentMarko.1 <= mutaciaTeksto.length else { continue }
mutaciaTeksto.addAttribute(.font, value: akcentaTeksto, range: NSMakeRange(akcentMarko.0, akcentMarko.1 - akcentMarko.0))
}
for fortMarko in markoj[markoFortoKlavo]! {
guard fortMarko.0 >= 0 && fortMarko.1 <= mutaciaTeksto.length else { continue }
var fortaRange = NSMakeRange(fortMarko.0, fortMarko.1 - fortMarko.0)
let attributes = mutaciaTeksto.attributes(at: fortMarko.0, effectiveRange: &fortaRange)
if attributes[.font] as! UIFont == akcentaTeksto {
mutaciaTeksto.addAttribute(.font, value: fortaAkcentaTeksto, range: NSMakeRange(fortMarko.0, fortMarko.1 - fortMarko.0))
} else {
mutaciaTeksto.addAttribute(.font, value: fortaTeksto, range: NSMakeRange(fortMarko.0, fortMarko.1 - fortMarko.0))
}
}
for superMarko in markoj[markoSuperKlavo]! {
guard superMarko.0 >= 0 && superMarko.1 <= mutaciaTeksto.length else { continue }
mutaciaTeksto.addAttribute(kCTSuperscriptAttributeName as NSAttributedString.Key, value: 2, range: NSMakeRange(superMarko.0, superMarko.1 - superMarko.0))
}
for subMarko in markoj[markoSubKlavo]! {
guard subMarko.0 >= 0 && subMarko.1 <= mutaciaTeksto.length else { continue }
mutaciaTeksto.addAttribute(kCTSuperscriptAttributeName as NSAttributedString.Key, value: -2, range: NSMakeRange(subMarko.0, subMarko.1 - subMarko.0))
}
return mutaciaTeksto
}
static func superLit(_ litero: String) -> String {
var ret: String = ""
for char in litero {
switch char {
case "*":
ret += "*";
case "0":
ret += "⁰";
case "1":
ret += "¹";
case "2":
ret += "²";
case "3":
ret += "³";
case "4":
ret += "⁴";
case "5":
ret += "⁵";
case "6":
ret += "⁶";
case "7":
ret += "⁷";
case "8":
ret += "⁸";
case "9":
ret += "⁹";
default:
ret += "";
}
}
return ret
}
//MARK: - Lingvo-traktado
public static func filtriLingvojn(teksto: String, lingvoj: [Lingvo], montriEsperanton: Bool = true) -> [Lingvo] {
var trovitaj = [Lingvo]()
for lingvo in lingvoj {
if lingvo.nomo.prefix(teksto.count).lowercased() == teksto.lowercased() &&
!(!montriEsperanton && lingvo == Lingvo.esperanto) {
trovitaj.append(lingvo)
}
}
return trovitaj
}
}
|
mit
|
6a05841cd5cfeed3f8cc608e59daea79
| 35.017291 | 166 | 0.483357 | 3.834919 | false | false | false | false |
yourtion/HTTPDNS-Swift
|
HTTPDNS/Factory.swift
|
1
|
2593
|
//
// Factory.swift
// HTTPDNS
//
// Created by YourtionGuo on 4/21/16.
// Copyright © 2016 Yourtion. All rights reserved.
//
import Foundation
struct DNSRecord {
let ip : String
let ttl : Int
let ips : Array<String>
}
protocol HTTPDNSBaseProtocol {
func parseResult (_ data: Data) -> DNSRecord!
func getRequestString(_ domain: String) -> String
}
class HTTPDNSBase: HTTPDNSBaseProtocol {
func getRequestString(_ domain: String) -> String {
return ""
}
func parseResult (_ data: Data) -> DNSRecord! {
return nil
}
func requsetRecord(_ domain: String, callback: @escaping (_ result:DNSRecord?) -> Void) {
let urlString = getRequestString(domain)
guard let url = URL(string: urlString) else {
print("Error: cannot create URL")
callback(nil)
return
}
let task = URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) in
guard let responseData = data else {
print("Error: Didn't receive data")
callback(nil)
return
}
guard error == nil else {
print("Error: Calling GET error on " + urlString)
print(error?.localizedDescription)
callback(nil)
return
}
if let result = NSString(data: responseData, encoding: String.Encoding.utf8.rawValue) {
print("result = \(result)")
}
guard let res = self.parseResult(responseData) else {
return callback(nil)
}
callback(res)
})
task.resume()
}
func requsetRecordSync(_ domain: String) -> DNSRecord! {
let urlString = getRequestString(domain)
print(urlString)
guard let url = URL(string: urlString) else {
print("Error: Can't create URL")
return nil
}
guard let data = try? Data.init(contentsOf: url) else {
print("Error: Did not receive data")
return nil
}
guard let res = self.parseResult(data) else {
print("Error: ParseResult error")
return nil
}
return res
}
}
class HTTPDNSFactory {
func getDNSPod() -> HTTPDNSBase {
return DNSpod()
}
func getAliYun(_ key:String = "100000") -> HTTPDNSBase {
return AliYun(account:key)
}
func getGoogle() -> HTTPDNSBase {
return Google()
}
}
|
mit
|
1de0a052be2f0f521f8b460bd08118ef
| 26.284211 | 103 | 0.545525 | 4.531469 | false | false | false | false |
lerigos/music-service
|
iOS_9/Pods/SwiftyVK/Source/API/Pages.swift
|
2
|
2339
|
extension _VKAPI {
///Methods for working with community pages. More - https://vk.com/dev/pages
public struct Pages {
///Returns information about a wiki page. More - https://vk.com/dev/pages.get
public static func get(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "pages.get", parameters: parameters)
}
///Saves the text of a wiki page. More - https://vk.com/dev/pages.save
public static func save(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "pages.save", parameters: parameters)
}
///Saves modified read and edit access settings for a wiki page. More - https://vk.com/dev/pages.saveAccess
public static func saveAccess(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "pages.saveAccess", parameters: parameters)
}
///Returns a list of all previous versions of a wiki page. More - https://vk.com/dev/pages.getHistory
public static func getHistory(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "pages.getHistory", parameters: parameters)
}
///Returns a list of wiki pages in a group. More - https://vk.com/dev/pages.getTitles
public static func getTitles(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "pages.getTitles", parameters: parameters)
}
///Returns the text of one of the previous versions of a wiki page. More - https://vk.com/dev/pages.getVersion
public static func getVersion(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "pages.getVersion", parameters: parameters)
}
///Returns HTML representation of the wiki markup. More - https://vk.com/dev/pages.parseWiki
public static func parseWiki(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "pages.parseWiki", parameters: parameters)
}
///Allows to clear the cache of particular external pages which may be attached to VK posts. More - https://vk.com/dev/pages.clearCache
public static func clearCache(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "pages.clearCache", parameters: parameters)
}
}
}
|
apache-2.0
|
7f8b8dbd9e30ce979dff3ea6be8bb6d6
| 37.344262 | 139 | 0.644292 | 4.237319 | false | false | false | false |
lerigos/music-service
|
iOS_9/Pods/SwiftyVK/Source/API/Audio.swift
|
2
|
5925
|
extension _VKAPI {
///Methods for working with audio. More - https://vk.com/dev/audio
public struct Audio {
///Returns a list of audio files of a user or community. More - https://vk.com/dev/audio.get
public static func get(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.get", parameters: parameters)
}
///Returns information about audio files by their IDs. More - https://vk.com/dev/audio.getById
public static func getById(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.getById", parameters: parameters)
}
///Returns lyrics associated with an audio file. More - https://vk.com/dev/audio.getLyrics
public static func getLyrics(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.getLyrics", parameters: parameters)
}
///Returns a list of audio files. More - https://vk.com/dev/audio.search
public static func search(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.search", parameters: parameters)
}
///Returns the server address to upload audio files. More - https://vk.com/dev/audio.getUploadServer
public static func getUploadServer(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.getUploadServer", parameters: parameters)
}
///Saves audio files after successful uploading. More - https://vk.com/dev/audio.save
public static func save(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.save", parameters: parameters)
}
///Copies an audio file to a user page or community page. More - https://vk.com/dev/audio.add
public static func add(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.add", parameters: parameters)
}
///Deletes an audio file from a user page or community page. More - https://vk.com/dev/audio.delete
public static func delete(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.delete", parameters: parameters)
}
///Edits an audio file on a user or community page. More - https://vk.com/dev/audio.edit
public static func edit(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.edit", parameters: parameters)
}
///Reorders an audio file, placing it between other specified audio files. More - https://vk.com/dev/audio.reorder
public static func reorder(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.reorder", parameters: parameters)
}
///Restores a deleted audio file. More - https://vk.com/dev/audio.restore
public static func restore(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.restore", parameters: parameters)
}
///Returns a list of audio albums of a user or community. More - https://vk.com/dev/audio.getAlbums
public static func getAlbums(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.getAlbums", parameters: parameters)
}
///Creates an empty audio album. More - https://vk.com/dev/audio.addAlbum
public static func addAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.addAlbum", parameters: parameters)
}
///Edits the title of an audio album. More - https://vk.com/dev/audio.editAlbum
public static func editAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.editAlbum", parameters: parameters)
}
///Deletes an audio album. More - https://vk.com/dev/audio.deleteAlbum
public static func deleteAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.deleteAlbum", parameters: parameters)
}
///Moves audio files to an album. More - https://vk.com/dev/audio.moveToAlbum
public static func moveToAlbum(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.moveToAlbum", parameters: parameters)
}
///Activates an audio broadcast to the status of a user or community. More - https://vk.com/dev/audio.setBroadcast
public static func setBroadcast(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.setBroadcast", parameters: parameters)
}
///Returns a list of the user's friends and communities that are broadcasting music in their statuses. More - https://vk.com/dev/audio.getBroadcastList
public static func getBroadcastList(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.getBroadcastList", parameters: parameters)
}
///Returns a list of suggested audio files based on a user's playlist or a particular audio file. More - https://vk.com/dev/audio.getRecommendations
public static func getRecommendations(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.getRecommendations", parameters: parameters)
}
///Returns a list of audio files from the "Popular". More - https://vk.com/dev/audio.getPopular
public static func getPopular(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.getPopular", parameters: parameters)
}
///Returns the total number of audio files on a user or community page. More - https://vk.com/dev/audio.getCount
public static func getCount(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "audio.getCount", parameters: parameters)
}
}
}
|
apache-2.0
|
849154b71082b06532ca2c6403b3c896
| 37.980263 | 155 | 0.644388 | 4.284165 | false | false | false | false |
banxi1988/BXForm
|
Pod/Classes/View/RadioGroup.swift
|
3
|
2127
|
//
// RadioGroup.swift
//
// Created by Haizhen Lee on 15/12/5.
//
import UIKit
import SwiftyJSON
import BXModel
// -RadioGroup:c
class RadioGroup<T:BXRadioItemAware> : UICollectionView where T:Equatable{
let flowLayout : UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 72, height: 36)
layout.minimumInteritemSpacing = 8
layout.minimumLineSpacing = 0
return layout
}()
lazy var adapter: SimpleGenericCollectionViewAdapter<T,RadioButtonCell> = {
let adapter = SimpleGenericCollectionViewAdapter<T,RadioButtonCell>(collectionView:self)
adapter.didSelectedItem = {
item,path in
self.selectedIndexPath = path
}
return adapter
}()
init(frame:CGRect) {
super.init(frame: frame, collectionViewLayout: flowLayout)
commonInit()
}
func bind<S:Sequence>(_ items:S) where S.Iterator.Element == T{
adapter.updateItems(items)
}
func selectItem(_ item:T){
if let index = adapter.indexOfItem(item){
let indexPath = IndexPath(item: index, section: 0)
selectedIndexPath = indexPath
selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
}
}
override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
var allOutlets :[UIView]{
return []
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func commonInit(){
for childView in allOutlets{
addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
func installConstaints(){
}
func setupAttrs(){
backgroundColor = .clear
}
var selectedIndexPath:IndexPath?
var selectedItem:T?{
if let path = selectedIndexPath{
return adapter.itemAtIndexPath(path)
}
return nil
}
// UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) {
selectedIndexPath = indexPath
}
}
|
mit
|
733ae1f97ef16846e7b161b30d404668
| 20.27 | 116 | 0.692525 | 4.812217 | false | false | false | false |
ochan1/OC-PublicCode
|
MakeSchoolNotes-Swift-V2-Starter-swift3-coredata/MakeSchoolNotes/AppDelegate.swift
|
3
|
4466
|
//
// AppDelegate.swift
// MakeSchoolNotes
//
// Created by Chris Orcutt on 1/10/16.
// Copyright © 2016 MakeSchool. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Core Data stack
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 container = NSPersistentContainer(name: "MakeSchoolNotes")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// 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), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// 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.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
mit
|
f24ef34fb33352de821147719560d9c2
| 48.065934 | 285 | 0.675476 | 5.875 | false | false | false | false |
vapor/vapor
|
Sources/Vapor/HTTP/Headers/HTTPHeaders+ContentRange.swift
|
1
|
10522
|
import Foundation
extension HTTPHeaders {
/// The unit in which `ContentRange`s and `Range`s are specified. This is usually `bytes`.
/// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
public enum RangeUnit: Equatable {
case bytes
case custom(value: String)
public func serialize() -> String {
switch self {
case .bytes:
return "bytes"
case .custom(let value):
return value
}
}
}
/// Represents the HTTP `Range` request header.
/// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range
public struct Range: Equatable {
public let unit: RangeUnit
public let ranges: [HTTPHeaders.Range.Value]
public init(unit: RangeUnit, ranges: [HTTPHeaders.Range.Value]) {
self.unit = unit
self.ranges = ranges
}
init?(directives: [HTTPHeaders.Directive]) {
let rangeCandidates: [HTTPHeaders.Range.Value] = directives.enumerated().compactMap {
if $0.0 == 0, let parameter = $0.1.parameter {
return HTTPHeaders.Range.Value.from(requestStr: parameter)
}
return HTTPHeaders.Range.Value.from(requestStr: $0.1.value)
}
guard !rangeCandidates.isEmpty else {
return nil
}
self.ranges = rangeCandidates
let lowerCasedUnit = directives[0].value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
self.unit = lowerCasedUnit == "bytes"
? RangeUnit.bytes
: RangeUnit.custom(value: lowerCasedUnit)
}
public func serialize() -> String {
return "\(unit.serialize())=\(ranges.map { $0.serialize() }.joined(separator: ", "))"
}
}
/// Represents the HTTP `Content-Range` response header.
///
/// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
public struct ContentRange: Equatable {
public let unit: RangeUnit
public let range: HTTPHeaders.ContentRange.Value
init?(directive: HTTPHeaders.Directive) {
let splitResult = directive.value.split(separator: " ")
guard splitResult.count == 2 else {
return nil
}
let (unitStr, rangeStr) = (splitResult[0], splitResult[1])
let lowerCasedUnit = unitStr.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
guard let contentRange = HTTPHeaders.ContentRange.Value.from(responseStr: rangeStr) else {
return nil
}
self.unit = lowerCasedUnit == "bytes"
? RangeUnit.bytes
: RangeUnit.custom(value: lowerCasedUnit)
self.range = contentRange
}
public init(unit: RangeUnit, range: HTTPHeaders.ContentRange.Value) {
self.unit = unit
self.range = range
}
init?(directives: [Directive]) {
guard directives.count == 1 else {
return nil
}
self.init(directive: directives[0])
}
public func serialize() -> String {
return "\(unit.serialize()) \(range.serialize())"
}
}
/// Convenience for accessing the Content-Range response header.
///
/// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
public var contentRange: ContentRange? {
get {
return HTTPHeaders.ContentRange(directives: self.parseDirectives(name: .contentRange).flatMap { $0 })
}
set {
if self.contains(name: .contentRange) {
self.remove(name: .contentRange)
}
guard let newValue = newValue else {
return
}
self.add(name: .contentRange, value: newValue.serialize())
}
}
/// Convenience for accessing the `Range` request header.
///
/// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range
public var range: Range? {
get {
return HTTPHeaders.Range(directives: self.parseDirectives(name: .range).flatMap { $0 })
}
set {
if self.contains(name: .range) {
self.remove(name: .range)
}
guard let newValue = newValue else {
return
}
self.add(name: .range, value: newValue.serialize())
}
}
}
extension HTTPHeaders.Range {
/// Represents one value of the `Range` request header.
///
/// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range
public enum Value: Equatable {
///Integer with single trailing dash, e.g. `25-`
case start(value: Int)
///Integer with single leading dash, e.g. `-25`
case tail(value: Int)
///Two integers with single dash in between, e.g. `20-25`
case within(start: Int, end: Int)
///Parses a string representing a requested range in one of the following formats:
///
///- `<range-start>-<range-end>`
///- `-<range-end>`
///- `<range-start>-`
///
/// - parameters:
/// - requestStr: String representing a requested range
/// - returns: A `HTTPHeaders.Range.Value` if the `requestStr` is valid, `nil` otherwise.
public static func from<T>(requestStr: T) -> HTTPHeaders.Range.Value? where T: StringProtocol {
let ranges = requestStr.split(separator: "-", omittingEmptySubsequences: false)
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
let count = ranges.count
guard count <= 2 else { return nil }
switch (count > 0 ? Int(ranges[0]) : nil, count > 1 ? Int(ranges[1]) : nil) {
case (nil, nil):
return nil
case let (.some(start), nil):
return .start(value: start)
case let (nil, .some(tail)):
return .tail(value: tail)
case let (.some(start), .some(end)):
return .within(start: start, end: end)
}
}
///Serializes `HTTPHeaders.Range.Value` to a string for use within the HTTP `Range` header.
public func serialize() -> String {
switch self {
case .start(let value):
return "\(value)-"
case .tail(let value):
return "-\(value)"
case .within(let start, let end):
return "\(start)-\(end)"
}
}
}
}
extension HTTPHeaders.ContentRange {
/// Represents the value of the `Content-Range` request header.
///
/// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
public enum Value : Equatable {
case within(start: Int, end: Int)
case withinWithLimit(start: Int, end: Int, limit: Int)
case any(size: Int)
///Parses a string representing a response range in one of the following formats:
///
///- `<range-start>-<range-end>/<size>`
///- `<range-start>-<range-end>/*`
///- `*/<size>`
///
/// - parameters:
/// - requestStr: String representing the response range
/// - returns: A `HTTPHeaders.ContentRange.Value` if the `responseStr` is valid, `nil` otherwise.
public static func from<T>(responseStr: T) -> HTTPHeaders.ContentRange.Value? where T : StringProtocol {
let ranges = responseStr.split(separator: "-", omittingEmptySubsequences: false)
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
switch ranges.count {
case 1:
let anyRangeOfSize = ranges[0].split(separator: "/", omittingEmptySubsequences: false)
guard anyRangeOfSize.count == 2,
anyRangeOfSize[0] == "*",
let size = Int(anyRangeOfSize[1]) else {
return nil
}
return .any(size: size)
case 2:
guard let start = Int(ranges[0]) else {
return nil
}
let limits = ranges[1].split(separator: "/", omittingEmptySubsequences: false)
guard limits.count == 2, let end = Int(limits[0]) else {
return nil
}
if limits[1] == "*" {
return .within(start: start, end: end)
}
guard let limit = Int(limits[1]) else {
return nil
}
return .withinWithLimit(start: start, end: end, limit: limit)
default: return nil
}
}
///Serializes `HTTPHeaders.Range.Value` to a string for use within the HTTP `Content-Range` header.
public func serialize() -> String {
switch self {
case .any(let size):
return "*/\(size)"
case .within(let start, let end):
return "\(start)-\(end)/*"
case .withinWithLimit(let start, let end, let limit):
return "\(start)-\(end)/\(limit)"
}
}
}
}
extension HTTPHeaders.Range.Value {
///Converts this `HTTPHeaders.Range.Value` to a `HTTPHeaders.ContentRange.Value` with the given `limit`.
public func asResponseContentRange(limit: Int) throws -> HTTPHeaders.ContentRange.Value {
switch self {
case .start(let start):
guard start <= limit, start >= 0 else {
throw Abort(.badRequest)
}
return .withinWithLimit(start: start, end: limit - 1, limit: limit)
case .tail(let end):
guard end <= limit, end >= 0 else {
throw Abort(.badRequest)
}
return .withinWithLimit(start: (limit - end), end: limit - 1, limit: limit)
case .within(let start, let end):
guard start >= 0, end >= 0, start < end, start <= limit, end <= limit else {
throw Abort(.badRequest)
}
return .withinWithLimit(start: start, end: end, limit: limit)
}
}
}
|
mit
|
3c7eec0382e6a60638927c14b738bebc
| 37.683824 | 113 | 0.53754 | 4.666075 | false | false | false | false |
gessulat/hackathon_bmvi
|
app/badmap/badmap/PathProvider.swift
|
1
|
1726
|
//
// PathProvider.swift
// badmap
//
// Created by Engin Kurutepe on 13/11/15.
// Copyright © 2015 Fifteen Jugglers Software. All rights reserved.
//
import MapKit
import GoogleMaps
class Path {
let totalCost : Double
let polyline : MKPolyline
let points : [CLLocationCoordinate2D]
var name : String?
var key : String?
var length : String?
init(points : [CLLocationCoordinate2D], pl : MKPolyline, cost : Double) {
self.totalCost = cost;
self.polyline = pl;
self.points = points
}
}
class PathProvider {
let googleAPIKey: String
let routesArray: [String:[String:AnyObject]]
init(apiKey : String, routes : [String:[String:AnyObject]]) {
googleAPIKey = apiKey
routesArray = routes
}
func pathForKey(key: String) -> Path? {
guard let routeDict = self.routesArray[key] else { return nil }
guard let encodedPath = routeDict["points"] as? String else { return nil }
let gmsPath = GMSPath(fromEncodedPath: encodedPath)
let count = Int(gmsPath.count())
var coords : [CLLocationCoordinate2D] = []
coords.reserveCapacity(count)
for idx in 0..<gmsPath.count() {
coords.append(gmsPath.coordinateAtIndex(idx))
}
let polyline = MKGeodesicPolyline(coordinates: UnsafeMutablePointer(coords), count: count)
let cost = routeDict["maut_cost"] as? Double ?? 0.0
let path = Path(points:coords, pl: polyline, cost: cost)
path.name = key.capitalizedString
path.key = key
path.length = routeDict["length"] as? String
return path
}
}
|
gpl-2.0
|
f85f4b6e89a8659690df1a327dafdc3e
| 25.953125 | 98 | 0.608696 | 4.227941 | false | false | false | false |
mirkofetter/TUIOSwift
|
TUIOSwift/Manager.swift
|
1
|
2634
|
//
// Manager.swift
// TUIOSwift
//
// Created by Mirko Fetter on 28.02.17.
// Copyright © 2017 grugru. All rights reserved.
//
import Foundation
public class Manager {
private let negPi = Float.pi * -1.0;
private let posPi = Float.pi;
private let halfPi = (Float)(Float.pi/2.0);
private let doublePi = (Float)(Float.pi*2.0);
var verbose:Bool = false;
var antialiasing:Bool = true;
var collision:Bool = false;
var invertx:Bool = false;
var inverty:Bool = false;
var inverta:Bool = false;
var objectList = [Int: Tangible]()
var cursorList = [Int: Finger]()
func readConfig(){
}
func reset() {
cursorList.removeAll()
objectList.removeAll();
readConfig();
}
func activateObject( old_id:Int, session_id:Int) {
let tangible:Tangible = objectList[old_id]!
if(!tangible.isActive()) {
if (verbose) {
print("add obj \(session_id) \(tangible.fiducial_id)");
}
}
tangible.activate(s_id: session_id);
objectList.removeValue(forKey: old_id)
objectList[session_id] = tangible;
}
func deactivateObject( tangible:Tangible) {
if(tangible.isActive()) {
if (verbose) {
print("del obj \(tangible.session_id) \(tangible.fiducial_id)");
}
}
tangible.deactivate();
}
func updateObject( tangible:Tangible, x:Int, y:Int, a:Float) {
let pt = tangible.getPosition();
let dx = Float(x)-pt.x;
let dy = Float(y)-pt.y;
var dt = a - tangible.getAngle();
if (dt < negPi) {
dt += doublePi;
}
if (dt > posPi) {
dt -= doublePi;
}
if (!(dx==0) || !(dy==0)) {
tangible.translate(dx: dx,dy: dy);
}
if (!(dt==0)) {
tangible.rotate(theta: Double(dt));
}
}
func addCursor( s_id:Int, x:Int, y:Int) -> Finger{
let cursor = Finger(s_id: s_id,xpos: x,ypos: y);
cursorList[s_id]=cursor;
return cursor;
}
func updateCursor( cursor:Finger, x:Int, y:Int) {
cursor.update(xpos: x,int: y);
}
func getCursor( s_id:Int)->Finger {
return cursorList[s_id]!;
}
func terminateCursor( cursor:Finger) {
cursorList.removeValue(forKey:cursor.session_id);
}
}
|
mit
|
c489c07082d76373b30b76bb96d342ba
| 21.698276 | 80 | 0.496392 | 3.793948 | false | false | false | false |
saeta/penguin
|
Sources/PenguinBenchmarks/NonBlockingThreadPool.swift
|
1
|
2711
|
// Copyright 2020 Penguin Authors
//
// 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.
// -------------------------------------------------------------------------------------------------
// WARNING: temporary duplication of code in PenguinParallel
// (https://github.com/saeta/penguin/issues/114)
// -------------------------------------------------------------------------------------------------
import Benchmark
import PenguinParallelWithFoundation
let nonBlockingThreadPool = BenchmarkSuite(name: "NonBlockingThreadPool") { suite in
typealias Pool = NonBlockingThreadPool<PosixConcurrencyPlatform>
let pool = Pool(name: "benchmark-pool", threadCount: 4)
let helpers = Helpers()
suite.benchmark("join, one level") {
pool.join({}, {})
}
suite.benchmark("join, two levels") {
pool.join(
{ pool.join({}, {}) },
{ pool.join({}, {}) })
}
suite.benchmark("join, three levels") {
pool.join(
{ pool.join({ pool.join({}, {}) }, { pool.join({}, {}) }) },
{ pool.join({ pool.join({}, {}) }, { pool.join({}, {}) }) })
}
suite.benchmark("join, four levels, three on thread pool thread") {
pool.join(
{},
{
pool.join(
{ pool.join({ pool.join({}, {}) }, { pool.join({}, {}) }) },
{ pool.join({ pool.join({}, {}) }, { pool.join({}, {}) }) })
})
}
suite.benchmark("parallel for, one level") {
let buffer1 = helpers.buffer1
pool.parallelFor(n: buffer1.count) { (i, n) in buffer1[i] = true }
}
suite.benchmark("parallel for, two levels") {
let buffer2 = helpers.buffer2
pool.parallelFor(n: buffer2.count) { (i, n) in
pool.parallelFor(n: buffer2[i].count) { (j, _) in buffer2[i][j] = true }
}
}
}
fileprivate class Helpers {
lazy var buffer1 = UnsafeMutableBufferPointer<Bool>.allocate(capacity: 10000)
lazy var buffer2 = { () -> UnsafeMutableBufferPointer<UnsafeMutableBufferPointer<Bool>> in
typealias Buffer = UnsafeMutableBufferPointer<Bool>
typealias Spine = UnsafeMutableBufferPointer<Buffer>
let spine = Spine.allocate(capacity: 10)
for i in 0..<spine.count {
spine[i] = Buffer.allocate(capacity: 1000)
}
return spine
}()
}
|
apache-2.0
|
eb3407bad168f0ea3cdcce8a660cc621
| 32.8875 | 100 | 0.599779 | 4.138931 | false | false | false | false |
rpistorello/rp-game-engine
|
rp-game-engine-src/Util/SKTUtils/CGVector+Extensions.swift
|
1
|
5417
|
/*
* Copyright (c) 2013-2014 Razeware LLC
*
* 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 CoreGraphics
import SpriteKit
public extension CGVector {
/**
* Creates a new CGVector given a CGPoint.
*/
public init(point: CGPoint) {
self.init(dx: point.x, dy: point.y)
}
/**
* Given an angle in radians, creates a vector of length 1.0 and returns the
* result as a new CGVector. An angle of 0 is assumed to point to the right.
*/
public init(angle: CGFloat) {
self.init(dx: cos(angle), dy: sin(angle))
}
/**
* Adds (dx, dy) to the vector.
*/
public mutating func offset(dx dx: CGFloat, dy: CGFloat) -> CGVector {
self.dx += dx
self.dy += dy
return self
}
/**
* Returns the length (magnitude) of the vector described by the CGVector.
*/
public func length() -> CGFloat {
return sqrt(dx*dx + dy*dy)
}
/**
* Returns the squared length of the vector described by the CGVector.
*/
public func lengthSquared() -> CGFloat {
return dx*dx + dy*dy
}
/**
* Normalizes the vector described by the CGVector to length 1.0 and returns
* the result as a new CGVector.
public */
func normalized() -> CGVector {
let len = length()
return len>0 ? self / len : CGVector.zero
}
/**
* Normalizes the vector described by the CGVector to length 1.0.
*/
public mutating func normalize() -> CGVector {
self = normalized()
return self
}
/**
* Calculates the distance between two CGVectors. Pythagoras!
*/
public func distanceTo(vector: CGVector) -> CGFloat {
return (self - vector).length()
}
/**
* Returns the angle in radians of the vector described by the CGVector.
* The range of the angle is -π to π; an angle of 0 points to the right.
*/
public var angle: CGFloat {
return atan2(dy, dx)
}
public func toPoint() -> CGPoint{
return CGPoint(x: self.dx, y: self.dy)
}
}
/**
* Adds two CGVector values and returns the result as a new CGVector.
*/
public func + (left: CGVector, right: CGVector) -> CGVector {
return CGVector(dx: left.dx + right.dx, dy: left.dy + right.dy)
}
/**
* Increments a CGVector with the value of another.
*/
public func += (inout left: CGVector, right: CGVector) {
left = left + right
}
/**
* Subtracts two CGVector values and returns the result as a new CGVector.
*/
public func - (left: CGVector, right: CGVector) -> CGVector {
return CGVector(dx: left.dx - right.dx, dy: left.dy - right.dy)
}
/**
* Decrements a CGVector with the value of another.
*/
public func -= (inout left: CGVector, right: CGVector) {
left = left - right
}
/**
* Multiplies two CGVector values and returns the result as a new CGVector.
*/
public func * (left: CGVector, right: CGVector) -> CGVector {
return CGVector(dx: left.dx * right.dx, dy: left.dy * right.dy)
}
/**
* Multiplies a CGVector with another.
*/
public func *= (inout left: CGVector, right: CGVector) {
left = left * right
}
/**
* Multiplies the x and y fields of a CGVector with the same scalar value and
* returns the result as a new CGVector.
*/
public func * (vector: CGVector, scalar: CGFloat) -> CGVector {
return CGVector(dx: vector.dx * scalar, dy: vector.dy * scalar)
}
/**
* Multiplies the x and y fields of a CGVector with the same scalar value.
*/
public func *= (inout vector: CGVector, scalar: CGFloat) {
vector = vector * scalar
}
/**
* Divides two CGVector values and returns the result as a new CGVector.
*/
public func / (left: CGVector, right: CGVector) -> CGVector {
return CGVector(dx: left.dx / right.dx, dy: left.dy / right.dy)
}
/**
* Divides a CGVector by another.
*/
public func /= (inout left: CGVector, right: CGVector) {
left = left / right
}
/**
* Divides the dx and dy fields of a CGVector by the same scalar value and
* returns the result as a new CGVector.
*/
public func / (vector: CGVector, scalar: CGFloat) -> CGVector {
return CGVector(dx: vector.dx / scalar, dy: vector.dy / scalar)
}
/**
* Divides the dx and dy fields of a CGVector by the same scalar value.
*/
public func /= (inout vector: CGVector, scalar: CGFloat) {
vector = vector / scalar
}
/**
* Performs a linear interpolation between two CGVector values.
*/
public func lerp(start start: CGVector, end: CGVector, t: CGFloat) -> CGVector {
return start + (end - start) * t
}
|
mit
|
4d419f39fcf86b3b5548ede367f989b5
| 27.056995 | 80 | 0.676824 | 3.854093 | false | false | false | false |
mike4aday/SwiftlySalesforce
|
Sources/SwiftlySalesforce/Extensions/URLRequest+Credential.swift
|
1
|
2242
|
import Foundation
public extension URLRequest {
static let defaultTimeoutInterval: TimeInterval = 60.0
init(
credential: Credential,
method: String? = nil,
path: String,
queryItems: [String: String]? = nil,
headers: [String: String]? = nil,
body: Data? = nil,
cachePolicy: CachePolicy = .useProtocolCachePolicy,
timeoutInterval: TimeInterval = URLRequest.defaultTimeoutInterval
) throws {
// URL
var comps = URLComponents()
comps.scheme = "https"
comps.host = credential.siteURL?.host ?? credential.instanceURL.host
comps.path = path.starts(with: "/") ? path : "/\(path)"
comps.percentEncodedQuery = queryItems.flatMap { String(byPercentEncoding: $0) }
guard let url = comps.url else {
throw URLError(.badURL)
}
// URLRequest
self = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
self.httpMethod = method
self.httpBody = body
// Headers
let contentType: String = {
switch self.httpMethod?.uppercased() {
case nil, HTTP.Method.get.uppercased(), HTTP.Method.delete.uppercased():
return HTTP.MIMEType.formUrlEncoded
default:
return HTTP.MIMEType.json
}
}()
let defaultHeaders: [String:String] = [
HTTP.Header.accept : HTTP.MIMEType.json,
HTTP.Header.contentType : contentType
].reduce(into: [:]) { $0[$1.0] = $1.1 }
self.allHTTPHeaderFields = defaultHeaders.merging(headers ?? [:]) { (_, new) in new }
self.setAuthorizationHeader(with: credential.accessToken)
}
static func identity(with credential: Credential) -> Self {
var req = URLRequest(url: credential.identityURL)
req.setValue(HTTP.MIMEType.json, forHTTPHeaderField: HTTP.Header.accept)
req.setAuthorizationHeader(with: credential.accessToken)
return req
}
mutating func setAuthorizationHeader(with accessToken: String) {
setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
}
}
|
mit
|
a865a6330ef289ec9f28b835e7ae29d0
| 36.366667 | 95 | 0.607939 | 4.982222 | false | false | false | false |
usiu/noticeboard
|
ios/NoticeBoard/Utils/NSDate+TimeAgo.swift
|
1
|
2600
|
//
// NSDate+TimeAgo.swift
//
// https://gist.github.com/minorbug/468790060810e0d29545
//
import Foundation
extension NSDate {
func timeAgo(numericDates:Bool) -> String {
let calendar = NSCalendar.currentCalendar()
let unitFlags = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitSecond
let now = NSDate()
let earliest = now.earlierDate(self)
let latest = (earliest == now) ? self : now
let components:NSDateComponents = calendar.components(unitFlags, fromDate: earliest, toDate: latest, options: nil)
if (components.year >= 2) {
return "\(components.year) years ago"
} else if (components.year >= 1){
if (numericDates){
return "1 year ago"
} else {
return "Last year"
}
} else if (components.month >= 2) {
return "\(components.month) months ago"
} else if (components.month >= 1){
if (numericDates){
return "1 month ago"
} else {
return "Last month"
}
} else if (components.weekOfYear >= 2) {
return "\(components.weekOfYear) weeks ago"
} else if (components.weekOfYear >= 1){
if (numericDates){
return "1 week ago"
} else {
return "Last week"
}
} else if (components.day >= 2) {
return "\(components.day) days ago"
} else if (components.day >= 1){
if (numericDates){
return "1 day ago"
} else {
return "Yesterday"
}
} else if (components.hour >= 2) {
return "\(components.hour) hours ago"
} else if (components.hour >= 1){
if (numericDates){
return "1 hour ago"
} else {
return "An hour ago"
}
} else if (components.minute >= 2) {
return "\(components.minute) minutes ago"
} else if (components.minute >= 1){
if (numericDates){
return "1 minute ago"
} else {
return "A minute ago"
}
} else if (components.second >= 3) {
return "\(components.second) seconds ago"
} else {
return "Just now"
}
}
}
|
mit
|
9b275862f5feb3eecf4a9ce8c1275334
| 33.210526 | 269 | 0.521154 | 4.832714 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.