repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
Holmusk/HMRequestFramework-iOS | HMRequestFramework/database/model/HMCursorDirection.swift | 1 | 1028 | //
// HMCursorDirection.swift
// HMRequestFramework
//
// Created by Hai Pham on 30/8/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import SwiftUtilities
/// In a paginated DB stream, this enum provides a means to determine backward
/// or forward pagination.
///
/// - backward: Go back 1 page.
/// - remain: Remain on the same page and reload items if needed.
/// - forward: Go forward 1 page.
public enum HMCursorDirection: Int {
case backward = -1
case remain = 0
case forward = 1
/// We do not care how large the value is, just whether it is positive or
/// not.
///
/// - Parameter value: An Int value.
public init(from value: Int) {
if value > 0 {
self = .forward
} else if value < 0 {
self = .backward
} else {
self = .remain
}
}
}
extension HMCursorDirection: EnumerableType {
public static func allValues() -> [HMCursorDirection] {
return [.backward, .remain, .forward]
}
}
| apache-2.0 |
masters3d/xswift | exercises/poker/Tests/PokerTests/PokerTests.swift | 2 | 10033 | import XCTest
@testable import Poker
class PokerTests: XCTestCase {
var validTestCases:[(name: String, hands: [String], best: String)] = []
var invalidTestCases:[(name: String, hand: String)] = []
func testInvalidCases() {
for each in invalidTestCases {
XCTAssertNil(PokerHand(each.hand), "\(each.name)")
}
}
func testAllValid() {
for each in validTestCases {
XCTAssertEqual(Poker.bestHand(each.hands), each.best, "\(each.name)")
}
}
override func setUp() {
super.setUp()
validTestCases = [
(
name: "single hand is always best",
hands: ["3♡ 10♢ 7♧ 8♤ A♢"],
best: "3♡ 10♢ 7♧ 8♤ A♢"
),
(
name: "highest card",
hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 2♡ 5♧ 6♢ 10♡"],
best: "3♡ 2♡ 5♧ 6♢ 10♡"
),
(
name: "One pair",
hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 3♤ 5♧ 6♢ 9♢"],
best: "3♡ 3♤ 5♧ 6♢ 9♢"
),
(
name: "pair beats lower",
hands: ["4♢ 3♤ 4♤ J♤ K♤", "A♡ K♡ J♢ 10♧ 9♡"],
best: "4♢ 3♤ 4♤ J♤ K♤"
),
(
name: "best pair",
hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "3♢ 3♡ 5♤ 6♤ 9♡"],
best: "4♡ 2♡ 5♧ 4♢ 10♡"
),
(
name: "best pair with same pair and highest cards",
hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♤ 4♧ 5♡ 10♢ 3♡"],
best: "4♤ 4♧ 5♡ 10♢ 3♡"
),
(
name: "two pair beats lower",
hands: [
"4♢ 3♤ 4♤ J♤ K♤",
"A♡ K♡ J♢ 10♧ 9♡",
"2♢ 8♡ 5♢ 2♡ 8♧"
],
best: "2♢ 8♡ 5♢ 2♡ 8♧"
),
(
name: "best two pair",
hands: [
"4♢ J♧ 4♤ J♤ K♤",
"A♡ K♡ J♢ 10♧ 9♡",
"2♢ 8♡ 5♢ 2♡ 8♧"
],
best: "4♢ J♧ 4♤ J♤ K♤"
),
(
name: "best two pair with equal highest pair",
hands: [
"4♢ J♧ 4♤ J♤ K♤",
"A♡ K♡ J♢ 10♧ 9♡",
"3♢ J♡ 5♢ 3♡ J♢"
],
best: "4♢ J♧ 4♤ J♤ K♤"
),
(
name: "best two pair with equal pairs",
hands: [
"4♢ J♧ 4♤ J♤ 2♤",
"A♡ K♡ J♢ 10♧ 9♡",
"4♧ J♡ 5♢ 4♡ J♢"
],
best: "4♧ J♡ 5♢ 4♡ J♢"
),
(
name: "full house",
hands: [
"4♢ 3♤ 4♤ J♤ K♤",
"A♡ K♡ J♢ 10♧ 9♡",
"3♡ 8♡ 3♢ 3♧ 8♧",
"2♢ 8♡ 5♢ 2♡ 8♧"
],
best: "3♡ 8♡ 3♢ 3♧ 8♧"
),
(
name: "best three of a kind",
hands: [
"4♢ 3♤ 4♤ J♤ 4♡",
"A♡ K♡ J♢ 10♧ 9♡",
"3♢ 8♡ 3♡ 3♧ 9♧",
"2♢ 8♡ 5♢ 2♡ 8♧"
],
best: "4♢ 3♤ 4♤ J♤ 4♡"
),
(
name: "straight beats lower",
hands: [
"4♢ 3♤ 4♤ J♤ K♤",
"Q♡ K♡ J♢ 10♧ 9♡",
"3♡ 8♡ 3♢ 3♧ 9♧",
"2♢ 8♡ 5♢ 2♡ 8♧"
],
best: "Q♡ K♡ J♢ 10♧ 9♡"
),
(
name: "straight includes ace as one",
hands: [
"4♢ 3♤ 4♤ J♤ K♤",
"2♤ 3♡ A♤ 5♤ 4♤",
"3♢ 8♡ 3♡ 3♧ 9♧",
"2♢ 8♡ 5♢ 2♡ 8♧"
],
best: "2♤ 3♡ A♤ 5♤ 4♤"
),
(
name: "best straight",
hands: [
"4♢ 3♤ 4♤ J♤ K♤",
"Q♡ K♡ J♢ 10♧ 9♡",
"A♢ K♧ 10♢ J♢ Q♢",
"2♢ 8♡ 5♢ 2♡ 8♧"
],
best: "A♢ K♧ 10♢ J♢ Q♢"
),
(
name: "flush beats lower",
hands: [
"4♤ 3♤ 8♤ J♤ K♤",
"Q♡ K♡ J♢ 10♧ 9♡",
"3♢ 8♡ 3♢ 3♧ 9♧",
"2♢ 8♡ 5♢ 2♡ 8♧"
],
best: "4♤ 3♤ 8♤ J♤ K♤"
),
(
name: "best flush",
hands: [
"4♤ 3♤ 8♤ J♤ K♤",
"Q♡ K♡ J♢ 10♧ 9♡",
"3♢ 8♢ A♢ 2♢ 7♢",
"2♢ 8♡ 5♢ 2♡ 8♧"
],
best: "3♢ 8♢ A♢ 2♢ 7♢"
),
(
name: "full house beats lower",
hands: [
"4♤ 3♤ 8♤ J♤ K♤",
"2♢ 8♡ 8♢ 2♡ 8♧",
"Q♡ K♡ J♢ 10♧ 9♡",
"3♡ A♡ 3♢ 3♧ A♧"
],
best: "2♢ 8♡ 8♢ 2♡ 8♧"
),
(
name: "best full house",
hands: [
"4♤ 3♤ 8♤ J♤ K♤",
"2♢ 8♡ 8♢ 2♡ 8♧",
"5♡ 5♢ A♤ 5♧ A♢",
"3♡ A♡ 3♢ 3♧ A♧"
],
best: "2♢ 8♡ 8♢ 2♡ 8♧"
),
(
name: "four of a kind beats lower",
hands: [
"4♤ 5♤ 8♤ J♤ K♤",
"2♢ 8♡ 8♢ 2♡ 8♧",
"Q♡ K♡ J♢ 10♧ 9♡",
"3♢ 3♡ 3♤ 3♧ A♧"
],
best: "3♢ 3♡ 3♤ 3♧ A♧"
),
(
name: "best four of a kind",
hands: [
"4♤ 5♤ 8♤ J♤ K♤",
"2♢ 2♧ 8♢ 2♡ 2♤",
"Q♡ K♡ J♢ 10♧ 9♡",
"3♢ 3♡ 3♤ 3♧ A♧"
],
best: "3♢ 3♡ 3♤ 3♧ A♧"
),
(
name: "straight flush beats lower",
hands: [
"4♤ 4♢ 4♡ 4♧ K♤",
"2♢ 8♡ 8♢ 2♡ 8♧",
"Q♡ K♡ 8♡ 10♡ 9♡",
"2♤ 3♤ A♤ 5♤ 4♤"
],
best: "2♤ 3♤ A♤ 5♤ 4♤"
),
(
name: "best straight flush is royal flush",
hands: [
"4♤ 5♤ 8♤ J♤ K♤",
"2♢ 8♡ 8♢ 2♡ 8♧",
"Q♡ K♡ J♡ 10♡ 9♡",
"Q♢ K♢ J♢ 10♢ A♢"
],
best: "Q♢ K♢ J♢ 10♢ A♢"
),
(
name: "tie for best pair: brake tide by suit",
hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♧ 10♢ 5♤ 2♤ 4♤"],
best: "4♡ 2♡ 5♧ 4♢ 10♡"
),
(
name: "tie of three: brake tide by suit",
hands: [
"A♡ 2♡ 3♡ 4♡ 5♡",
"A♤ 2♤ 3♤ 4♤ 5♤",
"5♧ 4♧ 3♧ 2♧ A♧",
"A♢ 2♢ 6♢ 4♢ 5♢"
],
best: "A♤ 2♤ 3♤ 4♤ 5♤"
)
]
invalidTestCases =
[
(
name: "1 is an invalid card rank",
hand: "1♢ 2♡ 3♡ 4♡ 5♡"
),
(
name: "15 is an invalid card rank",
hand: "15♢ 2♡ 3♡ 4♡ 5♡"
),
(
name: "too few cards",
hand: "2♡ 3♡ 4♡ 5♡"
),
(
name: "too many cards",
hand: "2♡ 3♡ 4♡ 5♡ 6♡ 7♡"
),
(
name: "lack of rank",
hand: "11♢ 2♡ ♡ 4♡ 5♡"
),
(
name: "lack of suit",
hand: "2♡ 3♡ 4 5♡ 7♡"
),
(
name: "H is an invalid suit",
hand: "2♡ 3♡ 4H 5♡ 7♡"
),
(
name: "♥ is an invalid suit",
hand: "2♡ 3♡ 4♥ 5♡ 7♡"
),
(
name: "lack of spacing",
hand: "2♡ 3♡ 5♡7♡ 8♡"
),
(
name: "double suits after rank",
hand: "2♡ 3♡ 5♡♡ 8♡ 9♡"
)
]
}
static var allTests: [(String, (PokerTests) -> () throws -> Void)] {
return [
("testInvalidCases", testInvalidCases),
("testAllValid", testAllValid),
]
}
}
| mit |
rodrigosoldi/XCTestsExample | XCTestsExample/SearchSongWorker.swift | 1 | 1175 | //
// SearchSongWorker.swift
// XCTestsExample
//
// Created by Rodrigo Soldi Lopes on 06/09/16.
// Copyright (c) 2016 Rodrigo Soldi Lopes. All rights reserved.
//
// Generated via Aleph Clean Swift Xcode Templates
// http://alaphao.github.io
//
// This is a modification of Clean Swift Xcode Templates, see http://clean-swift.com
//
import UIKit
class SearchSongWorker {
// MARK: Business Logic
func searchSong(search: String, completionHandler: (songs: [Song]?) -> Void) {
completionHandler(songs: [
Song(name: "Sugar", singer: "Maroon 5"),
Song(name: "Sorry", singer: "Justin Bieber"),
Song(name: "Just the way you are", singer: "Bruno Mars"),
Song(name: "Uptown Funk", singer: "Bruno Mars"),
Song(name: "We are the champions", singer: "Queen"),
Song(name: "She will be loved", singer: "Maroon 5"),
Song(name: "Photograph", singer: "Ed Sheeran"),
Song(name: "One", singer: "Ed Sheeran"),
Song(name: "Drag me down", singer: "One Direction"),
Song(name: "Hello", singer: "Adele")
])
}
}
| mit |
iCrany/iOSExample | iOSExample/Module/SomeInterestingExample/SomeInterestingExampleTableViewController.swift | 1 | 3842 | //
// SomeInterestingExampleTableViewController.swift
// iOSExample
//
// Created by yuanchao on 2017/9/24.
// Copyright (c) 2017 iCrany. All rights reserved.
//
import Foundation
import UIKit
class SomeInterestingExampleTableViewController: UIViewController {
struct Constant {
static let kSomeInterestingExample1 = "SomeInterestingExample-DeadLockInMainThread"
static let kInputAccessViewExample = "InputAccessoryViewExample"
static let kCoreAnimationCrashExample = "CABasicAnimation.position crash when user tap"
}
private lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: .zero, style: .plain)
tableView.tableFooterView = UIView.init()
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
fileprivate var dataSource: [String] = []
init() {
super.init(nibName: nil, bundle: nil)
self.prepareDataSource()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "HitTest Example"
self.setupUI()
}
private func setupUI() {
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { maker in
maker.edges.equalTo(self.view)
}
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kSomeInterestingExample1)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kInputAccessViewExample)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kCoreAnimationCrashExample)
}
private func prepareDataSource() {
self.dataSource.append(Constant.kSomeInterestingExample1)
self.dataSource.append(Constant.kInputAccessViewExample)
self.dataSource.append(Constant.kCoreAnimationCrashExample)
}
}
extension SomeInterestingExampleTableViewController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedDataSourceStr = self.dataSource[indexPath.row]
switch selectedDataSourceStr {
case Constant.kSomeInterestingExample1:
let vc: DeadLockInMainThreadViewController = DeadLockInMainThreadViewController.init()
self.navigationController?.pushViewController(vc, animated: true)
case Constant.kInputAccessViewExample:
let vc: TestInputAccessoryViewVC = TestInputAccessoryViewVC()
self.navigationController?.pushViewController(vc, animated: true)
case Constant.kCoreAnimationCrashExample:
let vc: CoreAnimationDemoVC = CoreAnimationDemoVC()
self.navigationController?.pushViewController(vc, animated: true)
default:
break
}
}
}
extension SomeInterestingExampleTableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dataSourceStr: String = self.dataSource[indexPath.row]
let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: dataSourceStr)
if let cell = tableViewCell {
cell.textLabel?.text = dataSourceStr
cell.textLabel?.textColor = UIColor.black
return cell
} else {
return UITableViewCell.init(style: .default, reuseIdentifier: "error")
}
}
}
| mit |
lisafiedler/AccordianView | AccordianView/View/MKAccordionView.swift | 1 | 10048 | //
// MKAccordionView.swift
// AccrodianView
//
// Created by Milan Kamilya on 26/06/15.
// Copyright (c) 2015 Milan Kamilya. All rights reserved.
//
import UIKit
import Foundation
// MARK: - MKAccordionViewDelegate
@objc protocol MKAccordionViewDelegate : NSObjectProtocol {
optional func accordionView(accordionView: MKAccordionView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
optional func accordionView(accordionView: MKAccordionView, heightForHeaderInSection section: Int) -> CGFloat
optional func accordionView(accordionView: MKAccordionView, heightForFooterInSection section: Int) -> CGFloat
optional func accordionView(accordionView: MKAccordionView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool
optional func accordionView(accordionView: MKAccordionView, didHighlightRowAtIndexPath indexPath: NSIndexPath)
optional func accordionView(accordionView: MKAccordionView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath)
// Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.
optional func accordionView(accordionView: MKAccordionView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath?
optional func accordionView(accordionView: MKAccordionView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath?
// Called after the user changes the selection.
optional func accordionView(accordionView: MKAccordionView, didSelectRowAtIndexPath indexPath: NSIndexPath)
optional func accordionView(accordionView: MKAccordionView, didDeselectRowAtIndexPath indexPath: NSIndexPath)
optional func accordionView(accordionView: MKAccordionView, viewForHeaderInSection section: Int, isSectionOpen sectionOpen: Bool) -> UIView?
optional func accordionView(accordionView: MKAccordionView, viewForFooterInSection section: Int, isSectionOpen sectionOpen: Bool) -> UIView?
}
// MARK: - MKAccordionViewDatasource
@objc protocol MKAccordionViewDatasource : NSObjectProtocol {
func accordionView(accordionView: MKAccordionView, numberOfRowsInSection section: Int) -> Int
func accordionView(accordionView: MKAccordionView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
optional func numberOfSectionsInAccordionView(accordionView: MKAccordionView) -> Int // Default is 1 if not implemented
optional func accordionView(accordionView: MKAccordionView, titleForHeaderInSection section: Int) -> String? // fixed font style. use custom view (UILabel) if you want something different
optional func accordionView(accordionView: MKAccordionView, titleForFooterInSection section: Int) -> String?
}
// MARK: - MKAccordionView Main Definition
class MKAccordionView: UIView {
var dataSource: MKAccordionViewDatasource?
var delegate: MKAccordionViewDelegate?
var tableView : UITableView?
private var arrayOfBool : NSMutableArray?
override init(frame: CGRect) {
super.init(frame: frame)
tableView = UITableView(frame: frame)
tableView?.delegate = self;
tableView?.dataSource = self;
self.addSubview(tableView!);
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func sectionHeaderTapped(recognizer: UITapGestureRecognizer) {
println("Tapping working")
println(recognizer.view?.tag)
var indexPath : NSIndexPath = NSIndexPath(forRow: 0, inSection:(recognizer.view?.tag as Int!)!)
if (indexPath.row == 0) {
var collapsed : Bool! = arrayOfBool?.objectAtIndex(indexPath.section).boolValue
collapsed = !collapsed;
arrayOfBool?.replaceObjectAtIndex(indexPath.section, withObject: NSNumber(bool: collapsed))
//reload specific section animated
var range = NSMakeRange(indexPath.section, 1)
var sectionToReload = NSIndexSet(indexesInRange: range)
tableView?.reloadSections(sectionToReload, withRowAnimation:UITableViewRowAnimation.Fade)
}
}
}
// MARK: - Implemention of UITableViewDelegate methods
extension MKAccordionView : UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height : CGFloat! = 0.0
var collapsed: Bool! = arrayOfBool?.objectAtIndex(indexPath.section).boolValue
if collapsed! {
if (delegate?.respondsToSelector(Selector("accordionView:heightForRowAtIndexPath:")))! {
height = delegate?.accordionView!(self, heightForRowAtIndexPath: indexPath)
}
}
return height
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
var height : CGFloat! = 0.0
if (delegate?.respondsToSelector(Selector("accordionView:heightForHeaderInSection:")))! {
height = delegate?.accordionView!(self, heightForHeaderInSection: section)
}
return height
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
var height : CGFloat! = 0.0
if (delegate?.respondsToSelector(Selector("accordionView:heightForFooterInSection:")))! {
height = delegate?.accordionView!(self, heightForFooterInSection: section)
}
return height
}
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
var selection : Bool! = false
if (delegate?.respondsToSelector(Selector("accordionView:shouldHighlightRowAtIndexPath:")))!{
selection = delegate?.accordionView!(self, shouldHighlightRowAtIndexPath: indexPath)
}
return true;
}
func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
}
// Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return indexPath;
}
func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return indexPath;
}
// Called after the user changes the selection.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var view : UIView! = nil
if (delegate?.respondsToSelector(Selector("accordionView:viewForHeaderInSection:isSectionOpen:")))! {
var collapsed: Bool! = arrayOfBool?.objectAtIndex(section).boolValue
view = delegate?.accordionView!(self, viewForHeaderInSection: section, isSectionOpen: collapsed)
view.tag = section;
// tab recognizer
let headerTapped = UITapGestureRecognizer (target: self, action:"sectionHeaderTapped:")
view .addGestureRecognizer(headerTapped)
}
return view
}
}
// MARK: - Implemention of UITableViewDataSource methods
extension MKAccordionView : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var no : Int! = 0
var collapsed: Bool! = arrayOfBool?.objectAtIndex(section).boolValue
if collapsed! {
if (dataSource?.respondsToSelector(Selector("accordionView:numberOfRowsInSection:")))! {
no = dataSource?.accordionView(self, numberOfRowsInSection: section)
}
}
return no
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell? = nil
if (dataSource?.respondsToSelector(Selector("accordionView:cellForRowAtIndexPath:")))! {
cell = (dataSource?.accordionView(self, cellForRowAtIndexPath: indexPath))!
}
return cell!
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var numberOfSections : Int! = 1
if (dataSource?.respondsToSelector(Selector("numberOfSectionsInAccordionView:")))! {
numberOfSections = dataSource?.numberOfSectionsInAccordionView!(self)
if arrayOfBool == nil {
arrayOfBool = NSMutableArray()
var sections : Int! = numberOfSections - 1
for _ in 0...sections {
arrayOfBool?.addObject(NSNumber(bool: false))
}
}
}
return numberOfSections;
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title : String! = nil
if (dataSource?.respondsToSelector(Selector("accordionView:titleForHeaderInSection:")))! {
title = dataSource?.accordionView!(self, titleForHeaderInSection: section)
}
return title
}
func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
var title : String! = nil
if (dataSource?.respondsToSelector(Selector("accordionView:titleForFooterInSection:")))! {
title = dataSource?.accordionView!(self, titleForFooterInSection: section)
}
return title
}
}
| mit |
airbnb/lottie-ios | Sources/Private/Model/ShapeItems/Stroke.swift | 2 | 3433 | //
// Stroke.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
import Foundation
final class Stroke: ShapeItem {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Stroke.CodingKeys.self)
opacity = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .opacity)
color = try container.decode(KeyframeGroup<LottieColor>.self, forKey: .color)
width = try container.decode(KeyframeGroup<LottieVector1D>.self, forKey: .width)
lineCap = try container.decodeIfPresent(LineCap.self, forKey: .lineCap) ?? .round
lineJoin = try container.decodeIfPresent(LineJoin.self, forKey: .lineJoin) ?? .round
miterLimit = try container.decodeIfPresent(Double.self, forKey: .miterLimit) ?? 4
dashPattern = try container.decodeIfPresent([DashElement].self, forKey: .dashPattern)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
let opacityDictionary: [String: Any] = try dictionary.value(for: CodingKeys.opacity)
opacity = try KeyframeGroup<LottieVector1D>(dictionary: opacityDictionary)
let colorDictionary: [String: Any] = try dictionary.value(for: CodingKeys.color)
color = try KeyframeGroup<LottieColor>(dictionary: colorDictionary)
let widthDictionary: [String: Any] = try dictionary.value(for: CodingKeys.width)
width = try KeyframeGroup<LottieVector1D>(dictionary: widthDictionary)
if
let lineCapRawValue = dictionary[CodingKeys.lineCap.rawValue] as? Int,
let lineCap = LineCap(rawValue: lineCapRawValue)
{
self.lineCap = lineCap
} else {
lineCap = .round
}
if
let lineJoinRawValue = dictionary[CodingKeys.lineJoin.rawValue] as? Int,
let lineJoin = LineJoin(rawValue: lineJoinRawValue)
{
self.lineJoin = lineJoin
} else {
lineJoin = .round
}
miterLimit = (try? dictionary.value(for: CodingKeys.miterLimit)) ?? 4
let dashPatternDictionaries = dictionary[CodingKeys.dashPattern.rawValue] as? [[String: Any]]
dashPattern = try? dashPatternDictionaries?.map { try DashElement(dictionary: $0) }
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The opacity of the stroke
let opacity: KeyframeGroup<LottieVector1D>
/// The Color of the stroke
let color: KeyframeGroup<LottieColor>
/// The width of the stroke
let width: KeyframeGroup<LottieVector1D>
/// Line Cap
let lineCap: LineCap
/// Line Join
let lineJoin: LineJoin
/// Miter Limit
let miterLimit: Double
/// The dash pattern of the stroke
let dashPattern: [DashElement]?
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(opacity, forKey: .opacity)
try container.encode(color, forKey: .color)
try container.encode(width, forKey: .width)
try container.encode(lineCap, forKey: .lineCap)
try container.encode(lineJoin, forKey: .lineJoin)
try container.encode(miterLimit, forKey: .miterLimit)
try container.encodeIfPresent(dashPattern, forKey: .dashPattern)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case opacity = "o"
case color = "c"
case width = "w"
case lineCap = "lc"
case lineJoin = "lj"
case miterLimit = "ml"
case dashPattern = "d"
}
}
| apache-2.0 |
NachoSoto/Result | Tests/Result/ResultTests.swift | 1 | 8816 | // Copyright (c) 2015 Rob Rix. All rights reserved.
final class ResultTests: XCTestCase {
func testMapTransformsSuccesses() {
XCTAssertEqual(success.map { $0.characters.count } ?? 0, 7)
}
func testMapRewrapsFailures() {
XCTAssertEqual(failure.map { $0.characters.count } ?? 0, 0)
}
func testInitOptionalSuccess() {
XCTAssert(Result("success" as String?, failWith: error) == success)
}
func testInitOptionalFailure() {
XCTAssert(Result(nil, failWith: error) == failure)
}
// MARK: Errors
func testErrorsIncludeTheSourceFile() {
let file = #file
XCTAssert(Result<(), NSError>.error().file == file)
}
func testErrorsIncludeTheSourceLine() {
let (line, error) = (#line, Result<(), NSError>.error())
XCTAssertEqual(error.line ?? -1, line)
}
func testErrorsIncludeTheCallingFunction() {
let function = #function
XCTAssert(Result<(), NSError>.error().function == function)
}
// MARK: Try - Catch
func testTryCatchProducesSuccesses() {
let result: Result<String, NSError> = Result(try tryIsSuccess("success"))
XCTAssert(result == success)
}
func testTryCatchProducesFailures() {
#if os(Linux)
/// FIXME: skipped on Linux because of crash with swift-3.0-preview-1.
print("Test Case `\(#function)` skipped on Linux because of crash with swift-3.0-preview-1.")
#else
let result: Result<String, NSError> = Result(try tryIsSuccess(nil))
XCTAssert(result.error == error)
#endif
}
func testTryCatchWithFunctionProducesSuccesses() {
let function = { try tryIsSuccess("success") }
let result: Result<String, NSError> = Result(attempt: function)
XCTAssert(result == success)
}
func testTryCatchWithFunctionCatchProducesFailures() {
#if os(Linux)
/// FIXME: skipped on Linux because of crash with swift-3.0-preview-1.
print("Test Case `\(#function)` skipped on Linux because of crash with swift-3.0-preview-1.")
#else
let function = { try tryIsSuccess(nil) }
let result: Result<String, NSError> = Result(attempt: function)
XCTAssert(result.error == error)
#endif
}
func testMaterializeProducesSuccesses() {
let result1 = materialize(try tryIsSuccess("success"))
XCTAssert(result1 == success)
let result2: Result<String, NSError> = materialize { try tryIsSuccess("success") }
XCTAssert(result2 == success)
}
func testMaterializeProducesFailures() {
#if os(Linux)
/// FIXME: skipped on Linux because of crash with swift-3.0-preview-1.
print("Test Case `\(#function)` skipped on Linux because of crash with swift-3.0-preview-1.")
#else
let result1 = materialize(try tryIsSuccess(nil))
XCTAssert(result1.error == error)
let result2: Result<String, NSError> = materialize { try tryIsSuccess(nil) }
XCTAssert(result2.error == error)
#endif
}
// MARK: Recover
func testRecoverProducesLeftForLeftSuccess() {
let left = Result<String, NSError>.success("left")
XCTAssertEqual(left.recover("right"), "left")
}
func testRecoverProducesRightForLeftFailure() {
struct Error: ErrorProtocol {}
let left = Result<String, Error>.failure(Error())
XCTAssertEqual(left.recover("right"), "right")
}
// MARK: Recover With
func testRecoverWithProducesLeftForLeftSuccess() {
let left = Result<String, NSError>.success("left")
let right = Result<String, NSError>.success("right")
XCTAssertEqual(left.recover(with: right).value, "left")
}
func testRecoverWithProducesRightSuccessForLeftFailureAndRightSuccess() {
struct Error: ErrorProtocol {}
let left = Result<String, Error>.failure(Error())
let right = Result<String, Error>.success("right")
XCTAssertEqual(left.recover(with: right).value, "right")
}
func testRecoverWithProducesRightFailureForLeftFailureAndRightFailure() {
enum Error: ErrorProtocol { case left, right }
let left = Result<String, Error>.failure(.left)
let right = Result<String, Error>.failure(.right)
XCTAssertEqual(left.recover(with: right).error, .right)
}
// MARK: Cocoa API idioms
#if !os(Linux)
func testTryProducesFailuresForBooleanAPIWithErrorReturnedByReference() {
let result = `try` { attempt(true, succeed: false, error: $0) }
XCTAssertFalse(result ?? false)
XCTAssertNotNil(result.error)
}
func testTryProducesFailuresForOptionalWithErrorReturnedByReference() {
let result = `try` { attempt(1, succeed: false, error: $0) }
XCTAssertEqual(result ?? 0, 0)
XCTAssertNotNil(result.error)
}
func testTryProducesSuccessesForBooleanAPI() {
let result = `try` { attempt(true, succeed: true, error: $0) }
XCTAssertTrue(result ?? false)
XCTAssertNil(result.error)
}
func testTryProducesSuccessesForOptionalAPI() {
let result = `try` { attempt(1, succeed: true, error: $0) }
XCTAssertEqual(result ?? 0, 1)
XCTAssertNil(result.error)
}
func testTryMapProducesSuccess() {
let result = success.tryMap(tryIsSuccess)
XCTAssert(result == success)
}
func testTryMapProducesFailure() {
let result = Result<String, NSError>.success("fail").tryMap(tryIsSuccess)
XCTAssert(result == failure)
}
#endif
// MARK: Operators
func testConjunctionOperator() {
let resultSuccess = success &&& success
if let (x, y) = resultSuccess.value {
XCTAssertTrue(x == "success" && y == "success")
} else {
XCTFail()
}
let resultFailureBoth = failure &&& failure2
XCTAssert(resultFailureBoth.error == error)
let resultFailureLeft = failure &&& success
XCTAssert(resultFailureLeft.error == error)
let resultFailureRight = success &&& failure2
XCTAssert(resultFailureRight.error == error2)
}
}
// MARK: - Fixtures
let success = Result<String, NSError>.success("success")
let error = NSError(domain: "com.antitypical.Result", code: 1, userInfo: nil)
let error2 = NSError(domain: "com.antitypical.Result", code: 2, userInfo: nil)
let failure = Result<String, NSError>.failure(error)
let failure2 = Result<String, NSError>.failure(error2)
// MARK: - Helpers
#if !os(Linux)
func attempt<T>(_ value: T, succeed: Bool, error: NSErrorPointer) -> T? {
if succeed {
return value
} else {
error?.pointee = Result<(), NSError>.error()
return nil
}
}
#endif
func tryIsSuccess(_ text: String?) throws -> String {
guard let text = text, text == "success" else {
throw error
}
return text
}
extension NSError {
var function: String? {
return userInfo[Result<(), NSError>.functionKey] as? String
}
var file: String? {
return userInfo[Result<(), NSError>.fileKey] as? String
}
var line: Int? {
return userInfo[Result<(), NSError>.lineKey] as? Int
}
}
#if os(Linux)
extension ResultTests {
static var allTests: [(String, (ResultTests) -> () throws -> Void)] {
return [
("testMapTransformsSuccesses", testMapTransformsSuccesses),
("testMapRewrapsFailures", testMapRewrapsFailures),
("testInitOptionalSuccess", testInitOptionalSuccess),
("testInitOptionalFailure", testInitOptionalFailure),
("testErrorsIncludeTheSourceFile", testErrorsIncludeTheSourceFile),
("testErrorsIncludeTheSourceLine", testErrorsIncludeTheSourceLine),
("testErrorsIncludeTheCallingFunction", testErrorsIncludeTheCallingFunction),
("testTryCatchProducesSuccesses", testTryCatchProducesSuccesses),
("testTryCatchProducesFailures", testTryCatchProducesFailures),
("testTryCatchWithFunctionProducesSuccesses", testTryCatchWithFunctionProducesSuccesses),
("testTryCatchWithFunctionCatchProducesFailures", testTryCatchWithFunctionCatchProducesFailures),
("testMaterializeProducesSuccesses", testMaterializeProducesSuccesses),
("testMaterializeProducesFailures", testMaterializeProducesFailures),
("testRecoverProducesLeftForLeftSuccess", testRecoverProducesLeftForLeftSuccess),
("testRecoverProducesRightForLeftFailure", testRecoverProducesRightForLeftFailure),
("testRecoverWithProducesLeftForLeftSuccess", testRecoverWithProducesLeftForLeftSuccess),
("testRecoverWithProducesRightSuccessForLeftFailureAndRightSuccess", testRecoverWithProducesRightSuccessForLeftFailureAndRightSuccess),
("testRecoverWithProducesRightFailureForLeftFailureAndRightFailure", testRecoverWithProducesRightFailureForLeftFailureAndRightFailure),
// ("testTryProducesFailuresForBooleanAPIWithErrorReturnedByReference", testTryProducesFailuresForBooleanAPIWithErrorReturnedByReference),
// ("testTryProducesFailuresForOptionalWithErrorReturnedByReference", testTryProducesFailuresForOptionalWithErrorReturnedByReference),
// ("testTryProducesSuccessesForBooleanAPI", testTryProducesSuccessesForBooleanAPI),
// ("testTryProducesSuccessesForOptionalAPI", testTryProducesSuccessesForOptionalAPI),
// ("testTryMapProducesSuccess", testTryMapProducesSuccess),
// ("testTryMapProducesFailure", testTryMapProducesFailure),
("testConjunctionOperator", testConjunctionOperator),
]
}
}
#endif
import Foundation
import Result
import XCTest
| mit |
DanielAsher/EmotionFinder | EmotionFinderControl/EmotionFinderControl/EmotionFinderView.swift | 1 | 7351 | //
// EmotionFinderView.swift
// EmotionFinderControl
//
// Created by Daniel Asher on 11/04/2015.
// Copyright (c) 2015 AsherEnterprises. All rights reserved.
//
import UIKit
import Cartography
import Darwin
@IBDesignable
public class EmotionFinderView: UIControl {
let centreEmotion = "Emote"
let topLevelEmotions = ["Peaceful", "Mad", "Sad", "Scared", "Joyful", "Powerful"]
let centreEmotionLabel : LTMorphingLabel
var topLevelEmotionLabels : [String: LTMorphingLabel] = [:]
var secondLevelEmotions : [String: [String]] =
["Peaceful" : ["Content", "Thoughtful"],
"Mad" : ["Hurt", "Hostile"],
"Sad" : ["Guily", "Ashamed"],
"Scared" : ["Rejected", "Helpless"],
"Joyful" : ["Playful", "Sexy"],
"Powerful" : ["Proud", "Hopeful"]]
var secondLevelEmotionLabels : [String : [String: LTMorphingLabel]] = [:]
var initialAlpha: CGFloat { return CGFloat(0.1) }
var startColor : UIColor {return UIColor(red: 1, green: 0, blue: 0, alpha: initialAlpha)}
var colors: [UIColor] { return [
startColor,
UIColor(red: 1, green: 1, blue: 0, alpha: initialAlpha),
UIColor(red: 0, green: 1, blue: 0, alpha: initialAlpha),
UIColor(red: 0, green: 1, blue: 1, alpha: initialAlpha),
UIColor(red: 1, green: 0, blue: 1, alpha: initialAlpha),
UIColor(red: 1, green: 0, blue: 0, alpha: initialAlpha),
startColor] }
var radials : [GradientView] = []
override init(frame: CGRect) {
centreEmotionLabel = LTMorphingLabel()
centreEmotionLabel.textAlignment = NSTextAlignment.Center
super.init(frame: frame)
setup()
}
public required init(coder aDecoder: NSCoder) {
centreEmotionLabel = LTMorphingLabel()
super.init(coder: aDecoder)
setup()
}
func setup() {
centreEmotionLabel.text = centreEmotion
self.addSubview(centreEmotionLabel)
for (i, emotion) in enumerate(topLevelEmotions) {
let label = LTMorphingLabel()
label.text = emotion
label.textAlignment = NSTextAlignment.Center
topLevelEmotionLabels[emotion] = label
self.addSubview(label)
let radial = GradientView()
radial.backgroundColor = UIColor.clearColor()
radial.colors = [colors[i], UIColor.clearColor()]
// radial.mode = .Linear
radials.append(radial)
self.addSubview(radial)
}
// let l: AngleGradientLayer = self.layer as! AngleGradientLayer
//
// l.colors = colors
// l.cornerRadius = CGRectGetWidth(self.bounds) / 2
}
public override func layoutSubviews() {
if needsUpdateConstraints() {
let centreSize = self.centreEmotionLabel.intrinsicContentSize()
layout(centreEmotionLabel, self) { label, view in
label.center == view.center
label.width == centreSize.width
label.height == centreSize.height
}
var angles: Array<AnyObject> = []
var incr = 2 * M_PI / Double(topLevelEmotions.count)
for (i, (emotion, label)) in enumerate(topLevelEmotionLabels) {
println(emotion)
let size = label.intrinsicContentSize()
let angle = Double(i) * incr
angles.append(angle / 2 * M_PI - 0.5 * M_PI)
layout(centreEmotionLabel, label) { centreLabel, label in
label.centerX == centreLabel.centerX + sin(angle) * 75.0
label.centerY == centreLabel.centerY + cos(angle) * 75.0
label.width == size.width
label.height == size.height
}
let radial = radials[i]
radial.colors = [colors[i], UIColor.clearColor()]
// radial.colors = [UIColor.redColor(), UIColor.clearColor()]
radial.mode = .Radial
layout(label, radial) { label, radial in
radial.centerX == label.centerX
radial.centerY == label.centerY
radial.width == self.frame.width
radial.height == self.frame.height
}
// for (i, (emotion, subemotions)) in secondLevelEmotionLabels {
//
// }
}
// let l: AngleGradientLayer = self.layer as! AngleGradientLayer
// l.locations = angles
}
}
// override public class func layerClass() -> AnyClass {
// return AngleGradientLayer.self
// }
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
return
}
func distanceBetween(p1: CGPoint, _ p2: CGPoint) -> CGFloat {
return CGFloat(hypotf(Float(p1.x - p2.x), Float(p1.y - p2.y)))
}
public override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches.first as? UITouch {
let location = touch.locationInView(self)
// let initialAlpha = CGFloat(0.1)
// let startColor = UIColor(red: 0, green: 1, blue: 1, alpha: initialAlpha)
// var colors: Array<AnyObject> = [
// startColor,
// UIColor(red: 1, green: 0, blue: 0, alpha: initialAlpha),
// UIColor(red: 0, green: 0, blue: 1, alpha: initialAlpha),
// UIColor(red: 1, green: 0, blue: 1, alpha: initialAlpha),
// UIColor(red: 1, green: 1, blue: 0, alpha: initialAlpha),
// UIColor(red: 0, green: 1, blue: 0, alpha: initialAlpha),
// startColor,
// ]
for (i, (emotion, label)) in enumerate(topLevelEmotionLabels) {
let centre = CGPoint(x: label.frame.midX, y: label.frame.midY)
let distance = distanceBetween(centre, location)
// println("== \(i): \(distance)")
//
let color = colors[i]
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: &a)
let newAlpha = max(a, 1.0 / max(0.2 * distance, 1.0))
// println(newAlpha)
let radial = radials[i]
let newColor = UIColor(red: r, green: g, blue: b, alpha: newAlpha)
radial.colors = [newColor, UIColor.clearColor()]
// colors[i] = UIColor(red: r, green: g, blue: b, alpha: newAlpha).CGColor
}
// let l: AngleGradientLayer = self.layer as! AngleGradientLayer
// l.setNeedsDisplay()
// l.colors = colors
// println(l.locations)
}
return
}
public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
return
}
public override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
return
}
}
| apache-2.0 |
edx/edx-app-ios | Source/PaymentManager.swift | 1 | 7332 | //
// PaymentManager.swift
// edX
//
// Created by Muhammad Umer on 22/06/2021.
// Copyright © 2021 edX. All rights reserved.
//
import Foundation
import SwiftyStoreKit
let CourseUpgradeCompleteNotification: String = "CourseUpgradeCompleteNotification"
// In case of completeTransctions SDK returns SwiftyStoreKit.Purchase
// And on the in-app purchase SDK returns SwiftyStoreKit.PurchaseDetails
enum TransctionType: String {
case transction
case purchase
}
enum PurchaseError: String {
case paymentsNotAvailebe // device isn't allowed to make payments
case invalidUser // app user isn't available
case paymentError // unable to purchase a product
case receiptNotAvailable // unable to fetech inapp purchase receipt
case basketError // basket API returns error
case checkoutError // checkout API returns error
case verifyReceiptError // verify receipt API returns error
case generalError // general error
}
@objc class PaymentManager: NSObject {
private typealias storeKit = SwiftyStoreKit
@objc static let shared = PaymentManager()
// Use this dictionary to keep track of inprocess transctions and allow only one transction at a time
private var purchasess: [String: Any] = [:]
typealias PurchaseCompletionHandler = ((success: Bool, receipt: String?, error: PurchaseError?)) -> Void
var completion: PurchaseCompletionHandler?
var isIAPInprocess:Bool {
return purchasess.count > 0
}
var inprocessPurchases: [String: Any] {
return purchasess
}
private override init() {
}
@objc func completeTransactions() {
// save and check if purchase is already there
storeKit.completeTransactions(atomically: false) { [weak self] purchases in // atomically = false
for purchase in purchases {
switch purchase.transaction.transactionState {
case .purchased, .restored:
if purchase.needsFinishTransaction {
// Deliver content from server, then:
// self?.markPurchaseComplete(productID, type: .transction)
// SwiftyStoreKit.finishTransaction(purchase.transaction)
self?.purchasess[purchase.productId] = purchase
}
case .failed, .purchasing, .deferred:
// TODO: Will handle while implementing the final version
// At the momewnt don't have anything to add here
break // do nothing
@unknown default:
break // do nothing
}
}
}
}
func purchaseProduct(_ identifier: String, completion: PurchaseCompletionHandler?) {
guard storeKit.canMakePayments else {
if let controller = UIApplication.shared.topMostController() {
UIAlertController().showAlert(withTitle: "Payment Error", message: "This device is not able or allowed to make payments", onViewController: controller)
}
completion?((false, receipt: nil, error: .paymentsNotAvailebe))
return
}
guard let applicationUserName = OEXSession.shared()?.currentUser?.username else {
completion?((false, receipt: nil, error: .invalidUser))
return
}
self.completion = completion
storeKit.purchaseProduct(identifier, atomically: false, applicationUsername: applicationUserName) { [weak self] result in
switch result {
case .success(let purchase):
self?.purchasess[purchase.productId] = purchase
self?.purchaseReceipt()
break
case .error(let error):
completion?((false, receipt: nil, error: .paymentError))
switch error.code {
//TOD: handle the following cases according to the requirments
case .unknown:
break
case .clientInvalid:
break
case .paymentCancelled:
break
case .paymentInvalid:
break
case .paymentNotAllowed:
break
case .storeProductNotAvailable:
break
case .cloudServicePermissionDenied:
break
case .cloudServiceNetworkConnectionFailed:
break
case .cloudServiceRevoked:
break
default: print((error as NSError).localizedDescription)
}
}
}
}
func productPrice(_ identifier: String, completion: @escaping (String?) -> Void) {
storeKit.retrieveProductsInfo([identifier]) { result in
if let product = result.retrievedProducts.first {
completion(product.localizedPrice)
}
else if let _ = result.invalidProductIDs.first {
completion(nil)
}
else {
completion(nil)
}
}
}
private func purchaseReceipt() {
storeKit.fetchReceipt(forceRefresh: false) { [weak self] result in
switch result {
case .success(let receiptData):
let encryptedReceipt = receiptData.base64EncodedString(options: [])
self?.completion?((true, receipt: encryptedReceipt, error: nil))
case .error(_):
self?.completion?((false, receipt: nil, error: .receiptNotAvailable))
}
}
}
func restorePurchases() {
guard let applicationUserName = OEXSession.shared()?.currentUser?.username else { return }
storeKit.restorePurchases(atomically: false, applicationUsername: applicationUserName) { results in
if results.restoreFailedPurchases.count > 0 {
//TODO: Handle failed restore purchases
}
else if results.restoredPurchases.count > 0 {
for _ in results.restoredPurchases {
//TODO: Handle restore purchases
}
}
}
}
func markPurchaseComplete(_ courseID: String, type: TransctionType) {
// Mark the purchase complete
switch type {
case .transction:
if let purchase = purchasess[courseID] as? Purchase {
if purchase.needsFinishTransaction {
storeKit.finishTransaction(purchase.transaction)
}
}
break
case .purchase:
if let purchase = purchasess[courseID] as? PurchaseDetails {
if purchase.needsFinishTransaction {
storeKit.finishTransaction(purchase.transaction)
}
}
break
}
purchasess.removeValue(forKey: courseID)
NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: CourseUpgradeCompleteNotification)))
}
func restoreFailedPurchase() {
storeKit.restorePurchases { restoreResults in
restoreResults.restoreFailedPurchases.forEach { error, _ in
print(error)
}
}
}
}
| apache-2.0 |
JaNd3r/swift-behave | TestApp/TestApp/MasterViewController.swift | 1 | 3485 | //
// MasterViewController.swift
// TestApp
//
// Created by Christian Klaproth on 04.12.15.
// Copyright © 2015 Christian Klaproth. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [Any]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MasterViewController.insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func insertNewObject(_ sender: AnyObject) {
objects.insert(NSDate(), at: 0)
let indexPath = IndexPath(row: 0, section: 0)
self.tableView.insertRows(at: [indexPath], with: .automatic)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
objects.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .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.
}
}
}
| mit |
edx/edx-app-ios | Source/CalendarManager.swift | 1 | 15682 | //
// CalendarEventManager.swift
// edX
//
// Created by Muhammad Umer on 20/04/2021.
// Copyright © 2021 edX. All rights reserved.
//
import Foundation
import EventKit
struct CourseCalendar: Codable {
var identifier: String
let courseID: String
let title: String
var isOn: Bool
var modalPresented: Bool
}
class CalendarManager: NSObject {
private let courseName: String
private let courseID: String
private let courseQuerier: CourseOutlineQuerier
private let eventStore = EKEventStore()
private let iCloudCalendar = "icloud"
private let alertOffset = -1
private let calendarKey = "CalendarEntries"
private var localCalendar: EKCalendar? {
if authorizationStatus != .authorized { return nil }
var calendars = eventStore.calendars(for: .event).filter { $0.title == calendarName }
if calendars.isEmpty {
return nil
} else {
let calendar = calendars.removeLast()
// calendars.removeLast() pop the element from array and after that,
// following is run on remaing members of array to remove them
// calendar app, if they had been added.
calendars.forEach { try? eventStore.removeCalendar($0, commit: true) }
return calendar
}
}
private let calendarColor = OEXStyles.shared().primaryBaseColor()
private var calendarSource: EKSource? {
eventStore.refreshSourcesIfNecessary()
let iCloud = eventStore.sources.first(where: { $0.sourceType == .calDAV && $0.title.localizedCaseInsensitiveContains(iCloudCalendar) })
let local = eventStore.sources.first(where: { $0.sourceType == .local })
let fallback = eventStore.defaultCalendarForNewEvents?.source
return iCloud ?? local ?? fallback
}
private func calendar() -> EKCalendar {
let calendar = EKCalendar(for: .event, eventStore: eventStore)
calendar.title = calendarName
calendar.cgColor = calendarColor.cgColor
calendar.source = calendarSource
return calendar
}
var authorizationStatus: EKAuthorizationStatus {
return EKEventStore.authorizationStatus(for: .event)
}
var calendarName: String {
return OEXConfig.shared().platformName() + " - " + courseName
}
private lazy var branchEnabled: Bool = {
return OEXConfig.shared().branchConfig.enabled
}()
var syncOn: Bool {
set {
updateCalendarState(isOn: newValue)
}
get {
if let calendarEntry = calendarEntry,
let localCalendar = localCalendar {
if calendarEntry.identifier == localCalendar.calendarIdentifier {
return calendarEntry.isOn
}
} else {
if let localCalendar = localCalendar {
let courseCalendar = CourseCalendar(identifier: localCalendar.calendarIdentifier, courseID: courseID, title: calendarName, isOn: true, modalPresented: false)
addOrUpdateCalendarEntry(courseCalendar: courseCalendar)
return true
}
}
return false
}
}
var isModalPresented: Bool {
set {
setModalPresented(presented: newValue)
}
get {
return getModalPresented()
}
}
required init(courseID: String, courseName: String, courseQuerier: CourseOutlineQuerier) {
self.courseID = courseID
self.courseName = courseName
self.courseQuerier = courseQuerier
}
func requestAccess(completion: @escaping (Bool, EKAuthorizationStatus, EKAuthorizationStatus) -> ()) {
let previousStatus = EKEventStore.authorizationStatus(for: .event)
eventStore.requestAccess(to: .event) { [weak self] access, _ in
self?.eventStore.reset()
let currentStatus = EKEventStore.authorizationStatus(for: .event)
DispatchQueue.main.async {
completion(access, previousStatus, currentStatus)
}
}
}
func addEventsToCalendar(for dateBlocks: [Date : [CourseDateBlock]], completion: @escaping (Bool) -> ()) {
if !generateCourseCalendar() {
completion(false)
return
}
DispatchQueue.global().async { [weak self] in
guard let weakSelf = self else { return }
let events = weakSelf.generateEvents(for: dateBlocks, generateDeepLink: true)
if events.isEmpty {
//Ideally this shouldn't happen, but in any case if this happen so lets remove the calendar
weakSelf.removeCalendar()
completion(false)
} else {
events.forEach { event in weakSelf.addEvent(event: event) }
do {
try weakSelf.eventStore.commit()
DispatchQueue.main.async {
completion(true)
}
} catch {
DispatchQueue.main.async {
completion(false)
}
}
}
}
}
func checkIfEventsShouldBeShifted(for dateBlocks: [Date : [CourseDateBlock]]) -> Bool {
guard let _ = calendarEntry else { return true }
let events = generateEvents(for: dateBlocks, generateDeepLink: false)
let allEvents = events.allSatisfy { alreadyExist(event: $0) }
return !allEvents
}
private func generateEvents(for dateBlocks: [Date : [CourseDateBlock]], generateDeepLink: Bool) -> [EKEvent] {
var events: [EKEvent] = []
dateBlocks.forEach { item in
let blocks = item.value
if blocks.count > 1 {
if let generatedEvent = calendarEvent(for: blocks, generateDeepLink: generateDeepLink) {
events.append(generatedEvent)
}
} else {
if let block = blocks.first {
if let generatedEvent = calendarEvent(for: block, generateDeepLink: generateDeepLink) {
events.append(generatedEvent)
}
}
}
}
return events
}
private func generateCourseCalendar() -> Bool {
guard localCalendar == nil else { return true }
do {
let newCalendar = calendar()
try eventStore.saveCalendar(newCalendar, commit: true)
let courseCalendar: CourseCalendar
if var calendarEntry = calendarEntry {
calendarEntry.identifier = newCalendar.calendarIdentifier
courseCalendar = calendarEntry
} else {
courseCalendar = CourseCalendar(identifier: newCalendar.calendarIdentifier, courseID: courseID, title: calendarName, isOn: true, modalPresented: false)
}
addOrUpdateCalendarEntry(courseCalendar: courseCalendar)
return true
} catch {
return false
}
}
func removeCalendar(completion: ((Bool)->())? = nil) {
guard let calendar = localCalendar else { return }
do {
try eventStore.removeCalendar(calendar, commit: true)
updateSyncSwitchStatus(isOn: false)
completion?(true)
} catch {
completion?(false)
}
}
private func calendarEvent(for block: CourseDateBlock, generateDeepLink: Bool) -> EKEvent? {
guard !block.title.isEmpty else { return nil }
let title = block.title + ": " + courseName
// startDate is the start date and time for the event,
// it is also being used as first alert for the event
let startDate = block.blockDate.add(.hour, value: alertOffset)
let secondAlert = startDate.add(.day, value: alertOffset)
let endDate = block.blockDate
var notes = "\(courseName)\n\n\(block.title)"
if generateDeepLink && branchEnabled {
if let link = generateDeeplink(componentBlockID: block.firstComponentBlockID) {
notes = notes + "\n\(link)"
}
}
return generateEvent(title: title, startDate: startDate, endDate: endDate, secondAlert: secondAlert, notes: notes)
}
private func calendarEvent(for blocks: [CourseDateBlock], generateDeepLink: Bool) -> EKEvent? {
guard let block = blocks.first, !block.title.isEmpty else { return nil }
let title = block.title + ": " + courseName
// startDate is the start date and time for the event,
// it is also being used as first alert for the event
let startDate = block.blockDate.add(.hour, value: alertOffset)
let secondAlert = startDate.add(.day, value: alertOffset)
let endDate = block.blockDate
let notes = "\(courseName)\n\n" + blocks.compactMap { block -> String in
if generateDeepLink && branchEnabled {
if let link = generateDeeplink(componentBlockID: block.firstComponentBlockID) {
return "\(block.title)\n\(link)"
} else {
return block.title
}
} else {
return block.title
}
}.joined(separator: "\n\n")
return generateEvent(title: title, startDate: startDate, endDate: endDate, secondAlert: secondAlert, notes: notes)
}
private func generateDeeplink(componentBlockID: String) -> String? {
guard !componentBlockID.isEmpty else { return nil }
let branchUniversalObject = BranchUniversalObject(canonicalIdentifier: "\(DeepLinkType.courseComponent.rawValue)/\(componentBlockID)")
let dictionary: NSMutableDictionary = [
DeepLinkKeys.screenName.rawValue: DeepLinkType.courseComponent.rawValue,
DeepLinkKeys.courseId.rawValue: courseID,
DeepLinkKeys.componentID.rawValue: componentBlockID
]
let metadata = BranchContentMetadata()
metadata.customMetadata = dictionary
branchUniversalObject.contentMetadata = metadata
let properties = BranchLinkProperties()
if let block = courseQuerier.blockWithID(id: componentBlockID).value, let webURL = block.webURL {
properties.addControlParam("$desktop_url", withValue: webURL.absoluteString)
}
return branchUniversalObject.getShortUrl(with: properties)
}
private func generateEvent(title: String, startDate: Date, endDate: Date, secondAlert: Date, notes: String) -> EKEvent {
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate
event.endDate = endDate
event.calendar = localCalendar
event.notes = notes
if startDate > Date() {
let alarm = EKAlarm(absoluteDate: startDate)
event.addAlarm(alarm)
}
if secondAlert > Date() {
let alarm = EKAlarm(absoluteDate: secondAlert)
event.addAlarm(alarm)
}
return event
}
private func addEvent(event: EKEvent) {
if !alreadyExist(event: event) {
try? eventStore.save(event, span: .thisEvent)
}
}
private func alreadyExist(event eventToAdd: EKEvent) -> Bool {
guard let courseCalendar = calendarEntry else { return false }
let calendars = eventStore.calendars(for: .event).filter { $0.calendarIdentifier == courseCalendar.identifier }
let predicate = eventStore.predicateForEvents(withStart: eventToAdd.startDate, end: eventToAdd.endDate, calendars: calendars)
let existingEvents = eventStore.events(matching: predicate)
return existingEvents.contains { event -> Bool in
return event.title == eventToAdd.title
&& event.startDate == eventToAdd.startDate
&& event.endDate == eventToAdd.endDate
}
}
private func addOrUpdateCalendarEntry(courseCalendar: CourseCalendar) {
var calenders: [CourseCalendar] = []
if let decodedCalendars = courseCalendars() {
calenders = decodedCalendars
}
if let index = calenders.firstIndex(where: { $0.title == calendarName }) {
calenders.modifyElement(atIndex: index) { element in
element = courseCalendar
}
} else {
calenders.append(courseCalendar)
}
saveCalendarEntry(calendars: calenders)
}
private func updateCalendarState(isOn: Bool) {
guard var calendars = courseCalendars(),
let index = calendars.firstIndex(where: { $0.title == calendarName })
else { return }
calendars.modifyElement(atIndex: index) { element in
element.isOn = isOn
}
saveCalendarEntry(calendars: calendars)
}
private func setModalPresented(presented: Bool) {
guard var calendars = courseCalendars(),
let index = calendars.firstIndex(where: { $0.title == calendarName })
else { return }
calendars.modifyElement(atIndex: index) { element in
element.modalPresented = presented
}
saveCalendarEntry(calendars: calendars)
}
private func getModalPresented() -> Bool {
guard let calendars = courseCalendars(),
let calendar = calendars.first(where: { $0.title == calendarName })
else { return false }
return calendar.modalPresented
}
private func removeCalendarEntry() {
guard var calendars = courseCalendars() else { return }
if let index = calendars.firstIndex(where: { $0.title == calendarName }) {
calendars.remove(at: index)
}
saveCalendarEntry(calendars: calendars)
}
private func updateSyncSwitchStatus(isOn: Bool) {
guard var calendars = courseCalendars() else { return }
if let index = calendars.firstIndex(where: { $0.title == calendarName }) {
calendars.modifyElement(atIndex: index) { element in
element.isOn = isOn
}
}
saveCalendarEntry(calendars: calendars)
}
private var calendarEntry: CourseCalendar? {
guard let calendars = courseCalendars() else { return nil }
return calendars.first(where: { $0.title == calendarName })
}
private func courseCalendars() -> [CourseCalendar]? {
guard let data = UserDefaults.standard.data(forKey: calendarKey),
let courseCalendars = try? PropertyListDecoder().decode([CourseCalendar].self, from: data)
else { return nil }
return courseCalendars
}
private func saveCalendarEntry(calendars: [CourseCalendar]) {
guard let data = try? PropertyListEncoder().encode(calendars) else { return }
UserDefaults.standard.set(data, forKey: calendarKey)
UserDefaults.standard.synchronize()
}
}
fileprivate extension Date {
func add(_ unit: Calendar.Component, value: Int) -> Date {
return Calendar.current.date(byAdding: unit, value: value, to: self) ?? self
}
}
| apache-2.0 |
dogsfield/Comrade | Comrade/ComradeTests/Spec/Core/TestDataStorage.swift | 1 | 1355 | //
// TestDataStorage.swift
// Comrade
//
// Copyright © 2017 Michal Miedlarz
//
// 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 Comrade
class TestDataStorage: DataStorage
{
func store(chunk: DataChunk)
{
}
func fetch<T : DataChunk>(type: T.Type)
{
}
}
| mit |
mattadatta/sulfur | Sulfur/TabbedViewController.swift | 1 | 18640 | /*
This file is subject to the terms and conditions defined in
file 'LICENSE', which is part of this source code package.
*/
import UIKit
import Cartography
// MARK: - TabbedViewController
public final class TabbedViewController: UIViewController {
public typealias Tab = TabbedView.Tab
public typealias TabViewBinding = TabbedView.TabViewBinding
public typealias TabbedViewControllerBinding = TabBinding<UIViewController>
fileprivate var tabMappings: [Tab: TabbedViewControllerBinding] = [:]
public var tabBindings: [TabbedViewControllerBinding] = [] {
didSet {
self.tabbedView.tabBindings = self.tabBindings.map { viewControllerBinding in
return TabViewBinding(
tab: viewControllerBinding.tab,
action: {
switch viewControllerBinding.action {
case .performAction(let action):
return .performAction(action: action)
case .displayContent(let retrieveViewController):
return .displayContent(retrieveContent: { [weak self] tab in
guard
let sSelf = self,
let viewController = retrieveViewController(tab) else { return nil }
sSelf.activeViewController = viewController
return viewController.view
})
}
}())
}
self.tabMappings = self.tabBindings.reduce([:]) { partial, binding in
var dict = partial
dict[binding.tab] = binding
return dict
}
}
}
public weak var delegate: TabbedViewControllerDelegate?
public fileprivate(set) var activeViewController: UIViewController?
public fileprivate(set) weak var tabbedView: TabbedView!
public var tabBarView: TabBarView {
return self.tabbedView.tabBarView
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
fileprivate func commonInit() {
self.loadViewIfNeeded()
}
override public func loadView() {
let tabbedView = TabbedView()
self.view = tabbedView
}
override public func viewDidLoad() {
super.viewDidLoad()
self.tabbedView = self.view as! TabbedView
self.tabbedView.translatesAutoresizingMaskIntoConstraints = false
self.tabbedView.delegate = self
}
}
// MARK: - TabbedViewControllerDelegate
public protocol TabbedViewControllerDelegate: class {
func tabbedViewController(_ tabbedViewController: TabbedViewController, isTabEnabled tab: TabBarView.Tab?) -> Bool
func tabbedViewController(_ tabbedViewController: TabbedViewController, didChangeFromTab fromTab: TabBarView.Tab?, toTab: TabBarView.Tab?)
func tabbedViewController(_ tabbedViewController: TabbedViewController, willRemove viewController: UIViewController, for tab: TabBarView.Tab)
func tabbedViewController(_ tabbedViewController: TabbedViewController, didRemove viewController: UIViewController, for tab: TabBarView.Tab)
func tabbedViewController(_ tabbedViewController: TabbedViewController, willAdd viewController: UIViewController, for tab: TabBarView.Tab)
func tabbedViewController(_ tabbedViewController: TabbedViewController, didAdd viewController: UIViewController, for tab: TabBarView.Tab)
func tabbedViewController(_ tabbedViewController: TabbedViewController, constrain view: UIView, inContainer containerView: UIView, for tab: TabBarView.Tab)
}
// MARK: - TabbedViewController: TabbedViewDelegate
extension TabbedViewController: TabbedViewDelegate {
public func tabbedView(_ tabbedView: TabbedView, isTabEnabled tab: TabBarView.Tab?) -> Bool {
return self.delegate?.tabbedViewController(self, isTabEnabled: tab) ?? true
}
public func tabbedView(_ tabbedView: TabbedView, didChangeFromTab fromTab: TabBarView.Tab?, toTab: TabBarView.Tab?) {
self.delegate?.tabbedViewController(self, didChangeFromTab: fromTab, toTab: toTab)
}
public func tabbedView(_ tabbedView: TabbedView, willRemove view: UIView, for tab: TabBarView.Tab) {
guard let viewController = self.activeViewController else { return }
self.delegate?.tabbedViewController(self, willRemove: viewController, for: tab)
viewController.willMove(toParentViewController: nil)
}
public func tabbedView(_ tabbedView: TabbedView, didRemove view: UIView, for tab: TabBarView.Tab) {
guard let viewController = self.activeViewController else { return }
viewController.removeFromParentViewController()
self.activeViewController = nil
self.delegate?.tabbedViewController(self, didRemove: viewController, for: tab)
}
public func tabbedView(_ tabbedView: TabbedView, willAdd view: UIView, for tab: TabBarView.Tab) {
guard let viewController = self.activeViewController else { return }
self.delegate?.tabbedViewController(self, willAdd: viewController, for: tab)
self.addChildViewController(viewController)
}
public func tabbedView(_ tabbedView: TabbedView, didAdd view: UIView, for tab: TabBarView.Tab) {
guard let viewController = self.activeViewController else { return }
viewController.didMove(toParentViewController: self)
self.delegate?.tabbedViewController(self, didAdd: viewController, for: tab)
}
public func tabbedView(_ tabbedView: TabbedView, constrain view: UIView, inContainer containerView: UIView, for tab: TabBarView.Tab) {
self.delegate?.tabbedViewController(self, constrain: view, inContainer: containerView, for: tab)
}
}
// MARK: - TabbedView
public final class TabbedView: UIView {
public typealias Tab = TabBarView.Tab
public typealias TabViewBinding = TabBinding<UIView>
fileprivate weak var containerView: UIView!
public fileprivate(set) weak var tabBarView: TabBarView!
fileprivate var tabMappings: [Tab: TabViewBinding] = [:]
public var tabBindings: [TabViewBinding] = [] {
didSet {
self.tabBarView.tabs = self.tabBindings.map({ $0.tab })
self.tabMappings = self.tabBindings.reduce([:]) { partial, binding in
var dict = partial
dict[binding.tab] = binding
return dict
}
}
}
public weak var delegate: TabbedViewDelegate?
public fileprivate(set) var activeView: UIView?
public enum TabBarAlignment {
case top(CGFloat)
case bottom(CGFloat)
}
fileprivate var tabBarConstraintGroup = ConstraintGroup()
public var tabBarAlignment: TabBarAlignment = .top(0) {
didSet {
self.tabBarConstraintGroup = constrain(self, self.tabBarView, replace: self.tabBarConstraintGroup) { superview, tabBarView in
tabBarView.left == superview.left
tabBarView.right == superview.right
switch self.tabBarAlignment {
case .top(let inset):
tabBarView.top == superview.top + inset
case .bottom(let inset):
tabBarView.bottom == superview.bottom + inset
}
}
}
}
fileprivate var tabBarHeightConstraintGroup = ConstraintGroup()
public var tabBarHeight: CGFloat = -1 {
didSet {
guard self.tabBarHeight != oldValue else { return }
self.tabBarHeightConstraintGroup = constrain(self.tabBarView, replace: self.tabBarHeightConstraintGroup) { tabBarView in
tabBarView.height == self.tabBarHeight
}
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
fileprivate func commonInit() {
let containerView = UIView()
self.addAndConstrainView(containerView)
self.containerView = containerView
let tabBarView = TabBarView()
tabBarView.delegate = self
tabBarView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(tabBarView)
self.tabBarView = tabBarView
self.tabBarAlignment = .bottom(0)
self.tabBarHeight = 60
}
}
// MARK: - TabbedViewDelegate
public protocol TabbedViewDelegate: class {
func tabbedView(_ tabbedView: TabbedView, isTabEnabled tab: TabBarView.Tab?) -> Bool
func tabbedView(_ tabbedView: TabbedView, didChangeFromTab fromTab: TabBarView.Tab?, toTab: TabBarView.Tab?)
func tabbedView(_ tabbedView: TabbedView, willRemove view: UIView, for tab: TabBarView.Tab)
func tabbedView(_ tabbedView: TabbedView, didRemove view: UIView, for tab: TabBarView.Tab)
func tabbedView(_ tabbedView: TabbedView, willAdd view: UIView, for tab: TabBarView.Tab)
func tabbedView(_ tabbedView: TabbedView, didAdd view: UIView, for tab: TabBarView.Tab)
func tabbedView(_ tabbedView: TabbedView, constrain view: UIView, inContainer containerView: UIView, for tab: TabBarView.Tab)
}
// MARK: - TabbedView: TabBarViewDelegate
extension TabbedView: TabBarViewDelegate {
public func tabBarView(_ tabBarView: TabBarView, shouldChangeFromTab fromTab: TabBarView.Tab?, toTab: TabBarView.Tab?) -> Bool {
let shouldChange = self.delegate?.tabbedView(self, isTabEnabled: toTab) ?? true
guard shouldChange else { return false }
// TODO: Animation injection
if let activeView = self.activeView, let tab = fromTab {
self.delegate?.tabbedView(self, willRemove: activeView, for: tab)
activeView.removeFromSuperview()
self.activeView = nil
self.delegate?.tabbedView(self, didRemove: activeView, for: tab)
}
guard
let tab = toTab,
let binding = self.tabMappings[tab] else { return false }
switch binding.action {
case .performAction(let action):
action(tab)
return false
case .displayContent(let retrieveView):
guard let view = retrieveView(tab) else { return false }
self.delegate?.tabbedView(self, willAdd: view, for: tab)
self.containerView.addSubview(view)
self.delegate?.tabbedView(self, constrain: view, inContainer: self.containerView, for: tab)
self.activeView = view
self.delegate?.tabbedView(self, didAdd: view, for: tab)
return true
}
}
public func tabBarView(_ tabBarView: TabBarView, didChangeFromTab fromTab: TabBarView.Tab?, toTab: TabBarView.Tab?) {
self.delegate?.tabbedView(self, didChangeFromTab: fromTab, toTab: toTab)
}
}
public enum TabAction<ContentType> {
public typealias Tab = TabBarView.Tab
public typealias PerformAction = (Tab) -> Void
public typealias RetrieveContent = (Tab) -> ContentType?
case performAction(action: PerformAction)
case displayContent(retrieveContent: RetrieveContent)
fileprivate var isPerformAction: Bool {
switch self {
case .performAction(_): return true
default: return false
}
}
fileprivate var isDisplayContent: Bool {
switch self {
case .displayContent(_): return true
default: return false
}
}
}
public struct TabBinding<ContentType>: Hashable {
public typealias Tab = TabBarView.Tab
public var tab: Tab
public var action: TabAction<ContentType>
public init(tab: Tab, action: TabAction<ContentType>) {
self.tab = tab
self.action = action
}
// MARK: Hashable conformance
public var hashValue: Int {
return self.tab.hashValue
}
public static func ==<ContentType> (lhs: TabBinding<ContentType>, rhs: TabBinding<ContentType>) -> Bool {
return lhs.tab == rhs.tab
}
}
// MARK: - TabBarView
public final class TabBarView: UIView {
public struct Tab: Hashable {
public var tag: String
public var view: UIView
public var delegate: TabBarViewTabDelegate?
public init(tag: String, view: UIView, delegate: TabBarViewTabDelegate? = nil) {
self.tag = tag
self.view = view
self.delegate = delegate ?? (view as? TabBarViewTabDelegate)
}
// MARK: Hashable conformance
public var hashValue: Int {
return self.tag.hashValue
}
public static func == (lhs: Tab, rhs: Tab) -> Bool {
return lhs.tag == rhs.tag
}
}
fileprivate final class TabManager {
unowned let tabBarView: TabBarView
let tab: Tab
let index: Int
let tabView = UIView()
let tapGestureRecognizer = UITapGestureRecognizer()
init(tabBarView: TabBarView, tab: Tab, index: Int) {
self.tabBarView = tabBarView
self.tab = tab
self.index = index
self.tabView.translatesAutoresizingMaskIntoConstraints = false
self.tabView.addAndConstrainView(self.tab.view)
self.tapGestureRecognizer.addTarget(self, action: #selector(self.tabViewDidTap(_:)))
self.tabView.addGestureRecognizer(self.tapGestureRecognizer)
}
dynamic func tabViewDidTap(_ tapGestureRecognizer: UITapGestureRecognizer) {
if tapGestureRecognizer.state == .ended {
self.tabBarView.didTapView(for: self)
}
}
func uninstall() {
self.tabView.removeGestureRecognizer(self.tapGestureRecognizer)
self.tabView.removeFromSuperview()
self.tab.view.removeFromSuperview()
}
}
public var tabs: [Tab] {
get { return self.tabManagers.map({ $0.tab }) }
set(newTabs) {
self.tabManagers = newTabs.enumerated().map({ TabManager(tabBarView: self, tab: $1, index: $0) })
self._selectedIndex = nil
self.desiredIndex = self.tabManagers.isEmpty ? nil : 0
self.forceTabReselection = true
self.setNeedsLayout()
}
}
fileprivate var tabManagers: [TabManager] = [] {
willSet {
self.tabManagers.forEach { tabManager in
tabManager.uninstall()
}
}
didSet {
self.tabManagers.forEach { tabManager in
self.stackView.addArrangedSubview(tabManager.tabView)
}
}
}
fileprivate weak var stackView: UIStackView!
public weak var delegate: TabBarViewDelegate?
fileprivate var forceTabReselection = false
fileprivate var dirtySelection = false
fileprivate var desiredIndex: Int?
fileprivate var _selectedIndex: Int?
public var selectedIndex: Int? {
get {
if self.dirtySelection { return self.desiredIndex }
return self._selectedIndex
}
set { self.setDesiredIndex(newValue) }
}
fileprivate func setDesiredIndex(_ index: Int?, needsLayout: Bool = true) {
if let index = index, index < 0 || index >= self.tabManagers.count {
self.desiredIndex = nil
} else {
self.desiredIndex = index
}
self.dirtySelection = (self.desiredIndex != self._selectedIndex)
if needsLayout && self.dirtySelection {
self.setNeedsLayout()
}
}
fileprivate func updateSelectedIndexIfNecessary() {
guard self.dirtySelection || self.forceTabReselection else { return }
let currentTabManager = self.tabManager(forIndex: self._selectedIndex)
let desiredTabManager = self.tabManager(forIndex: self.desiredIndex)
let shouldChange = self.delegate?.tabBarView(self, shouldChangeFromTab: currentTabManager?.tab, toTab: desiredTabManager?.tab) ?? true
guard shouldChange else { return }
let indicateSelected = { (manager: TabManager?, selected: Bool) in
guard let manager = manager else { return }
manager.tab.delegate?.tabBarView(self, shouldIndicate: manager.tab, isSelected: selected)
}
self._selectedIndex = self.desiredIndex
indicateSelected(currentTabManager, false)
indicateSelected(desiredTabManager, true)
self.dirtySelection = false
self.forceTabReselection = false
self.delegate?.tabBarView(self, didChangeFromTab: currentTabManager?.tab, toTab: desiredTabManager?.tab)
}
public var selectedTab: (index: Int, item: Tab)? {
guard let selectedIndex = self.selectedIndex else { return nil }
return (selectedIndex, self.tabManagers[selectedIndex].tab)
}
fileprivate func tabManager(forIndex index: Int?) -> TabManager? {
if let index = index {
return self.tabManagers[index]
} else {
return nil
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
fileprivate func commonInit() {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.alignment = .fill
self.addAndConstrainView(stackView)
self.stackView = stackView
}
override public func layoutSubviews() {
super.layoutSubviews()
self.updateSelectedIndexIfNecessary()
}
fileprivate func didTapView(for tabManager: TabManager) {
self.setDesiredIndex(tabManager.index, needsLayout: false)
self.updateSelectedIndexIfNecessary()
}
}
// MARK: - TabBarViewDelegate
public protocol TabBarViewDelegate: class {
func tabBarView(_ tabBarView: TabBarView, shouldChangeFromTab fromTab: TabBarView.Tab?, toTab: TabBarView.Tab?) -> Bool
func tabBarView(_ tabBarView: TabBarView, didChangeFromTab fromTab: TabBarView.Tab?, toTab: TabBarView.Tab?)
}
// MARK: - TabBarViewItemDelegate
public protocol TabBarViewTabDelegate {
func tabBarView(_ tabBarView: TabBarView, shouldIndicate tab: TabBarView.Tab, isSelected selected: Bool)
}
| mit |
adis300/Swift-Learn | SwiftLearn/Source/ML/NEAT/Evaluation.swift | 1 | 1591 | //
// Evaluation.swift
// Swift-Learn
//
// Created by Disi A on 1/19/17.
// Copyright © 2017 Votebin. All rights reserved.
//
import Foundation
public class EvaluationFunc{
public let evaluate :(Genome) -> Double
init(_ name: String) {
switch name {
case "xortest":
evaluate = EvaluationFunc.xortest
default:
fatalError("Evaluation function name not recognized")
}
}
public init(function: @escaping (Genome) -> Double) {
evaluate = function
}
fileprivate static func xortest(genome: Genome) -> Double{
let network = NEATNetwork(genome: genome)
var sse = 0.0
var inputs = [Double](repeating: 0, count: 3)
// 0 xor 0
inputs[0] = 1.0 // bias
// 0 xor 0
inputs[1] = 0.0
inputs[2] = 0.0
var outputs = network.forwardPropagate(inputs: inputs)
sse += pow((outputs[0] - 0.0), 2.0)
// 0 xor 1
inputs[1] = 0.0
inputs[2] = 1.0
outputs = network.forwardPropagate(inputs: inputs)
sse += pow((outputs[0] - 1.0), 2.0)
// 1 xor 0
inputs[1] = 1.0
inputs[2] = 0.0
outputs = network.forwardPropagate(inputs: inputs)
sse += pow((outputs[0] - 1.0), 2.0)
// 1 xor 1
inputs[1] = 1.0
inputs[2] = 1.0
outputs = network.forwardPropagate(inputs: inputs)
sse += pow((outputs[0] - 0.0), 2.0)
return 4.0 - sse
}
}
| apache-2.0 |
ndevenish/KerbalHUD | KerbalHUD/StringFormat.swift | 1 | 12274 | //
// StringFormat.swift
// KerbalHUD
//
// Created by Nicholas Devenish on 03/09/2015.
// Copyright © 2015 Nicholas Devenish. All rights reserved.
//
import Foundation
private let formatRegex = Regex(pattern: "\\{(\\d+)(?:,(\\d+))?(?::(.+?))?\\}")
private let sipRegex = Regex(pattern: "SIP(_?)(0?)(\\d+)(?:\\.(\\d+))?")
enum StringFormatError : ErrorType {
case InvalidIndex
case InvalidAlignment
case CannotCastToDouble
case NaNOrInvalidDouble
}
func downcastToDouble(val : Any) throws -> Double {
guard let dbl = val as? DoubleCoercible else {
if let v = val as? String where v == "NaN" {
throw StringFormatError.NaNOrInvalidDouble
}
print("Cannot convert '\(val)' to double!")
throw StringFormatError.CannotCastToDouble
}
return dbl.asDoubleValue
// let db : Double
// if val is Float {
// db = Double(val as! Float)
// } else if val is Double {
// db = val as! Double
// } else if val is Int {
// db = Double(val as! Int)
// } else if val is NSNumber {
// db = (val as! NSNumber).doubleValue
// } else {
// print("Couldn't parse")
// throw StringFormatError.CannotCastToDouble
// return 0
//// fatalError()
// }
// return db
}
private func getSIPrefix(exponent : Int) -> String {
let units = ["y", "z", "a", "f", "p", "n", "μ", "m",
"",
"k", "M", "G", "T", "P", "E", "Z", "Y"]
let unitOffset = 8
let index = min(max(exponent / 3 + unitOffset, 0), units.count-1)
return units[index]
}
func processSIPFormat(value : Double, formatString : String) -> String {
let matchParts = sipRegex.firstMatchInString(formatString)!
let space = matchParts.groups[0] == "_"
let zeros = matchParts.groups[1] == "0"
let length = Int(matchParts.groups[2])!
if !value.isFinite {
return String(value)
}
let leadingExponent = value == 0.0 ? 0 : max(0, Int(floor(log10(abs(value)))))
let siExponent = Int(floor(Float(leadingExponent) / 3.0))*3
// If no precision specified, use the SI exponent
var precision : Int = Int(matchParts.groups[3]) ?? max(0, siExponent)
// Calculate the bare minimum characters required
let requiredCharacters = 1 + (leadingExponent-siExponent)
+ (value < 0 ? 1 : 0) + (siExponent != 0 ? 1 : 0) + (space ? 1 : 0)
if requiredCharacters >= length {
// Drop decimal values since we are already over budget
precision = 0
} else if (precision > 0) {
// See how many we can fit.
precision = min(precision, (length-requiredCharacters-1))
}
// Scale the value to it's SI prefix
let scaledValue = abs(value / pow(10, Double(siExponent)))
var parts : [String] = []
if value < 0 {
parts.append("-")
}
parts.append(String(format: "%.\(precision)f", scaledValue))
if space {
parts.append(" ")
}
parts.append(getSIPrefix(siExponent))
// Handle undersized
let currentLength = parts.reduce(0, combine: {$0 + $1.characters.count })
if length > currentLength {
let fillCharacter = zeros ? Character("0") : Character(" ")
let insertPoint = value < 0 && zeros ? 1 : 0
let fillString = String(count: length-currentLength, repeatedValue: fillCharacter)
parts.insert(fillString, atIndex: insertPoint)
}
return parts.joinWithSeparator("")
}
extension String {
static func Format(formatString : String, _ args: Any...) throws -> String {
return try Format(formatString, argList: args)
}
static func Format(var formatString : String, argList args: [Any]) throws -> String {
var returnString = ""
var position = 0
// Attempt to use the built in formatting
if !formatString.containsString("{") {
let argList = args.map { $0 is CVarArgType ? try! downcastToDouble($0) as CVarArgType : 0 }
formatString = String(format: formatString, arguments: argList)
}
let nsS = formatString as NSString
// Compose the string with the regex formatting
for match in formatRegex.matchesInString(formatString) {
if match.range.location > position {
let intermediateRange = NSRange(location: position, length: match.range.location-position)
returnString += formatString.substringWithRange(intermediateRange)
}
guard let index = Int(match.groups[0]) else {
throw StringFormatError.InvalidIndex
}
guard index < args.count else {
throw StringFormatError.InvalidIndex
}
let alignment = Int(match.groups[1])
if !match.groups[1].isEmpty && alignment == nil {
throw StringFormatError.InvalidAlignment
}
let format = match.groups[2]
let formatValue = args[index]
var postFormat = ExpandSingleFormat(format, arg: formatValue)
// Pad with alignment!
if let align = alignment where postFormat.characters.count < abs(align) {
let difference = abs(align) - postFormat.characters.count
let fillString = String(count: difference, repeatedValue: Character(" "))
if align < 0 {
postFormat = postFormat + fillString
} else {
postFormat = fillString + postFormat
}
}
// Append this new entry to our total string
returnString += postFormat
position = match.range.location + match.range.length
}
if position < nsS.length {
returnString += nsS.substringFromIndex(position)
}
return returnString
}
}
enum NumericFormatSpecifier : String {
case Currency = "C"
case Decimal = "D"
case Exponential = "E"
case FixedPoint = "F"
case General = "G"
case Number = "N"
case Percent = "P"
case RoundTrip = "R"
case Hexadecimal = "X"
}
let numericPrefix = Regex(pattern: "^([CDEFGNPRX])(\\d{0,2})$")
let conditionalSeparator = Regex(pattern: "(?<!\\\\);")
let percentCounter = Regex(pattern: "(?<!\\\\)%")
let decimalFinder = Regex(pattern: "\\.")
let placementFinder = Regex(pattern: "(?<!\\\\)0|(?<!\\\\)#")
//let nonEndHashes = Regex(pattern: "^#*0((?!<\\\\)#*.+)0#*$")
let endHashes = Regex(pattern: "(#*)$")
let startHashes = Regex(pattern: "^(#*)")
private var formatComplaints = Set<String>()
private func ExpandSingleFormat(format : String, arg: Any) -> String {
// If not format, use whatever default.
if format.isEmpty {
return String(arg)
}
// Attempt to split the format string on ; - conditionals
let parts = conditionalSeparator.splitString(format)
switch parts.count {
case 1:
// Just one entry - no splitting
break
case 2:
// 0 : positive and zero, negative
let val = try! downcastToDouble(arg)
if val >= 0 {
return ExpandSingleFormat(parts[0], arg: arg)
} else {
return ExpandSingleFormat(parts[1], arg: abs(val))
}
case 3:
//The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros.
let val = try! downcastToDouble(arg)
if val == 0 {
return ExpandSingleFormat(parts[2], arg: arg)
} else {
return ExpandSingleFormat(
parts[(val > 0 || parts[1].isEmpty) ? 0 : 1],
arg: abs(val))
}
default:
// More than three. This is an error.
fatalError()
}
//Axx
// let postFormat : String
// Look for form AXX e.g. standard numeric formats
if let match = numericPrefix.firstMatchInString(format.uppercaseString) {
let formatType = NumericFormatSpecifier(rawValue: match.groups[0])!
let precision = match.groups[1].isEmpty ? 2 : Int(match.groups[1].isEmpty)
let value = try! downcastToDouble(arg)
switch formatType {
case .Percent:
return String(format: "%.\(precision)f%%", value*100)
default:
fatalError()
}
}
if format.hasPrefix("SIP") {
do {
let val = try downcastToDouble(arg)
return processSIPFormat(val, formatString: format)
} catch StringFormatError.NaNOrInvalidDouble {
return String(arg)
} catch {
fatalError()
}
} else if format.hasPrefix("DMS") {
print("Warning: DMS not handled")
return String(arg)
} else if format.hasPrefix("KDT") || format.hasPrefix("MET") {
if !formatComplaints.contains(format) {
print("Warning: KDT/MET not handled: ", format)
formatComplaints.insert(format)
}
return String(arg)
}
// Attempt to handle a custom numeric format.
if var value = Double.coerceTo(arg) {
let percents = percentCounter.numberOfMatchesInString(format)
value = value * pow(100, Double(percents))
// Split the string around the first decimal
var (fmtPre, fmtPost) = splitOnFirstDecimal(format)
// Handle the 1000 divider
if fmtPre.hasSuffix(",") {
value = value / 1000
fmtPre = fmtPre.substringToIndex(fmtPre.endIndex.advancedBy(-1))
}
// Count the incidents of 0/#
let counts = (placementFinder.numberOfMatchesInString(fmtPre),
placementFinder.numberOfMatchesInString(fmtPost))
// Make the string to do comparisons on
let expanded = counts.0 > 0 || counts.1 > 0 ? String(format: "%0\(counts.0+counts.1+1).\(counts.1)f", value) : ""
let (expPre, expPost) = splitOnFirstDecimal(expanded)
// If we have a longer pre-string than we have pre-placement characters,
// insert some more so that we know we match
if expPre.characters.count > counts.0 {
// Get rid of hashes - we know we don't use
fmtPre = fmtPre.stringByReplacingOccurrencesOfString("#", withString: "0")
let extraZeros = String(count: (expPre.characters.count - counts.0), repeatedValue: Character("0"))
// Two cases - a) no existing. b) existing
if counts.0 == 0 {
fmtPre = fmtPre + extraZeros
} else {
// Replace the first occurence.
let index = fmtPre.rangeOfString("0")!.startIndex
fmtPre = fmtPre.substringToIndex(index) + extraZeros + fmtPre.substringFromIndex(index)
}
}
// Wind over each of these strings, matching with the format specifiers
let woundPre = windOverStrings(fmtPre, value: expPre)
let woundPost = windOverStrings(fmtPost.reverse(), value: expPost.reverse()).reverse()
// Finally, join the parts (if we have any post)
if woundPost.isEmpty {
return woundPre
} else {
return woundPre + "." + woundPost
}
}
// Else, not a format we recognised. Until we are sure we
// have complete formatting, warn about this
if !formatComplaints.contains(format) {
print("Unrecognised string format: ", format)
formatComplaints.insert(format)
}
return format
}
extension String {
func reverse() -> String {
return self.characters.reverse().map({String($0)}).joinWithSeparator("")
}
}
private func splitOnFirstDecimal(format : String) -> (pre: String, post: String) {
let preDecimal : String
let postDecimal : String
if let decimalIndex = decimalFinder.firstMatchInString(format) {
// Split around this decimal, remove any more from the format
let location = format.startIndex.advancedBy(decimalIndex.range.location)
preDecimal = format.substringToIndex(location)
postDecimal = format.substringFromIndex(location.advancedBy(1)).stringByReplacingOccurrencesOfString(".", withString: "")
} else {
preDecimal = format
postDecimal = ""
}
return (pre: preDecimal, post: postDecimal)
}
private func windOverStrings(format : String, value : String) -> String {
var iFmt = format.startIndex
var iVal = value.startIndex
var out : [Character] = []
var endedHashes = false
while iFmt != format.endIndex && iVal != value.endIndex {
let cFmt = format.characters[iFmt]
let cVal = value.characters[iVal]
if cFmt == "#" && cVal == "0" && !endedHashes {
iFmt = iFmt.advancedBy(1)
iVal = iVal.advancedBy(1)
continue
}
if cFmt == "0" {
endedHashes = true
}
// if cFmt is #/0 and we have a digit, add it
// - we know format never non-digit &&
if cFmt == "#" || cFmt == "0" {
out.append(cVal)
iFmt = iFmt.advancedBy(1)
iVal = iVal.advancedBy(1)
} else {
out.append(cFmt)
iFmt = iFmt.advancedBy(1)
}
}
guard iVal == value.endIndex else {
fatalError()
}
while iFmt != format.endIndex {
out.append(format.characters[iFmt])
iFmt = iFmt.advancedBy(1)
}
return out.map({String($0)}).joinWithSeparator("")
} | mit |
iStig/Uther_Swift | Pods/CryptoSwift/CryptoSwift/SHA1.swift | 3 | 3586 | //
// SHA1.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 16/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
final class SHA1 : CryptoSwift.HashBase, _Hash {
var size:Int = 20 // 160 / 8
override init(_ message: NSData) {
super.init(message)
}
private let h:[UInt32] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
func calculate() -> NSData {
var tmpMessage = self.prepare()
// hash values
var hh = h
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage.appendBytes((message.length * 8).bytes(64 / 8));
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
var leftMessageBytes = tmpMessage.length
for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes {
let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 32-bit words into eighty 32-bit words:
var M:[UInt32] = [UInt32](count: 80, repeatedValue: 0)
for x in 0..<M.count {
switch (x) {
case 0...15:
var le:UInt32 = 0
chunk.getBytes(&le, range:NSRange(location:x * sizeofValue(M[x]), length: sizeofValue(M[x])));
M[x] = le.bigEndian
break
default:
M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], 1)
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
// Main loop
for j in 0...79 {
var f: UInt32 = 0;
var k: UInt32 = 0
switch (j) {
case 0...19:
f = (B & C) | ((~B) & D)
k = 0x5A827999
break
case 20...39:
f = B ^ C ^ D
k = 0x6ED9EBA1
break
case 40...59:
f = (B & C) | (B & D) | (C & D)
k = 0x8F1BBCDC
break
case 60...79:
f = B ^ C ^ D
k = 0xCA62C1D6
break
default:
break
}
var temp = (rotateLeft(A,5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff
E = D
D = C
C = rotateLeft(B, 30)
B = A
A = temp
}
hh[0] = (hh[0] &+ A) & 0xffffffff
hh[1] = (hh[1] &+ B) & 0xffffffff
hh[2] = (hh[2] &+ C) & 0xffffffff
hh[3] = (hh[3] &+ D) & 0xffffffff
hh[4] = (hh[4] &+ E) & 0xffffffff
}
// Produce the final hash value (big-endian) as a 160 bit number:
var buf: NSMutableData = NSMutableData();
for item in hh {
var i:UInt32 = item.bigEndian
buf.appendBytes(&i, length: sizeofValue(i))
}
return buf.copy() as! NSData;
}
} | mit |
IvanKalaica/GitHubSearch | GitHubSearch/GitHubSearch/Extensions/FormViewController+Extensions.swift | 1 | 1142 | //
// FormViewController+Extensions.swift
// GitHubSearch
//
// Created by Ivan Kalaica on 21/09/2017.
// Copyright © 2017 Kalaica. All rights reserved.
//
import Eureka
typealias TitleValuePair = (title: String, value: String?)
extension FormViewController {
func set(_ titleValuePair: TitleValuePair, forTag: String) {
guard let row = self.form.rowBy(tag: forTag) as? LabelRow else { return }
row.value = titleValuePair.value
row.title = titleValuePair.title
row.reload()
}
}
class EurekaLogoView: UIView {
let imageView: UIImageView
override init(frame: CGRect) {
self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 320, height: 130))
self.imageView.image = UIImage(named: "icon_github")
self.imageView.autoresizingMask = .flexibleWidth
super.init(frame: frame)
self.frame = CGRect(x: 0, y: 0, width: 320, height: 130)
self.imageView.contentMode = .scaleAspectFit
addSubview(self.imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
bpolat/Music-Player | Music Player/PlayerViewController.swift | 1 | 23039 | //
// ViewController.swift
// Music Player
//
// Created by polat on 19/08/14.
// Copyright (c) 2014 polat. All rights reserved.
// contact bpolat@live.com
// Build 3 - July 1 2015 - Please refer git history for full changes
// Build 4 - Oct 24 2015 - Please refer git history for full changes
//Build 5 - Dec 14 - 2015 Adding shuffle - repeat
//Build 6 - Oct 10 - 2016 iOS 10 update - iPhone 3g, 3gs screensize no more supported.
import UIKit
import AVFoundation
import MediaPlayer
extension UIImageView {
func setRounded() {
let radius = self.frame.width / 2
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
}
class PlayerViewController: UIViewController, UITableViewDelegate,UITableViewDataSource,AVAudioPlayerDelegate {
//Choose background here. Between 1 - 7
let selectedBackground = 1
var audioPlayer:AVAudioPlayer! = nil
var currentAudio = ""
var currentAudioPath:URL!
var audioList:NSArray!
var currentAudioIndex = 0
var timer:Timer!
var audioLength = 0.0
var toggle = true
var effectToggle = true
var totalLengthOfAudio = ""
var finalImage:UIImage!
var isTableViewOnscreen = false
var shuffleState = false
var repeatState = false
var shuffleArray = [Int]()
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet var songNo : UILabel!
@IBOutlet var lineView : UIView!
@IBOutlet weak var albumArtworkImageView: UIImageView!
@IBOutlet weak var artistNameLabel: UILabel!
@IBOutlet weak var albumNameLabel: UILabel!
@IBOutlet var songNameLabel : UILabel!
@IBOutlet var songNameLabelPlaceHolder : UILabel!
@IBOutlet var progressTimerLabel : UILabel!
@IBOutlet var playerProgressSlider : UISlider!
@IBOutlet var totalLengthOfAudioLabel : UILabel!
@IBOutlet var previousButton : UIButton!
@IBOutlet var playButton : UIButton!
@IBOutlet var nextButton : UIButton!
@IBOutlet var listButton : UIButton!
@IBOutlet var tableView : UITableView!
@IBOutlet var blurImageView : UIImageView!
@IBOutlet var enhancer : UIView!
@IBOutlet var tableViewContainer : UIView!
@IBOutlet weak var shuffleButton: UIButton!
@IBOutlet weak var repeatButton: UIButton!
@IBOutlet weak var blurView: UIVisualEffectView!
@IBOutlet weak var tableViewContainerTopConstrain: NSLayoutConstraint!
//MARK:- Lockscreen Media Control
// This shows media info on lock screen - used currently and perform controls
func showMediaInfo(){
let artistName = readArtistNameFromPlist(currentAudioIndex)
let songName = readSongNameFromPlist(currentAudioIndex)
MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyArtist : artistName, MPMediaItemPropertyTitle : songName]
}
override func remoteControlReceived(with event: UIEvent?) {
if event!.type == UIEvent.EventType.remoteControl{
switch event!.subtype{
case UIEventSubtype.remoteControlPlay:
play(self)
case UIEventSubtype.remoteControlPause:
play(self)
case UIEventSubtype.remoteControlNextTrack:
next(self)
case UIEventSubtype.remoteControlPreviousTrack:
previous(self)
default:
print("There is an issue with the control")
}
}
}
//MARK-
// Table View Part of the code. Displays Song name and Artist Name
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return audioList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var songNameDict = NSDictionary();
songNameDict = audioList.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
let songName = songNameDict.value(forKey: "songName") as! String
var albumNameDict = NSDictionary();
albumNameDict = audioList.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
let albumName = albumNameDict.value(forKey: "albumName") as! String
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
cell.textLabel?.font = UIFont(name: "BodoniSvtyTwoITCTT-BookIta", size: 25.0)
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.text = songName
cell.detailTextLabel?.font = UIFont(name: "BodoniSvtyTwoITCTT-Book", size: 16.0)
cell.detailTextLabel?.textColor = UIColor.white
cell.detailTextLabel?.text = albumName
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 54.0
}
func tableView(_ tableView: UITableView,willDisplay cell: UITableViewCell,forRowAt indexPath: IndexPath){
tableView.backgroundColor = UIColor.clear
let backgroundView = UIView(frame: CGRect.zero)
backgroundView.backgroundColor = UIColor.clear
cell.backgroundView = backgroundView
cell.backgroundColor = UIColor.clear
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
animateTableViewToOffScreen()
currentAudioIndex = (indexPath as NSIndexPath).row
prepareAudio()
playAudio()
effectToggle = !effectToggle
let showList = UIImage(named: "list")
let removeList = UIImage(named: "listS")
listButton.setImage(effectToggle ? showList : removeList, for: UIControl.State())
let play = UIImage(named: "play")
let pause = UIImage(named: "pause")
playButton.setImage(audioPlayer.isPlaying ? pause : play, for: UIControl.State())
blurView.isHidden = true
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.default
}
override var prefersStatusBarHidden : Bool {
if isTableViewOnscreen{
return true
}else{
return false
}
}
override func viewDidLoad() {
super.viewDidLoad()
//assing background
backgroundImageView.image = UIImage(named: "background\(selectedBackground)")
//this sets last listened trach number as current
retrieveSavedTrackNumber()
prepareAudio()
updateLabels()
assingSliderUI()
setRepeatAndShuffle()
retrievePlayerProgressSliderValue()
//LockScreen Media control registry
if UIApplication.shared.responds(to: #selector(UIApplication.beginReceivingRemoteControlEvents)){
UIApplication.shared.beginReceivingRemoteControlEvents()
UIApplication.shared.beginBackgroundTask(expirationHandler: { () -> Void in
})
}
}
func setRepeatAndShuffle(){
shuffleState = UserDefaults.standard.bool(forKey: "shuffleState")
repeatState = UserDefaults.standard.bool(forKey: "repeatState")
if shuffleState == true {
shuffleButton.isSelected = true
} else {
shuffleButton.isSelected = false
}
if repeatState == true {
repeatButton.isSelected = true
}else{
repeatButton.isSelected = false
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableViewContainerTopConstrain.constant = 1000.0
self.tableViewContainer.layoutIfNeeded()
blurView.isHidden = true
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
albumArtworkImageView.setRounded()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK:- AVAudioPlayer Delegate's Callback method
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){
if flag == true {
if shuffleState == false && repeatState == false {
// do nothing
playButton.setImage( UIImage(named: "play"), for: UIControl.State())
return
} else if shuffleState == false && repeatState == true {
//repeat same song
prepareAudio()
playAudio()
} else if shuffleState == true && repeatState == false {
//shuffle songs but do not repeat at the end
//Shuffle Logic : Create an array and put current song into the array then when next song come randomly choose song from available song and check against the array it is in the array try until you find one if the array and number of songs are same then stop playing as all songs are already played.
shuffleArray.append(currentAudioIndex)
if shuffleArray.count >= audioList.count {
playButton.setImage( UIImage(named: "play"), for: UIControl.State())
return
}
var randomIndex = 0
var newIndex = false
while newIndex == false {
randomIndex = Int(arc4random_uniform(UInt32(audioList.count)))
if shuffleArray.contains(randomIndex) {
newIndex = false
}else{
newIndex = true
}
}
currentAudioIndex = randomIndex
prepareAudio()
playAudio()
} else if shuffleState == true && repeatState == true {
//shuffle song endlessly
shuffleArray.append(currentAudioIndex)
if shuffleArray.count >= audioList.count {
shuffleArray.removeAll()
}
var randomIndex = 0
var newIndex = false
while newIndex == false {
randomIndex = Int(arc4random_uniform(UInt32(audioList.count)))
if shuffleArray.contains(randomIndex) {
newIndex = false
}else{
newIndex = true
}
}
currentAudioIndex = randomIndex
prepareAudio()
playAudio()
}
}
}
//Sets audio file URL
func setCurrentAudioPath(){
currentAudio = readSongNameFromPlist(currentAudioIndex)
currentAudioPath = URL(fileURLWithPath: Bundle.main.path(forResource: currentAudio, ofType: "mp3")!)
print("\(String(describing: currentAudioPath))")
}
func saveCurrentTrackNumber(){
UserDefaults.standard.set(currentAudioIndex, forKey:"currentAudioIndex")
UserDefaults.standard.synchronize()
}
func retrieveSavedTrackNumber(){
if let currentAudioIndex_ = UserDefaults.standard.object(forKey: "currentAudioIndex") as? Int{
currentAudioIndex = currentAudioIndex_
}else{
currentAudioIndex = 0
}
}
// Prepare audio for playing
func prepareAudio(){
setCurrentAudioPath()
do {
//keep alive audio at background
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback)))
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
UIApplication.shared.beginReceivingRemoteControlEvents()
audioPlayer = try? AVAudioPlayer(contentsOf: currentAudioPath)
audioPlayer.delegate = self
// audioPlayer
audioLength = audioPlayer.duration
playerProgressSlider.maximumValue = CFloat(audioPlayer.duration)
playerProgressSlider.minimumValue = 0.0
playerProgressSlider.value = 0.0
audioPlayer.prepareToPlay()
showTotalSongLength()
updateLabels()
progressTimerLabel.text = "00:00"
}
//MARK:- Player Controls Methods
func playAudio(){
audioPlayer.play()
startTimer()
updateLabels()
saveCurrentTrackNumber()
showMediaInfo()
}
func playNextAudio(){
currentAudioIndex += 1
if currentAudioIndex>audioList.count-1{
currentAudioIndex -= 1
return
}
if audioPlayer.isPlaying{
prepareAudio()
playAudio()
}else{
prepareAudio()
}
}
func playPreviousAudio(){
currentAudioIndex -= 1
if currentAudioIndex<0{
currentAudioIndex += 1
return
}
if audioPlayer.isPlaying{
prepareAudio()
playAudio()
}else{
prepareAudio()
}
}
func stopAudiplayer(){
audioPlayer.stop();
}
func pauseAudioPlayer(){
audioPlayer.pause()
}
//MARK:-
func startTimer(){
if timer == nil {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(PlayerViewController.update(_:)), userInfo: nil,repeats: true)
timer.fire()
}
}
deinit {
timer.invalidate()
}
func stopTimer(){
timer.invalidate()
}
@objc func update(_ timer: Timer){
if !audioPlayer.isPlaying{
return
}
let time = calculateTimeFromNSTimeInterval(audioPlayer.currentTime)
progressTimerLabel.text = "\(time.minute):\(time.second)"
playerProgressSlider.value = CFloat(audioPlayer.currentTime)
UserDefaults.standard.set(playerProgressSlider.value , forKey: "playerProgressSliderValue")
}
func retrievePlayerProgressSliderValue(){
let playerProgressSliderValue = UserDefaults.standard.float(forKey: "playerProgressSliderValue")
if playerProgressSliderValue != 0 {
playerProgressSlider.value = playerProgressSliderValue
audioPlayer.currentTime = TimeInterval(playerProgressSliderValue)
let time = calculateTimeFromNSTimeInterval(audioPlayer.currentTime)
progressTimerLabel.text = "\(time.minute):\(time.second)"
playerProgressSlider.value = CFloat(audioPlayer.currentTime)
}else{
playerProgressSlider.value = 0.0
audioPlayer.currentTime = 0.0
progressTimerLabel.text = "00:00:00"
}
}
//This returns song length
func calculateTimeFromNSTimeInterval(_ duration:TimeInterval) ->(minute:String, second:String){
// let hour_ = abs(Int(duration)/3600)
let minute_ = abs(Int((duration/60).truncatingRemainder(dividingBy: 60)))
let second_ = abs(Int(duration.truncatingRemainder(dividingBy: 60)))
// var hour = hour_ > 9 ? "\(hour_)" : "0\(hour_)"
let minute = minute_ > 9 ? "\(minute_)" : "0\(minute_)"
let second = second_ > 9 ? "\(second_)" : "0\(second_)"
return (minute,second)
}
func showTotalSongLength(){
calculateSongLength()
totalLengthOfAudioLabel.text = totalLengthOfAudio
}
func calculateSongLength(){
let time = calculateTimeFromNSTimeInterval(audioLength)
totalLengthOfAudio = "\(time.minute):\(time.second)"
}
//Read plist file and creates an array of dictionary
func readFromPlist(){
let path = Bundle.main.path(forResource: "list", ofType: "plist")
audioList = NSArray(contentsOfFile:path!)
}
func readArtistNameFromPlist(_ indexNumber: Int) -> String {
readFromPlist()
var infoDict = NSDictionary();
infoDict = audioList.object(at: indexNumber) as! NSDictionary
let artistName = infoDict.value(forKey: "artistName") as! String
return artistName
}
func readAlbumNameFromPlist(_ indexNumber: Int) -> String {
readFromPlist()
var infoDict = NSDictionary();
infoDict = audioList.object(at: indexNumber) as! NSDictionary
let albumName = infoDict.value(forKey: "albumName") as! String
return albumName
}
func readSongNameFromPlist(_ indexNumber: Int) -> String {
readFromPlist()
var songNameDict = NSDictionary();
songNameDict = audioList.object(at: indexNumber) as! NSDictionary
let songName = songNameDict.value(forKey: "songName") as! String
return songName
}
func readArtworkNameFromPlist(_ indexNumber: Int) -> String {
readFromPlist()
var infoDict = NSDictionary();
infoDict = audioList.object(at: indexNumber) as! NSDictionary
let artworkName = infoDict.value(forKey: "albumArtwork") as! String
return artworkName
}
func updateLabels(){
updateArtistNameLabel()
updateAlbumNameLabel()
updateSongNameLabel()
updateAlbumArtwork()
}
func updateArtistNameLabel(){
let artistName = readArtistNameFromPlist(currentAudioIndex)
artistNameLabel.text = artistName
}
func updateAlbumNameLabel(){
let albumName = readAlbumNameFromPlist(currentAudioIndex)
albumNameLabel.text = albumName
}
func updateSongNameLabel(){
let songName = readSongNameFromPlist(currentAudioIndex)
songNameLabel.text = songName
}
func updateAlbumArtwork(){
let artworkName = readArtworkNameFromPlist(currentAudioIndex)
albumArtworkImageView.image = UIImage(named: artworkName)
}
//creates animation and push table view to screen
func animateTableViewToScreen(){
self.blurView.isHidden = false
UIView.animate(withDuration: 0.15, delay: 0.01, options:
UIView.AnimationOptions.curveEaseIn, animations: {
self.tableViewContainerTopConstrain.constant = 0.0
self.tableViewContainer.layoutIfNeeded()
}, completion: { (bool) in
})
}
func animateTableViewToOffScreen(){
isTableViewOnscreen = false
setNeedsStatusBarAppearanceUpdate()
self.tableViewContainerTopConstrain.constant = 1000.0
UIView.animate(withDuration: 0.20, delay: 0.0, options: UIView.AnimationOptions.curveEaseOut, animations: {
self.tableViewContainer.layoutIfNeeded()
}, completion: {
(value: Bool) in
self.blurView.isHidden = true
})
}
func assingSliderUI () {
let minImage = UIImage(named: "slider-track-fill")
let maxImage = UIImage(named: "slider-track")
let thumb = UIImage(named: "thumb")
playerProgressSlider.setMinimumTrackImage(minImage, for: UIControl.State())
playerProgressSlider.setMaximumTrackImage(maxImage, for: UIControl.State())
playerProgressSlider.setThumbImage(thumb, for: UIControl.State())
}
@IBAction func play(_ sender : AnyObject) {
if shuffleState == true {
shuffleArray.removeAll()
}
let play = UIImage(named: "play")
let pause = UIImage(named: "pause")
if audioPlayer.isPlaying{
pauseAudioPlayer()
}else{
playAudio()
}
playButton.setImage(audioPlayer.isPlaying ? pause : play, for: UIControl.State())
}
@IBAction func next(_ sender : AnyObject) {
playNextAudio()
}
@IBAction func previous(_ sender : AnyObject) {
playPreviousAudio()
}
@IBAction func changeAudioLocationSlider(_ sender : UISlider) {
audioPlayer.currentTime = TimeInterval(sender.value)
}
@IBAction func userTapped(_ sender : UITapGestureRecognizer) {
play(self)
}
@IBAction func userSwipeLeft(_ sender : UISwipeGestureRecognizer) {
next(self)
}
@IBAction func userSwipeRight(_ sender : UISwipeGestureRecognizer) {
previous(self)
}
@IBAction func userSwipeUp(_ sender : UISwipeGestureRecognizer) {
presentListTableView(self)
}
@IBAction func shuffleButtonTapped(_ sender: UIButton) {
shuffleArray.removeAll()
if sender.isSelected == true {
sender.isSelected = false
shuffleState = false
UserDefaults.standard.set(false, forKey: "shuffleState")
} else {
sender.isSelected = true
shuffleState = true
UserDefaults.standard.set(true, forKey: "shuffleState")
}
}
@IBAction func repeatButtonTapped(_ sender: UIButton) {
if sender.isSelected == true {
sender.isSelected = false
repeatState = false
UserDefaults.standard.set(false, forKey: "repeatState")
} else {
sender.isSelected = true
repeatState = true
UserDefaults.standard.set(true, forKey: "repeatState")
}
}
@IBAction func presentListTableView(_ sender : AnyObject) {
if effectToggle{
isTableViewOnscreen = true
setNeedsStatusBarAppearanceUpdate()
self.animateTableViewToScreen()
}else{
self.animateTableViewToOffScreen()
}
effectToggle = !effectToggle
let showList = UIImage(named: "list")
let removeList = UIImage(named: "listS")
listButton.setImage(effectToggle ? showList : removeList, for: UIControl.State())
}
}
//extension AVPlayer {
// override convenience init() {
// if #available(iOS 10.0, *) {
// automaticallyWaitsToMinimizeStalling = false
// }
// }
//}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
return input.rawValue
}
| unlicense |
gservera/TaxonomyKit | Sources/TaxonomyKit/Wikipedia.swift | 1 | 20559 | /*
* Wikipedia.swift
* TaxonomyKit
*
* Created: Guillem Servera on 17/09/2017.
* Copyright: © 2017-2019 Guillem Servera (https://github.com/gservera)
*
* 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
/// The base class from which all the Wikipedia related tasks are initiated. This class
/// is not meant to be instantiated but it serves as a start node to invoke the
/// TaxonomyKit functions in your code.
public final class Wikipedia {
private let language: WikipediaLanguage
/// The max width in pixels of the image that the Wikipedia API should return. Defaults to 600.
public var thumbnailWidth: Int = 600
/// Set to `true` to retrieve Wikipedia extracts as an `NSAttributedString`. Default is `false`.
public var usesRichText: Bool = false
/// Creates a new Wikipedia instance with a given locale. Defaults to system's.
///
/// - Parameter language: The `WikipediaLanguage` object that will be passed to
/// every method called from this instance.
public init(language: WikipediaLanguage = WikipediaLanguage()) {
self.language = language
}
/// Attempts to guess scientific names that could match a specific query using info from
/// the corresponding Wikipedia article.
///
/// - Since: TaxonomyKit 1.5.
/// - Parameters:
/// - query: The query for which to retrieve Wikipedia metadata.
/// - callback: A callback closure that will be called when the request completes or
/// if an error occurs. This closure has a `TaxonomyResult<[String]>`
/// parameter that contains a wrapper with the found names (or `[]` if
/// no results are found) when the request succeeds.
/// - Warning: Please note that the callback may not be called on the main thread.
/// - Returns: The `URLSessionDataTask` object that has begun handling the request. You
/// may keep a reference to this object if you plan it should be canceled at some
/// point.
@discardableResult
public func findPossibleScientificNames(matching query: String,
callback: @escaping(_ result: Result<[String], TaxonomyError>) -> Void) -> URLSessionTask {
let request = TaxonomyRequest.scientificNameGuess(query: query, language: language)
let task = Taxonomy.internalUrlSession.dataTask(with: request.url) { data, response, error in
guard let data = filter(response, data, error, callback) else { return }
let decoder = JSONDecoder()
guard let wikipediaResponse = try? decoder.decode(WikipediaResponse.self, from: data) else {
callback(.failure(.parseError(message: "Could not parse JSON data")))
return
}
guard let page = wikipediaResponse.query.pages.values.first else {
callback(.failure(.unknownError)) // Unknown JSON structure
return
}
guard !page.isMissing, page.identifier != nil, let extract = page.extract else {
callback(.success([]))
return
}
var names: [String] = []
if page.title != query && page.title.components(separatedBy: " ").count > 1 {
names.append(page.title)
}
if let match = extract.range(of: "\\((.*?)([.,\\(\\)\\[\\]\\{\\}])", options: .regularExpression) {
let toBeTrimmed = CharacterSet(charactersIn: " .,()[]{}\n")
names.append(String(extract[match].trimmingCharacters(in: toBeTrimmed)))
}
callback(.success(names))
}
return task.resumed()
}
/// Sends an asynchronous request to Wikipedia servers asking for metadata such as an extract
/// and the Wikipedia page URL for a concrete taxon.
///
/// - Since: TaxonomyKit 1.3.
/// - Parameters:
/// - taxon: The taxon for which to retrieve Wikipedia metadata.
/// - callback: A callback closure that will be called when the request completes or
/// if an error occurs. This closure has a `TaxonomyResult<WikipediaResult?>`
/// parameter that contains a wrapper with the requested metadata (or `nil` if
/// no results are found) when the request succeeds.
/// - Warning: Please note that the callback may not be called on the main thread.
/// - Returns: The `URLSessionDataTask` object that has begun handling the request. You
/// may keep a reference to this object if you plan it should be canceled at some
/// point.
@discardableResult
public func retrieveAbstract<T: TaxonRepresenting>(for taxon: T,
callback: @escaping (Result<WikipediaResult?, TaxonomyError>) -> Void) -> URLSessionTask {
let request = TaxonomyRequest.wikipediaAbstract(query: taxon.name, richText: usesRichText, language: language)
return retrieveAbstract(with: request, callback: callback)
}
/// Sends an asynchronous request to Wikipedia servers asking for metadata such as an extract
/// and the Wikipedia page URL for a concrete Wikipedia Page ID.
///
/// - Since: TaxonomyKit 1.5.
/// - Parameters:
/// - identifier: The Wikipedia Page ID for which to retrieve the requested metadata.
/// - callback: A callback closure that will be called when the request completes or
/// if an error occurs. This closure has a `TaxonomyResult<WikipediaResult?>`
/// parameter that contains a wrapper with the requested metadata (or `nil` if
/// no results are found) when the request succeeds.
/// - Warning: Please note that the callback may not be called on the main thread.
/// - Returns: The `URLSessionDataTask` object that has begun handling the request. You
/// may keep a reference to this object if you plan it should be canceled at some
/// point.
@discardableResult
public func retrieveAbstract(for identifier: String,
callback: @escaping (Result<WikipediaResult?, TaxonomyError>) -> Void) -> URLSessionDataTask {
let request = TaxonomyRequest.knownWikipediaAbstract(pageId: identifier,
richText: usesRichText, language: language)
return retrieveAbstract(with: request, callback: callback)
}
private func retrieveAbstract(with request: TaxonomyRequest,
callback: @escaping (Result<WikipediaResult?, TaxonomyError>) -> Void) -> URLSessionDataTask {
let language = self.language
let task = Taxonomy.internalUrlSession.dataTask(with: request.url) { data, response, error in
guard let data = filter(response, data, error, callback) else { return }
do {
let decoder = JSONDecoder()
let wikipediaResponse = try decoder.decode(WikipediaResponse.self, from: data)
if let page = wikipediaResponse.query.pages.values.first {
guard !page.isMissing, let identifier = page.identifier, let extract = page.extract else {
callback(.success(nil))
return
}
var wikiResult = WikipediaResult(language: language, identifier: identifier, title: page.title)
if self.usesRichText {
wikiResult.attributedExtract = WikipediaAttributedExtract(htmlString: extract)
} else {
wikiResult.extract = extract
}
callback(.success(wikiResult))
} else {
callback(.failure(.unknownError)) // Unknown JSON structure
}
} catch _ {
callback(.failure(.parseError(message: "Could not parse JSON data")))
}
}
return task.resumed()
}
/// Sends an asynchronous request to Wikipedia servers asking for the Wikipedia page
/// thumbnail for a concrete taxon.
///
/// - Since: TaxonomyKit 1.4.
/// - Parameters:
/// - taxon: The taxon for which to retrieve Wikipedia thumbnail.
/// - callback: A callback closure that will be called when the request completes or
/// if an error occurs. This closure has a `TaxonomyResult<Data?>`
/// parameter that contains a wrapper with the requested image data (or `nil` if
/// no results are found) when the request succeeds.
/// - Warning: Please note that the callback may not be called on the main thread.
/// - Returns: The `URLSessionDataTask` object that has begun handling the request. You
/// may keep a reference to this object if you plan it should be canceled at some
/// point.
@discardableResult
public func retrieveThumbnail<T: TaxonRepresenting>(for taxon: T,
callback: @escaping(Result<Data?, TaxonomyError>) -> Void) -> URLSessionTask {
let request = TaxonomyRequest.wikipediaThumbnail(query: taxon.name, width: thumbnailWidth, language: language)
return retrieveThumbnail(with: request, callback: callback)
}
/// Sends an asynchronous request to Wikipedia servers asking for the Wikipedia page
/// thumbnail for a concrete Wikipedia Page ID.
///
/// - Since: TaxonomyKit 1.4.
/// - Parameters:
/// - identifier: The Wikipedia Page ID for which to retrieve the requested metadata.
/// - callback: A callback closure that will be called when the request completes or
/// if an error occurs. This closure has a `TaxonomyResult<Data?>`
/// parameter that contains a wrapper with the requested image data (or `nil` if
/// no results are found) when the request succeeds.
/// - Warning: Please note that the callback may not be called on the main thread.
/// - Returns: The `URLSessionDataTask` object that has begun handling the request. You
/// may keep a reference to this object if you plan it should be canceled at some
/// point.
@discardableResult
public func retrieveThumbnail(for identifier: String,
callback: @escaping (Result<Data?, TaxonomyError>) -> Void) -> URLSessionTask {
let request = TaxonomyRequest.knownWikipediaThumbnail(pageId: identifier,
width: thumbnailWidth, language: language)
return retrieveThumbnail(with: request, callback: callback)
}
private func retrieveThumbnail(with request: TaxonomyRequest,
callback: @escaping (Result<Data?, TaxonomyError>) -> Void) -> URLSessionDataTask {
let task = Taxonomy.internalUrlSession.dataTask(with: request.url) { data, response, error in
guard let data = filter(response, data, error, callback) else { return }
do {
let decoder = JSONDecoder()
let wikipediaResponse = try decoder.decode(WikipediaResponse.self, from: data)
if let page = wikipediaResponse.query.pages.values.first {
guard !page.isMissing, let thumbnail = page.thumbnail else {
callback(.success(nil))
return
}
if let data = Wikipedia.downloadImage(from: thumbnail.source) {
callback(.success(data))
} else {
callback(.failure(.unknownError)) // Could not download image
}
} else {
callback(.failure(.unknownError)) // Unknown JSON structure
}
} catch let error {
callback(.failure(.parseError(message: "Could not parse JSON data. Error: \(error)")))
}
}
return task.resumed()
}
/// Sends an asynchronous request to Wikipedia servers asking for the Wikipedia page
/// thumbnail and page extract for a concrete Wikipedia Page ID.
///
/// - Since: TaxonomyKit 1.5.
/// - Parameters:
/// - identifier: The Wikipedia Page ID for which to retrieve the requested metadata.
/// - inlineImage: Pass `true` to download the found thumbnail immediately. Defaults to
/// `false`, which means onlu the thumbnail URL is returned.
/// - callback: A callback closure that will be called when the request completes or
/// if an error occurs. This closure has a `TaxonomyResult<WikipediaResult?>`
/// parameter that contains a wrapper with the requested metadata (or `nil` if
/// no results are found) when the request succeeds.
/// - Warning: Please note that the callback may not be called on the main thread.
/// - Returns: The `URLSessionDataTask` object that has begun handling the request. You
/// may keep a reference to this object if you plan it should be canceled at some
/// point.
@discardableResult
public func retrieveFullRecord(for identifier: String, inlineImage: Bool = false,
callback: @escaping (Result<WikipediaResult?, TaxonomyError>) -> Void) -> URLSessionTask {
let request = TaxonomyRequest.knownWikipediaFullRecord(pageId: identifier, richText: usesRichText,
thumbnailWidth: thumbnailWidth, language: language)
return retrieveFullRecord(with: request, inlineImage: inlineImage, callback: callback)
}
/// Sends an asynchronous request to Wikipedia servers asking for the thumbnail and extract of a
/// page whose title matches a given taxon's scientific name.
///
/// - Since: TaxonomyKit 1.5.
/// - Parameters:
/// - taxon: The taxon whose scientific name will be evaluated to find a matching Wikipedia page.
/// - inlineImage: Pass `true` to download the found thumbnail immediately. Defaults to
/// `false`, which means onlu the thumbnail URL is returned.
/// - callback: A callback closure that will be called when the request completes or
/// if an error occurs. This closure has a `TaxonomyResult<WikipediaResult?>`
/// parameter that contains a wrapper with the requested metadata (or `nil` if
/// no matching Wikipedia pages are found) when the request succeeds.
/// - Warning: Please note that the callback may not be called on the main thread.
/// - Returns: The `URLSessionDataTask` object that has begun handling the request. You
/// may keep a reference to this object if you plan it should be canceled at some
/// point.
@discardableResult
public func findPossibleMatch<T: TaxonRepresenting>(for taxon: T, inlineImage: Bool = false,
callback: @escaping(Result<WikipediaResult?, TaxonomyError>) -> Void) -> URLSessionTask {
let request = TaxonomyRequest.wikipediaFullRecord(query: taxon.name, richText: usesRichText,
thumbnailWidth: thumbnailWidth, language: language)
return retrieveFullRecord(with: request, inlineImage: inlineImage, strict: true, callback: callback)
}
/// Sends an asynchronous request to Wikipedia servers to retrieve the Wikipedia page
/// thumbnail and page extract for a concrete taxon.
///
/// - Since: TaxonomyKit 1.5.
/// - Parameters:
/// - taxon: The taxon for which to retrieve Wikipedia thumbnail.
/// - inlineImage: Pass `true` to download the found thumbnail immediately. Defaults to
/// `false`, which means only the thumbnail URL is returned.
/// - callback: A callback closure that will be called when the request completes or
/// if an error occurs. This closure has a `TaxonomyResult<WikipediaResult?>`
/// parameter that contains a wrapper with the requested metadata (or `nil` if
/// no results are found) when the request succeeds.
/// - Warning: Please note that the callback might not be called on the main thread.
/// - Returns: The `URLSessionDataTask` object that has begun handling the request. You
/// may keep a reference to this object if you plan to cancel it at some point.
@discardableResult
public func retrieveFullRecord<T: TaxonRepresenting>(for taxon: T, inlineImage: Bool = false,
callback: @escaping (Result<WikipediaResult?, TaxonomyError>) -> Void) -> URLSessionTask {
let request = TaxonomyRequest.wikipediaFullRecord(query: taxon.name, richText: usesRichText,
thumbnailWidth: thumbnailWidth, language: language)
return retrieveFullRecord(with: request, inlineImage: inlineImage, callback: callback)
}
private func retrieveFullRecord(with request: TaxonomyRequest, inlineImage: Bool = false, strict: Bool = false,
callback: @escaping (Result<WikipediaResult?, TaxonomyError>) -> Void) -> URLSessionDataTask {
let task = Taxonomy.internalUrlSession.dataTask(with: request.url) { data, response, error in
let language = self.language
guard let data = filter(response, data, error, callback) else { return }
guard let wikipediaResponse = try? JSONDecoder().decode(WikipediaResponse.self, from: data) else {
callback(.failure(.parseError(message: "Could not parse JSON data.")))
return
}
guard let page = wikipediaResponse.query.pages.values.first else {
callback(.failure(.unknownError)) // Unknown JSON structure
return
}
guard !page.isMissing, let pageID = page.identifier, let extract = page.extract,
!(strict && !wikipediaResponse.query.redirects.isEmpty) else {
callback(.success(nil))
return
}
var wikiResult = WikipediaResult(language: language, identifier: pageID, title: page.title)
if let thumbnail = page.thumbnail {
wikiResult.pageImageUrl = thumbnail.source
if inlineImage {
wikiResult.pageImageData = Wikipedia.downloadImage(from: thumbnail.source)
}
}
if self.usesRichText {
wikiResult.attributedExtract = WikipediaAttributedExtract(htmlString: extract)
} else {
wikiResult.extract = extract
}
callback(.success(wikiResult))
}
return task.resumed()
}
static func downloadImage(from url: URL) -> Data? {
var downloadedData: Data?
let semaphore = DispatchSemaphore(value: 0)
URLSession(configuration: .default).dataTask(with: url) { dlData, dlResponse, dlError in
downloadedData = filter(dlResponse, dlData, dlError, { (_: Result<Void, TaxonomyError>) in })
semaphore.signal()
}.resume()
_ = semaphore.wait(timeout: .distantFuture)
return downloadedData
}
}
| mit |
uberbruns/CasingTools | Tests/CasingToolsTests/CasingToolsTests.swift | 1 | 4629 | //
// CasingToolsTests.swift
// CasingTools
//
// Created by Karsten Bruns on 2017-04-29.
// Copyright © 2017 CasingTools. All rights reserved.
//
import Foundation
import XCTest
class CasingToolsTests: XCTestCase {
static let allTests = [
("testLowerCamelCase", testLowerCamelCase),
("testLowercaseSnailCase", testLowercaseSnailCase),
("testLowercaseTrainCase", testLowercaseTrainCase),
("testUpperCamelCase", testUpperCamelCase),
("testUppercaseSnailCase", testUppercaseSnailCase),
("testUppercaseTrainCase", testUppercaseTrainCase),
("testComponentPerformance", testComponentPerformance),
("testUsagePerformance", testUsagePerformance),
("testEmpty", testEmpty),
]
let testStringA = "Some people tell Me that I need HELP!"
let testStringB = "SomePeopleTellMeThatINeedHELP"
let testStringC = "Some-Pêöple\nTellMe??ThatINeedHELP "
func testLowerCamelCase() {
XCTAssertEqual(Casing.lowerCamelCase(testStringA), "somePeopleTellMeThatINeedHELP")
XCTAssertEqual(Casing.lowerCamelCase(testStringB), "somePeopleTellMeThatINeedHELP")
XCTAssertEqual(Casing.lowerCamelCase(testStringC), "somePeopleTellMeThatINeedHELP")
}
func testLowercaseSnailCase() {
XCTAssertEqual(Casing.lowercaseSnailCase(testStringA), "some_people_tell_me_that_i_need_help")
XCTAssertEqual(Casing.lowercaseSnailCase(testStringB), "some_people_tell_me_that_i_need_help")
XCTAssertEqual(Casing.lowercaseSnailCase(testStringC), "some_people_tell_me_that_i_need_help")
}
func testLowercaseTrainCase() {
XCTAssertEqual(Casing.lowercaseTrainCase(testStringA), "some-people-tell-me-that-i-need-help")
XCTAssertEqual(Casing.lowercaseTrainCase(testStringB), "some-people-tell-me-that-i-need-help")
XCTAssertEqual(Casing.lowercaseTrainCase(testStringC), "some-people-tell-me-that-i-need-help")
}
func testUpperCamelCase() {
XCTAssertEqual(Casing.upperCamelCase(testStringA), "SomePeopleTellMeThatINeedHELP")
XCTAssertEqual(Casing.upperCamelCase(testStringB), "SomePeopleTellMeThatINeedHELP")
XCTAssertEqual(Casing.upperCamelCase(testStringC), "SomePeopleTellMeThatINeedHELP")
}
func testUppercaseSnailCase() {
XCTAssertEqual(Casing.uppercaseSnailCase(testStringA), "SOME_PEOPLE_TELL_ME_THAT_I_NEED_HELP")
XCTAssertEqual(Casing.uppercaseSnailCase(testStringB), "SOME_PEOPLE_TELL_ME_THAT_I_NEED_HELP")
XCTAssertEqual(Casing.uppercaseSnailCase(testStringC), "SOME_PEOPLE_TELL_ME_THAT_I_NEED_HELP")
}
func testUppercaseTrainCase() {
XCTAssertEqual(Casing.uppercaseTrainCase(testStringA), "SOME-PEOPLE-TELL-ME-THAT-I-NEED-HELP")
XCTAssertEqual(Casing.uppercaseTrainCase(testStringB), "SOME-PEOPLE-TELL-ME-THAT-I-NEED-HELP")
XCTAssertEqual(Casing.uppercaseTrainCase(testStringC), "SOME-PEOPLE-TELL-ME-THAT-I-NEED-HELP")
print(Casing.splitIntoWords(testStringA))
print(Casing.splitIntoWords(testStringC))
}
func testComponentPerformance() {
let test = testStringA
self.measure {
for _ in 0..<10000 {
_ = Casing.splitIntoWords(test)
}
}
}
func testUsagePerformance() {
let test = testStringA
self.measure {
for _ in 0..<1000 {
_ = Casing.lowerCamelCase(test)
_ = Casing.lowercaseSnailCase(test)
_ = Casing.lowercaseTrainCase(test)
_ = Casing.upperCamelCase(test)
_ = Casing.uppercaseSnailCase(test)
_ = Casing.uppercaseTrainCase(test)
}
}
}
func testEmpty() {
var test = ""
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "")
test = " "
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "")
test = "\n"
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "")
test = " \n "
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "")
test = "a"
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "a")
test = "A"
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "a")
test = "aa"
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "aa")
test = "aA"
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "a_a")
test = "Aa"
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "aa")
test = "AA"
XCTAssertTrue(Casing.lowercaseSnailCase(test) == "aa")
}
}
| mit |
andrea-prearo/ContactList | ContactList/TableViewCells/ContactCell.swift | 1 | 818 | //
// ContactCell.swift
// ContactList
//
// Created by Andrea Prearo on 3/9/16.
// Copyright © 2016 Andrea Prearo
//
import UIKit
import AlamofireImage
class ContactCell: UITableViewCell {
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var company: UILabel!
func configure(_ viewModel: ContactViewModel) {
if let urlString = viewModel.avatarUrl, let url = URL(string: urlString) {
let filter = RoundedCornersFilter(radius: avatar.frame.size.width * 0.5)
avatar.af_setImage(withURL: url,
placeholderImage: UIImage.defaultAvatarImage(),
filter: filter)
}
username.text = viewModel.username
company.text = viewModel.company
}
}
| mit |
joninsky/JVUtilities | JVUtilities/LocalImageManager.swift | 1 | 5973 | //
// LocalImageManager.swift
// JVUtilities
//
// Created by Jon Vogel on 5/4/16.
// Copyright © 2016 Jon Vogel. All rights reserved.
//
import UIKit
public enum ImageType: String {
case PNG = "png"
case JPEG = "jpeg"
}
public class ImageManager {
//MARK: Properties
let fileManager = NSFileManager.defaultManager()
//MARK: Inti
public init(){
}
public func writeImageToFile(fileName: String, fileExtension: ImageType, imageToWrite: UIImage, completion: (fileURL: NSURL?) -> Void){
let file = fileName + "Image." + fileExtension.rawValue
let subFolder = fileName + "Image"
var imageData: NSData!
switch fileExtension {
case .PNG:
guard let data = UIImagePNGRepresentation(imageToWrite) else {
completion(fileURL: nil)
return
}
imageData = data
case .JPEG:
guard let data = UIImageJPEGRepresentation(imageToWrite, 0.8) else {
completion(fileURL: nil)
return
}
imageData = data
}
var documentsURL: NSURL!
do {
documentsURL = try self.fileManager.URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)
}catch {
completion(fileURL: nil)
return
}
let folderURL = documentsURL.URLByAppendingPathComponent(subFolder)
let fileURL = folderURL.URLByAppendingPathComponent(file)
//if fileURL.checkPromisedItemIsReachableAndReturnError(nil) == true {
do {
try self.fileManager.createDirectoryAtURL(folderURL, withIntermediateDirectories: true, attributes: nil)
}catch{
completion(fileURL: nil)
return
}
do {
try imageData.writeToURL(fileURL, options: NSDataWritingOptions.AtomicWrite)
completion(fileURL: fileURL)
}catch {
completion(fileURL: nil)
}
// }else{
// completion(fileURL: nil)
//}
}
public func getImageFromFile(fileName: String, fileExtension: ImageType, completion:(theImage: UIImage?) -> Void) {
let file = fileName + "Image." + fileExtension.rawValue
let subFolder = fileName + "Image"
var documentsURL: NSURL!
do {
documentsURL = try self.fileManager.URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)
}catch {
completion(theImage: nil)
return
}
let folderURL = documentsURL.URLByAppendingPathComponent(subFolder)
let fileURL = folderURL.URLByAppendingPathComponent(file)
guard let imageData = NSData(contentsOfURL: fileURL) else {
completion(theImage: nil)
return
}
guard let image = UIImage(data: imageData) else {
completion(theImage: nil)
return
}
completion(theImage: image)
}
public func getImageDataFromFile(fileName: String, fileExtension: ImageType) -> NSData?{
let file = fileName + "Image." + fileExtension.rawValue
let subFolder = fileName + "Image"
var documentsURL: NSURL!
do {
documentsURL = try self.fileManager.URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)
}catch {
return nil
}
let folderURL = documentsURL.URLByAppendingPathComponent(subFolder)
let fileURL = folderURL.URLByAppendingPathComponent(file)
guard let imageData = NSData(contentsOfURL: fileURL) else {
return nil
}
return imageData
}
public func generateFolderForDownload(fileName: String, fileExtension: String) -> NSURL? {
let file = fileName + "Image." + fileExtension
let subFolder = fileName + "Image"
var documentsURL: NSURL!
do {
documentsURL = try self.fileManager.URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)
}catch {
return nil
}
let folderURL = documentsURL.URLByAppendingPathComponent(subFolder)
let fileURL = folderURL.URLByAppendingPathComponent(file)
return fileURL
}
public func removeImageAtURL(fileName: String, fileExtension: String, completion: (didComplete: Bool) -> Void) {
let file = fileName + "Image." + fileExtension
let subFolder = fileName + "Image"
var documentsURL: NSURL!
do {
documentsURL = try self.fileManager.URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false)
}catch {
completion(didComplete: false)
return
}
let folderURL = documentsURL.URLByAppendingPathComponent(subFolder)
let fileURL = folderURL.URLByAppendingPathComponent(file)
if fileURL.checkPromisedItemIsReachableAndReturnError(nil) == true {
do {
try self.fileManager.removeItemAtURL(fileURL)
}catch{
completion(didComplete: false)
return
}
}else{
completion(didComplete: false)
}
}
//MARK: End Class
}
| mit |
acumen1005/iSwfit | ACSearchViewController/ACSearchViewControllerTests/ACSearchViewControllerTests.swift | 1 | 1023 | //
// ACSearchViewControllerTests.swift
// ACSearchViewControllerTests
//
// Created by acumen on 16/11/30.
// Copyright © 2016年 acumen. All rights reserved.
//
import XCTest
@testable import ACSearchViewController
class ACSearchViewControllerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
omise/omise-ios | OmiseSDK/Source.swift | 1 | 4242 | import Foundation
/// Represents an Omise Source object
public struct Source: CreatableObject {
public typealias CreateParameter = CreateSourceParameter
public static let postURL: URL = Configuration.default.environment.sourceURL
public let object: String
/// Omise Source ID
public let id: String
/// The payment information of this source describes how the payment is processed
public let paymentInformation: PaymentInformation
/// Processing Flow of this source
/// - SeeAlso: Flow
public let flow: Flow
/// Payment amount of this Source
public let amount: Int64
/// Payment currency of this Source
public let currency: Currency
enum CodingKeys: String, CodingKey {
case object
case id
case flow
case currency
case amount
case platformType = "platform_type"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
paymentInformation = try PaymentInformation(from: decoder)
object = try container.decode(String.self, forKey: .object)
id = try container.decode(String.self, forKey: .id)
flow = try container.decode(Flow.self, forKey: .flow)
currency = try container.decode(Currency.self, forKey: .currency)
amount = try container.decode(Int64.self, forKey: .amount)
}
}
/// Parameter for creating a new `Source`
/// - SeeAlso: Source
public struct CreateSourceParameter: Encodable {
/// The payment information that is used to create a new Source
public let paymentInformation: PaymentInformation
/// The amount of the creating Source
public let amount: Int64
/// The currench of the creating Source
public let currency: Currency
private let platformType: String
private enum CodingKeys: String, CodingKey {
case amount
case currency
case platformType = "platform_type"
}
/// Create a new `Create Source Parameter` that will be used to create a new Source
///
/// - Parameters:
/// - paymentInformation: The payment informaiton of the creating Source
/// - amount: The amount of the creating Source
/// - currency: The currency of the creating Source
public init(paymentInformation: PaymentInformation, amount: Int64, currency: Currency) {
self.paymentInformation = paymentInformation
self.amount = amount
self.currency = currency
self.platformType = "IOS"
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(amount, forKey: .amount)
try container.encode(currency, forKey: .currency)
try paymentInformation.encode(to: encoder)
try container.encode(platformType, forKey: .platformType)
}
}
/// The processing flow of a Source
///
/// - redirect: The customer need to be redirected to another URL in order to process the source
/// - offline: The customer need to do something in offline in order to process the source
/// - other: Other processing flow
public enum Flow: RawRepresentable, Decodable, Equatable {
case redirect
case offline
case appRedirect
case other(String)
public typealias RawValue = String
public var rawValue: String {
switch self {
case .offline:
return "offline"
case .redirect:
return "redirect"
case .appRedirect:
return "app_redirect"
case .other(let value):
return value
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let flow = try container.decode(String.self)
self.init(rawValue: flow)! // swiftlint:disable:this force_unwrapping
}
public init?(rawValue: String) {
switch rawValue {
case "redirect":
self = .redirect
case "offline":
self = .offline
case "app_redirect":
self = .appRedirect
default:
self = .other(rawValue)
}
}
}
| mit |
Constructor-io/constructorio-client-swift | AutocompleteClientTests/FW/UI/ViewModel/AutocompleteResultTests.swift | 1 | 1420 | //
// AutocompleteResultTests.swift
// AutocompleteClientTests
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import XCTest
import ConstructorAutocomplete
class AutocompleteResultTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testIsAfter_ifCorrectTimestampsArePassed() {
let query = CIOAutocompleteQuery(query: "")
let earlyResult = AutocompleteResult(query: query, timestamp: 10)
let lateResult = AutocompleteResult(query: query, timestamp: 20)
XCTAssertTrue(lateResult.isInitiatedAfter(result: earlyResult), "isAfter should return true if earlier initiated result is passed as a parameter")
}
func testIsAfter_ifIncorrectTimestampsArePassed() {
let query = CIOAutocompleteQuery(query: "")
let earlyResult = AutocompleteResult(query: query, timestamp: 20)
let lateResult = AutocompleteResult(query: query, timestamp: 10)
XCTAssertFalse(lateResult.isInitiatedAfter(result: earlyResult), "isAfter should return false if later initiated result is passed as a parameter")
}
}
| mit |
LYM-mg/MGDYZB | MGDYZB简单封装版/MGDYZB/Class/Home/ViewModel/DetailGameViewModel.swift | 1 | 784 | //
// DetailGameViewModel.swift
// MGDYZB
//
// Created by i-Techsys.com on 17/4/8.
// Copyright © 2017年 ming. All rights reserved.
//
import UIKit
class DetailGameViewModel: BaseViewModel {
var tag_id: String = "1"
lazy var offset: NSInteger = 0
// http://capi.douyucdn.cn/api/v1/live/1?limit=20&client_sys=ios&offset=0
// http://capi.douyucdn.cn/api/v1/live/2?limit=20&client_sys=ios&offset=0
func loadDetailGameData(_ finishedCallback: @escaping () -> ()) {
let urlStr = "http://capi.douyucdn.cn/api/v1/live/\(tag_id)"
let parameters: [String: Any] = ["limit": 20,"client_sys": "ios","offset": offset]
loadAnchorData(isGroup: false, urlString: urlStr, parameters: parameters, finishedCallback: finishedCallback)
}
}
| mit |
kuruvilla6970/Zoot | Example/ZootExample/AppDelegate.swift | 1 | 2483 | //
// AppDelegate.swift
// ZootExample
//
// Created by Angelo Di Paolo on 5/11/15.
// Copyright (c) 2015 TheHolyGrail. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let viewController = ViewController(nibName: "ViewController", bundle: nil)
let navController = UINavigationController(rootViewController: viewController)
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = navController
window?.makeKeyAndVisible()
// Override point for customization after application launch.
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:.
}
}
| mit |
Daniel1of1/Venice | Sources/Venice/Poll/Poll.swift | 3 | 794 | import CLibvenice
public enum PollError : Error {
case timeout
case failure
}
public struct PollEvent : OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let read = PollEvent(rawValue: Int(FDW_IN))
public static let write = PollEvent(rawValue: Int(FDW_OUT))
}
/// Polls file descriptor for events
public func poll(_ fileDescriptor: FileDescriptor, events: PollEvent, deadline: Double) throws -> PollEvent {
let event = mill_fdwait(fileDescriptor, Int32(events.rawValue), deadline.int64milliseconds, "pollFileDescriptor")
if event == 0 {
throw PollError.timeout
}
if event == FDW_ERR {
throw PollError.failure
}
return PollEvent(rawValue: Int(event))
}
| mit |
benlangmuir/swift | test/Serialization/Inputs/private_import_other_2.swift | 34 | 150 | private struct Base {
private func member() {}
private func bar() {}
}
private struct Other {
}
extension Value {
fileprivate func foo() {}
}
| apache-2.0 |
PureSwift/Cacao | Sources/Cacao/UIButton.swift | 1 | 1020 | //
// Button.swift
// Cacao
//
// Created by Alsey Coleman Miller on 5/28/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
import struct Foundation.CGFloat
import struct Foundation.CGPoint
import struct Foundation.CGSize
import struct Foundation.CGRect
import Silica
public final class UIButton: UIControl {
// MARK: - Methods
public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
guard isHidden == false,
alpha > 0,
isUserInteractionEnabled,
self.point(inside: point, with: event)
else { return nil }
// swallows touches intended for subviews
return self
}
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
sendActions(for: .touchDown)
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
sendActions(for: .touchUpInside)
}
}
| mit |
benlangmuir/swift | test/Interop/Cxx/templates/Inputs/SwiftClassInstantiationModule.swift | 11 | 293 | import ClassTemplateForSwiftModule
public func makeWrappedMagicNumber() -> MagicWrapper<IntWrapper> {
let t = IntWrapper(value: 42)
return MagicWrapper<IntWrapper>(t: t)
}
public func readWrappedMagicNumber(_ i: inout MagicWrapper<IntWrapper>) -> CInt {
return i.getValuePlusArg(13)
}
| apache-2.0 |
jngd/advanced-ios10-training | T15E01/T15E01/ViewController.swift | 1 | 6383 | //
// ViewController.swift
// T15E01
//
// Created by jngd on 22/03/2017.
// Copyright © 2017 jngd. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDelegate,
UICollectionViewDataSource{
@available(iOS 2.0, *)
public func numberOfComponents(in pickerView: UIPickerView) -> Int {return 0}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{return 0}
@IBOutlet weak var collectionView: UICollectionView!
var cells: Array<Any> = []
let container = FileManager.default.url(forUbiquityContainerIdentifier: nil)
var metadataQuery: NSMetadataQuery = NSMetadataQuery()
@IBAction func ereasePhoto(_ sender: Any) {
removeImagesFromICloud()
}
@IBAction func choosePhoto(_ sender: Any) {
print("choose photo")
let action = UIAlertController(title: "Photos",
message: "From where you want your photos?",
preferredStyle: .actionSheet)
action.addAction(UIAlertAction(title: "Camera", style: .default,
handler: { (action) -> Void in
print("Choose camera")
self.capturePhotos(camara: true)
}))
action.addAction(UIAlertAction(title: "Gallery", style: .default,
handler: { (action) -> Void in
print("Choose gallery")
self.capturePhotos(camara: false)
}))
action.popoverPresentationController?.sourceView = self.view
self.present(action, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
loadImagesFromICloud()
}
func capturePhotos(camara: Bool) {
let picker = UIImagePickerController()
picker.delegate = self
if (camara == true){
picker.sourceType = .camera
}else{
picker.sourceType = .photoLibrary
}
picker.allowsEditing = false
self.present(picker, animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
if let fullImage = info[UIImagePickerControllerOriginalImage] as?
UIImage {
self.savePhotoICloud(imagen: fullImage)
} else{
print("Something went wrong")
}
self.dismiss(animated: true, completion: nil)
}
func savePhotoICloud (imagen: UIImage){
let fecha = Date()
let df = DateFormatter()
df.dateFormat = "dd_MM_yy_hh_mm_ss"
let photoName = String(format: "PHOTO_%@", df.string(from: fecha)) +
".jpg"
if (container != nil){
let fileURLiCloud =
container?.appendingPathComponent("Documents").appendingPathComponent(photoName)
let photo = DocumentPhoto(fileURL: fileURLiCloud!)
photo.image = imagen
photo.save(to: fileURLiCloud!, for: .forCreating, completionHandler:
{ (sucess) -> Void in
print ("Image saved")
self.cells.append(imagen)
self.collectionView.reloadData()
})
}
}
func loadImagesFromICloud (){
if (container != nil){
metadataQuery = NSMetadataQuery()
metadataQuery.searchScopes =
[NSMetadataQueryUbiquitousDocumentsScope]
let predicate = NSPredicate(format: "%K like 'PHOTO*'",
NSMetadataItemFSNameKey)
metadataQuery.predicate = predicate
NotificationCenter.default.addObserver(self, selector:
#selector(queryFinished), name:
NSNotification.Name.NSMetadataQueryDidFinishGathering, object:
metadataQuery)
metadataQuery.start()
}
}
func removeImagesFromICloud (){
if (container != nil){
metadataQuery = NSMetadataQuery()
metadataQuery.searchScopes =
[NSMetadataQueryUbiquitousDocumentsScope]
let predicate = NSPredicate(format: "%K like 'PHOTO*'",
NSMetadataItemFSNameKey)
metadataQuery.predicate = predicate
NotificationCenter.default.addObserver(self, selector:
#selector(removeQueryFinished), name:
NSNotification.Name.NSMetadataQueryDidFinishGathering, object:
metadataQuery)
metadataQuery.start()
}
}
func removeQueryFinished(notification: NSNotification) {
let mq = notification.object as! NSMetadataQuery
mq.disableUpdates()
mq.stop()
cells.removeAll()
for i in 0 ..< mq.resultCount {
let result = mq.result(at: i) as! NSMetadataItem
let url = result.value(forAttribute: NSMetadataItemURLKey) as! URL
// Remove all items in icloud
do {
try FileManager.default.removeItem(at: url)
} catch {
print("error: \(error.localizedDescription)")
}
}
}
func queryFinished(notification: NSNotification) {
let mq = notification.object as! NSMetadataQuery
mq.disableUpdates()
mq.stop()
cells.removeAll()
for i in 0 ..< mq.resultCount {
let result = mq.result(at: i) as! NSMetadataItem
let name = result.value(forAttribute: NSMetadataItemFSNameKey) as! String
let url = result.value(forAttribute: NSMetadataItemURLKey) as! URL
let document: DocumentPhoto! = DocumentPhoto(fileURL: url)
document?.open(completionHandler: {(success) -> Void in
if (success) {
print("Image loaded with name \(name)")
self.cells.append(document.image)
self.collectionView.reloadData()
}
})
}
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cells.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath as IndexPath) as! ImageCollectionViewCell
cell.image.image = self.cells[indexPath.row] as! UIImage
return cell
}
}
class DocumentPhoto: UIDocument {
var image: UIImage!
override func load(fromContents contents: Any, ofType typeName: String?)
throws {
let data = Data(bytes: (contents as AnyObject).bytes, count:
(contents as AnyObject).length)
self.image = UIImage(data: data)
}
override func contents(forType typeName: String) throws -> Any {
return UIImageJPEGRepresentation(self.image, 1.0)!
}
}
| apache-2.0 |
RedMadRobot/DAO | Example/RealmDAOTests/RealmDAOBookTests.swift | 1 | 1552 | //
// RealmDAOBookTests.swift
// DAO
//
// Created by Ivan Vavilov on 5/17/17.
// Copyright © 2017 RedMadRobot LLC. All rights reserved.
//
import XCTest
import DAO
@testable import DAO_Example
final class RealmDAOBookTests: XCTestCase {
private var dao: RealmDAO<Book, DBBook>!
override func setUp() {
super.setUp()
dao = RealmDAO(RLMBookTranslator())
}
override func tearDown() {
super.tearDown()
try! dao.erase()
dao = nil
}
func testPersist() {
let book = Book(
entityId: "book1",
name: "Swift",
authors: ["Chris Lattner"],
dates: [Date(timeIntervalSince1970: 1000000)],
pages: [100, 200],
attachments: [Data()]
)
XCTAssertNoThrow(try dao.persist(book), "Persist is failed")
XCTAssertEqual(book, dao.read(book.entityId), "Persist is failed")
XCTAssertFalse((dao.read(book.entityId)?.authors.isEmpty) == true, "Persist is failed")
XCTAssertEqual(dao.read(book.entityId)?.authors.first, "Chris Lattner", "Persist is failed")
XCTAssertFalse((dao.read(book.entityId)?.dates.isEmpty) == true, "Persist is failed")
XCTAssertFalse((dao.read(book.entityId)?.pages.isEmpty) == true, "Persist is failed")
XCTAssertEqual(dao.read(book.entityId)?.pages.count, 2, "Persist is failed")
XCTAssertFalse((dao.read(book.entityId)?.attachments.isEmpty) == true, "Persist is failed")
}
}
| mit |
Wakup/Wakup-iOS-SDK | Wakup/WakupAppearance.swift | 1 | 5654 | //
// WakupAppearance.swift
// Wakup
//
// Created by Guillermo Gutiérrez Doral on 14/12/17.
// Copyright © 2017 Yellow Pineapple. All rights reserved.
//
import Foundation
import UIKit
@objc
public class WakupAppearance: NSObject {
@objc public func setTint(mainColor: UIColor, secondaryColor: UIColor? = nil, contrastColor: UIColor? = nil) {
let isLight = mainColor.isLight()
let contrastColor = contrastColor ?? (isLight ? mainColor.darker(by: 80) : mainColor.lighter(by: 80))
let secondaryColor = secondaryColor ?? (isLight ? mainColor.darker(by: 30) : mainColor.lighter(by: 30))
let secondaryContrastColor = secondaryColor.isLight() ? secondaryColor.darker(by: 80) : secondaryColor.lighter(by: 80)
setNavigationBarTint(navBarColor: mainColor, tintColor: contrastColor)
setCategoryFilterTint(backgroundColor: contrastColor, buttonColor: mainColor)
setDiscountTagTint(secondaryColor, labelColor: secondaryContrastColor)
setQuickActionsTint(mainColor)
setOfferActionButtonsTint(secondaryColor)
setTagListTint(mainColor)
setSearchTint(mainColor)
}
@objc public func setNavigationBarTint(navBarColor: UIColor, tintColor: UIColor) {
UINavigationBar.appearance().barTintColor = navBarColor
UINavigationBar.appearance().tintColor = tintColor
UINavigationBar.appearance().titleTextAttributes = [
NSAttributedString.Key.foregroundColor: tintColor
]
NavBarIconView.appearance().iconColor = tintColor
}
@objc public func setCategoryFilterTint(backgroundColor: UIColor, buttonColor: UIColor, highlightedButtonColor: UIColor = .white) {
CategoryFilterButton.appearance().setTitleColor(buttonColor, for: [])
CategoryFilterButton.appearance().setTitleColor(highlightedButtonColor, for: .selected)
CategoryFilterView.appearance().backgroundColor = backgroundColor
CompanyFilterIndicatorView.appearance().iconColor = backgroundColor
}
@objc public func setOfferViewsTint(titleColor: UIColor = .black, descriptionColor: UIColor = UIColor(white: 0.33, alpha: 1), detailsColor: UIColor = UIColor(white:0.56, alpha:1)) {
CouponCollectionViewCell.appearance().storeNameTextColor = titleColor
CouponCollectionViewCell.appearance().descriptionTextColor = descriptionColor
CouponCollectionViewCell.appearance().distanceTextColor = detailsColor
CouponCollectionViewCell.appearance().distanceIconColor = detailsColor
CouponCollectionViewCell.appearance().expirationTextColor = detailsColor
CouponCollectionViewCell.appearance().expirationIconColor = detailsColor
}
@objc public func setDiscountTagTint(_ tintColor: UIColor, labelColor: UIColor = .white) {
DiscountTagView.appearance().backgroundColor = tintColor
DiscountTagView.appearance().labelColor = labelColor
}
@objc public func setQuickActionsTint(_ mainColor: UIColor, secondaryColor: UIColor = .white) {
ContextItemView.appearance().backgroundColor = mainColor
ContextItemView.appearance().highlightedBackgroundColor = mainColor.lighter(by: 20)
ContextItemView.appearance().iconColor = secondaryColor
ContextItemView.appearance().highlightedIconColor = secondaryColor
ContextItemView.appearance().borderColor = secondaryColor
}
@objc public func setOfferDetailsTint(titleColor: UIColor = .black, descriptionColor: UIColor = UIColor(white: 0.33, alpha: 1), detailsColor: UIColor = UIColor(white:0.56, alpha:1)) {
CouponDetailHeaderView.appearance().companyNameTextColor = titleColor
CouponDetailHeaderView.appearance().storeAddressTextColor = detailsColor
CouponDetailHeaderView.appearance().storeDistanceTextColor = detailsColor
CouponDetailHeaderView.appearance().storeDistanceIconColor = detailsColor
CouponDetailHeaderView.appearance().couponNameTextColor = descriptionColor
CouponDetailHeaderView.appearance().couponDescriptionTextColor = detailsColor
CouponDetailHeaderView.appearance().expirationTextColor = detailsColor
CouponDetailHeaderView.appearance().expirationIconColor = detailsColor
CouponDetailHeaderView.appearance().companyDisclosureColor = detailsColor
CouponDetailHeaderView.appearance().couponDescriptionDisclosureColor = detailsColor
CouponDetailHeaderView.appearance().companyNameTextColor = detailsColor
}
@objc public func setOfferActionButtonsTint(_ actionColor: UIColor) {
CouponActionButton.appearance().iconColor = actionColor
CouponActionButton.appearance().highlightedBackgroundColor = actionColor
CouponActionButton.appearance().setTitleColor(actionColor, for: [])
CouponActionButton.appearance().normalBorderColor = actionColor
}
@objc public func setTagListTint(_ tintColor: UIColor) {
WakupTagListView.appearance().tagBackgroundColor = tintColor
WakupTagListView.appearance().tagHighlightedBackgroundColor = tintColor.darker()
WakupTagListView.appearance().wakupBorderColor = tintColor.darker()
}
@objc public func setSearchTint(_ tintColor: UIColor) {
SearchFilterButton.appearance().iconColor = tintColor
SearchFilterButton.appearance().highlightedBackgroundColor = tintColor
SearchFilterButton.appearance().setTitleColor(tintColor, for: [])
SearchFilterButton.appearance().normalBorderColor = tintColor
SearchResultCell.appearance().iconColor = tintColor
}
}
| mit |
KrishMunot/swift | test/IDE/dump_swift_lookup_tables.swift | 1 | 2819 | // RUN: %target-swift-ide-test -dump-importer-lookup-table -source-filename %s -import-objc-header %S/Inputs/swift_name.h -I %S/Inputs/custom-modules > %t.log 2>&1
// RUN: FileCheck %s < %t.log
// REQUIRES: objc_interop
import ImportAsMember
// CHECK-LABEL: <<ImportAsMember lookup table>>
// CHECK-NEXT: Base name -> entry mappings:
// CHECK: Struct1:
// CHECK-NEXT: TU: IAMStruct1
// CHECK: init:
// CHECK-NEXT: IAMStruct1: IAMStruct1CreateSimple
// CHECK: radius:
// CHECK-NEXT: IAMStruct1: IAMStruct1GetRadius, IAMStruct1SetRadius
// CHECK: Globals-as-members mapping:
// CHECK-NEXT: IAMStruct1: IAMStruct1GlobalVar, IAMStruct1CreateSimple, IAMStruct1Invert, IAMStruct1InvertInPlace, IAMStruct1Rotate, IAMStruct1Scale, IAMStruct1GetRadius, IAMStruct1SetRadius, IAMStruct1GetAltitude, IAMStruct1SetAltitude, IAMStruct1GetMagnitude, IAMStruct1StaticMethod, IAMStruct1StaticGetProperty, IAMStruct1StaticSetProperty, IAMStruct1StaticGetOnlyProperty, IAMStruct1SelfComesLast, IAMStruct1SelfComesThird, IAMStruct1StaticVar1, IAMStruct1StaticVar2, IAMStruct1CreateFloat, IAMStruct1GetZeroStruct1
// CHECK-LABEL: <<Bridging header lookup table>>
// CHECK-NEXT: Base name -> entry mappings:
// CHECK-NEXT: Bar:
// CHECK-NEXT: TU: SNFoo
// CHECK-NEXT: MyInt:
// CHECK-NEXT: TU: SNIntegerType
// CHECK-NEXT: Point:
// CHECK-NEXT: TU: SNPoint
// CHECK-NEXT: Rouge:
// CHECK-NEXT: SNColorChoice: SNColorRed
// CHECK-NEXT: SNColorChoice:
// CHECK-NEXT: TU: SNColorChoice, SNColorChoice
// CHECK-NEXT: SomeStruct:
// CHECK-NEXT: TU: SNSomeStruct
// CHECK-NEXT: __SNTransposeInPlace:
// CHECK-NEXT: TU: SNTransposeInPlace
// CHECK-NEXT: __swift:
// CHECK-NEXT: TU: __swift
// CHECK-NEXT: adding:
// CHECK-NEXT: SNSomeStruct: SNAdding
// CHECK-NEXT: blue:
// CHECK-NEXT: SNColorChoice: SNColorBlue
// CHECK-NEXT: defaultValue:
// CHECK-NEXT: SNSomeStruct: SNSomeStructGetDefault, SNSomeStructSetDefault
// CHECK-NEXT: defaultX:
// CHECK-NEXT: SNSomeStruct: DefaultXValue
// CHECK-NEXT: foo:
// CHECK-NEXT: SNSomeStruct: SNSomeStructGetFoo, SNSomeStructSetFoo
// CHECK-NEXT: green:
// CHECK-NEXT: SNColorChoice: SNColorGreen
// CHECK-NEXT: init:
// CHECK-NEXT: SNSomeStruct: SNCreate
// CHECK-NEXT: makeSomeStruct:
// CHECK-NEXT: TU: SNMakeSomeStruct, SNMakeSomeStructForX
// CHECK-NEXT: x:
// CHECK-NEXT: SNSomeStruct: X
// CHECK-NEXT: SNPoint: x
// CHECK-NEXT: y:
// CHECK-NEXT: SNPoint: y
// CHECK-NEXT: z:
// CHECK-NEXT: SNPoint: z
// CHECK-NEXT: Globals-as-members mapping:
// CHECK-NEXT: SNSomeStruct: DefaultXValue, SNAdding, SNCreate, SNSomeStructGetDefault, SNSomeStructSetDefault, SNSomeStructGetFoo, SNSomeStructSetFoo
| apache-2.0 |
Restofire/Restofire | Sources/Configuration/Protocols/Syncable.swift | 1 | 3429 | //
// Syncable.swift
// Restofire
//
// Created by RahulKatariya on 31/12/18.
// Copyright © 2018 Restofire. All rights reserved.
//
import Foundation
public protocol Syncable {
associatedtype Request: Requestable
var request: Request { get }
func shouldSync() throws -> Bool
func insert(model: Request.Response, completion: @escaping () throws -> Void) throws
}
extension Syncable {
public func shouldSync() throws -> Bool {
return true
}
public func sync(
parameters: Any? = nil,
downloadProgressHandler: ((Progress) -> Void, queue: DispatchQueue?)? = nil,
completionQueue: DispatchQueue = .main,
immediate: Bool = false,
completion: ((Error?) -> Void)? = nil
) -> Cancellable? {
let parametersType = ParametersType<EmptyCodable>.any(parameters)
return sync(
parametersType: parametersType,
downloadProgressHandler: downloadProgressHandler,
completionQueue: completionQueue,
immediate: immediate,
completion: completion
)
}
public func sync<T: Encodable>(
parameters: T,
downloadProgressHandler: ((Progress) -> Void, queue: DispatchQueue?)? = nil,
completionQueue: DispatchQueue = .main,
immediate: Bool = false,
completion: ((Error?) -> Void)? = nil
) -> Cancellable? {
let parametersType = ParametersType<T>.encodable(parameters)
return sync(
parametersType: parametersType,
downloadProgressHandler: downloadProgressHandler,
completionQueue: completionQueue,
immediate: immediate,
completion: completion
)
}
public func sync<T: Encodable>(
parametersType: ParametersType<T>,
downloadProgressHandler: ((Progress) -> Void, queue: DispatchQueue?)? = nil,
completionQueue: DispatchQueue = .main,
immediate: Bool = false,
completion: ((Error?) -> Void)? = nil
) -> Cancellable? {
do {
let flag = try self.shouldSync()
guard flag else {
completionQueue.async { completion?(nil) }
return nil
}
let completionHandler = { (response: DataResponse<Self.Request.Response>) in
switch response.result {
case .success(let value):
do {
try self.insert(model: value) {
completionQueue.async { completion?(nil) }
}
} catch {
completionQueue.async { completion?(error) }
}
case .failure(let error):
completionQueue.async { completion?(error) }
}
}
let operation: RequestOperation<Request> = try self.request.operation(
parametersType: parametersType,
downloadProgressHandler: downloadProgressHandler,
completionQueue: completionQueue,
completionHandler: completionHandler
)
if immediate { operation.start() } else {
request.requestQueue.addOperation(operation)
}
return operation
} catch {
completionQueue.async { completion?(error) }
return nil
}
}
}
| mit |
sqlpro/swift03-basic | AutoResizing-Practice/AutoResizing-Practice/ViewController.swift | 1 | 518 | //
// ViewController.swift
// AutoResizing-Practice
//
// Created by prologue on 2016. 8. 24..
// Copyright © 2016년 SQLPRO. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 |
caicai0/ios_demo | load/thirdpart/SwiftSoup/ParseSettings.swift | 3 | 1550 | //
// ParseSettings.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 14/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class ParseSettings {
/**
* HTML default settings: both tag and attribute names are lower-cased during parsing.
*/
public static let htmlDefault: ParseSettings = ParseSettings(false, false)
/**
* Preserve both tag and attribute case.
*/
public static let preserveCase: ParseSettings = ParseSettings(true, true)
private let preserveTagCase: Bool
private let preserveAttributeCase: Bool
/**
* Define parse settings.
* @param tag preserve tag case?
* @param attribute preserve attribute name case?
*/
public init(_ tag: Bool, _ attribute: Bool) {
preserveTagCase = tag
preserveAttributeCase = attribute
}
open func normalizeTag(_ name: String) -> String {
var name = name.trim()
if (!preserveTagCase) {
name = name.lowercased()
}
return name
}
open func normalizeAttribute(_ name: String) -> String {
var name = name.trim()
if (!preserveAttributeCase) {
name = name.lowercased()
}
return name
}
open func normalizeAttributes(_ attributes: Attributes)throws ->Attributes {
if (!preserveAttributeCase) {
for attr in attributes {
try attr.setKey(key: attr.getKey().lowercased())
}
}
return attributes
}
}
| mit |
hipposan/LemonDeer | LemonDeer/Classes/VideoDownloader.swift | 1 | 6101 | //
// VideoDownloader.swift
// WindmillComic
//
// Created by Ziyi Zhang on 09/06/2017.
// Copyright © 2017 Ziyideas. All rights reserved.
//
import Foundation
public enum Status {
case started
case paused
case canceled
case finished
}
protocol VideoDownloaderDelegate {
func videoDownloadSucceeded(by downloader: VideoDownloader)
func videoDownloadFailed(by downloader: VideoDownloader)
func update(_ progress: Float)
}
open class VideoDownloader {
public var downloadStatus: Status = .paused
var m3u8Data: String = ""
var tsPlaylist = M3u8Playlist()
var segmentDownloaders = [SegmentDownloader]()
var tsFilesIndex = 0
var neededDownloadTsFilesCount = 0
var downloadURLs = [String]()
var downloadingProgress: Float {
let finishedDownloadFilesCount = segmentDownloaders.filter({ $0.finishedDownload == true }).count
let fraction = Float(finishedDownloadFilesCount) / Float(neededDownloadTsFilesCount)
let roundedValue = round(fraction * 100) / 100
return roundedValue
}
fileprivate var startDownloadIndex = 2
var delegate: VideoDownloaderDelegate?
open func startDownload() {
checkOrCreatedM3u8Directory()
var newSegmentArray = [M3u8TsSegmentModel]()
let notInDownloadList = tsPlaylist.tsSegmentArray.filter { !downloadURLs.contains($0.locationURL) }
neededDownloadTsFilesCount = tsPlaylist.length
for i in 0 ..< notInDownloadList.count {
let fileName = "\(tsFilesIndex).ts"
let segmentDownloader = SegmentDownloader(with: notInDownloadList[i].locationURL,
filePath: tsPlaylist.identifier,
fileName: fileName,
duration: notInDownloadList[i].duration,
index: tsFilesIndex)
segmentDownloader.delegate = self
segmentDownloaders.append(segmentDownloader)
downloadURLs.append(notInDownloadList[i].locationURL)
var segmentModel = M3u8TsSegmentModel()
segmentModel.duration = segmentDownloaders[i].duration
segmentModel.locationURL = segmentDownloaders[i].fileName
segmentModel.index = segmentDownloaders[i].index
newSegmentArray.append(segmentModel)
tsPlaylist.tsSegmentArray = newSegmentArray
tsFilesIndex += 1
}
segmentDownloaders[0].startDownload()
segmentDownloaders[1].startDownload()
segmentDownloaders[2].startDownload()
downloadStatus = .started
}
func checkDownloadQueue() {
}
func updateLocalM3U8file() {
checkOrCreatedM3u8Directory()
let filePath = getDocumentsDirectory().appendingPathComponent("Downloads").appendingPathComponent(tsPlaylist.identifier).appendingPathComponent("\(tsPlaylist.identifier).m3u8")
var header = "#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:15\n"
var content = ""
for i in 0 ..< tsPlaylist.tsSegmentArray.count {
let segmentModel = tsPlaylist.tsSegmentArray[i]
let length = "#EXTINF:\(segmentModel.duration),\n"
let fileName = "http://127.0.0.1:8080/\(segmentModel.index).ts\n"
content += (length + fileName)
}
header.append(content)
header.append("#EXT-X-ENDLIST\n")
let writeData: Data = header.data(using: .utf8)!
try! writeData.write(to: filePath)
}
private func checkOrCreatedM3u8Directory() {
let filePath = getDocumentsDirectory().appendingPathComponent("Downloads").appendingPathComponent(tsPlaylist.identifier)
if !FileManager.default.fileExists(atPath: filePath.path) {
try! FileManager.default.createDirectory(at: filePath, withIntermediateDirectories: true, attributes: nil)
}
}
open func deleteAllDownloadedContents() {
let filePath = getDocumentsDirectory().appendingPathComponent("Downloads").path
if FileManager.default.fileExists(atPath: filePath) {
try! FileManager.default.removeItem(atPath: filePath)
} else {
print("File has already been deleted.")
}
}
open func deleteDownloadedContents(with name: String) {
let filePath = getDocumentsDirectory().appendingPathComponent("Downloads").appendingPathComponent(name).path
if FileManager.default.fileExists(atPath: filePath) {
try! FileManager.default.removeItem(atPath: filePath)
} else {
print("Could not find directory with name: \(name)")
}
}
open func pauseDownloadSegment() {
_ = segmentDownloaders.map { $0.pauseDownload() }
downloadStatus = .paused
}
open func cancelDownloadSegment() {
_ = segmentDownloaders.map { $0.cancelDownload() }
downloadStatus = .canceled
}
open func resumeDownloadSegment() {
_ = segmentDownloaders.map { $0.resumeDownload() }
downloadStatus = .started
}
}
extension VideoDownloader: SegmentDownloaderDelegate {
func segmentDownloadSucceeded(with downloader: SegmentDownloader) {
let finishedDownloadFilesCount = segmentDownloaders.filter({ $0.finishedDownload == true }).count
DispatchQueue.main.async {
self.delegate?.update(self.downloadingProgress)
}
updateLocalM3U8file()
let downloadingFilesCount = segmentDownloaders.filter({ $0.isDownloading == true }).count
if finishedDownloadFilesCount == neededDownloadTsFilesCount {
delegate?.videoDownloadSucceeded(by: self)
downloadStatus = .finished
} else if startDownloadIndex == neededDownloadTsFilesCount - 1 {
if segmentDownloaders[startDownloadIndex].isDownloading == true { return }
}
else if downloadingFilesCount < 3 || finishedDownloadFilesCount != neededDownloadTsFilesCount {
if startDownloadIndex < neededDownloadTsFilesCount - 1 {
startDownloadIndex += 1
}
segmentDownloaders[startDownloadIndex].startDownload()
}
}
func segmentDownloadFailed(with downloader: SegmentDownloader) {
delegate?.videoDownloadFailed(by: self)
}
}
| mit |
RikkiGibson/Corvallis-Bus-iOS | CorvallisBus/View Controllers/BusMapViewController.swift | 1 | 10129 | //
// BusMapViewController.swift
// CorvallisBus
//
// Created by Rikki Gibson on 8/23/15.
// Copyright © 2015 Rikki Gibson. All rights reserved.
//
import Foundation
protocol BusMapViewControllerDelegate : class {
func busMapViewController(_ viewController: BusMapViewController, didSelectStopWithID stopID: Int)
func busMapViewControllerDidClearSelection(_ viewController: BusMapViewController)
}
protocol BusMapViewControllerDataSource : class {
func busStopAnnotations() -> Promise<[Int : BusStopAnnotation], BusError>
}
let CORVALLIS_LOCATION = CLLocation(latitude: 44.56802, longitude: -123.27926)
let DEFAULT_SPAN = MKCoordinateSpan.init(latitudeDelta: 0.01, longitudeDelta: 0.01)
class BusMapViewController : UIViewController, MKMapViewDelegate {
let locationManagerDelegate = PromiseLocationManagerDelegate()
@IBOutlet weak var mapView: MKMapView!
weak var delegate: BusMapViewControllerDelegate?
weak var dataSource: BusMapViewControllerDataSource?
/// Temporary storage for the stop ID to display once the view controller is ready to do so.
private var externalStopID: Int?
private var reloadTimer: Timer?
var viewModel: BusMapViewModel = BusMapViewModel(stops: [:], selectedRoute: nil, selectedStopID: nil)
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.setRegion(MKCoordinateRegion(center: CORVALLIS_LOCATION.coordinate, span: DEFAULT_SPAN), animated: false)
locationManagerDelegate.userLocation { maybeLocation in
// Don't muck with the location if an annotation is selected right now
guard self.mapView.selectedAnnotations.isEmpty else { return }
// Only go to the user's location if they're within about 20 miles of Corvallis
if case .success(let location) = maybeLocation, location.distance(from: CORVALLIS_LOCATION) < 32000 {
let region = MKCoordinateRegion(center: location.coordinate, span: DEFAULT_SPAN)
self.mapView.setRegion(region, animated: false)
}
}
dataSource?.busStopAnnotations().startOnMainThread(populateMap)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(BusMapViewController.reloadAnnotationsIfExpired),
name: UIApplication.didBecomeActiveNotification, object: nil)
reloadTimer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(BusMapViewController.reloadAnnotationsIfExpired), userInfo: nil, repeats: true)
let favoriteStopIDs = UserDefaults.groupUserDefaults().favoriteStopIds
for annotation in viewModel.stops.values {
annotation.isFavorite = favoriteStopIDs.contains(annotation.stop.id)
if let view = mapView.view(for: annotation) {
view.updateWithBusStopAnnotation(annotation,
isSelected: annotation.stop.id == viewModel.selectedStopID,
animated: false)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
reloadTimer?.invalidate()
}
@IBAction func goToUserLocation() {
locationManagerDelegate.userLocation { maybeLocation in
if case .success(let location) = maybeLocation {
let span = self.mapView.region.span
let region = MKCoordinateRegion(center: location.coordinate, span: span)
self.mapView.setRegion(region, animated: true)
} else if case .error(let error) = maybeLocation, let message = error.getMessage() {
self.presentError(message)
}
}
}
var lastReloadedDate = Date()
/// The point of this daily reloading stuff is that when stops become active or inactive
/// over the course of the year (especially when OSU terms start and end) the map will get reloaded.
/// This is not the cleanest solution (relies on the manager getting new static data every day) but it gets the job done.
@objc func reloadAnnotationsIfExpired() {
if !lastReloadedDate.isToday() {
lastReloadedDate = Date()
dataSource?.busStopAnnotations().startOnMainThread(populateMap)
}
}
func populateMap(_ failable: Failable<[Int : BusStopAnnotation], BusError>) {
if case .success(let annotations) = failable {
mapView.removeAnnotations(mapView.annotations.filter{ $0 is BusStopAnnotation })
viewModel.stops = annotations
for annotation in annotations.values {
mapView.addAnnotation(annotation)
}
if let externalStopID = externalStopID {
self.externalStopID = nil
selectStopExternally(externalStopID)
}
} else {
// The request failed. Try again.
dataSource?.busStopAnnotations().startOnMainThread(populateMap)
}
}
func setFavoriteState(_ isFavorite: Bool, forStopID stopID: Int) {
if let annotation = viewModel.stops[stopID] {
annotation.isFavorite = isFavorite
// The annotation view only exists if it's visible
if let view = mapView.view(for: annotation) {
let isSelected = viewModel.selectedStopID == stopID
view.updateWithBusStopAnnotation(annotation, isSelected: isSelected, animated: false)
}
}
}
func selectStopExternally(_ stopID: Int) {
if let annotation = viewModel.stops[stopID] {
// select the annotation that currently exists
let region = MKCoordinateRegion(center: annotation.stop.location.coordinate, span: DEFAULT_SPAN)
mapView.setRegion(region, animated: true)
mapView.selectAnnotation(annotation, animated: true)
} else {
// select this stop once data is populated
externalStopID = stopID
}
}
func clearDisplayedRoute() {
if let polyline = viewModel.selectedRoute?.polyline {
mapView.removeOverlay(polyline)
}
for annotation in viewModel.stops.values {
annotation.isDeemphasized = false
if let view = mapView.view(for: annotation) {
view.updateWithBusStopAnnotation(annotation, isSelected: viewModel.selectedStopID == annotation.stop.id, animated: false)
}
}
viewModel.selectedRoute = nil
}
func displayRoute(_ route: BusRoute) {
guard route.name != viewModel.selectedRoute?.name else {
return
}
if let polyline = viewModel.selectedRoute?.polyline {
mapView.removeOverlay(polyline)
}
viewModel.selectedRoute = route
for (stopID, annotation) in viewModel.stops {
annotation.isDeemphasized = !route.path.contains(stopID)
if let view = mapView.view(for: annotation) {
view.updateWithBusStopAnnotation(annotation, isSelected: viewModel.selectedStopID == annotation.stop.id, animated: false)
}
}
mapView.addOverlay(route.polyline)
}
// MARK: MKMapViewDelegate
let ANNOTATION_VIEW_IDENTIFIER = "MKAnnotationView"
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: ANNOTATION_VIEW_IDENTIFIER) ??
MKAnnotationView(annotation: annotation, reuseIdentifier: ANNOTATION_VIEW_IDENTIFIER)
if let annotation = annotation as? BusStopAnnotation {
let isSelected = viewModel.selectedStopID == annotation.stop.id
annotationView.updateWithBusStopAnnotation(annotation, isSelected: isSelected, animated: false)
}
return annotationView
}
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
if let view = mapView.view(for: mapView.userLocation) {
view.isEnabled = false
}
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let annotation = view.annotation as? BusStopAnnotation else {
return
}
viewModel.selectedStopID = annotation.stop.id
delegate?.busMapViewController(self, didSelectStopWithID: annotation.stop.id)
view.updateWithBusStopAnnotation(annotation, isSelected: true, animated: true)
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
guard let annotation = view.annotation as? BusStopAnnotation else {
return
}
viewModel.selectedStopID = nil
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
if self.mapView.selectedAnnotations.isEmpty {
self.clearDisplayedRoute()
self.delegate?.busMapViewControllerDidClearSelection(self)
}
}
UIView.animate(withDuration: 0.1, animations: {
view.transform = CGAffineTransform(rotationAngle: CGFloat(annotation.stop.bearing))
})
view.updateWithBusStopAnnotation(annotation, isSelected: false, animated: true)
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
guard let polyline = overlay as? MKPolyline, let route = viewModel.selectedRoute else {
return MKOverlayRenderer(overlay: overlay)
}
let renderer = MKPolylineRenderer(polyline: polyline)
renderer.strokeColor = route.color
renderer.lineWidth = 5
return renderer
}
}
| mit |
zmeyc/SQLite.swift | Tests/SQLite/FTS4Tests.swift | 1 | 3883 | import XCTest
import SQLite
class FTS4Tests : XCTestCase {
func test_create_onVirtualTable_withFTS4_compilesCreateVirtualTableExpression() {
XCTAssertEqual(
"CREATE VIRTUAL TABLE \"virtual_table\" USING fts4()",
virtualTable.create(.FTS4())
)
XCTAssertEqual(
"CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(\"string\")",
virtualTable.create(.FTS4(string))
)
XCTAssertEqual(
"CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(tokenize=simple)",
virtualTable.create(.FTS4(tokenize: .Simple))
)
XCTAssertEqual(
"CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(\"string\", tokenize=porter)",
virtualTable.create(.FTS4([string], tokenize: .Porter))
)
XCTAssertEqual(
"CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(tokenize=unicode61 \"removeDiacritics=0\")",
virtualTable.create(.FTS4(tokenize: .Unicode61(removeDiacritics: false)))
)
XCTAssertEqual(
"CREATE VIRTUAL TABLE \"virtual_table\" USING fts4(tokenize=unicode61 \"removeDiacritics=1\" \"tokenchars=.\" \"separators=X\")",
virtualTable.create(.FTS4(tokenize: .Unicode61(removeDiacritics: true, tokenchars: ["."], separators: ["X"])))
)
}
func test_match_onVirtualTableAsExpression_compilesMatchExpression() {
AssertSQL("(\"virtual_table\" MATCH 'string')", virtualTable.match("string") as Expression<Bool>)
AssertSQL("(\"virtual_table\" MATCH \"string\")", virtualTable.match(string) as Expression<Bool>)
AssertSQL("(\"virtual_table\" MATCH \"stringOptional\")", virtualTable.match(stringOptional) as Expression<Bool?>)
}
func test_match_onVirtualTableAsQueryType_compilesMatchExpression() {
AssertSQL("SELECT * FROM \"virtual_table\" WHERE (\"virtual_table\" MATCH 'string')", virtualTable.match("string") as QueryType)
AssertSQL("SELECT * FROM \"virtual_table\" WHERE (\"virtual_table\" MATCH \"string\")", virtualTable.match(string) as QueryType)
AssertSQL("SELECT * FROM \"virtual_table\" WHERE (\"virtual_table\" MATCH \"stringOptional\")", virtualTable.match(stringOptional) as QueryType)
}
}
class FTS4IntegrationTests : SQLiteTestCase {
// func test_registerTokenizer_registersTokenizer() {
// let emails = VirtualTable("emails")
// let subject = Expression<String?>("subject")
// let body = Expression<String?>("body")
//
// let locale = CFLocaleCopyCurrent()
// let tokenizerName = "tokenizer"
// let tokenizer = CFStringTokenizerCreate(nil, "", CFRangeMake(0, 0), UInt(kCFStringTokenizerUnitWord), locale)
// try! db.registerTokenizer(tokenizerName) { string in
// CFStringTokenizerSetString(tokenizer, string, CFRangeMake(0, CFStringGetLength(string)))
// if CFStringTokenizerAdvanceToNextToken(tokenizer) == .none {
// return nil
// }
// let range = CFStringTokenizerGetCurrentTokenRange(tokenizer)
// let input = CFStringCreateWithSubstring(kCFAllocatorDefault, string, range)
// let token = CFStringCreateMutableCopy(nil, range.length, input)
// CFStringLowercase(token, locale)
// CFStringTransform(token, nil, kCFStringTransformStripDiacritics, false)
// return (token as String, string.range(of: input as String)!)
// }
//
// try! db.run(emails.create(.FTS4([subject, body], tokenize: .Custom(tokenizerName))))
// AssertSQL("CREATE VIRTUAL TABLE \"emails\" USING fts4(\"subject\", \"body\", tokenize=\"SQLite.swift\" \"tokenizer\")")
//
// try! db.run(emails.insert(subject <- "Aún más cáfe!"))
// XCTAssertEqual(1, db.scalar(emails.filter(emails.match("aun")).count))
// }
}
| mit |
ImJCabus/UIBezierPath-Superpowers | Demo/BezierPlayground/Demo.swift | 1 | 2228 | //
// Demos.swift
// UIBezierPath+Length
//
// Created by Maximilian Kraus on 15.07.17.
// Copyright © 2017 Maximilian Kraus. All rights reserved.
//
import UIKit
//MARK: - Random numbers
fileprivate extension BinaryInteger {
static func random(min: Self, max: Self) -> Self {
assert(min < max, "min must be smaller than max")
let delta = max - min
return min + Self(arc4random_uniform(UInt32(delta)))
}
}
fileprivate extension FloatingPoint {
static func random(min: Self, max: Self, resolution: Int = 1000) -> Self {
let randomFraction = Self(Int.random(min: 0, max: resolution)) / Self(resolution)
return min + randomFraction * max
}
}
// -
enum Demo {
case chaos, santa, tan, apeidos, slope, random, custom
static var fractionDemos: [Demo] {
return [.santa, .chaos, .apeidos, .tan, .random, .custom]
}
static var perpendicularDemos: [Demo] {
return [.santa, .chaos, .apeidos, .tan, .random]
}
static var tangentDemos: [Demo] {
return [.santa, .chaos, .apeidos, .tan, .slope]
}
var path: UIBezierPath {
switch self {
case .chaos:
return UIBezierPath.pathWithSVG(fileName: "chaos")
case .santa:
return UIBezierPath.pathWithSVG(fileName: "santa")
case .tan:
return UIBezierPath.pathWithSVG(fileName: "tan")
case .apeidos:
return UIBezierPath.pathWithSVG(fileName: "apeidos")
case .slope:
return UIBezierPath.pathWithSVG(fileName: "slope")
case .custom:
return UIBezierPath()
case .random:
let path = UIBezierPath()
let randomPoints = (0..<14).map { _ in CGPoint(x: .random(min: 20, max: 280), y: .random(min: 20, max: 280)) }
for (idx, p) in randomPoints.enumerated() {
if idx % 3 != 0 {
path.move(to: p)
}
path.addLine(to: p)
}
return path
}
}
var displayName: String {
switch self {
case .chaos:
return "Chaos"
case .santa:
return "Santas house"
case .tan:
return "Tan-ish"
case .apeidos:
return "Apeidos"
case .slope:
return "Slope"
case .custom:
return "Custom"
case .random:
return "Random"
}
}
}
| mit |
nsutanto/ios-VirtualTourist | VirtualTourist/Utility/CellCancelTask.swift | 1 | 556 | //
// CellCancelTask.swift
// VirtualTourist
//
// Created by Nicholas Sutanto on 10/12/17.
// Copyright © 2017 Nicholas Sutanto. All rights reserved.
//
import Foundation
import UIKit
// https://discussions.udacity.com/t/retrieving-images-from-flickr/177208
// Task to cancel from Favorite Actors app
class CellCancelTask : UICollectionViewCell {
var taskToCancelifCellIsReused: URLSessionTask? {
didSet {
if let taskToCancel = oldValue {
taskToCancel.cancel()
}
}
}
}
| mit |
kdawgwilk/vapor | Sources/Vapor/Multipart/Multipart+Parse.swift | 1 | 6430 | extension Multipart {
public enum Error: ErrorProtocol {
case invalidBoundary
}
static func parseBoundary(contentType: String) throws -> String {
let boundaryPieces = contentType.components(separatedBy: "boundary=")
guard boundaryPieces.count == 2 else {
throw Error.invalidBoundary
}
return boundaryPieces[1]
}
static func parse(_ body: Data, boundary: String) -> [String: Multipart] {
let boundary = Data([.hyphen, .hyphen] + boundary.data)
var form = [String: Multipart]()
// Separate by boundry and loop over the "multi"-parts
for part in body.split(separator: boundary, excludingFirst: true, excludingLast: true) {
let headBody = part.split(separator: Data(Byte.crlf + Byte.crlf))
// Separate the head and body
guard headBody.count == 2, let head = headBody.first, let body = headBody.last else {
continue
}
guard let storage = parseMultipartStorage(head: head, body: body) else {
continue
}
// There's always a name for a field. Otherwise we can't store it under a key
guard let name = storage["name"] else {
continue
}
// If this key already exists it needs to be an array
if form.keys.contains(name) {
// If it's a file.. there are multiple files being uploaded under the same key
if storage.keys.contains("content-type") || storage.keys.contains("filename") {
var mediaType: String? = nil
// Take the content-type if it's there
if let contentType = storage["content-type"] {
mediaType = contentType
}
// Create the suple to be added to the array
let new = Multipart.File(name: storage["filename"], type: mediaType, data: body)
// If there is only one file. Make it a file array
if let o = form[name], case .file(let old) = o {
form[name] = .files([old, new])
// If there's a file array. Append it
} else if let o = form[name], case .files(var old) = o {
old.append(new)
form[name] = .files(old)
// If it's neither.. It's a duplicate key. This means we're going to be ditched or overriding the existing key
// Since we're later, we're overriding
} else {
let file = Multipart.File(name: new.name, type: new.type, data: new.data)
form[name] = .file(file)
}
} else {
let new = body.string.components(separatedBy: "\r\n").joined(separator: "")
if let o = form[name], case .input(let old) = o {
form[name] = .inputArray([old, new])
} else if let o = form[name], case .inputArray(var old) = o {
old.append(new)
form[name] = .inputArray(old)
} else {
form[name] = .input(new)
}
}
// If it's a new key
} else {
// Ensure it's a file. There's no proper way of detecting this if there's no filename and no content-type
if storage.keys.contains("content-type") || storage.keys.contains("filename") {
var mediaType: String? = nil
// Take the optional content type and convert it to a MediaType
if let contentType = storage["content-type"] {
mediaType = contentType
}
// Store the file in the form
let file = Multipart.File(name: storage["filename"], type: mediaType, data: body)
form[name] = .file(file)
// If it's not a file (or not for sure) we're storing the information String
} else {
let input = body.string.components(separatedBy: "\r\n").joined(separator: "")
form[name] = .input(input)
}
}
}
return form
}
static func parseMultipartStorage(head: Data, body: Data) -> [String: String]? {
var storage = [String: String]()
// Separate the individual headers
let headers = head.split(separator: Data(Byte.crlf))
for line in headers {
// Make the header a String
let header = line.string.components(separatedBy: "\r\n").joined(separator: "")
// Split the header parts into an array
var headerParts = header.characters.split(separator: ";").map(String.init)
// The header has a base. Like "Content-Type: text/html; other=3" would have "Content-Type: text/html;
guard let base = headerParts.first else {
continue
}
// The base always has two parts. Key + Value
let baseParts = base.characters.split(separator: ":", maxSplits: 1).map(String.init)
// Check that the count is right
guard baseParts.count == 2 else {
continue
}
// Add the header to the storage
storage[baseParts[0].bytes.trimmed([.space]).lowercased.string] = baseParts[1].bytes.trimmed([.space]).string
// Remove the header base so we can parse the rest
headerParts.remove(at: 0)
// remaining parts
for part in headerParts {
// Split key-value
let subParts = part.characters.split(separator: "=", maxSplits: 1).map(String.init)
// There's a key AND a Value. No more, no less
guard subParts.count == 2 else {
continue
}
// Strip all unnecessary characters
storage[subParts[0].bytes.trimmed([.space]).string] = subParts[1].bytes.trimmed([.space, .horizontalTab, .carriageReturn, .newLine, .backSlash, .apostrophe, .quote]).string
}
}
return storage
}
}
| mit |
NaughtyOttsel/swift-corelibs-foundation | TestFoundation/TestNSJSONSerialization.swift | 1 | 28056 | // 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
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSJSONSerialization : XCTestCase {
let supportedEncodings = [
NSUTF8StringEncoding,
NSUTF16LittleEndianStringEncoding, NSUTF16BigEndianStringEncoding,
NSUTF32LittleEndianStringEncoding, NSUTF32BigEndianStringEncoding
]
static var allTests: [(String, (TestNSJSONSerialization) -> () throws -> Void)] {
return JSONObjectWithDataTests
+ deserializationTests
+ isValidJSONObjectTests
+ serializationTests
}
}
//MARK: - JSONObjectWithData
extension TestNSJSONSerialization {
class var JSONObjectWithDataTests: [(String, (TestNSJSONSerialization) -> () throws -> Void)] {
return [
("test_JSONObjectWithData_emptyObject", test_JSONObjectWithData_emptyObject),
("test_JSONObjectWithData_encodingDetection", test_JSONObjectWithData_encodingDetection),
]
}
func test_JSONObjectWithData_emptyObject() {
let subject = NSData(bytes: UnsafePointer<Void>([UInt8]([0x7B, 0x7D])), length: 2)
let object = try! NSJSONSerialization.jsonObject(with: subject, options: []) as? [String:Any]
XCTAssertEqual(object?.count, 0)
}
//MARK: - Encoding Detection
func test_JSONObjectWithData_encodingDetection() {
let subjects: [(String, [UInt8])] = [
// BOM Detection
("{} UTF-8 w/BOM", [0xEF, 0xBB, 0xBF, 0x7B, 0x7D]),
("{} UTF-16BE w/BOM", [0xFE, 0xFF, 0x0, 0x7B, 0x0, 0x7D]),
("{} UTF-16LE w/BOM", [0xFF, 0xFE, 0x7B, 0x0, 0x7D, 0x0]),
("{} UTF-32BE w/BOM", [0x00, 0x00, 0xFE, 0xFF, 0x0, 0x0, 0x0, 0x7B, 0x0, 0x0, 0x0, 0x7D]),
("{} UTF-32LE w/BOM", [0xFF, 0xFE, 0x00, 0x00, 0x7B, 0x0, 0x0, 0x0, 0x7D, 0x0, 0x0, 0x0]),
// RFC4627 Detection
("{} UTF-8", [0x7B, 0x7D]),
("{} UTF-16BE", [0x0, 0x7B, 0x0, 0x7D]),
("{} UTF-16LE", [0x7B, 0x0, 0x7D, 0x0]),
("{} UTF-32BE", [0x0, 0x0, 0x0, 0x7B, 0x0, 0x0, 0x0, 0x7D]),
("{} UTF-32LE", [0x7B, 0x0, 0x0, 0x0, 0x7D, 0x0, 0x0, 0x0]),
// // Single Characters
// ("'3' UTF-8", [0x33]),
// ("'3' UTF-16BE", [0x0, 0x33]),
// ("'3' UTF-16LE", [0x33, 0x0]),
]
for (description, encoded) in subjects {
let result = try? NSJSONSerialization.jsonObject(with: NSData(bytes:UnsafePointer<Void>(encoded), length: encoded.count), options: [])
XCTAssertNotNil(result, description)
}
}
}
//MARK: - JSONDeserialization
extension TestNSJSONSerialization {
class var deserializationTests: [(String, (TestNSJSONSerialization) -> () throws -> Void)] {
return [
("test_deserialize_emptyObject", test_deserialize_emptyObject),
("test_deserialize_multiStringObject", test_deserialize_multiStringObject),
("test_deserialize_emptyArray", test_deserialize_emptyArray),
("test_deserialize_multiStringArray", test_deserialize_multiStringArray),
("test_deserialize_unicodeString", test_deserialize_unicodeString),
("test_deserialize_stringWithSpacesAtStart", test_deserialize_stringWithSpacesAtStart),
("test_deserialize_values", test_deserialize_values),
("test_deserialize_numbers", test_deserialize_numbers),
("test_deserialize_simpleEscapeSequences", test_deserialize_simpleEscapeSequences),
("test_deserialize_unicodeEscapeSequence", test_deserialize_unicodeEscapeSequence),
("test_deserialize_unicodeSurrogatePairEscapeSequence", test_deserialize_unicodeSurrogatePairEscapeSequence),
// Disabled due to uninitialized memory SR-606
// ("test_deserialize_allowFragments", test_deserialize_allowFragments),
("test_deserialize_unterminatedObjectString", test_deserialize_unterminatedObjectString),
("test_deserialize_missingObjectKey", test_deserialize_missingObjectKey),
("test_deserialize_unexpectedEndOfFile", test_deserialize_unexpectedEndOfFile),
("test_deserialize_invalidValueInObject", test_deserialize_invalidValueInObject),
("test_deserialize_invalidValueIncorrectSeparatorInObject", test_deserialize_invalidValueIncorrectSeparatorInObject),
("test_deserialize_invalidValueInArray", test_deserialize_invalidValueInArray),
("test_deserialize_badlyFormedArray", test_deserialize_badlyFormedArray),
("test_deserialize_invalidEscapeSequence", test_deserialize_invalidEscapeSequence),
("test_deserialize_unicodeMissingTrailingSurrogate", test_deserialize_unicodeMissingTrailingSurrogate),
]
}
//MARK: - Object Deserialization
func test_deserialize_emptyObject() {
let subject = "{}"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
let t = try NSJSONSerialization.jsonObject(with: data, options: [])
let result = t as? [String: Any]
XCTAssertEqual(result?.count, 0)
} catch {
XCTFail("Error thrown: \(error)")
}
}
func test_deserialize_multiStringObject() {
let subject = "{ \"hello\": \"world\", \"swift\": \"rocks\" }"
do {
for encoding in [NSUTF8StringEncoding, NSUTF16BigEndianStringEncoding] {
guard let data = subject.bridge().data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
XCTAssertEqual(result?["hello"] as? String, "world")
XCTAssertEqual(result?["swift"] as? String, "rocks")
}
} catch {
XCTFail("Error thrown: \(error)")
}
}
func test_deserialize_stringWithSpacesAtStart(){
let subject = "{\"title\" : \" hello world!!\" }"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
XCTAssertEqual(result?["title"] as? String, " hello world!!")
} catch{
XCTFail("Error thrown: \(error)")
}
}
//MARK: - Array Deserialization
func test_deserialize_emptyArray() {
let subject = "[]"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?.count, 0)
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func test_deserialize_multiStringArray() {
let subject = "[\"hello\", \"swift⚡️\"]"
do {
for encoding in [NSUTF8StringEncoding, NSUTF16BigEndianStringEncoding] {
guard let data = subject.bridge().data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? String, "hello")
XCTAssertEqual(result?[1] as? String, "swift⚡️")
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func test_deserialize_unicodeString() {
/// Ģ has the same LSB as quotation mark " (U+0022) so test guarding against this case
let subject = "[\"unicode\", \"Ģ\", \"😢\"]"
do {
for encoding in [NSUTF16LittleEndianStringEncoding, NSUTF16BigEndianStringEncoding, NSUTF32LittleEndianStringEncoding, NSUTF32BigEndianStringEncoding] {
guard let data = subject.bridge().data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? String, "unicode")
XCTAssertEqual(result?[1] as? String, "Ģ")
XCTAssertEqual(result?[2] as? String, "😢")
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
//MARK: - Value parsing
func test_deserialize_values() {
let subject = "[true, false, \"hello\", null, {}, []]"
do {
for encoding in supportedEncodings {
guard let data = subject.bridge().data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? Bool, true)
XCTAssertEqual(result?[1] as? Bool, false)
XCTAssertEqual(result?[2] as? String, "hello")
XCTAssertNotNil(result?[3] as? NSNull)
XCTAssertNotNil(result?[4] as? [String:Any])
XCTAssertNotNil(result?[5] as? [Any])
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
//MARK: - Number parsing
func test_deserialize_numbers() {
let subject = "[1, -1, 1.3, -1.3, 1e3, 1E-3]"
do {
for encoding in supportedEncodings {
guard let data = subject.bridge().data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? Int, 1)
XCTAssertEqual(result?[1] as? Int, -1)
XCTAssertEqual(result?[2] as? Double, 1.3)
XCTAssertEqual(result?[3] as? Double, -1.3)
XCTAssertEqual(result?[4] as? Double, 1000)
XCTAssertEqual(result?[5] as? Double, 0.001)
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
//MARK: - Escape Sequences
func test_deserialize_simpleEscapeSequences() {
let subject = "[\"\\\"\", \"\\\\\", \"\\/\", \"\\b\", \"\\f\", \"\\n\", \"\\r\", \"\\t\"]"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
let res = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any]
let result = res?.flatMap { $0 as? String }
XCTAssertEqual(result?[0], "\"")
XCTAssertEqual(result?[1], "\\")
XCTAssertEqual(result?[2], "/")
XCTAssertEqual(result?[3], "\u{08}")
XCTAssertEqual(result?[4], "\u{0C}")
XCTAssertEqual(result?[5], "\u{0A}")
XCTAssertEqual(result?[6], "\u{0D}")
XCTAssertEqual(result?[7], "\u{09}")
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func test_deserialize_unicodeEscapeSequence() {
let subject = "[\"\\u2728\"]"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? String, "✨")
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func test_deserialize_unicodeSurrogatePairEscapeSequence() {
let subject = "[\"\\uD834\\udd1E\"]"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [Any]
XCTAssertEqual(result?[0] as? String, "\u{1D11E}")
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func test_deserialize_allowFragments() {
let subject = "3"
do {
for encoding in supportedEncodings {
guard let data = subject.bridge().data(using: encoding) else {
XCTFail("Unable to convert string to data")
return
}
let result = try NSJSONSerialization.jsonObject(with: data, options: .AllowFragments) as? Int
XCTAssertEqual(result, 3)
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}
//MARK: - Parsing Errors
func test_deserialize_unterminatedObjectString() {
let subject = "{\"}"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
try NSJSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: UnterminatedString")
} catch {
// Passing case; the object as unterminated
}
}
func test_deserialize_missingObjectKey() {
let subject = "{3}"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
try NSJSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Missing key for value")
} catch {
// Passing case; the key was missing for a value
}
}
func test_deserialize_unexpectedEndOfFile() {
let subject = "{"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
try NSJSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Unexpected end of file")
} catch {
// Success
}
}
func test_deserialize_invalidValueInObject() {
let subject = "{\"error\":}"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
try NSJSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Invalid value")
} catch {
// Passing case; the value is invalid
}
}
func test_deserialize_invalidValueIncorrectSeparatorInObject() {
let subject = "{\"missing\";}"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
try NSJSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Invalid value")
} catch {
// passing case the value is invalid
}
}
func test_deserialize_invalidValueInArray() {
let subject = "[,"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
try NSJSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Invalid value")
} catch {
// Passing case; the element in the array is missing
}
}
func test_deserialize_badlyFormedArray() {
let subject = "[2b4]"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
try NSJSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Badly formed array")
} catch {
// Passing case; the array is malformed
}
}
func test_deserialize_invalidEscapeSequence() {
let subject = "[\"\\e\"]"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
try NSJSONSerialization.jsonObject(with: data, options: [])
XCTFail("Expected error: Invalid escape sequence")
} catch {
// Passing case; the escape sequence is invalid
}
}
func test_deserialize_unicodeMissingTrailingSurrogate() {
let subject = "[\"\\uD834\"]"
do {
guard let data = subject.bridge().data(using: NSUTF8StringEncoding) else {
XCTFail("Unable to convert string to data")
return
}
try NSJSONSerialization.jsonObject(with: data, options: []) as? [String]
XCTFail("Expected error: Missing Trailing Surrogate")
} catch {
// Passing case; the unicode character is malformed
}
}
}
// MARK: - isValidJSONObjectTests
extension TestNSJSONSerialization {
class var isValidJSONObjectTests: [(String, (TestNSJSONSerialization) -> () throws -> Void)] {
return [
("test_isValidJSONObjectTrue", test_isValidJSONObjectTrue),
("test_isValidJSONObjectFalse", test_isValidJSONObjectFalse),
]
}
func test_isValidJSONObjectTrue() {
let trueJSON: [Any] = [
// []
Array<Any>(),
// [1, ["string", [[]]]]
Array<Any>(arrayLiteral:
NSNumber(value: Int(1)),
Array<Any>(arrayLiteral:
"string",
Array<Any>(arrayLiteral:
Array<Any>()
)
)
),
// [NSNull(), ["1" : ["string", 1], "2" : NSNull()]]
Array<Any>(arrayLiteral:
NSNull(),
Dictionary<String, Any>(dictionaryLiteral:
(
"1",
Array<Any>(arrayLiteral:
"string",
NSNumber(value: Int(1))
)
),
(
"2",
NSNull()
)
)
),
// ["0" : 0]
Dictionary<String, Any>(dictionaryLiteral:
(
"0",
NSNumber(value: Int(0))
)
)
]
for testCase in trueJSON {
XCTAssertTrue(NSJSONSerialization.isValidJSONObject(testCase))
}
}
func test_isValidJSONObjectFalse() {
let falseJSON: [Any] = [
// 0
NSNumber(value: Int(0)),
// NSNull()
NSNull(),
// "string"
"string",
// [1, 2, 3, [4 : 5]]
Array<Any>(arrayLiteral:
NSNumber(value: Int(1)),
NSNumber(value: Int(2)),
NSNumber(value: Int(3)),
Dictionary<NSNumber, Any>(dictionaryLiteral:
(
NSNumber(value: Int(4)),
NSNumber(value: Int(5))
)
)
),
// [1, 2, Infinity]
[NSNumber(value: Int(1)), NSNumber(value: Int(2)), NSNumber(value: Double(1) / Double(0))],
// [NSNull() : 1]
[NSNull() : NSNumber(value: Int(1))],
// [[[[1 : 2]]]]
Array<Any>(arrayLiteral:
Array<Any>(arrayLiteral:
Array<Any>(arrayLiteral:
Dictionary<NSNumber, Any>(dictionaryLiteral:
(
NSNumber(value: Int(1)),
NSNumber(value: Int(2))
)
)
)
)
)
]
for testCase in falseJSON {
XCTAssertFalse(NSJSONSerialization.isValidJSONObject(testCase))
}
}
}
// MARK: - serializationTests
extension TestNSJSONSerialization {
class var serializationTests: [(String, (TestNSJSONSerialization) -> () throws -> Void)] {
return [
("test_serialize_emptyObject", test_serialize_emptyObject),
("test_serialize_null", test_serialize_null),
("test_serialize_complexObject", test_serialize_complexObject),
("test_nested_array", test_nested_array),
("test_nested_dictionary", test_nested_dictionary),
("test_serialize_number", test_serialize_number),
("test_serialize_stringEscaping", test_serialize_stringEscaping),
("test_serialize_invalid_json", test_serialize_invalid_json),
]
}
func trySerialize(_ obj: AnyObject) throws -> String {
let data = try NSJSONSerialization.data(withJSONObject: obj, options: [])
guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) else {
XCTFail("Unable to create string")
return ""
}
return string.bridge()
}
func test_serialize_emptyObject() {
let dict1 = [String: Any]().bridge()
XCTAssertEqual(try trySerialize(dict1), "{}")
let dict2 = [String: NSNumber]().bridge()
XCTAssertEqual(try trySerialize(dict2), "{}")
let dict3 = [String: String]().bridge()
XCTAssertEqual(try trySerialize(dict3), "{}")
let array1 = [String]().bridge()
XCTAssertEqual(try trySerialize(array1), "[]")
let array2 = [NSNumber]().bridge()
XCTAssertEqual(try trySerialize(array2), "[]")
}
func test_serialize_null() {
let arr = [NSNull()].bridge()
XCTAssertEqual(try trySerialize(arr), "[null]")
let dict = ["a":NSNull()].bridge()
XCTAssertEqual(try trySerialize(dict), "{\"a\":null}")
let arr2 = [NSNull(), NSNull(), NSNull()].bridge()
XCTAssertEqual(try trySerialize(arr2), "[null,null,null]")
let dict2 = [["a":NSNull()], ["b":NSNull()], ["c":NSNull()]].bridge()
XCTAssertEqual(try trySerialize(dict2), "[{\"a\":null},{\"b\":null},{\"c\":null}]")
}
func test_serialize_complexObject() {
let jsonDict = ["a": 4].bridge()
XCTAssertEqual(try trySerialize(jsonDict), "{\"a\":4}")
let jsonArr = [1, 2, 3, 4].bridge()
XCTAssertEqual(try trySerialize(jsonArr), "[1,2,3,4]")
let jsonDict2 = ["a": [1,2]].bridge()
XCTAssertEqual(try trySerialize(jsonDict2), "{\"a\":[1,2]}")
let jsonArr2 = ["a", "b", "c"].bridge()
XCTAssertEqual(try trySerialize(jsonArr2), "[\"a\",\"b\",\"c\"]")
let jsonArr3 = [["a":1],["b":2]].bridge()
XCTAssertEqual(try trySerialize(jsonArr3), "[{\"a\":1},{\"b\":2}]")
let jsonArr4 = [["a":NSNull()],["b":NSNull()]].bridge()
XCTAssertEqual(try trySerialize(jsonArr4), "[{\"a\":null},{\"b\":null}]")
}
func test_nested_array() {
var arr = ["a"].bridge()
XCTAssertEqual(try trySerialize(arr), "[\"a\"]")
arr = [["b"]].bridge()
XCTAssertEqual(try trySerialize(arr), "[[\"b\"]]")
arr = [[["c"]]].bridge()
XCTAssertEqual(try trySerialize(arr), "[[[\"c\"]]]")
arr = [[[["d"]]]].bridge()
XCTAssertEqual(try trySerialize(arr), "[[[[\"d\"]]]]")
}
func test_nested_dictionary() {
var dict = ["a":1].bridge()
XCTAssertEqual(try trySerialize(dict), "{\"a\":1}")
dict = ["a":["b":1]].bridge()
XCTAssertEqual(try trySerialize(dict), "{\"a\":{\"b\":1}}")
dict = ["a":["b":["c":1]]].bridge()
XCTAssertEqual(try trySerialize(dict), "{\"a\":{\"b\":{\"c\":1}}}")
dict = ["a":["b":["c":["d":1]]]].bridge()
XCTAssertEqual(try trySerialize(dict), "{\"a\":{\"b\":{\"c\":{\"d\":1}}}}")
}
func test_serialize_number() {
var json = [1, 1.1, 0, -2].bridge()
XCTAssertEqual(try trySerialize(json), "[1,1.1,0,-2]")
// Cannot generate "true"/"false" currently
json = [NSNumber(value:false),NSNumber(value:true)].bridge()
XCTAssertEqual(try trySerialize(json), "[0,1]")
}
func test_serialize_stringEscaping() {
var json = ["foo"].bridge()
XCTAssertEqual(try trySerialize(json), "[\"foo\"]")
json = ["a\0"].bridge()
XCTAssertEqual(try trySerialize(json), "[\"a\\u0000\"]")
json = ["b\\"].bridge()
XCTAssertEqual(try trySerialize(json), "[\"b\\\\\"]")
json = ["c\t"].bridge()
XCTAssertEqual(try trySerialize(json), "[\"c\\t\"]")
json = ["d\n"].bridge()
XCTAssertEqual(try trySerialize(json), "[\"d\\n\"]")
json = ["e\r"].bridge()
XCTAssertEqual(try trySerialize(json), "[\"e\\r\"]")
json = ["f\""].bridge()
XCTAssertEqual(try trySerialize(json), "[\"f\\\"\"]")
json = ["g\'"].bridge()
XCTAssertEqual(try trySerialize(json), "[\"g\'\"]")
json = ["h\u{7}"].bridge()
XCTAssertEqual(try trySerialize(json), "[\"h\\u0007\"]")
json = ["i\u{1f}"].bridge()
XCTAssertEqual(try trySerialize(json), "[\"i\\u001f\"]")
}
func test_serialize_invalid_json() {
let str = "Invalid JSON".bridge()
do {
let _ = try trySerialize(str)
XCTFail("Top-level JSON object cannot be string")
} catch {
// should get here
}
let double = NSNumber(value: Double(1.2))
do {
let _ = try trySerialize(double)
XCTFail("Top-level JSON object cannot be double")
} catch {
// should get here
}
let dict = [NSNumber(value: Double(1.2)):"a"].bridge()
do {
let _ = try trySerialize(dict)
XCTFail("Dictionary keys must be strings")
} catch {
// should get here
}
}
}
| apache-2.0 |
richardpiazza/SOSwift | Sources/SOSwift/Review.swift | 1 | 2015 | import Foundation
/// A review of an item - for example, of a restaurant, movie, or store.
public class Review: CreativeWork {
/// The item that is being reviewed/rated.
public var itemReviewed: Thing?
/// This Review or Rating is relevant to this part or facet of the
/// `itemReviewed`.
public var reviewAspect: String?
/// The actual body of the review.
public var reviewBody: String?
/// The rating given in this review.
/// - note: Reviews can themselves be rated. The reviewRating applies
/// to rating given by the review. The aggregateRating property
/// applies to the review itself, as a creative work.
public var reviewRating: Rating?
internal enum ReviewCodingKeys: String, CodingKey {
case itemReviewed
case reviewAspect
case reviewBody
case reviewRating
}
public override init() {
super.init()
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: ReviewCodingKeys.self)
itemReviewed = try container.decodeIfPresent(Thing.self, forKey: .itemReviewed)
reviewAspect = try container.decodeIfPresent(String.self, forKey: .reviewAspect)
reviewBody = try container.decodeIfPresent(String.self, forKey: .reviewBody)
reviewRating = try container.decodeIfPresent(Rating.self, forKey: .reviewRating)
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: ReviewCodingKeys.self)
try container.encodeIfPresent(itemReviewed, forKey: .itemReviewed)
try container.encodeIfPresent(reviewAspect, forKey: .reviewAspect)
try container.encodeIfPresent(reviewBody, forKey: .reviewBody)
try container.encodeIfPresent(reviewRating, forKey: .reviewRating)
try super.encode(to: encoder)
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers/28504-anonymous-namespace-verifier-verifychecked-swift-type-llvm-smallptrset-swift-arc.swift | 2 | 424 | // 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
// RUN: not --crash %target-swift-frontend %s -emit-ir
{{}
return.h.h == Int
| apache-2.0 |
yichizhang/YZLibrary | YZLibraryDemo/Pods/Nimble/Sources/Nimble/Matchers/SatisfyAnyOf.swift | 55 | 2612 | import Foundation
/// A Nimble matcher that succeeds when the actual value matches with any of the matchers
/// provided in the variable list of matchers.
public func satisfyAnyOf<T,U where U: Matcher, U.ValueType == T>(matchers: U...) -> NonNilMatcherFunc<T> {
return satisfyAnyOf(matchers)
}
internal func satisfyAnyOf<T,U where U: Matcher, U.ValueType == T>(matchers: [U]) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc<T> { actualExpression, failureMessage in
let postfixMessages = NSMutableArray()
var matches = false
for matcher in matchers {
if try matcher.matches(actualExpression, failureMessage: failureMessage) {
matches = true
}
postfixMessages.addObject(NSString(string: "{\(failureMessage.postfixMessage)}"))
}
failureMessage.postfixMessage = "match one of: " + postfixMessages.componentsJoinedByString(", or ")
if let actualValue = try actualExpression.evaluate() {
failureMessage.actualValue = "\(actualValue)"
}
return matches
}
}
public func ||<T>(left: NonNilMatcherFunc<T>, right: NonNilMatcherFunc<T>) -> NonNilMatcherFunc<T> {
return satisfyAnyOf(left, right)
}
public func ||<T>(left: FullMatcherFunc<T>, right: FullMatcherFunc<T>) -> NonNilMatcherFunc<T> {
return satisfyAnyOf(left, right)
}
public func ||<T>(left: MatcherFunc<T>, right: MatcherFunc<T>) -> NonNilMatcherFunc<T> {
return satisfyAnyOf(left, right)
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func satisfyAnyOfMatcher(matchers: [NMBObjCMatcher]) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
if matchers.isEmpty {
failureMessage.stringValue = "satisfyAnyOf must be called with at least one matcher"
return false
}
var elementEvaluators = [NonNilMatcherFunc<NSObject>]()
for matcher in matchers {
let elementEvaluator: (Expression<NSObject>, FailureMessage) -> Bool = {
expression, failureMessage in
return matcher.matches(
{try! expression.evaluate()}, failureMessage: failureMessage, location: actualExpression.location)
}
elementEvaluators.append(NonNilMatcherFunc(elementEvaluator))
}
return try! satisfyAnyOf(elementEvaluators).matches(actualExpression, failureMessage: failureMessage)
}
}
}
#endif
| mit |
betterdi/SinaWeibo | SinaWeibo/SinaWeibo/Classes/Module/Main/View/WDTabBar.swift | 1 | 1701 | //
// WDTabBar.swift
// SinaWeibo
//
// Created by 吴迪 on 16/7/18.
// Copyright © 2016年 wudi. All rights reserved.
//
import UIKit
class WDTabBar: UITabBar {
var composeCallBack: (() -> Void)?
///TabBar按钮个数
let btnNum : Int = 5
///懒加载发布按钮
lazy var composeBtn: UIButton = {
let btn = UIButton(type: UIButtonType.Custom)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
btn.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(btn)
return btn;
}()
override func layoutSubviews() {
let itemWidth = self.frame.size.width / CGFloat(btnNum)
var itemIndex = 0
for item in self.subviews {
let cls = NSClassFromString("UITabBarButton")
if item.isKindOfClass(cls!) {
item.frame = CGRect(x: itemWidth * CGFloat(itemIndex), y: 0, width: itemWidth, height: self.frame.height)
itemIndex++
if itemIndex == 2 {
itemIndex++
}
}
}
composeBtn.frame = CGRect(x: itemWidth * CGFloat(2), y: 0, width: itemWidth, height: self.frame.height)
}
func composeClick() {
composeCallBack?()
}
}
| mit |
citysite102/kapi-kaffeine | kapi-kaffeine/KPServiceHandler.swift | 1 | 45590 | //
// KPServiceHandler.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/5/26.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import Foundation
import ObjectMapper
import PromiseKit
import Crashlytics
class KPServiceHandler {
static let sharedHandler = KPServiceHandler()
private var kapiDataRequest: KPCafeRequest!
private var kapiSimpleInfoRequest: KPSimpleCafeRequest!
private var kapiDetailedInfoRequest: KPCafeDetailedInfoRequest!
// 目前儲存所有的咖啡店
var currentCafeDatas: [KPDataModel]!
var currentDisplayModel: KPDataModel? {
didSet {
CLSLogv("Information Controller with cafe id: %@", getVaList([currentDisplayModel?.identifier ?? ""]))
}
}
var isCurrentShopClosed: Bool! {
return self.currentDisplayModel?.closed ?? false
}
var currentCity: String?
var relatedDisplayModel: [KPDataModel]? {
if currentDisplayModel != nil {
let filteredLocationModel = KPFilter.filterData(source: self.currentCafeDatas,
withCity: self.currentDisplayModel?.city ?? "taipei")
var relativeArray: [(cafeModel: KPDataModel, weight: CGFloat)] =
[(cafeModel: KPDataModel, weight: CGFloat)]()
for dataModel in filteredLocationModel {
if dataModel.identifier != currentDisplayModel?.identifier {
relativeArray.append((cafeModel: dataModel,
weight: relativeWeight(currentDisplayModel!, dataModel)))
}
}
relativeArray.sort(by: { (model1, model2) -> Bool in
model1.weight < model2.weight
})
if relativeArray.count >= 5 {
return [relativeArray[0].cafeModel,
relativeArray[1].cafeModel,
relativeArray[2].cafeModel,
relativeArray[3].cafeModel,
relativeArray[4].cafeModel]
} else {
var responseResult: [KPDataModel] = [KPDataModel]()
for relativeModel in relativeArray {
responseResult.append(relativeModel.cafeModel)
}
return responseResult
}
}
return nil
}
var featureTags: [KPDataTagModel] = []
// MARK: Initialization
private init() {
kapiDataRequest = KPCafeRequest()
kapiSimpleInfoRequest = KPSimpleCafeRequest()
kapiDetailedInfoRequest = KPCafeDetailedInfoRequest()
}
func relativeWeight(_ model1: KPDataModel,
_ model2: KPDataModel) -> CGFloat {
var totalWeight: CGFloat = 0
totalWeight = totalWeight + pow(Decimal((model1.standingDesk?.intValue)! - (model2.standingDesk?.intValue)!), 2).cgFloatValue
totalWeight = totalWeight + pow(Decimal((model1.socket?.intValue)! - (model2.socket?.intValue)!), 2).cgFloatValue
totalWeight = totalWeight + pow(Decimal((model1.limitedTime?.intValue)! - (model2.limitedTime?.intValue)!), 2).cgFloatValue
totalWeight = totalWeight + pow(Decimal((model1.averageRate?.intValue)! - (model2.averageRate?.intValue)!), 2).cgFloatValue
return totalWeight
}
// MARK: Global API
func fetchRemoteData(_ limitedTime: NSNumber? = nil,
_ socket: NSNumber? = nil,
_ standingDesk: NSNumber? = nil,
_ mrt: String? = nil,
_ city: String? = nil,
_ rightTop: CLLocationCoordinate2D? = nil,
_ leftBottom: CLLocationCoordinate2D? = nil,
_ searchText: String? = nil,
_ completion:((_ result: [KPDataModel]?, _ error: NetworkRequestError?) -> Void)!) {
kapiDataRequest.perform(limitedTime,
socket,
standingDesk,
mrt,
city,
rightTop,
leftBottom,
searchText).then { result -> Void in
DispatchQueue.global().async {
var cafeDatas = [KPDataModel]()
if result["data"].arrayObject != nil {
for data in (result["data"].arrayObject)! {
if let cafeData = KPDataModel(JSON: (data as! [String: Any])) {
cafeDatas.append(cafeData)
}
}
self.currentCafeDatas = cafeDatas.filter({ (dataModel) -> Bool in
dataModel.verified == true
})
completion?(cafeDatas, nil)
} else {
completion?(nil, NetworkRequestError.resultUnavailable)
}
}
}.catch { error in
DispatchQueue.global().async {
completion?(nil, (error as! NetworkRequestError))
}
}
}
func fetchSimpleStoreInformation(_ cafeID: String!,
_ completion:((_ result: KPDataModel?) -> Void)!) {
kapiSimpleInfoRequest.perform(cafeID).then {result -> Void in
if let data = result["data"].dictionaryObject {
if let cafeData = KPDataModel(JSON: data) {
completion(cafeData)
}
} else {
completion(nil)
}
}.catch { error in
completion(nil)
}
}
func fetchStoreInformation(_ cafeID: String!,
_ completion:((_ result: KPDetailedDataModel?) -> Void)!) {
kapiDetailedInfoRequest.perform(cafeID).then {result -> Void in
if let data = result["data"].dictionaryObject {
if let cafeData = KPDetailedDataModel(JSON: data) {
completion(cafeData)
}
}
}.catch { error in
completion(nil)
}
}
func addNewShop(_ name: String,
_ address: String,
_ country: String,
_ city: String,
_ latitude: Double,
_ longitude: Double,
_ fb_url: String,
_ limited_time: Int,
_ standingDesk: Int,
_ socket: Int,
_ wifi: Int,
_ quiet: Int,
_ cheap: Int,
_ seat: Int,
_ tasty: Int,
_ food: Int,
_ music: Int,
_ phone: String,
_ tags: [KPDataTagModel],
_ business_hour: [String: String],
_ price_average: Int,
_ menus: [UIImage],
_ photos: [UIImage],
_ completion: ((_ successed: Bool) -> Swift.Void)?) {
let newShopRequest = KPAddNewCafeRequest()
let loadingView = KPLoadingView(("新增中..", "新增成功", "新增失敗"))
UIApplication.shared.topViewController.view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
newShopRequest.perform(name,
address,
country,
city,
latitude,
longitude,
fb_url,
limited_time,
standingDesk,
socket,
wifi,
quiet,
cheap,
seat,
tasty,
food,
music,
phone,
tags,
business_hour,
price_average).then { result -> Void in
if let addResult = result["result"].bool {
loadingView.state = addResult ? .successed : .failed
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5,
execute: {
loadingView.dismiss()
completion?(addResult)
})
if let cafeID = result["data"]["cafe_id"].string {
self.uploadPhotos(photos, cafeID, false, { (success) in
// TODO: upload failed error handle
})
self.uploadMenus(menus, cafeID, false, { (success) in
// TODO: upload failed error handle
})
}
} else {
loadingView.state = .failed
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0,
execute: {
loadingView.dismiss()
completion?(false)
})
}
}.catch { (error) in
loadingView.state = .failed
print(error)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0,
execute: {
loadingView.dismiss()
completion?(false)
})
}
}
func modifyCafeData(_ cafeid: String,
_ name:String,
_ address:String,
_ city:String,
_ latitude: Double,
_ longitude: Double,
_ fb_url:String,
_ limited_time: Int,
_ standingDesk: Int,
_ socket: Int,
_ phone: String,
_ tags: [KPDataTagModel],
_ business_hour: [String: String],
_ price_average: Int,
_ completion: ((_ successed: Bool) -> Swift.Void)?) {
let modifyRequest = KPModifyCafeDataRequest()
let loadingView = KPLoadingView(("修改中..", "修改成功", "修改失敗"))
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
modifyRequest.perform(cafeid,
name,
address,
city,
latitude,
longitude,
fb_url,
limited_time,
standingDesk,
socket,
phone,
tags,
business_hour,
price_average).then { result -> Void in
if let addResult = result["result"].bool {
loadingView.state = addResult ? .successed : .failed
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5,
execute: {
loadingView.dismiss()
completion?(addResult)
})
} else {
loadingView.state = .failed
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0,
execute: {
loadingView.dismiss()
completion?(false)
})
}
}.catch { (error) in
loadingView.state = .failed
print(error)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0,
execute: {
loadingView.dismiss()
completion?(false)
})
}
}
// MARK: Rating API
func reportStoreClosed(_ completion: ((_ successed: Bool) -> Swift.Void)?) {
let loadingView = KPLoadingView(("回報中..", "回報成功", "回報失敗"))
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
loadingView.state = .successed
completion?(true)
}
}
// MARK: Comment API
func addComment(_ comment: String? = "",
_ completion: ((_ successed: Bool) -> Swift.Void)?) {
let loadingView = KPLoadingView(("新增中..", "新增成功", "新增失敗"))
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
let commentRequest = KPNewCommentRequest()
commentRequest.perform((currentDisplayModel?.identifier)!,
nil,
comment!,
.add).then { result -> Void in
if let commentResult = result["result"].bool {
loadingView.state = commentResult ? .successed : .failed
if commentResult {
let notification = Notification.Name(KPNotification.information.commentInformation)
NotificationCenter.default.post(name: notification, object: nil)
}
completion?(commentResult)
guard let _ = KPUserManager.sharedManager.currentUser?.reviews?.first(where: {$0.identifier == self.currentDisplayModel?.identifier}) else {
KPUserManager.sharedManager.currentUser?.reviews?.append(self.currentDisplayModel!)
KPUserManager.sharedManager.storeUserInformation()
return
}
} else {
completion?(false)
}
}.catch { (error) in
completion?(false)
}
}
func modifyComment(_ comment: String? = "",
_ comment_id: String,
_ completion: ((_ successed: Bool) -> Swift.Void)?) {
let loadingView = KPLoadingView(("修改中..", "修改成功", "修改失敗"))
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
let commentRequest = KPNewCommentRequest()
commentRequest.perform((currentDisplayModel?.identifier)!,
comment_id,
comment!,
.put).then { result -> Void in
if let commentResult = result["result"].bool {
loadingView.state = commentResult ? .successed : .failed
if commentResult {
let notification = Notification.Name(KPNotification.information.commentInformation)
NotificationCenter.default.post(name: notification, object: nil)
}
completion?(commentResult)
guard let _ = KPUserManager.sharedManager.currentUser?.reviews?.first(where: {$0.identifier == self.currentDisplayModel?.identifier}) else {
KPUserManager.sharedManager.currentUser?.reviews?.append(self.currentDisplayModel!)
KPUserManager.sharedManager.storeUserInformation()
return
}
} else {
completion?(false)
}
}.catch { (error) in
loadingView.state = .failed
completion?(false)
}
}
func getComments(_ completion: ((_ successed: Bool,
_ comments: [KPCommentModel]?) -> Swift.Void)?) {
let commentRequest = KPGetCommentRequest()
commentRequest.perform((currentDisplayModel?.identifier)!).then { result -> Void in
var resultComments = [KPCommentModel]()
if result["result"].boolValue {
if let commentDatas = result["data"]["comments"].arrayObject {
for case let commentDataModel as Dictionary<String, Any> in commentDatas {
if let commentModel = KPCommentModel(JSON: commentDataModel) {
resultComments.append(commentModel)
}
}
}
let sortedComments = resultComments.sorted(by: { (comment1, comment2) -> Bool in
return comment1.createdTime.intValue > comment2.createdTime.intValue
})
completion?(true, sortedComments)
} else {
completion?(false, nil)
}
}.catch { (error) in
completion?(false, nil)
}
}
// MARK: Rating API
func addRating(_ wifi: NSNumber? = 0,
_ seat: NSNumber? = 0,
_ food: NSNumber? = 0,
_ quiet: NSNumber? = 0,
_ tasty: NSNumber? = 0,
_ cheap: NSNumber? = 0,
_ music: NSNumber? = 0,
_ completion: ((_ successed: Bool) -> Swift.Void)?) {
let loadingView = KPLoadingView(("新增中..", "新增成功", "新增失敗"))
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
let ratingRequest = KPNewRatingRequest()
ratingRequest.perform((currentDisplayModel?.identifier)!,
wifi,
seat,
food,
quiet,
tasty,
cheap,
music,
.add).then { result -> Void in
if let commentResult = result["result"].bool {
loadingView.state = commentResult ? .successed : .failed
if commentResult {
let notification = Notification.Name(KPNotification.information.rateInformation)
NotificationCenter.default.post(name: notification, object: nil)
}
completion?(commentResult)
guard let _ = KPUserManager.sharedManager.currentUser?.rates?.first(where: {$0.identifier == self.currentDisplayModel?.identifier}) else {
KPUserManager.sharedManager.currentUser?.rates?.append(self.currentDisplayModel!)
KPUserManager.sharedManager.storeUserInformation()
return
}
} else {
completion?(false)
}
}.catch { (error) in
loadingView.state = .failed
completion?(false)
}
}
func updateRating(_ wifi: NSNumber? = 0,
_ seat: NSNumber? = 0,
_ food: NSNumber? = 0,
_ quiet: NSNumber? = 0,
_ tasty: NSNumber? = 0,
_ cheap: NSNumber? = 0,
_ music: NSNumber? = 0,
_ completion: ((_ successed: Bool) -> Swift.Void)?) {
let loadingView = KPLoadingView(("修改中..", "修改成功", "修改失敗"))
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
let ratingRequest = KPNewRatingRequest()
ratingRequest.perform((currentDisplayModel?.identifier)!,
wifi,
seat,
food,
quiet,
tasty,
cheap,
music,
.put).then { result -> Void in
if let commentResult = result["result"].bool {
loadingView.state = commentResult ? .successed : .failed
if commentResult {
let notification = Notification.Name(KPNotification.information.rateInformation)
NotificationCenter.default.post(name: notification, object: nil)
}
completion?(commentResult)
guard let _ = KPUserManager.sharedManager.currentUser?.rates?.first(where: {$0.identifier == self.currentDisplayModel?.identifier}) else {
KPUserManager.sharedManager.currentUser?.rates?.append(self.currentDisplayModel!)
KPUserManager.sharedManager.storeUserInformation()
return
}
} else {
completion?(false)
}
}.catch { (error) in
loadingView.state = .failed
completion?(false)
}
}
func getRatings(_ completion: ((_ successed: Bool,
_ rating: KPRateDataModel?) -> Swift.Void)?) {
let getRatingRequest = KPGetRatingRequest()
getRatingRequest.perform((currentDisplayModel?.identifier)!).then { result -> Void in
if let ratingResult = result["data"].dictionaryObject {
completion?(true, KPRateDataModel(JSON: ratingResult))
} else {
completion?(false, nil)
}
}.catch { (error) in
completion?(false, nil)
}
}
// MARK: Mix
func addCommentAndRatings(_ comment: String? = "",
_ wifi: NSNumber? = 0,
_ seat: NSNumber? = 0,
_ food: NSNumber? = 0,
_ quiet: NSNumber? = 0,
_ tasty: NSNumber? = 0,
_ cheap: NSNumber? = 0,
_ music: NSNumber? = 0,
_ completion: ((_ successed: Bool) -> Swift.Void)?) {
let loadingView = KPLoadingView(("新增中..", "新增成功", "新增失敗"))
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
let commentRequest = KPNewCommentRequest()
let ratingRequest = KPNewRatingRequest()
when(fulfilled:
commentRequest.perform((currentDisplayModel?.identifier)!, nil, comment!, .add),
ratingRequest.perform((currentDisplayModel?.identifier)!,
wifi,
seat,
food,
quiet,
tasty,
cheap,
music,
.add)).then { (response1, response2) -> Void in
var notification = Notification.Name(KPNotification.information.rateInformation)
NotificationCenter.default.post(name: notification, object: nil)
notification = Notification.Name(KPNotification.information.commentInformation)
NotificationCenter.default.post(name: notification, object: nil)
loadingView.state = .successed
completion?(true)
guard let _ = KPUserManager.sharedManager.currentUser?.reviews?.first(where: {$0.identifier == self.currentDisplayModel?.identifier}) else {
KPUserManager.sharedManager.currentUser?.reviews?.append(self.currentDisplayModel!)
KPUserManager.sharedManager.storeUserInformation()
guard let _ = KPUserManager.sharedManager.currentUser?.rates?.first(where: {$0.identifier == self.currentDisplayModel?.identifier}) else {
KPUserManager.sharedManager.currentUser?.rates?.append(self.currentDisplayModel!)
KPUserManager.sharedManager.storeUserInformation()
return
}
return
}
}.catch { (error) in
loadingView.state = .failed
completion?(false)
}
}
// MARK: Photo API
func getPhotos(_ completion: ((_ successed: Bool,
_ photos: [[String: String]]?) -> Swift.Void)?) {
let getPhotoRequest = KPGetPhotoRequest()
getPhotoRequest.perform((currentDisplayModel?.identifier)!).then { result -> Void in
completion?(true, result["data"].arrayObject as? [[String: String]])
}.catch { (error) in
completion?(false, nil)
}
}
// MARK: Menu API
func getMenus(_ completion: ((_ successed: Bool,
_ photos: [[String: Any]]?) -> Swift.Void)?) {
let getMenuRequest = KPGetMenuRequest()
getMenuRequest.perform((currentDisplayModel?.identifier)!).then { result -> Void in
completion?(true, result["data"].arrayObject as? [[String: Any]])
}.catch { (error) in
completion?(false, nil)
}
}
// MARK: Favorite / Visit
func addFavoriteCafe(_ completion: ((Bool) -> Swift.Void)? = nil) {
let addRequest = KPFavoriteRequest()
addRequest.perform((currentDisplayModel?.identifier)!,
KPFavoriteRequest.requestType.add).then { result -> Void in
guard let _ = KPUserManager.sharedManager.currentUser?.favorites?.first(where: {$0.identifier == self.currentDisplayModel?.identifier}) else {
KPUserManager.sharedManager.currentUser?.favorites?.append(self.currentDisplayModel!)
KPUserManager.sharedManager.storeUserInformation()
return
}
completion?(true)
}.catch { error in
print("Add Favorite Cafe error\(error)")
completion?(false)
}
}
// MARK: User API
func modifyRemoteUserData(_ user: KPUser, _ completion:((_ successed: Bool) -> Void)?) {
let loadingView = KPLoadingView(("修改中...", "修改成功", "修改失敗"))
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
let request = KPUserInformationRequest()
request.perform(user.displayName,
user.photoURL,
user.defaultLocation,
user.intro,
user.email,
.put).then { result -> Void in
KPUserManager.sharedManager.storeUserInformation()
loadingView.state = result["result"].boolValue ? .successed : .failed
completion?(result["result"].boolValue)
}.catch { error in
print(error)
loadingView.state = .failed
completion?(false)
}
}
func removeFavoriteCafe(_ cafeID: String,
_ completion: ((Bool) -> Swift.Void)? = nil) {
let removeRequest = KPFavoriteRequest()
removeRequest.perform(cafeID,
KPFavoriteRequest.requestType.delete).then { result -> Void in
// if let found = self.currentUser?.favorites?.first(where: {$0.identifier == cafeID}) {
if let foundOffset = KPUserManager.sharedManager.currentUser?.favorites?.index(where: {$0.identifier == cafeID}) {
KPUserManager.sharedManager.currentUser?.favorites?.remove(at: foundOffset)
}
KPUserManager.sharedManager.storeUserInformation()
completion?(true)
print("Result\(result)")
}.catch { (error) in
print("error\(error)")
completion?(false)
}
}
func addVisitedCafe(_ completion: ((Bool) -> Swift.Void)? = nil) {
let addRequest = KPVisitedRequest()
addRequest.perform((currentDisplayModel?.identifier)!,
KPVisitedRequest.requestType.add).then { result -> Void in
guard let _ = KPUserManager.sharedManager.currentUser?.visits?.first(where: {$0.identifier == self.currentDisplayModel?.identifier}) else {
KPUserManager.sharedManager.currentUser?.visits?.append(self.currentDisplayModel!)
KPUserManager.sharedManager.storeUserInformation()
return
}
completion?(true)
print("Result\(result)")
}.catch { (error) in
print("Remove Visited Cafe error\(error)")
completion?(false)
}
}
func removeVisitedCafe(_ cafeID: String,
_ completion: ((Bool) -> Swift.Void)? = nil) {
let removeRequest = KPVisitedRequest()
removeRequest.perform(cafeID,
KPVisitedRequest.requestType.delete).then { result -> Void in
if let foundOffset = KPUserManager.sharedManager.currentUser?.visits?.index(where: {$0.identifier == cafeID}) {
KPUserManager.sharedManager.currentUser?.visits?.remove(at: foundOffset)
}
KPUserManager.sharedManager.storeUserInformation()
completion?(true)
print("Result\(result)")
}.catch { (error) in
print("Remove Visited Error \(error)")
completion?(false)
}
}
// MARK: Comment Voting
func updateCommentVoteStatus(_ cafeID: String?,
_ commentID: String,
_ type: voteType,
_ completion: ((Bool) -> Swift.Void)? = nil) {
let commentVoteRequest = KPCommentVoteRequest()
commentVoteRequest.perform(cafeID ?? (self.currentDisplayModel?.identifier)!,
type,
commentID).then { result -> Void in
if let voteResult = result["result"].bool {
if voteResult {
let notification = Notification.Name(KPNotification.information.commentInformation)
NotificationCenter.default.post(name: notification, object: nil)
}
completion?(voteResult)
}
completion?(true)
print("Result\(result)")
}.catch { (error) in
print("Like Comment Error \(error)")
completion?(false)
}
}
// MARK: Report
func sendReport(_ content: String,
_ completion: ((Bool) -> Swift.Void)? = nil) {
let loadingView = KPLoadingView(("回報中...", "回報成功", "回報失敗"))
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
loadingView.state = .successed
DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
completion?(true)
}
}
}
// MARK: Tag
func fetchTagList() {
let tagListRequest = KPFeatureTagRequest()
tagListRequest.perform().then {[unowned self] result -> Void in
if let tagResult = result["result"].bool, tagResult == true {
var tagList = [KPDataTagModel]()
for data in (result["data"].arrayObject)! {
if let tagData = KPDataTagModel(JSON: (data as! [String: Any])) {
tagList.append(tagData)
}
}
if tagList.count > 0 {
self.featureTags = tagList
}
}
}.catch { (error) in
print(error)
}
}
// MARK: Photo Upload
func uploadPhoto(_ cafeID: String?,
_ photoData: Data!,
_ showLoading: Bool = true,
_ completion: ((Bool) -> Swift.Void)? = nil) {
let loadingView = KPLoadingView(("上傳中...", "上傳成功", "上傳失敗"))
if showLoading {
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
}
let photoUploadRequest = KPPhotoUploadRequest()
photoUploadRequest.perform(cafeID ?? (currentDisplayModel?.identifier)!,
nil,
photoData).then {result -> Void in
loadingView.state = result["result"].boolValue ?
.successed :
.failed
completion?(result["result"].boolValue)
}.catch { (error) in
print("Error:\(error)")
completion?(false)
}
}
func uploadMenus(_ menus: [UIImage],
_ cafeID: String?,
_ showLoading: Bool = true,
_ completion: ((_ success: Bool) -> Void)?) {
let loadingView = KPLoadingView(("上傳中...", "上傳成功", "上傳失敗"))
if showLoading {
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
}
var uploadRequests = [Promise<(RawJsonResult)>]()
for menu in menus {
if let imageData = UIImageJPEGRepresentation(menu, 1) {
let uploadPhotoRequest = KPMenuUploadRequest()
let uploadPromise = uploadPhotoRequest.perform(cafeID ?? (currentDisplayModel?.identifier)!,
nil,
imageData)
uploadRequests.append(uploadPromise)
} else {
loadingView.state = .failed
completion?(false)
}
}
/*
The other two functions are when and join. Those fulfill after all the specified promises are fulfilled.
Where these two differ is in the rejected case.
join always waits for all the promises to complete before rejected if one of them rejects,
but when(fulfilled:) rejects as soon as any one of the promises rejects.
There’s also a when(resolved:) that waits for all the promises to complete, but always calls the then block and never the catch.
*/
join(uploadRequests).then { (result) -> Void in
print("result : \(result)")
if let uploadResult = result.first?["result"].bool {
if uploadResult {
let notification = Notification.Name(KPNotification.information.photoInformation)
NotificationCenter.default.post(name: notification, object: nil)
loadingView.state = .successed
if showLoading {
DispatchQueue.main.asyncAfter(deadline: .now()+1.0,
execute: {
KPPopoverView.popoverPhotoInReviewNotification()
})
}
} else {
loadingView.state = .failed
}
completion?(uploadResult)
} else {
loadingView.state = .failed
completion?(false)
}
}.catch { (error) in
print("error : \(error)")
completion?(false)
}
}
func uploadPhotos(_ photos: [UIImage],
_ cafeID: String?,
_ showLoading: Bool = true,
_ completion: ((_ success: Bool) -> Void)?) {
let loadingView = KPLoadingView(("上傳中...", "上傳成功", "上傳失敗"))
if showLoading {
UIApplication.shared.KPTopViewController().view.addSubview(loadingView)
loadingView.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
}
var uploadRequests = [Promise<(RawJsonResult)>]()
for photo in photos {
if let imageData = UIImageJPEGRepresentation(photo, 1) {
let uploadPhotoRequest = KPPhotoUploadRequest()
let uploadPromise = uploadPhotoRequest.perform(cafeID ?? (currentDisplayModel?.identifier)!,
nil,
imageData)
uploadRequests.append(uploadPromise)
} else {
// let uploadPhotoRequest = KPPhotoUploadRequest()
// let uploadPromise = uploadPhotoRequest.perform(cafeID ?? (currentDisplayModel?.identifier)!,
// nil,
// photo.jpegData(withQuality: 1))
// uploadRequests.append(uploadPromise)
loadingView.state = .failed
completion?(false)
}
}
/*
The other two functions are when and join. Those fulfill after all the specified promises are fulfilled.
Where these two differ is in the rejected case.
join always waits for all the promises to complete before rejected if one of them rejects,
but when(fulfilled:) rejects as soon as any one of the promises rejects.
There’s also a when(resolved:) that waits for all the promises to complete, but always calls the then block and never the catch.
*/
join(uploadRequests).then { (result) -> Void in
print("result : \(result)")
if let uploadResult = result.first?["result"].bool {
if uploadResult {
let notification = Notification.Name(KPNotification.information.photoInformation)
NotificationCenter.default.post(name: notification, object: nil)
loadingView.state = .successed
if showLoading {
DispatchQueue.main.asyncAfter(deadline: .now()+1.0,
execute: {
KPPopoverView.popoverPhotoInReviewNotification()
})
}
} else {
loadingView.state = .failed
}
completion?(uploadResult)
} else {
loadingView.state = .failed
completion?(false)
}
}.catch { (error) in
print("error : \(error)")
completion?(false)
}
}
}
| mit |
spiltcocoa/SCDomElementView | iOS Example/iOS Example/AppDelegate.swift | 1 | 2051 | //
// AppDelegate.swift
// iOS Example
//
// Created by Jeff Boek on 5/21/15.
// Copyright (c) 2015 spiltcocoa. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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:.
}
}
| mit |
RxSwiftCommunity/RxAlamofire | Sources/RxAlamofire/RxAlamofire.swift | 1 | 66658 | // swiftlint:disable file_length
import Alamofire
import Foundation
import RxSwift
/// Default instance of unknown error
public let RxAlamofireUnknownError = NSError(domain: "RxAlamofireDomain", code: -1, userInfo: nil)
// MARK: Convenience functions
/**
Creates a NSMutableURLRequest using all necessary parameters.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An instance of `NSMutableURLRequest`
*/
public func urlRequest(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
throws -> Foundation.URLRequest {
var mutableURLRequest = Foundation.URLRequest(url: try url.asURL())
mutableURLRequest.httpMethod = method.rawValue
if let headers = headers {
for header in headers {
mutableURLRequest.setValue(header.value, forHTTPHeaderField: header.name)
}
}
if let parameters = parameters {
mutableURLRequest = try encoding.encode(mutableURLRequest, with: parameters)
}
return mutableURLRequest
}
// MARK: Request
/**
Creates an observable of the generated `Request`.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of a the `Request`
*/
public func request(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<DataRequest> {
return Alamofire.Session.default.rx.request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
/**
Creates an observable of the generated `Request`.
- parameter urlRequest: An object adopting `URLRequestConvertible`
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of a the `Request`
*/
public func request(_ urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<DataRequest> {
return Alamofire.Session.default.rx.request(urlRequest: urlRequest, interceptor: interceptor)
}
// MARK: response
/**
Creates an observable of the `NSHTTPURLResponse` instance.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `NSHTTPURLResponse`
*/
public func requestResponse(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<HTTPURLResponse> {
return Alamofire.Session.default.rx.response(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
/**
Creates an observable of the `NSHTTPURLResponse` instance.
- parameter urlRequest: An object adopting `URLRequestConvertible`
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `NSHTTPURLResponse`
*/
public func requestResponse(_ urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<HTTPURLResponse> {
return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.response() }
}
/**
Creates an observable of the returned data.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `NSHTTPURLResponse`
*/
public func response(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<HTTPURLResponse> {
return Alamofire.Session.default.rx.response(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
// MARK: data
/**
Creates an observable of the `(NSHTTPURLResponse, NSData)` instance.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of a tuple containing `(NSHTTPURLResponse, NSData)`
*/
public func requestData(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<(HTTPURLResponse, Data)> {
return Alamofire.Session.default.rx.responseData(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
/**
Creates an observable of the `(NSHTTPURLResponse, NSData)` instance.
- parameter urlRequest: An object adopting `URLRequestConvertible`
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of a tuple containing `(NSHTTPURLResponse, NSData)`
*/
public func requestData(_ urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<(HTTPURLResponse, Data)> {
return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.responseData() }
}
/**
Creates an observable of the returned data.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `NSData`
*/
public func data(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<Data> {
return Alamofire.Session.default.rx.data(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
// MARK: string
/**
Creates an observable of the returned decoded string and response.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, String)`
*/
public func requestString(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<(HTTPURLResponse, String)> {
return Alamofire.Session.default.rx.responseString(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
/**
Creates an observable of the returned decoded string and response.
- parameter urlRequest: An object adopting `URLRequestConvertible`
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, String)`
*/
public func requestString(_ urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<(HTTPURLResponse, String)> {
return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.responseString() }
}
/**
Creates an observable of the returned decoded string.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `String`
*/
public func string(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<String> {
return Alamofire.Session.default.rx.string(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
// MARK: JSON
/**
Creates an observable of the returned decoded JSON as `AnyObject` and the response.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)`
*/
public func requestJSON(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<(HTTPURLResponse, Any)> {
return Alamofire.Session.default.rx.responseJSON(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
/**
Creates an observable of the returned decoded JSON as `AnyObject` and the response.
- parameter urlRequest: An object adopting `URLRequestConvertible`
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)`
*/
public func requestJSON(_ urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<(HTTPURLResponse, Any)> {
return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.responseJSON() }
}
/**
Creates an observable of the returned decoded JSON.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the decoded JSON as `Any`
*/
public func json(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<Any> {
return Alamofire.Session.default.rx.json(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
// MARK: Decodable
/**
Creates an observable of the returned decoded Decodable as `T` and the response.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, T)`
*/
public func requestDecodable<T: Decodable>(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<(HTTPURLResponse, T)> {
return Alamofire.Session.default.rx.responseDecodable(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
/**
Creates an observable of the returned decoded Decodable as `T` and the response.
- parameter urlRequest: An object adopting `URLRequestConvertible`
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, T)`
*/
public func requestDecodable<T: Decodable>(_ urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<(HTTPURLResponse, T)> {
return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.responseDecodable() }
}
/**
Creates an observable of the returned decoded Decodable.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the decoded Decodable as `T`
*/
public func decodable<T: Decodable>(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<T> {
return Alamofire.Session.default.rx.decodable(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
// MARK: Upload
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter file: An instance of NSURL holding the information of the local file.
- parameter urlRequest: The request object to start the upload.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: The observable of `UploadRequest` for the created request.
*/
public func upload(_ file: URL,
urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<UploadRequest> {
return Alamofire.Session.default.rx.upload(file, urlRequest: urlRequest, interceptor: interceptor)
}
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter file: An instance of `URL` holding the information of the local file.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `UploadRequest` for the created request.
*/
public func upload(_ file: URL,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<UploadRequest> {
return Alamofire.Session.default.rx.upload(file, to: url, method: method, headers: headers)
}
/**
Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter file: An instance of `URL` holding the information of the local file.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `RxProgress` for the created request.
*/
public func upload(_ file: URL,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<RxProgress> {
return Alamofire.Session.default.rx.upload(file, to: url, method: method, headers: headers)
}
/**
Returns an observable of a request using the shared manager instance to upload any data to a specified URL.
The request is started immediately.
- parameter data: An instance of NSData holdint the data to upload.
- parameter urlRequest: The request object to start the upload.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: The observable of `UploadRequest` for the created request.
*/
public func upload(_ data: Data,
urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<UploadRequest> {
return Alamofire.Session.default.rx.upload(data, urlRequest: urlRequest, interceptor: interceptor)
}
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter data: An instance of `Data` holding the information of the local file.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `UploadRequest` for the created request.
*/
public func upload(_ data: Data,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<UploadRequest> {
return Alamofire.Session.default.rx.upload(data, to: url, method: method, headers: headers)
}
/**
Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter data: An instance of `Data` holding the information of the local file.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `RxProgress` for the created request.
*/
public func upload(_ data: Data,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<RxProgress> {
return Alamofire.Session.default.rx.upload(data, to: url, method: method, headers: headers)
}
/**
Returns an observable of a request using the shared manager instance to upload any stream to a specified URL.
The request is started immediately.
- parameter stream: The stream to upload.
- parameter urlRequest: The request object to start the upload.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: The observable of `Request` for the created upload request.
*/
public func upload(_ stream: InputStream,
urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<UploadRequest> {
return Alamofire.Session.default.rx.upload(stream, urlRequest: urlRequest, interceptor: interceptor)
}
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter stream: The `InputStream` to upload.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `UploadRequest` for the created request.
*/
public func upload(_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<UploadRequest> {
return Alamofire.Session.default.rx.upload(stream, to: url, method: method, headers: headers)
}
/**
Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter stream: The `InputStream` to upload.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `RxProgress` for the created request.
*/
public func upload(_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<RxProgress> {
return Alamofire.Session.default.rx.upload(stream, to: url, method: method, headers: headers)
}
/**
Returns an observable of a request using the shared manager instance to upload any stream to a specified URL.
The request is started immediately.
- parameter multipartFormData: The block for building `MultipartFormData`.
- parameter urlRequest: The request object to start the upload.
- returns: The observable of `UploadRequest` for the created upload request.
*/
public func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
urlRequest: URLRequestConvertible) -> Observable<UploadRequest> {
return Alamofire.Session.default.rx.upload(multipartFormData: multipartFormData, urlRequest: urlRequest)
}
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter multipartFormData: The block for building `MultipartFormData`.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `UploadRequest` for the created request.
*/
public func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<UploadRequest> {
return Alamofire.Session.default.rx.upload(multipartFormData: multipartFormData, to: url, method: method, headers: headers)
}
/**
Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter multipartFormData: The block for building `MultipartFormData`.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `RxProgress` for the created request.
*/
public func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<RxProgress> {
return Alamofire.Session.default.rx.upload(multipartFormData: multipartFormData, to: url, method: method, headers: headers)
}
// MARK: Download
/**
Creates a download request using the shared manager instance for the specified URL request.
- parameter urlRequest: The URL request.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The observable of `DownloadRequest` for the created download request.
*/
public func download(_ urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
to destination: @escaping DownloadRequest.Destination) -> Observable<DownloadRequest> {
return Alamofire.Session.default.rx.download(urlRequest, interceptor: interceptor, to: destination)
}
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a
previous request cancellation.
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
information.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The observable of `Request` for the created download request.
*/
public func download(resumeData: Data,
interceptor: RequestInterceptor? = nil,
to destination: @escaping DownloadRequest.Destination) -> Observable<DownloadRequest> {
return Alamofire.Session.default.rx.download(resumeData: resumeData, interceptor: interceptor, to: destination)
}
// MARK: Manager - Extension of Manager
extension Alamofire.Session: ReactiveCompatible {}
protocol RxAlamofireRequest {
func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void)
func resume() -> Self
func cancel() -> Self
}
protocol RxAlamofireResponse {
var error: Error? { get }
}
extension DataResponse: RxAlamofireResponse {
var error: Error? {
switch result {
case let .failure(error):
return error
default:
return nil
}
}
}
extension DownloadResponse: RxAlamofireResponse {
var error: Error? {
switch result {
case let .failure(error):
return error
default:
return nil
}
}
}
extension DataRequest: RxAlamofireRequest {
func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) {
response { response in
completionHandler(response)
}
}
}
extension DownloadRequest: RxAlamofireRequest {
func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) {
response { response in
completionHandler(response)
}
}
}
public extension Reactive where Base: Alamofire.Session {
// MARK: Generic request convenience
/**
Creates an observable of the DataRequest.
- parameter createRequest: A function used to create a `Request` using a `Manager`
- returns: A generic observable of created data request
*/
internal func request<R: RxAlamofireRequest>(_ createRequest: @escaping (Alamofire.Session) throws -> R) -> Observable<R> {
return Observable.create { observer -> Disposable in
let request: R
do {
request = try createRequest(self.base)
observer.on(.next(request))
request.responseWith(completionHandler: { response in
if let error = response.error {
observer.on(.error(error))
} else {
observer.on(.completed)
}
})
if !self.base.startRequestsImmediately {
_ = request.resume()
}
return Disposables.create {
_ = request.cancel()
}
} catch {
observer.on(.error(error))
return Disposables.create()
}
}
}
/**
Creates an observable of the `Request`.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the `Request`
*/
func request(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<DataRequest> {
return request { manager in
manager.request(url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
}
}
/**
Creates an observable of the `Request`.
- parameter URLRequest: An object adopting `URLRequestConvertible`
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the `Request`
*/
func request(urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil)
-> Observable<DataRequest> {
return request { manager in
manager.request(urlRequest, interceptor: interceptor)
}
}
// MARK: response
/**
Creates an observable of the response
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `NSHTTPURLResponse`
*/
func response(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<HTTPURLResponse> {
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor).flatMap { $0.rx.response() }
}
// MARK: data
/**
Creates an observable of the data.
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, NSData)`
*/
func responseData(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<(HTTPURLResponse, Data)> {
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor).flatMap { $0.rx.responseData() }
}
/**
Creates an observable of the data.
- parameter URLRequest: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `NSData`
*/
func data(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<Data> {
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor).flatMap { $0.rx.data() }
}
// MARK: string
/**
Creates an observable of the tuple `(NSHTTPURLResponse, String)`.
- parameter url: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, String)`
*/
func responseString(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<(HTTPURLResponse, String)> {
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor).flatMap { $0.rx.responseString() }
}
/**
Creates an observable of the data encoded as String.
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `String`
*/
func string(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<String> {
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor)
.flatMap { (request) -> Observable<String> in
request.rx.string()
}
}
// MARK: JSON
/**
Creates an observable of the data decoded from JSON and processed as tuple `(NSHTTPURLResponse, AnyObject)`.
- parameter url: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)`
*/
func responseJSON(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<(HTTPURLResponse, Any)> {
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor).flatMap { $0.rx.responseJSON() }
}
/**
Creates an observable of the data decoded from JSON and processed as `AnyObject`.
- parameter URLRequest: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `AnyObject`
*/
func json(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<Any> {
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor).flatMap { $0.rx.json() }
}
// MARK: Decodable
/**
Creates an observable of the data decoded from Decodable and processed as tuple `(NSHTTPURLResponse, T)`.
- parameter url: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of the tuple `(NSHTTPURLResponse, T)`
*/
func responseDecodable<T: Decodable>(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<(HTTPURLResponse, T)> {
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor).flatMap { $0.rx.responseDecodable() }
}
/**
Creates an observable of the data decoded from Decodable and processed as `T`.
- parameter URLRequest: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: An observable of `T`
*/
func decodable<T: Decodable>(_ method: HTTPMethod,
_ url: URLConvertible,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil)
-> Observable<T> {
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers,
interceptor: interceptor).flatMap { $0.rx.decodable() }
}
// MARK: Upload
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter file: An instance of NSURL holding the information of the local file.
- parameter urlRequest: The request object to start the upload.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: The observable of `AnyObject` for the created request.
*/
func upload(_ file: URL,
urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<UploadRequest> {
return request { manager in
manager.upload(file, with: urlRequest, interceptor: interceptor)
}
}
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter file: An instance of `URL` holding the information of the local file.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `UploadRequest` for the created request.
*/
func upload(_ file: URL,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<UploadRequest> {
return request { manager in
manager.upload(file, to: url, method: method, headers: headers)
}
}
/**
Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter file: An instance of `URL` holding the information of the local file.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `RxProgress` for the created request.
*/
func upload(_ file: URL,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<RxProgress> {
return upload(file, to: url, method: method, headers: headers)
.flatMap { $0.rx.progress() }
}
/**
Returns an observable of a request using the shared manager instance to upload any data to a specified URL.
The request is started immediately.
- parameter data: An instance of Data holdint the data to upload.
- parameter urlRequest: The request object to start the upload.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: The observable of `UploadRequest` for the created request.
*/
func upload(_ data: Data,
urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<UploadRequest> {
return request { manager in
manager.upload(data, with: urlRequest, interceptor: interceptor)
}
}
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter data: An instance of `Data` holding the information of the local file.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `UploadRequest` for the created request.
*/
func upload(_ data: Data,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<UploadRequest> {
return request { manager in
manager.upload(data, to: url, method: method, headers: headers)
}
}
/**
Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter data: An instance of `Data` holding the information of the local file.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `RxProgress` for the created request.
*/
func upload(_ data: Data,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<RxProgress> {
return upload(data, to: url, method: method, headers: headers)
.flatMap { $0.rx.progress() }
}
/**
Returns an observable of a request using the shared manager instance to upload any stream to a specified URL.
The request is started immediately.
- parameter stream: The stream to upload.
- parameter urlRequest: The request object to start the upload.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- returns: The observable of `(NSData?, RxProgress)` for the created upload request.
*/
func upload(_ stream: InputStream,
urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil) -> Observable<UploadRequest> {
return request { manager in
manager.upload(stream, with: urlRequest, interceptor: interceptor)
}
}
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter stream: The `InputStream` to upload.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `UploadRequest` for the created request.
*/
func upload(_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<UploadRequest> {
return request { manager in
manager.upload(stream, to: url, method: method, headers: headers)
}
}
/**
Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter stream: The `InputStream` to upload.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `RxProgress` for the created request.
*/
func upload(_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<RxProgress> {
return upload(stream, to: url, method: method, headers: headers)
.flatMap { $0.rx.progress() }
}
/**
Returns an observable of a request using the shared manager instance to upload any stream to a specified URL.
The request is started immediately.
- parameter multipartFormData: The block for building `MultipartFormData`.
- parameter urlRequest: The request object to start the upload.
- returns: The observable of `UploadRequest` for the created upload request.
*/
func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
urlRequest: URLRequestConvertible) -> Observable<UploadRequest> {
return request { manager in
manager.upload(multipartFormData: multipartFormData, with: urlRequest)
}
}
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter multipartFormData: The block for building `MultipartFormData`.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `UploadRequest` for the created request.
*/
func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<UploadRequest> {
return request { manager in
manager.upload(multipartFormData: multipartFormData, to: url, method: method, headers: headers)
}
}
/**
Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter multipartFormData: The block for building `MultipartFormData`.
- parameter url: An object adopting `URLConvertible`
- parameter method: Alamofire method object
- parameter headers: A `HTTPHeaders` containing all the additional headers
- returns: The observable of `RxProgress` for the created request.
*/
func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
to url: URLConvertible,
method: HTTPMethod,
headers: HTTPHeaders? = nil) -> Observable<RxProgress> {
return upload(multipartFormData: multipartFormData, to: url, method: method, headers: headers)
.flatMap { $0.rx.progress() }
}
// MARK: Download
/**
Creates a download request using the shared manager instance for the specified URL request.
- parameter urlRequest: The URL request.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The observable of `(NSData?, RxProgress)` for the created download request.
*/
func download(_ urlRequest: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
to destination: @escaping DownloadRequest.Destination) -> Observable<DownloadRequest> {
return request { manager in
manager.download(urlRequest, interceptor: interceptor, to: destination)
}
}
/**
Creates a request using the shared manager instance for downloading with a resume data produced from a
previous request cancellation.
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
information.
- parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The observable of `(NSData?, RxProgress)` for the created download request.
*/
func download(resumeData: Data,
interceptor: RequestInterceptor? = nil,
to destination: @escaping DownloadRequest.Destination) -> Observable<DownloadRequest> {
return request { manager in
manager.download(resumingWith: resumeData, interceptor: interceptor, to: destination)
}
}
}
// MARK: Request - Common Response Handlers
public extension ObservableType where Element == DataRequest {
func responseJSON() -> Observable<DataResponse<Any, AFError>> {
return flatMap { $0.rx.responseJSON() }
}
func json(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable<Any> {
return flatMap { $0.rx.json(options: options) }
}
func responseString(encoding: String.Encoding? = nil) -> Observable<(HTTPURLResponse, String)> {
return flatMap { $0.rx.responseString(encoding: encoding) }
}
func string(encoding: String.Encoding? = nil) -> Observable<String> {
return flatMap { $0.rx.string(encoding: encoding) }
}
func responseData() -> Observable<(HTTPURLResponse, Data)> {
return flatMap { $0.rx.responseData() }
}
func response() -> Observable<HTTPURLResponse> {
return flatMap { $0.rx.response() }
}
func data() -> Observable<Data> {
return flatMap { $0.rx.data() }
}
func progress() -> Observable<RxProgress> {
return flatMap { $0.rx.progress() }
}
}
// MARK: Request - Validation
public extension ObservableType where Element == DataRequest {
func validate<S: Sequence>(statusCode: S) -> Observable<Element> where S.Element == Int {
return map { $0.validate(statusCode: statusCode) }
}
func validate() -> Observable<Element> {
return map { $0.validate() }
}
func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Observable<Element> where S.Iterator.Element == String {
return map { $0.validate(contentType: acceptableContentTypes) }
}
func validate(_ validation: @escaping DataRequest.Validation) -> Observable<Element> {
return map { $0.validate(validation) }
}
}
extension Request: ReactiveCompatible {}
public extension Reactive where Base: DataRequest {
// MARK: Defaults
/**
Transform a request into an observable of the response
- parameter queue: The dispatch queue to use.
- returns: The observable of `NSHTTPURLResponse` for the created request.
*/
func response(queue: DispatchQueue = .main)
-> Observable<HTTPURLResponse> {
return Observable.create { observer in
let dataRequest = self.base
.response(queue: queue) { (packedResponse) -> Void in
switch packedResponse.result {
case .success:
if let httpResponse = packedResponse.response {
observer.on(.next(httpResponse))
observer.on(.completed)
} else {
observer.on(.error(RxAlamofireUnknownError))
}
case let .failure(error):
observer.on(.error(error as Error))
}
}
return Disposables.create {
dataRequest.cancel()
}
}
}
/**
Transform a request into an observable of the response and serialized object.
- parameter queue: The dispatch queue to use.
- parameter responseSerializer: The the serializer.
- returns: The observable of `(NSHTTPURLResponse, T.SerializedObject)` for the created download request.
*/
func responseResult<T: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
responseSerializer: T)
-> Observable<(HTTPURLResponse, T.SerializedObject)> {
return Observable.create { observer in
let dataRequest = self.base
.response(queue: queue, responseSerializer: responseSerializer) { (packedResponse) -> Void in
switch packedResponse.result {
case let .success(result):
if let httpResponse = packedResponse.response {
observer.on(.next((httpResponse, result)))
observer.on(.completed)
} else {
observer.on(.error(RxAlamofireUnknownError))
}
case let .failure(error):
observer.on(.error(error as Error))
}
}
return Disposables.create {
dataRequest.cancel()
}
}
}
func responseJSON() -> Observable<DataResponse<Any, AFError>> {
return Observable.create { observer in
let request = self.base
request.responseJSON { response in
switch response.result {
case .success:
observer.on(.next(response))
observer.on(.completed)
case let .failure(error):
observer.on(.error(error))
}
}
return Disposables.create {
request.cancel()
}
}
}
/**
Transform a request into an observable of the serialized object.
- parameter queue: The dispatch queue to use.
- parameter responseSerializer: The the serializer.
- returns: The observable of `T.SerializedObject` for the created download request.
*/
func result<T: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
responseSerializer: T)
-> Observable<T.SerializedObject> {
return Observable.create { observer in
let dataRequest = self.base
.response(queue: queue, responseSerializer: responseSerializer) { (packedResponse) -> Void in
switch packedResponse.result {
case let .success(result):
if packedResponse.response != nil {
observer.on(.next(result))
observer.on(.completed)
} else {
observer.on(.error(RxAlamofireUnknownError))
}
case let .failure(error):
observer.on(.error(error as Error))
}
}
return Disposables.create {
dataRequest.cancel()
}
}
}
/**
Returns an `Observable` of NSData for the current request.
- parameter cancelOnDispose: Indicates if the request has to be canceled when the observer is disposed, **default:** `false`
- returns: An instance of `Observable<NSData>`
*/
func responseData() -> Observable<(HTTPURLResponse, Data)> {
return responseResult(responseSerializer: DataResponseSerializer())
}
func data() -> Observable<Data> {
return result(responseSerializer: DataResponseSerializer())
}
/**
Returns an `Observable` of a String for the current request
- parameter encoding: Type of the string encoding, **default:** `nil`
- returns: An instance of `Observable<String>`
*/
func responseString(encoding: String.Encoding? = nil) -> Observable<(HTTPURLResponse, String)> {
return responseResult(responseSerializer: StringResponseSerializer(encoding: encoding))
}
func string(encoding: String.Encoding? = nil) -> Observable<String> {
return result(responseSerializer: StringResponseSerializer(encoding: encoding))
}
/**
Returns an `Observable` of a serialized JSON for the current request.
- parameter options: Reading options for JSON decoding process, **default:** `.AllowFragments`
- returns: An instance of `Observable<AnyObject>`
*/
func responseJSON(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable<(HTTPURLResponse, Any)> {
return responseResult(responseSerializer: JSONResponseSerializer(options: options))
}
/**
Returns an `Observable` of a serialized JSON for the current request.
- parameter options: Reading options for JSON decoding process, **default:** `.AllowFragments`
- returns: An instance of `Observable<AnyObject>`
*/
func json(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable<Any> {
return result(responseSerializer: JSONResponseSerializer(options: options))
}
/**
Returns an `Observable` of a serialized Decodable for the current request.
- parameter decoder: The `DataDecoder`. `JSONDecoder()` by default.
- returns: An instance of `Observable<(HTTPURLResponse, T)>`
*/
func responseDecodable<T: Decodable>(decoder: Alamofire.DataDecoder = JSONDecoder()) -> Observable<(HTTPURLResponse, T)> {
return responseResult(responseSerializer: DecodableResponseSerializer(decoder: decoder))
}
/**
Returns an `Observable` of a serialized Decodable for the current request.
- parameter decoder: The `DataDecoder`. `JSONDecoder()` by default.
- returns: An instance of `Observable<T>`
*/
func decodable<T: Decodable>(decoder: Alamofire.DataDecoder = JSONDecoder()) -> Observable<T> {
return result(responseSerializer: DecodableResponseSerializer(decoder: decoder))
}
}
public extension Reactive where Base: Request {
// MARK: Request - Upload and download progress
/**
Returns an `Observable` for the current progress status.
Parameters on observed tuple:
1. bytes written so far.
1. total bytes to write.
- returns: An instance of `Observable<RxProgress>`
*/
func progress() -> Observable<RxProgress> {
return Observable.create { observer in
let handler: Request.ProgressHandler = { progress in
let rxProgress = RxProgress(bytesWritten: progress.completedUnitCount,
totalBytes: progress.totalUnitCount)
observer.on(.next(rxProgress))
if rxProgress.bytesWritten >= rxProgress.totalBytes {
observer.on(.completed)
}
}
// Try in following order:
// - UploadRequest (Inherits from DataRequest, so we test the discrete case first)
// - DownloadRequest
// - DataRequest
if let uploadReq = self.base as? UploadRequest {
uploadReq.uploadProgress(closure: handler)
} else if let downloadReq = self.base as? DownloadRequest {
downloadReq.downloadProgress(closure: handler)
} else if let dataReq = self.base as? DataRequest {
dataReq.downloadProgress(closure: handler)
}
return Disposables.create()
}
// warm up a bit :)
.startWith(RxProgress(bytesWritten: 0, totalBytes: 0))
}
}
// MARK: RxProgress
public struct RxProgress {
public let bytesWritten: Int64
public let totalBytes: Int64
public init(bytesWritten: Int64, totalBytes: Int64) {
self.bytesWritten = bytesWritten
self.totalBytes = totalBytes
}
}
public extension RxProgress {
var bytesRemaining: Int64 {
return totalBytes - bytesWritten
}
var completed: Float {
if totalBytes > 0 {
return Float(bytesWritten) / Float(totalBytes)
} else {
return 0
}
}
}
extension RxProgress: Equatable {}
public func ==(lhs: RxProgress, rhs: RxProgress) -> Bool {
return lhs.bytesWritten == rhs.bytesWritten &&
lhs.totalBytes == rhs.totalBytes
}
| mit |
zachmokahn/SUV | Sources/SUV/IO/Buf/Buffer.swift | 1 | 810 | public class Buffer {
public let pointer: UnsafeMutablePointer<UVBufferType>
public var size: Int {
return pointer.memory.len
}
public init(_ pointer: UnsafePointer<UVBufferType>, _ size: Int, uv_buf_init: BufferInit = UVBufferInit) {
self.pointer = UnsafeMutablePointer.alloc(size)
self.pointer.memory = uv_buf_init(pointer.memory.base, UInt32(size))
}
public init(size: UInt32 = UInt32(sizeof(CChar)), uv_buf_init: BufferInit = UVBufferInit) {
self.pointer = UnsafeMutablePointer.alloc(sizeof(UVBufferType))
self.pointer.memory = uv_buf_init(UnsafeMutablePointer<CChar>.alloc(Int(size)), size)
}
public convenience init(_ original: Buffer, _ size: Int) {
self.init(size: UInt32(size))
memcpy(self.pointer.memory.base, original.pointer.memory.base, size)
}
}
| mit |
mscline/TTDWeatherApp | PigLatin/TextFormatter.swift | 1 | 2578 | //
// TextFormatter.swift
// BlogSplitScreenScroll
//
// Created by xcode on 1/9/15.
// Copyright (c) 2015 MSCline. All rights reserved.
//
import UIKit
class TextFormatter: NSObject {
class func createAttributedString(text: NSString, withFont: String?, fontSize:CGFloat?, fontColor:UIColor?, nsTextAlignmentStyle:NSTextAlignment?) -> (NSAttributedString)
{
// create attributed string to work with
let artString = NSMutableAttributedString(string: text as String)
// check to make sure have all our values
if (text == ""){ return artString;}
let theFont = withFont ?? "Palatino-Roman"
let theFontSize = fontSize ?? 12.0
let theFontColor = fontColor ?? UIColor.blackColor()
let textAlignmentStyle = nsTextAlignmentStyle ?? NSTextAlignment.Left
// prep work - build font, paragraph style, range
let fontX = UIFont(name: theFont, size: theFontSize) ?? UIFont(name: "Palatino-Roman", size: 12.0)
let artStringRange = NSMakeRange(0, artString.length) ?? NSMakeRange(0, 0)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = textAlignmentStyle;
// set attributes
artString.addAttribute(NSFontAttributeName, value:fontX!, range: artStringRange)
artString.addAttribute(NSForegroundColorAttributeName, value:theFontColor, range: artStringRange)
artString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range: artStringRange)
return artString;
}
class func combineAttributedStrings(arrayOfAttributedStrings:Array<NSAttributedString>) -> (NSAttributedString)
{
let artString = NSMutableAttributedString()
for insertMe:NSAttributedString in arrayOfAttributedStrings {
artString.appendAttributedString(insertMe)
}
return artString;
}
class func returnHeightOfAttributedStringGivenFixedHeightOrWidth(attributedString attrString: NSAttributedString!, maxWidth:CGFloat!, maxHeight: CGFloat!) -> (CGFloat) {
let maxWidth = maxWidth
let maxHeight = maxHeight
var desiredFrameHeight = attrString.boundingRectWithSize(CGSizeMake(maxWidth, maxHeight), options:NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil).size.height
// ??? NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading
return desiredFrameHeight
}
class func printListOfFontFamilyNames(){
println(UIFont.familyNames())
}
}
| mit |
swiftcodex/Universal-Game-Template-tvOS-OSX-iOS | Game Template iOS/GameViewController.swift | 1 | 1431 | //
// GameViewController.swift
// Universal Game Template
//
// Created by Matthew Fecher on 12/4/15.
// Copyright (c) 2015 Denver Swift Heads. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit |
rice-apps/wellbeing-app | app/Pods/Socket.IO-Client-Swift/Source/SocketParsable.swift | 2 | 6172 | //
// SocketParsable.swift
// Socket.IO-Client-Swift
//
// 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
protocol SocketParsable {
func parseBinaryData(_ data: Data)
func parseSocketMessage(_ message: String)
}
extension SocketParsable where Self: SocketIOClientSpec {
private func isCorrectNamespace(_ nsp: String) -> Bool {
return nsp == self.nsp
}
private func handleConnect(_ packetNamespace: String) {
if packetNamespace == "/" && nsp != "/" {
joinNamespace(nsp)
} else {
didConnect()
}
}
private func handlePacket(_ pack: SocketPacket) {
switch pack.type {
case .event where isCorrectNamespace(pack.nsp):
handleEvent(pack.event, data: pack.args, isInternalMessage: false, withAck: pack.id)
case .ack where isCorrectNamespace(pack.nsp):
handleAck(pack.id, data: pack.data)
case .binaryEvent where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .binaryAck where isCorrectNamespace(pack.nsp):
waitingPackets.append(pack)
case .connect:
handleConnect(pack.nsp)
case .disconnect:
didDisconnect(reason: "Got Disconnect")
case .error:
handleEvent("error", data: pack.data, isInternalMessage: true, withAck: pack.id)
default:
DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
}
}
/// Parses a messsage from the engine. Returning either a string error or a complete SocketPacket
func parseString(_ message: String) -> Either<String, SocketPacket> {
var reader = SocketStringReader(message: message)
guard let type = Int(reader.read(count: 1)).flatMap({ SocketPacket.PacketType(rawValue: $0) }) else {
return .left("Invalid packet type")
}
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: "/"))
}
var namespace = "/"
var placeholders = -1
if type == .binaryEvent || type == .binaryAck {
if let holders = Int(reader.readUntilOccurence(of: "-")) {
placeholders = holders
} else {
return .left("Invalid packet")
}
}
if reader.currentCharacter == "/" {
namespace = reader.readUntilOccurence(of: ",")
}
if !reader.hasNext {
return .right(SocketPacket(type: type, nsp: namespace, placeholders: placeholders))
}
var idString = ""
if type == .error {
reader.advance(by: -1)
} else {
while reader.hasNext {
if let int = Int(reader.read(count: 1)) {
idString += String(int)
} else {
reader.advance(by: -2)
break
}
}
}
var dataArray = message[message.characters.index(reader.currentIndex, offsetBy: 1)..<message.endIndex]
if type == .error && !dataArray.hasPrefix("[") && !dataArray.hasSuffix("]") {
dataArray = "[" + dataArray + "]"
}
switch parseData(dataArray) {
case let .left(err):
return .left(err)
case let .right(data):
return .right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
nsp: namespace, placeholders: placeholders))
}
}
// Parses data for events
private func parseData(_ data: String) -> Either<String, [Any]> {
do {
return .right(try data.toArray())
} catch {
return .left("Error parsing data for packet")
}
}
// Parses messages recieved
func parseSocketMessage(_ message: String) {
guard !message.isEmpty else { return }
DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message)
switch parseString(message) {
case let .left(err):
DefaultSocketLogger.Logger.error("\(err): %@", type: "SocketParser", args: message)
case let .right(pack):
DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description)
handlePacket(pack)
}
}
func parseBinaryData(_ data: Data) {
guard !waitingPackets.isEmpty else {
DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser")
return
}
// Should execute event?
guard waitingPackets[waitingPackets.count - 1].addData(data) else { return }
let packet = waitingPackets.removeLast()
if packet.type != .binaryAck {
handleEvent(packet.event, data: packet.args, isInternalMessage: false, withAck: packet.id)
} else {
handleAck(packet.id, data: packet.args)
}
}
}
| mit |
embryoconcepts/TIY-Assignments | 23 -- InDueTimeParsed/InDueTime/InDueTime/ToDoCell.swift | 2 | 581 | //
// ToDoCell.swift
// InDueTime
//
// Created by Jennifer Hamilton on 10/20/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class ToDoCell: UITableViewCell
{
@IBOutlet weak var checkbox: UIButton!
@IBOutlet weak var todoTextField: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| cc0-1.0 |
huonw/swift | validation-test/compiler_crashers_fixed/27601-swift-inflightdiagnostic.swift | 65 | 451 | // 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
// RUN: not %target-swift-frontend %s -typecheck
let a{{func a<T{b{{}struct S{var _=[V{{if{func a{a=F
| apache-2.0 |
radu-costea/ATests | ATests/ATests/UI/ImageSimulationQuestionTableViewCell.swift | 1 | 1249 | //
// ImageSimulationQuestionTableViewCell.swift
// ATests
//
// Created by Radu Costea on 15/06/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import UIKit
import Parse
class ImageSimulationQuestionTableViewCell: SimulationQuestionTableViewCell {
@IBOutlet var questionImage: UIImageView!
var imageContent: ParseImageContent?
var img: UIImage? = nil {
didSet {
questionImage?.image = img
}
}
override var builder: ParseExamQuestionBuilder? {
didSet {
imageContent = builder?.question.content as? ParseImageContent
getImage(imageContent)
refresh()
}
}
override func refresh() {
super.refresh()
questionImage?.image = img
}
/// MARK: -
/// MARK: Download image
var getImageOperation: NSBlockOperation?
func getImage(content: ParseImageContent?) {
content?.image?.cancel()
let currentContent = content
content?.image?.getImageInBackgroundWithBlock({ [weak self, weak currentContent] (img, error) in
guard let wSelf = self where currentContent === wSelf.imageContent else { return }
wSelf.img = img
})
}
}
| mit |
grpc/grpc-swift | Sources/GRPC/ConnectionPool/StreamLender.swift | 1 | 965 | /*
* Copyright 2021, gRPC Authors All rights reserved.
*
* 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.
*/
@usableFromInline
internal protocol StreamLender {
/// `count` streams are being returned to the given `pool`.
func returnStreams(_ count: Int, to pool: ConnectionPool)
/// Update the total number of streams which may be available at given time for `pool` by `delta`.
func changeStreamCapacity(by delta: Int, for pool: ConnectionPool)
}
| apache-2.0 |
kumapo/RxSwiftTestSchedulerExample | RxSwiftTestSchedulerExample/AppDelegate.swift | 1 | 2158 | //
// AppDelegate.swift
// RxSwiftTestSchedulerExample
//
// Created by kumapo on 2015/12/17.
// Copyright © 2015年 kumapo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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:.
}
}
| mit |
barteljan/VISPER | VISPER/Classes/Bridge/Bridge-Core.swift | 2 | 1479 | //
// BridgeCore.swift
// VISPER
//
// Created by bartel on 06.01.18.
//
import Foundation
import VISPER_Core
public typealias Action = VISPER_Core.Action
public typealias ActionDispatcher = VISPER_Core.ActionDispatcher
public typealias App = VISPER_Core.App
public typealias ControllerContainer = VISPER_Core.ControllerContainer
public typealias ControllerDismisser = VISPER_Core.ControllerDismisser
public typealias ControllerPresenter = VISPER_Core.ControllerPresenter
public typealias ControllerProvider = VISPER_Core.ControllerProvider
public typealias DefaultApp = VISPER_Core.DefaultApp
public typealias Feature = VISPER_Core.Feature
public typealias FeatureObserver = VISPER_Core.FeatureObserver
public typealias Presenter = VISPER_Core.Presenter
public typealias PresenterProvider = VISPER_Core.PresenterProvider
public typealias RouteResult = VISPER_Core.RouteResult
public typealias RoutingAwareViewController = VISPER_Core.RoutingAwareViewController
public typealias RoutingDelegate = VISPER_Core.RoutingDelegate
public typealias RoutingHandler = VISPER_Core.RoutingHandler
public typealias RoutingObserver = VISPER_Core.RoutingObserver
public typealias RoutingOption = VISPER_Core.RoutingOption
public typealias RoutingOptionProvider = VISPER_Core.RoutingOptionProvider
public typealias RoutingPresenter = VISPER_Core.RoutingPresenter
public typealias TopControllerResolver = VISPER_Core.TopControllerResolver
public typealias Wireframe = VISPER_Core.Wireframe
| mit |
sm00th1980/compass | animation.example.swift | 1 | 705 | [UIView animateWithDuration:1.0
delay:0.0
usingSpringWithDamping:0.8
initialSpringVelocity:1.0
options:0 animations:^{
CGPoint newPosition = self.myView.frame.origin;
newPosition.x += 50;
self.myView.frame.origin = newPosition;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.5
delay:0.0
options:UIViewAnimationOptionCurveEaseIn
animations:^{
self.myView.backgroundColor = [UIColor purpleColor];
} completion:nil];
}]; | mit |
Aadeshp/AsyncKit | AsyncKit/Classes/Executor.swift | 1 | 1866 | //
// AsyncKit
// Executor.swift
//
// Copyright (c) 2016 Aadesh Patel. All rights reserved.
//
//
import UIKit
/// Service that executes a block in the specified executor queue
internal class Executor {
/// Queue to execute block in
private var type: ExecutorType!
internal init(type: ExecutorType) {
self.type = type
}
/**
Executes block within the queue specified
- parameter type: Executor queue to execute block in
- parameter block: Block to execute
*/
internal func execute(block: dispatch_block_t) {
self.executionBlock(block)()
}
internal func executionBlock<T>(block: (T) -> Void) -> ((T) -> Void) {
let wrappedBlock = { (t: T) -> Void in
block(t)
}
switch(self.type!) {
case .Current:
return block
default:
return self.createDispatchBlock(self.type.queue, block: wrappedBlock)
}
}
private func createDispatchBlock<T>(queue: AKQueue, block: (T) -> Void) -> ((T) -> Void) {
let wrappedBlock = { (t: T) -> Void in
queue.async {
block(t)
}
}
return wrappedBlock
}
}
/// Queue executor enum
public enum ExecutorType {
/// Main Queue
case Main
/// Queue used in previous task block
case Current
/// Default priority global queue
case Async
/// Custom queue
case Queue(dispatch_queue_t)
/// Gets queue object based on ExecutorType
internal var queue: AKQueue {
get {
switch(self) {
case .Main:
return AKQueue.main
case let .Queue(queue):
return AKQueue(queue)
default:
return AKQueue.def
}
}
}
}
| mit |
brokenhandsio/SteamPress | Tests/SteamPressTests/AdminTests/AccessControlTests.swift | 1 | 4207 | import XCTest
import Vapor
import SteamPress
class AccessControlTests: XCTestCase {
// MARK: - Properties
private var app: Application!
private var testWorld: TestWorld!
private var user: BlogUser!
// MARK: - Overrides
override func setUp() {
testWorld = try! TestWorld.create(path: "blog")
user = testWorld.createUser()
}
override func tearDown() {
XCTAssertNoThrow(try testWorld.tryAsHardAsWeCanToShutdownApplication())
}
// MARK: - Tests
// MARK: - Access restriction tests
func testCannotAccessAdminPageWithoutBeingLoggedIn() throws {
try assertLoginRequired(method: .GET, path: "")
}
func testCannotAccessCreateBlogPostPageWithoutBeingLoggedIn() throws {
try assertLoginRequired(method: .GET, path: "createPost")
}
func testCannotSendCreateBlogPostPageWithoutBeingLoggedIn() throws {
try assertLoginRequired(method: .POST, path: "createPost")
}
func testCannotAccessEditPostPageWithoutLogin() throws {
let post = try testWorld.createPost()
try assertLoginRequired(method: .GET, path: "posts/\(post.post.blogID!)/edit")
}
func testCannotSendEditPostPageWithoutLogin() throws {
let post = try testWorld.createPost()
try assertLoginRequired(method: .POST, path: "posts/\(post.post.blogID!)/edit")
}
func testCannotAccessCreateUserPageWithoutLogin() throws {
try assertLoginRequired(method: .GET, path: "createUser")
}
func testCannotSendCreateUserPageWithoutLogin() throws {
try assertLoginRequired(method: .POST, path: "createUser")
}
func testCannotAccessEditUserPageWithoutLogin() throws {
try assertLoginRequired(method: .GET, path: "users/1/edit")
}
func testCannotSendEditUserPageWithoutLogin() throws {
try assertLoginRequired(method: .POST, path: "users/1/edit")
}
func testCannotDeletePostWithoutLogin() throws {
try assertLoginRequired(method: .POST, path: "posts/1/delete")
}
func testCannotDeleteUserWithoutLogin() throws {
try assertLoginRequired(method: .POST, path: "users/1/delete")
}
func testCannotAccessResetPasswordPageWithoutLogin() throws {
try assertLoginRequired(method: .GET, path: "resetPassword")
}
func testCannotSendResetPasswordPageWithoutLogin() throws {
try assertLoginRequired(method: .POST, path: "resetPassword")
}
// MARK: - Access Success Tests
func testCanAccessAdminPageWhenLoggedIn() throws {
let response = try testWorld.getResponse(to: "/blog/admin/", loggedInUser: user)
XCTAssertEqual(response.http.status, .ok)
}
func testCanAccessCreatePostPageWhenLoggedIn() throws {
let response = try testWorld.getResponse(to: "/blog/admin/createPost", loggedInUser: user)
XCTAssertEqual(response.http.status, .ok)
}
func testCanAccessEditPostPageWhenLoggedIn() throws {
let post = try testWorld.createPost()
let response = try testWorld.getResponse(to: "/blog/admin/posts/\(post.post.blogID!)/edit", loggedInUser: user)
XCTAssertEqual(response.http.status, .ok)
}
func testCanAccessCreateUserPageWhenLoggedIn() throws {
let response = try testWorld.getResponse(to: "/blog/admin/createUser", loggedInUser: user)
XCTAssertEqual(response.http.status, .ok)
}
func testCanAccessEditUserPageWhenLoggedIn() throws {
let response = try testWorld.getResponse(to: "/blog/admin/users/1/edit", loggedInUser: user)
XCTAssertEqual(response.http.status, .ok)
}
func testCanAccessResetPasswordPage() throws {
let response = try testWorld.getResponse(to: "/blog/admin/resetPassword", loggedInUser: user)
XCTAssertEqual(response.http.status, .ok)
}
// MARK: - Helpers
private func assertLoginRequired(method: HTTPMethod, path: String) throws {
let response = try testWorld.getResponse(to: "/blog/admin/\(path)", method: method)
XCTAssertEqual(response.http.status, .seeOther)
XCTAssertEqual(response.http.headers[.location].first, "/blog/admin/login/?loginRequired")
}
}
| mit |
mobilabsolutions/jenkins-ios | JenkinsiOS/Controller/AccountsViewController.swift | 1 | 9843 | //
// AccountsTableViewController.swift
// JenkinsiOS
//
// Created by Robert on 25.09.16.
// Copyright © 2016 MobiLab Solutions. All rights reserved.
//
import UIKit
protocol CurrentAccountProviding {
var account: Account? { get }
var currentAccountDelegate: CurrentAccountProvidingDelegate? { get set }
}
protocol CurrentAccountProvidingDelegate: class {
func didChangeCurrentAccount(current: Account)
}
protocol AccountDeletionNotified: class {
func didDeleteAccount(account: Account)
}
protocol AccountDeletionNotifying: class {
var accountDeletionDelegate: AccountDeletionNotified? { get set }
}
class AccountsViewController: UIViewController, AccountProvidable, UITableViewDelegate, UITableViewDataSource,
CurrentAccountProviding, AddAccountTableViewControllerDelegate, AccountDeletionNotifying {
weak var currentAccountDelegate: CurrentAccountProvidingDelegate?
weak var accountDeletionDelegate: AccountDeletionNotified?
@IBOutlet var tableView: UITableView!
@IBOutlet var newAccountButton: BigButton!
var account: Account?
private var hasAccounts: Bool {
return AccountManager.manager.accounts.isEmpty == false
}
private lazy var handler = { OnBoardingHandler() }()
// MARK: - View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = Constants.UI.backgroundColor
navigationItem.rightBarButtonItem = editButtonItem
title = "Accounts"
tableView.backgroundColor = Constants.UI.backgroundColor
tableView.tableHeaderView?.backgroundColor = Constants.UI.backgroundColor
tableView.separatorStyle = .none
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: tableView.frame.maxY - newAccountButton.frame.minY + 32, right: 0)
newAccountButton.addTarget(self, action: #selector(showAddAccountViewController), for: .touchUpInside)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
setBackNavigation(enabled: account != nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
LoggingManager.loggingManager.logAccountOverviewView()
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.reloadData()
}
// MARK: - View controller navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Constants.Identifiers.editAccountSegue, let dest = segue.destination as? AddAccountContainerViewController, let indexPath = sender as? IndexPath {
prepare(viewController: dest, indexPath: indexPath)
} else if let dest = segue.destination as? AddAccountContainerViewController {
dest.delegate = self
}
navigationController?.isToolbarHidden = true
}
fileprivate func prepare(viewController: UIViewController, indexPath: IndexPath) {
if let addAccountViewController = viewController as? AddAccountContainerViewController {
addAccountViewController.account = AccountManager.manager.accounts[indexPath.row]
addAccountViewController.delegate = self
addAccountViewController.editingCurrentAccount = addAccountViewController.account == account
}
}
@objc func showAddAccountViewController() {
performSegue(withIdentifier: Constants.Identifiers.editAccountSegue, sender: nil)
}
func didEditAccount(account: Account, oldAccount: Account?, useAsCurrentAccount: Bool) {
if useAsCurrentAccount {
self.account = account
currentAccountDelegate?.didChangeCurrentAccount(current: account)
}
var shouldAnimateNavigationStackChanges = true
if oldAccount == nil {
let confirmationController = AccountCreatedViewController(nibName: "AccountCreatedViewController", bundle: .main)
confirmationController.delegate = self
navigationController?.pushViewController(confirmationController, animated: true)
shouldAnimateNavigationStackChanges = false
}
var viewControllers = navigationController?.viewControllers ?? []
// Remove the add account view controller from the navigation controller stack
viewControllers = viewControllers.filter { !($0 is AddAccountContainerViewController) }
navigationController?.setViewControllers(viewControllers, animated: shouldAnimateNavigationStackChanges)
tableView.reloadData()
}
func didDeleteAccount(account: Account) {
let didDeleteSelectedAccount = account == self.account
tableView.reloadData()
if AccountManager.manager.accounts.isEmpty && handler.shouldShowAccountCreationViewController() {
let navigationController = UINavigationController()
present(navigationController, animated: false, completion: nil)
handler.showAccountCreationViewController(on: navigationController, delegate: self)
} else if !AccountManager.manager.accounts.isEmpty && didDeleteSelectedAccount, let selectedAccount = AccountManager.manager.accounts.first {
self.account = selectedAccount
currentAccountDelegate?.didChangeCurrentAccount(current: selectedAccount)
AccountManager.manager.currentAccount = selectedAccount
tableView.reloadSections([0], with: .automatic)
}
if navigationController?.topViewController != self {
navigationController?.popViewController(animated: true)
}
accountDeletionDelegate?.didDeleteAccount(account: account)
}
// MARK: - Tableview datasource and delegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.accountCell, for: indexPath) as! BasicTableViewCell
let account = AccountManager.manager.accounts[indexPath.row]
cell.title = AccountManager.manager.accounts[indexPath.row].displayName ?? account.baseUrl.absoluteString
if isEditing {
cell.nextImageType = .next
cell.selectionStyle = .default
} else {
cell.nextImageType = account.baseUrl == self.account?.baseUrl ? .checkmark : .none
cell.selectionStyle = .none
}
return cell
}
func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return AccountManager.manager.accounts.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedAccount = AccountManager.manager.accounts[indexPath.row]
if isEditing {
performSegue(withIdentifier: Constants.Identifiers.editAccountSegue, sender: indexPath)
} else if selectedAccount.baseUrl != account?.baseUrl {
account = selectedAccount
currentAccountDelegate?.didChangeCurrentAccount(current: selectedAccount)
AccountManager.manager.currentAccount = selectedAccount
setBackNavigation(enabled: true)
tableView.reloadSections([0], with: .automatic)
}
}
func numberOfSections(in _: UITableView) -> Int {
return hasAccounts ? 1 : 0
}
func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && !hasAccounts {
return 0
}
return 44
}
func tableView(_: UITableView, canEditRowAt _: IndexPath) -> Bool {
return true
}
func tableView(_: UITableView, editingStyleForRowAt _: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
func tableView(_: UITableView, shouldIndentWhileEditingRowAt _: IndexPath) -> Bool {
return false
}
func tableView(_: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return [
UITableViewRowAction(style: .destructive, title: "Delete", handler: { _, indexPath in
self.deleteAccount(at: indexPath)
}),
UITableViewRowAction(style: .normal, title: "Edit", handler: { _, indexPath in
self.performSegue(withIdentifier: Constants.Identifiers.editAccountSegue, sender: indexPath)
}),
]
}
func tableView(_: UITableView, willDisplay cell: UITableViewCell, forRowAt _: IndexPath) {
cell.backgroundColor = .clear
}
private func deleteAccount(at indexPath: IndexPath) {
do {
let accountToDelete = AccountManager.manager.accounts[indexPath.row]
try AccountManager.manager.deleteAccount(account: accountToDelete)
didDeleteAccount(account: accountToDelete)
} catch {
displayError(title: "Error", message: "Something went wrong", textFieldConfigurations: [], actions: [
UIAlertAction(title: "Alright", style: .cancel, handler: nil),
])
tableView.reloadData()
}
}
private func setBackNavigation(enabled: Bool) {
navigationItem.hidesBackButton = !enabled
navigationController?.interactivePopGestureRecognizer?.isEnabled = enabled
}
}
extension AccountsViewController: OnBoardingDelegate {
func didFinishOnboarding(didAddAccount _: Bool) {
dismiss(animated: true, completion: nil)
}
}
extension AccountsViewController: AccountCreatedViewControllerDelegate {
func doneButtonPressed() {
navigationController?.popViewController(animated: true)
}
}
| mit |
jmgc/swift | test/AutoDiff/compiler_crashers_fixed/sr12641-silgen-immutable-address-use-verification-failure.swift | 1 | 3849 | // RUN: %target-swift-frontend -enable-resilience -emit-sil -verify %s
// SR-12641: SILGen verification error regarding `ImmutableAddressUseVerifier` and AutoDiff-generated code.
import _Differentiation
public struct Resilient: Differentiable {
var x: Float
}
public class Class: Differentiable {
var x: Resilient
init(_ x: Resilient) {
self.x = x
}
}
public func f(_ c: Class) -> Resilient {
return Resilient(x: 0)
}
_ = pullback(at: Class(Resilient(x: 10)), in: f)
// swift/lib/SIL/Verifier/SILVerifier.cpp:456: bool (anonymous namespace)::ImmutableAddressUseVerifier::isConsumingOrMutatingArgumentConvention(swift::SILArgumentConvention): Assertion `conv.isIndirectConvention() && "Expect an indirect convention"' failed.
// Stack dump:
// ...
// 1. Swift version 5.3-dev (LLVM be43a34c3c, Swift 6d5b2f5220)
// 2. While evaluating request SILGenWholeModuleRequest(SIL Generation for module main)
// 3. While verifying SIL function "@$s4main5ClassC13TangentVectorVAA9ResilientVADVIeggr_AeHIegnr_TR".
// ...
// #8 0x00000000011e7a3e (anonymous namespace)::ImmutableAddressUseVerifier::isConsumingOrMutatingApplyUse(swift::Operand*)
// #9 0x00000000011e6add (anonymous namespace)::ImmutableAddressUseVerifier::isMutatingOrConsuming(swift::SILValue)
// #10 0x00000000011ce0b4 (anonymous namespace)::SILVerifier::visitSILBasicBlock(swift::SILBasicBlock*)
// Related crasher discovered while fixing SR-12641.
class LoadableOriginal<T: Differentiable>: Differentiable {
var x: T
init(_ x: T) { self.x = x }
}
@differentiable
func loadableOriginal<T: AdditiveArithmetic>(_ loadable: LoadableOriginal<T>) -> T {
return T.zero
}
// swift/include/swift/SIL/TypeLowering.h:845: swift::SILType swift::Lowering::TypeConverter::getLoweredLoadableType(swift::Type, swift::TypeExpansionContext, swift::SILModule &): Assertion `(ti.isLoadable() || !SILModuleConventions(M).useLoweredAddresses()) && "unexpected address-only type"' failed.
// Stack dump:
// ...
// 2. While evaluating request ExecuteSILPipelineRequest(Run pipelines { Guaranteed Passes } on SIL for main.main)
// 3. While running pass #153 SILModuleTransform "Differentiation".
// 4. While processing // differentiability witness for loadableOriginal<A>(_:)
// sil_differentiability_witness hidden [parameters 0] [results 0] <T where T : AdditiveArithmetic, T : Differentiable> @$s4main16loadableOriginalyxAA08LoadableC0CyxGs18AdditiveArithmeticRz16_Differentiation14DifferentiableRzlF : $@convention(thin) <T where T : Additive
// Arithmetic, T : Differentiable> (@guaranteed LoadableOriginal<T>) -> @out T {
// }
//
// on SIL function "@$s4main16loadableOriginalyxAA08LoadableC0CyxGs18AdditiveArithmeticRz16_Differentiation14DifferentiableRzlF".
// for 'loadableOriginal(_:)'
// 5. While generating VJP for SIL function "@$s4main16loadableOriginalyxAA08LoadableC0CyxGs18AdditiveArithmeticRz16_Differentiation14DifferentiableRzlF".
// for 'loadableOriginal(_:)'
// 6. While generating pullback for SIL function "@$s4main16loadableOriginalyxAA08LoadableC0CyxGs18AdditiveArithmeticRz16_Differentiation14DifferentiableRzlF".
// for 'loadableOriginal(_:)'
// ...
// #9 0x0000000000f83fbb swift::autodiff::PullbackEmitter::emitZeroDirect(swift::CanType, swift::SILLocation)
// #10 0x0000000000f8248b swift::autodiff::PullbackEmitter::emitZeroDerivativesForNonvariedResult(swift::SILValue)
// #11 0x0000000000f7fcae swift::autodiff::PullbackEmitter::run()
// #12 0x0000000000f3fba4 swift::autodiff::VJPEmitter::run()
// #13 0x0000000000eb1669 (anonymous namespace)::DifferentiationTransformer::canonicalizeDifferentiabilityWitness(swift::SILFunction*, swift::SILDifferentiabilityWitness*, swift::autodiff::DifferentiationInvoker, swift::IsSerialized_t)
// #14 0x0000000000eaea5e (anonymous namespace)::Differentiation::run()
| apache-2.0 |
Smisy/tracking-simulator | TrackingSimulator/location/Location.swift | 1 | 1857 | //
// Location.swift
// TrackingSimulator
//
// Created by Thanh Truong on 2/23/17.
// Copyright © 2017 SalonHelps. All rights reserved.
//
import Foundation
import MapKit
class Location {
private var currentLocation: CLLocation? = nil
private var locationManager:CLLocationManager? = nil
public var longitude: Double? = nil
public var latitude: Double? = nil
public var timestamp: Int? = nil
public var gas: Int? = nil
private var databaseService: FirebaseLocationDatabase? = nil;
init(deviceId:String) {
// perform some initialization here
self.locationManager = CLLocationManager()
self.databaseService = FirebaseLocationDatabase(deviceId: deviceId);
self.locationManager?.allowsBackgroundLocationUpdates = true;
self.locationManager?.pausesLocationUpdatesAutomatically = false;
}
func getLocation()->Void{
if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
self.currentLocation = self.locationManager?.location
// update object
self.longitude = (self.currentLocation!.coordinate.longitude) as Double
self.latitude = (self.currentLocation!.coordinate.latitude) as Double
self.timestamp = Int(NSDate().timeIntervalSince1970)
self.gas = 100
}
}
func getLocationAuthorization(){
self.locationManager?.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
self.locationManager?.startUpdatingLocation()
}
}
func sendDeviceLocationToSever(){
self.databaseService?.sendLocation(location: self);
}
}
| mit |
ioscreator/ioscreator | IOSSpriteKitParallaxScrollingTutorial/IOSSpriteKitParallaxScrollingTutorial/GameScene.swift | 1 | 1232 | //
// GameScene.swift
// IOSSpriteKitParallaxScrollingTutorial
//
// Created by Arthur Knopper on 19/01/2020.
// Copyright © 2020 Arthur Knopper. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
createBackground()
}
override func update(_ currentTime: TimeInterval) {
scrollBackground()
}
func createBackground() {
for i in 0...2 {
let sky = SKSpriteNode(imageNamed: "clouds")
sky.name = "clouds"
sky.size = CGSize(width: (self.scene?.size.width)!, height: (self.scene?.size.height)!)
sky.position = CGPoint(x: CGFloat(i) * sky.size.width , y: (self.frame.size.height / 2))
self.addChild(sky)
}
}
func scrollBackground(){
self.enumerateChildNodes(withName: "clouds", using: ({
(node, error) in
node.position.x -= 4
print("node position x = \(node.position.x)")
if node.position.x < -(self.scene?.size.width)! {
node.position.x += (self.scene?.size.width)! * 3
}
}))
}
}
| mit |
shaps80/Peek | Pod/Classes/Transformers/NSValue+Transformer.swift | 1 | 4002 | /*
Copyright © 23/04/2016 Shaps
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
/// Creates string representations of common values, e.g. CGPoint, CGRect, etc...
final class ValueTransformer: Foundation.ValueTransformer {
fileprivate static var floatFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
formatter.minimumFractionDigits = 0
formatter.minimumIntegerDigits = 1
formatter.roundingIncrement = 0.5
return formatter
}
override func transformedValue(_ value: Any?) -> Any? {
if let value = value as? NSValue {
let type = String(cString: value.objCType)
if type.hasPrefix("{CGRect") {
let rect = value.cgRectValue
return
"(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(rect.minX)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(rect.minY)))!)), " +
"(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(rect.width)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(rect.height)))!))"
}
if type.hasPrefix("{CGPoint") {
let point = value.cgPointValue
return "(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(point.x)))!), \(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(point.y)))!))"
}
if type.hasPrefix("{UIEdgeInset") {
let insets = value.uiEdgeInsetsValue
return
"(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(insets.left)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(insets.top)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(insets.right)))!), " +
"\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(insets.bottom)))!))"
}
if type.hasPrefix("{UIOffset") {
let offset = value.uiOffsetValue
return "(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(offset.horizontal)))!), \(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(offset.vertical)))!))"
}
if type.hasPrefix("{CGSize") {
let size = value.cgSizeValue
return "(\(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(size.width)))!), \(ValueTransformer.floatFormatter.string(from: NSNumber(value: Float(size.height)))!))"
}
}
return nil
}
override class func allowsReverseTransformation() -> Bool {
return false
}
}
| mit |
qiuncheng/study-for-swift | learn-rx-swift/Pods/RxSwift/RxSwift/Observables/Implementations/Materialize.swift | 14 | 953 | //
// Materialize.swift
// RxSwift
//
// Created by sergdort on 08/03/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
fileprivate final class MaterializeSink<Element, O: ObserverType>: Sink<O>, ObserverType where O.E == Event<Element> {
func on(_ event: Event<Element>) {
forwardOn(.next(event))
if event.isStopEvent {
forwardOn(.completed)
dispose()
}
}
}
final class Materialize<Element>: Producer<Event<Element>> {
private let _source: Observable<Element>
init(source: Observable<Element>) {
_source = source
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = MaterializeSink(observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| mit |
daaavid/TIY-Assignments | 22--Dude-Where's-My-Car/DudeWheresMyCar/DudeWheresMyCar/Pin.swift | 1 | 1388 | //
// Pins.swift
// DudeWheresMyCar
//
// Created by david on 11/3/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import Foundation
import CoreLocation
let kLatKey = "lat"
let kLngKey = "lng"
let knameKey = "name"
class Pin: NSObject, NSCoding
{
let lat: Double
let lng: Double
let name: String
init(lat: Double, lng: Double, name: String)
{
self.lat = lat
self.lng = lng
self.name = name
}
required convenience init?(coder aDecoder: NSCoder)
{
guard
let lat = aDecoder.decodeObjectForKey(kLatKey) as? Double,
let lng = aDecoder.decodeObjectForKey(kLngKey) as? Double,
let name = aDecoder.decodeObjectForKey(knameKey) as? String
else { return nil }
self.init(lat: lat, lng: lng, name: name)
}
func encodeWithCoder(aCoder: NSCoder)
{
aCoder.encodeObject(self.lat, forKey: kLatKey)
aCoder.encodeObject(self.lng, forKey: kLngKey)
aCoder.encodeObject(self.name, forKey: knameKey)
}
static func setValues(location: CLLocationCoordinate2D, name: String) -> Pin
{
var pin: Pin
let lat = location.latitude
let lng = location.longitude
let name = name
pin = Pin(lat: lat, lng: lng, name: name)
return pin
}
} | cc0-1.0 |
uasys/swift | test/SILGen/argument_shuffle.swift | 6 | 1374 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s
struct Horse<T> {
func walk(_: (String, Int), reverse: Bool) {}
func trot(_: (x: String, y: Int), halfhalt: Bool) {}
func canter(_: T, counter: Bool) {}
}
var kevin = Horse<(x: String, y: Int)>()
var loki = Horse<(String, Int)>()
//
// No conversion
let noLabelsTuple = ("x", 1)
kevin.walk(("x", 1), reverse: false)
kevin.walk(noLabelsTuple, reverse: false)
loki.canter(("x", 1), counter: false)
loki.canter(noLabelsTuple, counter: false)
// Introducing labels
kevin.trot(("x", 1), halfhalt: false)
kevin.trot(noLabelsTuple, halfhalt: false)
kevin.canter(("x", 1), counter: false)
kevin.canter(noLabelsTuple, counter: false)
// Eliminating labels
let labelsTuple = (x: "x", y: 1)
kevin.walk((x: "x", y: 1), reverse: false)
kevin.walk(labelsTuple, reverse: false)
loki.canter((x: "x", y: 1), counter: false)
loki.canter(labelsTuple, counter: false)
// No conversion
kevin.trot((x: "x", y: 1), halfhalt: false)
kevin.trot(labelsTuple, halfhalt: false)
kevin.canter((x: "x", y: 1), counter: false)
kevin.canter(labelsTuple, counter: false)
// Shuffling labels
let shuffledLabelsTuple = (y: 1, x: "x")
kevin.trot((y: 1, x: "x"), halfhalt: false)
kevin.trot(shuffledLabelsTuple, halfhalt: false)
kevin.canter((y: 1, x: "x"), counter: false)
kevin.canter(shuffledLabelsTuple, counter: false)
| apache-2.0 |
cwwise/CWWeChat | CWWeChat/MainClass/Base/CWSearch/CWSearchController.swift | 2 | 2089 | //
// CWSearchController.swift
// CWWeChat
//
// Created by chenwei on 16/5/29.
// Copyright © 2016年 chenwei. All rights reserved.
//
import UIKit
class CWSearchController: UISearchController {
///fix bug 必须添加这行 否则会崩溃
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
var showVoiceButton: Bool = false {
didSet {
if showVoiceButton {
self.searchBar.showsBookmarkButton = true
self.searchBar.setImage(CWAsset.SearchBar_voice.image, for: .bookmark, state: UIControlState())
self.searchBar.setImage(CWAsset.SearchBar_voice_HL.image, for: .bookmark, state: .highlighted)
} else {
self.searchBar.showsBookmarkButton = false
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override init(searchResultsController: UIViewController?) {
super.init(searchResultsController: searchResultsController)
self.searchBar.barTintColor = UIColor.searchBarTintColor()
self.searchBar.tintColor = UIColor.chatSystemColor()
self.searchBar.layer.borderWidth = 0.5
self.searchBar.layer.borderColor = UIColor.searchBarBorderColor().cgColor
self.searchBar.sizeToFit()
//通过KVO修改特性
let searchField = self.searchBar.value(forKey: "_searchField") as! UITextField
searchField.layer.masksToBounds = true
searchField.layer.borderWidth = 0.5
searchField.layer.borderColor = UIColor.tableViewCellLineColor().cgColor
searchField.layer.cornerRadius = 5.0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
WhatsTaste/WTImagePickerController | Vendor/Views/WTSelectionIndicatorView.swift | 1 | 3936 | //
// WTSelectionIndicatorView.swift
// WTImagePickerController
//
// Created by Jayce on 2017/2/17.
// Copyright © 2017年 WhatsTaste. All rights reserved.
//
import UIKit
enum WTSelectionIndicatorViewStyle : Int {
case none
case checkmark
case checkbox
}
class WTSelectionIndicatorView: UIControl {
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
super.draw(rect)
switch style {
case .checkmark:
let context = UIGraphicsGetCurrentContext()
let bounds = self.bounds.insetBy(dx: insets.left + insets.right, dy: insets.top + insets.bottom)
let size = bounds.width
var path = UIBezierPath(arcCenter: .init(x: bounds.midX, y: bounds.midY), radius: bounds.width / 2, startAngle: -CGFloat(Double.pi / 4), endAngle: CGFloat(2 * Double.pi - Double.pi / 4), clockwise: true)
context?.saveGState()
let tintColor = self.tintColor!
let fillColor = isSelected ? tintColor : tintColor.WTIPReverse(alpha: 0.5)
let strokeColor = isSelected ? UIColor.clear : UIColor.white
fillColor.setFill()
path.fill()
context?.restoreGState()
path.lineWidth = 1
strokeColor.setStroke()
path.stroke()
let offsetX = bounds.minX
let offsetY = bounds.minY
path = UIBezierPath()
path.move(to: .init(x: offsetX + size * 0.27083, y: offsetY + size * 0.54167))
path.addLine(to: .init(x: offsetX + size * 0.41667, y: offsetY + size * 0.68750))
path.addLine(to: .init(x: offsetX + size * 0.75000, y: offsetY + size * 0.35417))
path.lineCapStyle = .square
path.lineWidth = 1.3
UIColor.white.setStroke()
path.stroke()
case .checkbox:
let context = UIGraphicsGetCurrentContext()
// context?.saveGState()
// context?.setFillColor(UIColor.red.cgColor)
// context?.fill(rect)
// context?.restoreGState()
let bounds = self.bounds.insetBy(dx: insets.left + insets.right, dy: insets.top + insets.bottom)
let arcCenter = CGPoint.init(x: bounds.midX, y: bounds.midY)
let radius = bounds.width / 2
let startAngle = -CGFloat(Double.pi / 4)
let endAngle = CGFloat(2 * Double.pi - Double.pi / 4)
let clockwise = true
var path = UIBezierPath(arcCenter: arcCenter, radius: radius - 2, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
context?.saveGState()
let tintColor = self.tintColor!
let fillColor = isSelected ? tintColor : tintColor.WTIPReverse(alpha: 0.5)
fillColor.setFill()
path.fill()
context?.restoreGState()
let strokeColor = UIColor(white: 0, alpha: 0.2)
path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
path.lineWidth = 1
strokeColor.setStroke()
path.stroke()
default:
break
}
}
// MARK: - Properties
override var tintColor: UIColor! {
didSet {
setNeedsDisplay()
}
}
override var isSelected: Bool {
didSet {
setNeedsDisplay()
}
}
public var style: WTSelectionIndicatorViewStyle = .none {
didSet {
setNeedsDisplay()
}
}
public var insets: UIEdgeInsets = UIEdgeInsetsMake(1, 1, 1, 1) {
didSet {
setNeedsDisplay()
}
}
}
| mit |
jeffh/Nimble | Tests/NimbleTests/Matchers/BeNilTest.swift | 41 | 692 | import XCTest
import Nimble
final class BeNilTest: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (BeNilTest) -> () throws -> Void)] {
return [
("testBeNil", testBeNil),
]
}
func producesNil() -> [Int]? {
return nil
}
func testBeNil() {
expect(nil as Int?).to(beNil())
expect(1 as Int?).toNot(beNil())
expect(self.producesNil()).to(beNil())
failsWithErrorMessage("expected to not be nil, got <nil>") {
expect(nil as Int?).toNot(beNil())
}
failsWithErrorMessage("expected to be nil, got <1>") {
expect(1 as Int?).to(beNil())
}
}
}
| apache-2.0 |
qiuncheng/study-for-swift | learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/ElementAt.swift | 6 | 1968 | //
// ElementAt.swift
// Rx
//
// Created by Junior B. on 21/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ElementAtSink<SourceType, O: ObserverType> : Sink<O>, ObserverType where O.E == SourceType {
typealias Parent = ElementAt<SourceType>
let _parent: Parent
var _i: Int
init(parent: Parent, observer: O) {
_parent = parent
_i = parent._index
super.init(observer: observer)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(_):
if (_i == 0) {
forwardOn(event)
forwardOn(.completed)
self.dispose()
}
do {
let _ = try decrementChecked(&_i)
} catch(let e) {
forwardOn(.error(e))
dispose()
return
}
case .error(let e):
forwardOn(.error(e))
self.dispose()
case .completed:
if (_parent._throwOnEmpty) {
forwardOn(.error(RxError.argumentOutOfRange))
} else {
forwardOn(.completed)
}
self.dispose()
}
}
}
class ElementAt<SourceType> : Producer<SourceType> {
let _source: Observable<SourceType>
let _throwOnEmpty: Bool
let _index: Int
init(source: Observable<SourceType>, index: Int, throwOnEmpty: Bool) {
if index < 0 {
rxFatalError("index can't be negative")
}
self._source = source
self._index = index
self._throwOnEmpty = throwOnEmpty
}
override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == SourceType {
let sink = ElementAtSink(parent: self, observer: observer)
sink.disposable = _source.subscribeSafe(sink)
return sink
}
}
| mit |
hooman/swift | test/stdlib/RangeTraps.swift | 3 | 3470 | //===--- RangeTraps.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out_Debug -Onone
// RUN: %target-build-swift %s -o %t/a.out_Release -O
//
// RUN: %target-codesign %t/a.out_Debug
// RUN: %target-codesign %t/a.out_Release
// RUN: %target-run %t/a.out_Debug
// RUN: %target-run %t/a.out_Release
// REQUIRES: executable_test
import StdlibUnittest
let testSuiteSuffix = _isDebugAssertConfiguration() ? "_debug" : "_release"
var RangeTraps = TestSuite("RangeTraps" + testSuiteSuffix)
RangeTraps.test("HalfOpen")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var range = 1..<1
expectType(CountableRange<Int>.self, &range)
expectCrashLater()
_ = 1..<0
}
RangeTraps.test("Closed")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var range = 1...1
expectType(CountableClosedRange<Int>.self, &range)
expectCrashLater()
_ = 1...0
}
RangeTraps.test("OutOfRange")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
_ = 0..<Int.max // This is a CountableRange
// This works for Ranges now!
expectTrue((0...Int.max).contains(Int.max))
}
RangeTraps.test("CountablePartialRangeFrom")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let range = (Int.max - 1)...
var it = range.makeIterator()
_ = it.next()
expectCrashLater()
_ = it.next()
}
RangeTraps.test("nanLowerBound")
.code {
expectCrashLater()
_ = Double.nan ... 0
}
RangeTraps.test("nanUpperBound")
.code {
expectCrashLater()
_ = 0 ... Double.nan
}
RangeTraps.test("nanLowerBoundPartial")
.code {
expectCrashLater()
_ = Double.nan ..< 0
}
RangeTraps.test("nanUpperBoundPartial")
.code {
expectCrashLater()
_ = 0 ..< Double.nan
}
RangeTraps.test("fromNaN")
.code {
expectCrashLater()
_ = Double.nan...
}
RangeTraps.test("toNaN")
.code {
expectCrashLater()
_ = ..<Double.nan
}
RangeTraps.test("throughNaN")
.code {
expectCrashLater()
_ = ...Double.nan
}
if #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) {
// Debug check was introduced in https://github.com/apple/swift/pull/34961
RangeTraps.test("UncheckedHalfOpen")
.xfail(.custom(
{ !_isDebugAssertConfiguration() },
reason: "assertions are disabled in Release and Unchecked mode"))
.code {
expectCrashLater()
var range = Range(uncheckedBounds: (lower: 1, upper: 0))
}
RangeTraps.test("UncheckedClosed")
.xfail(.custom(
{ !_isDebugAssertConfiguration() },
reason: "assertions are disabled in Release and Unchecked mode"))
.code {
expectCrashLater()
var range = ClosedRange(uncheckedBounds: (lower: 1, upper: 0))
}
}
runAllTests()
| apache-2.0 |
attaswift/BigInt | Tests/BigIntTests/Violet - Helpers/GlobalFunctions.swift | 1 | 2725 | // This file was written by LiarPrincess for Violet - Python VM written in Swift.
// https://github.com/LiarPrincess/Violet
// MARK: - Pair values
internal struct PossiblePairings<T, V>: Sequence {
internal typealias Element = (T, V)
internal struct Iterator: IteratorProtocol {
private let lhsValues: [T]
private let rhsValues: [V]
private var lhsIndex = 0
private var rhsIndex = 0
fileprivate init(lhs: [T], rhs: [V]) {
self.lhsValues = lhs
self.rhsValues = rhs
}
internal mutating func next() -> Element? {
if self.lhsIndex == self.lhsValues.count {
return nil
}
let lhs = self.lhsValues[self.lhsIndex]
let rhs = self.rhsValues[self.rhsIndex]
self.rhsIndex += 1
if self.rhsIndex == self.rhsValues.count {
self.lhsIndex += 1
self.rhsIndex = 0
}
return (lhs, rhs)
}
}
private let lhsValues: [T]
private let rhsValues: [V]
fileprivate init(lhs: [T], rhs: [V]) {
self.lhsValues = lhs
self.rhsValues = rhs
}
internal func makeIterator() -> Iterator {
return Iterator(lhs: self.lhsValues, rhs: self.rhsValues)
}
}
/// `[1, 2] -> [(1,1), (1,2), (2,1), (2,2)]`
internal func allPossiblePairings<T>(values: [T]) -> PossiblePairings<T, T> {
return PossiblePairings(lhs: values, rhs: values)
}
/// `[1, 2], [1, 2] -> [(1,1), (1,2), (2,1), (2,2)]`
internal func allPossiblePairings<T, S>(lhs: [T], rhs: [S]) -> PossiblePairings<T, S> {
return PossiblePairings(lhs: lhs, rhs: rhs)
}
// MARK: - Powers of 2
internal typealias PowerOf2<T> = (power: Int, value: T)
/// `1, 2, 4, 8, 16, 32, 64, 128, 256, 512, etc…`
internal func allPositivePowersOf2<T: FixedWidthInteger>(
type: T.Type
) -> [PowerOf2<T>] {
var result = [PowerOf2<T>]()
result.reserveCapacity(T.bitWidth)
var value = T(1)
var power = 0
result.append(PowerOf2(power: power, value: value))
while true {
let (newValue, overflow) = value.multipliedReportingOverflow(by: 2)
if overflow {
return result
}
value = newValue
power += 1
result.append(PowerOf2(power: power, value: value))
}
}
/// `-1, -2, -4, -8, -16, -32, -64, -128, -256, -512, etc…`
internal func allNegativePowersOf2<T: FixedWidthInteger>(
type: T.Type
) -> [PowerOf2<T>] {
assert(T.isSigned)
var result = [PowerOf2<T>]()
result.reserveCapacity(T.bitWidth)
var value = T(-1)
var power = 0
result.append(PowerOf2(power: power, value: value))
while true {
let (newValue, overflow) = value.multipliedReportingOverflow(by: 2)
if overflow {
return result
}
value = newValue
power += 1
result.append(PowerOf2(power: power, value: value))
}
}
| mit |
guloooo128/Locals | Package.swift | 1 | 582 | // swift-tools-version:3.1
import PackageDescription
let package = Package(
name: "Locals",
targets: [
Target(name: "LocalsKit", dependencies: []),
Target(name: "Locals", dependencies: ["LocalsKit"])
],
dependencies: [
.Package(url: "https://github.com/jatoben/CommandLine.git", "3.0.0-pre1"),
.Package(url: "https://github.com/onevcat/Rainbow", "2.0.1"),
.Package(url: "https://github.com/kylef/PathKit", "0.8.0"),
// .Package(url:"https://github.com/kylef/Spectre", majorVersion: 0, minor: 7)
]
)
| mit |
warren-gavin/OBehave | OBehave/Classes/ViewController/Transition/OBTransitionDelegateBehavior.swift | 1 | 8079 | //
// OBTransitionDelegateBehavior.swift
// OBehave
//
// Created by Warren Gavin on 13/01/16.
// Copyright © 2016 Apokrupto. All rights reserved.
//
import UIKit
/// Transition animation settings
public protocol OBTransitionDelegateBehaviorDataSource: OBBehaviorDataSource {
var duration: TimeInterval { get }
var delay: TimeInterval { get }
var damping: CGFloat { get }
var velocity: CGFloat { get }
var options: UIView.AnimationOptions { get }
func presentationController(forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController) -> UIPresentationController
}
extension OBTransitionDelegateBehaviorDataSource {
public var duration: TimeInterval {
return .defaultDuration
}
public var delay: TimeInterval {
return .defaultDelay
}
public var damping: CGFloat {
return .defaultDamping
}
public var velocity: CGFloat {
return .defaultVelocity
}
public var options: UIView.AnimationOptions {
return .defaultOptions
}
public func presentationController(forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController) -> UIPresentationController {
return VanillaPresentationController(presentedViewController: presented, presenting: presenting)
}
}
/// Present a view controller modally with a custom transition
///
/// Specific types of transitions should extend this class and override
/// the animatePresentation(using:completion:) and animateDismissal(using:completion:)
/// methods to implement the exact type of transition needed
open class OBTransitionDelegateBehavior: OBBehavior, UIViewControllerTransitioningDelegate {
private var isPresenting = true
override open func setup() {
super.setup()
owner?.modalPresentationStyle = .custom
owner?.transitioningDelegate = self
}
/// Override this method to implement a specific type of transition as the view controller
/// appears onscreen.
///
/// - Parameters:
/// - transitionContext: Contains the presented and presenting views, controllers etc
/// - completion: completion handler on success or failure
public func animatePresentation(using transitionContext: UIViewControllerContextTransitioning) -> (() -> Void)? {
return nil
}
/// Override this method to clean up after a specific type of transition as the view
/// controller appears onscreen. This will be called in the presentation animation's
/// completion handler
///
/// - Returns: The cleanup code
public func cleanupPresentation() -> ((Bool) -> Void)? {
return nil
}
/// Override this method to implement a specific type of transition as the view controller
/// is dismissed from the view hierarchy
///
/// - Parameters:
/// - transitionContext: Contains the presented and presenting views, controllers etc
/// - completion: completion handler on success or failure
public func animateDismissal(using transitionContext: UIViewControllerContextTransitioning) -> (() -> Void)? {
return nil
}
/// Override this method to clean up after a specific type of transition as the view
/// controller is dismissed from the view hierarchy. This will be called in the dismissal
/// animation's completion handler
///
/// - Returns: The cleanup code
public func cleanupDismissal() -> ((Bool) -> Void)? {
return nil
}
}
// MARK: - Transition animation properties
extension OBTransitionDelegateBehavior {
public var duration: TimeInterval {
let dataSource: OBTransitionDelegateBehaviorDataSource? = getDataSource()
return dataSource?.duration ?? .defaultDuration
}
public var delay: TimeInterval {
let dataSource: OBTransitionDelegateBehaviorDataSource? = getDataSource()
return dataSource?.delay ?? .defaultDelay
}
public var damping: CGFloat {
let dataSource: OBTransitionDelegateBehaviorDataSource? = getDataSource()
return dataSource?.damping ?? .defaultDamping
}
public var velocity: CGFloat {
let dataSource: OBTransitionDelegateBehaviorDataSource? = getDataSource()
return dataSource?.velocity ?? .defaultVelocity
}
public var options: UIView.AnimationOptions {
let dataSource: OBTransitionDelegateBehaviorDataSource? = getDataSource()
return dataSource?.options ?? .defaultOptions
}
}
// MARK: - UIViewControllerTransitioningDelegate
extension OBTransitionDelegateBehavior {
public func presentationController(forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController) -> UIPresentationController? {
let dataSource: OBTransitionDelegateBehaviorDataSource? = getDataSource()
return dataSource?.presentationController(forPresented: presented, presenting: presenting, source: source) ??
VanillaPresentationController(presentedViewController: presented, presenting: presenting)
}
public func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
}
// MARK: - UIViewControllerAnimatedTransitioning
extension OBTransitionDelegateBehavior: UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let transition = (isPresenting ? animatePresentation : animateDismissal)
let completion = (isPresenting ? cleanupPresentation() : cleanupDismissal())
guard let animation = transition(transitionContext) else {
transitionContext.completeTransition(false)
return
}
UIView.animate(withDuration: duration,
delay: delay,
usingSpringWithDamping: damping,
initialSpringVelocity: velocity,
options: options,
animations: animation) { finished in
completion?(finished)
transitionContext.completeTransition(finished)
}
}
}
// MARK: - Defaults
private extension TimeInterval {
static let defaultDuration: TimeInterval = 0.67
static let defaultDelay: TimeInterval = 0.0
}
private extension CGFloat {
static let defaultDamping: CGFloat = 1.0
static let defaultVelocity: CGFloat = 0.0
}
private extension UIView.AnimationOptions {
static let defaultOptions: UIView.AnimationOptions = [.allowUserInteraction, .curveEaseInOut]
}
/// From the UIViewControllerTransitioningDelegate documentation:
/// "The default presentation controller does not add any views or content
/// to the view hierarchy."
///
/// How useless. Any transition must define a presentation controller that,
/// at the very least, adds the presented view to the container view, which
/// is what this boring class does.
private class VanillaPresentationController: UIPresentationController {
override func presentationTransitionWillBegin() {
if let presentedView = presentedView {
containerView?.addSubview(presentedView)
}
}
}
| mit |
vector-im/vector-ios | RiotSwiftUI/Modules/Spaces/SpaceCreation/SpaceCreationEmailInvites/Service/Mock/MockSpaceCreationEmailInvitesService.swift | 1 | 1502 | // File created from SimpleUserProfileExample
// $ createScreen.sh Spaces/SpaceCreation/SpaceCreationEmailInvites SpaceCreationEmailInvites
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Combine
@available(iOS 14.0, *)
class MockSpaceCreationEmailInvitesService: SpaceCreationEmailInvitesServiceProtocol {
var isLoadingSubject: CurrentValueSubject<Bool, Never>
private let defaultValidation: Bool
var isIdentityServiceReady: Bool {
return true
}
init(defaultValidation: Bool, isLoading: Bool) {
self.defaultValidation = defaultValidation
self.isLoadingSubject = CurrentValueSubject(isLoading)
}
func validate(_ emailAddresses: [String]) -> [Bool] {
return emailAddresses.map { _ in defaultValidation }
}
func prepareIdentityService(prepared: ((String?, String?) -> Void)?, failure: ((Error?) -> Void)?) {
failure?(nil)
}
}
| apache-2.0 |
vector-im/vector-ios | Riot/Modules/Common/CoachMessages/WindowOverlayPresenter.swift | 1 | 4226 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
/// `WindowOverlayPresenter` allows to add a given view to the presenting view or window.
/// The presenter also manages taps over the presenting view and the duration to dismiss the view.
class WindowOverlayPresenter: NSObject {
// MARK: Private
private weak var presentingView: UIView?
private weak var presentedView: UIView?
private weak var gestureRecognizer: UIGestureRecognizer?
private var timer: Timer?
// MARK: Public
/// Add a given view to the presenting view or window.
/// The presenter also manages taps over the presenting view and the duration to dismiss the view.
///
/// - parameters:
/// - view: instance of the view that will be displayed
/// - presentingView: instance of the presenting view. `nil` will display the view over the key window
/// - duration:if duration is not `nil`, the view will be dismissed after the given duration. The view is never dismissed otherwise
func show(_ view: UIView, over presentingView: UIView? = nil, duration: TimeInterval? = nil) {
guard presentedView == nil else {
return
}
let keyWindow: UIWindow? = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
guard let backView = presentingView ?? keyWindow else {
MXLog.error("[WindowOverlay] show: no eligible presenting view found")
return
}
view.alpha = 0
backView.addSubview(view)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.didTapOnBackView(sender:)))
tapGestureRecognizer.cancelsTouchesInView = false
backView.addGestureRecognizer(tapGestureRecognizer)
self.gestureRecognizer = tapGestureRecognizer
self.presentingView = backView
self.presentedView = view
UIView.animate(withDuration: 0.3) {
view.alpha = 1
}
if let timeout = duration {
timer = Timer.scheduledTimer(withTimeInterval: timeout, repeats: false, block: { [weak self] timer in
self?.dismiss()
})
}
}
/// Dismisses the currently presented view.
func dismiss() {
if let gestureRecognizer = self.gestureRecognizer {
self.presentingView?.removeGestureRecognizer(gestureRecognizer)
}
self.timer?.invalidate()
self.timer = nil
UIView.animate(withDuration: 0.3) {
self.presentedView?.alpha = 0
} completion: { isFinished in
if isFinished {
self.presentedView?.removeFromSuperview()
self.presentingView = nil
}
}
}
// MARK: Private
@objc private func didTapOnBackView(sender: UIGestureRecognizer) {
dismiss()
}
}
// MARK: Objective-C
extension WindowOverlayPresenter {
/// Add a given view to the presenting view or window.
/// The presenter also manages taps over the presenting view and the duration to dismiss the view.
///
/// - parameters:
/// - view: instance of the view that will be displayed
/// - presentingView: instance of the presenting view. `nil` will display the view over the key window
/// - duration:if duration > 0, the view will be dismissed after the given duration. The view is never dismissed otherwise
@objc func show(_ view: UIView, over presentingView: UIView?, duration: TimeInterval) {
self.show(view, over: presentingView, duration: duration > 0 ? duration : nil)
}
}
| apache-2.0 |
RuiAAPeres/TeamGen | TeamGen/Sources/Application/AppBuilder.swift | 1 | 1031 | import UIKit
import TeamGenFoundation
import ReactiveSwift
struct AppBuilder {
let dependencies: AppDependencies
func makeGroupsScreen() -> UIViewController {
// let groupsRepository = GroupsRepository()
// let viewModel = GroupsViewModel(groupsRepository: groupsRepository)
let group = Group(name: "A group", players: [], skillSpec: [])
let viewModel = Dummy_GroupsViewModel(state: Property(value: .groupsReady([group])))
let viewController = GroupsScreenViewController(viewModel: viewModel)
let navigationController = UINavigationController(rootViewController: viewController)
let flowController = GroupsScreenFlowController(dependencies: dependencies,
modal: viewController.modalFlow,
navigation: navigationController.navigationFlow)
viewModel.route.observeValues(flowController.observe)
return navigationController
}
}
| mit |
lanjing99/RxSwiftDemo | 11-time-based-operators/starter/RxSwiftPlayground/RxSwift.playground/Sources/Timer.swift | 3 | 418 | import Foundation
public extension DispatchSource {
public class func timer(interval: Double, queue: DispatchQueue, handler: @escaping () -> Void) -> DispatchSourceTimer {
let source = DispatchSource.makeTimerSource(queue: queue)
source.setEventHandler(handler: handler)
source.scheduleRepeating(deadline: .now(), interval: interval, leeway: .nanoseconds(0))
source.resume()
return source
}
}
| mit |
j4nnis/AImageFilters | ImageExperiments/ViewController.swift | 1 | 2745 | //
// ViewController.swift
// ImageExperiments
//
// Created by Jannis Muething on 10/2/14.
// Copyright (c) 2014 Jannis Muething. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var lowerImageView: UIImageView!
@IBOutlet weak var upperImageView: UIImageView!
var filter : Filter?
var image : UIImage = UIImage(named: "sharptest")
var intensityValue = 1
override func viewDidLoad() {
super.viewDidLoad()
self.upperImageView.image = image
if let aFilter = filter {
self.lowerImageView.image = aFilter(image)
}
// var imgArray = cgImageToImageArray(UIImage(named: "200").CGImage)
// imgArray[0][0] = [255,0,0, 255]
// imgArray[1][1] = [0,255,0, 255]
// imgArray[2][2] = [0,0,255, 255]
//
//
// self.lowerImageView.image = (UIImage(CGImage:imageArrayToCgImage(imgArray), scale:2, orientation: .Up))
}
@IBAction func intensitySliderDidChange(sender: AnyObject) {
if let slider = sender as? UISlider {
let cvalue = Int(slider.value)
if cvalue != intensityValue {
intensityValue = cvalue
self.lowerImageView.image = (filter! * intensityValue)(image)
slider.value = Float(intensityValue)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
return false
}
}
| mit |
soflare/XWebApp | XWebAppTests/XWebAppTests.swift | 1 | 876 | //
// XWebAppTests.swift
// XWebAppTests
//
// Created by Solar Flare on 7/5/15.
// Copyright (c) 2015 XWebView. All rights reserved.
//
import UIKit
import XCTest
class XWebAppTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
xuzhuoxi/SearchKit | Source/cs/search/SearchInfo.swift | 1 | 1784 | //
// SearchInfo.swift
// SearchKit
//
// Created by 许灼溪 on 15/12/21.
//
//
import Foundation
/**
*
* @author xuzhuoxi
*
*/
public struct SearchInfo {
/**
* 输入信息,保证已经去掉前后空格并把大写字母转为小写<br>
*
* @return 输入信息,保证已经去掉前后空格并把大写字母转为小写<br>
*/
public let inputStr: String
/**
* 需要执行的检索配置<br>
*
* @return 需要执行的检索配置<br>
*/
public let searchConfig: SearchConfig
/**
* 最大返回量
*
* @return 最大返回量
*/
public let maxResultCount: Int
/**
* 输入中是否带中文字
*
* @return 输入中是否带中文字
*/
public let isChineseInput: Bool
/**
* 当chineseInput为true时有效<br>
* 一个针对中文字生成的正则表达式{@link ChineseUtils#toChineseWordsRegexp(String)}<br>
*
* @return 输入的中文正则表达式
*/
public let chineseWordsRegexp: String?
/**
*
* @param inputStr
* 输入信息,掉前后空格并把大写字母转为小写后存于inputStr{@link #inputStr}<br>
* @param searchType
* 需要执行的检索类别<br>
* @param maxResultCount
* 最大返回量<br>
*/
public init(_ inputStr:String, _ searchConfig:SearchConfig, _ maxResultCount:Int) {
self.inputStr = inputStr.trim().lowercased()
self.searchConfig = searchConfig
self.maxResultCount = maxResultCount
self.isChineseInput = ChineseUtils.hasChinese(self.inputStr)
self.chineseWordsRegexp = isChineseInput ? ChineseUtils.toChineseWordsRegexp(self.inputStr) : nil
}
}
| mit |
guoc/spi | SPiKeyboard/TastyImitationKeyboard/ForwardingView.swift | 1 | 7896 | //
// ForwardingView.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/19/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
// Added by guoc for swiping gesture command
protocol ForwardingViewDelegate: class {
func didPan(from beginView: UIView, to endView: UIView)
}
// End
class ForwardingView: UIView {
var touchToView: [UITouch:UIView]
// Added by guoc for swiping gesture command
weak var delegate: ForwardingViewDelegate?
var touchBeginView: UIView? = nil
// End
override init(frame: CGRect) {
self.touchToView = [:]
super.init(frame: frame)
self.contentMode = UIViewContentMode.redraw
self.isMultipleTouchEnabled = true
self.isUserInteractionEnabled = true
self.isOpaque = false
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
// Why have this useless drawRect? Well, if we just set the backgroundColor to clearColor,
// then some weird optimization happens on UIKit's side where tapping down on a transparent pixel will
// not actually recognize the touch. Having a manual drawRect fixes this behavior, even though it doesn't
// actually do anything.
override func draw(_ rect: CGRect) {}
override func hitTest(_ point: CGPoint, with event: UIEvent!) -> UIView? {
if self.isHidden || self.alpha == 0 || !self.isUserInteractionEnabled {
return nil
}
else {
return (self.bounds.contains(point) ? self : nil)
}
}
func handleControl(_ view: UIView?, controlEvent: UIControlEvents) {
if let control = view as? UIControl {
let targets = control.allTargets
for target in targets {
if let actions = control.actions(forTarget: target, forControlEvent: controlEvent) {
for action in actions {
let selector = Selector(action)
control.sendAction(selector, to: target, for: nil)
}
}
}
}
}
// TODO: there's a bit of "stickiness" to Apple's implementation
func findNearestView(_ position: CGPoint) -> UIView? {
if !self.bounds.contains(position) {
return nil
}
var closest: (UIView, CGFloat)? = nil
for anyView in self.subviews {
if anyView.isHidden {
continue
}
anyView.alpha = 1
let distance = distanceBetween(anyView.frame, point: position)
if closest != nil {
if distance < closest!.1 {
closest = (anyView, distance)
}
}
else {
closest = (anyView, distance)
}
}
if closest != nil {
return closest!.0
}
else {
return nil
}
}
// http://stackoverflow.com/questions/3552108/finding-closest-object-to-cgpoint b/c I'm lazy
func distanceBetween(_ rect: CGRect, point: CGPoint) -> CGFloat {
if rect.contains(point) {
return 0
}
var closest = rect.origin
if (rect.origin.x + rect.size.width < point.x) {
closest.x += rect.size.width
}
else if (point.x > rect.origin.x) {
closest.x = point.x
}
if (rect.origin.y + rect.size.height < point.y) {
closest.y += rect.size.height
}
else if (point.y > rect.origin.y) {
closest.y = point.y
}
let a = pow(Double(closest.y - point.y), 2)
let b = pow(Double(closest.x - point.x), 2)
return CGFloat(sqrt(a + b));
}
// reset tracked views without cancelling current touch
func resetTrackedViews() {
for view in self.touchToView.values {
self.handleControl(view, controlEvent: .touchCancel)
}
self.touchToView.removeAll(keepingCapacity: true)
}
func ownView(_ newTouch: UITouch, viewToOwn: UIView?) -> Bool {
var foundView = false
if viewToOwn != nil {
for (touch, view) in self.touchToView {
if viewToOwn == view {
if touch == newTouch {
break
}
else {
self.touchToView[touch] = nil
foundView = true
}
break
}
}
}
self.touchToView[newTouch] = viewToOwn
return foundView
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let position = touch.location(in: self)
let view = findNearestView(position)
// Added by guoc for swiping gesture command
if touches.count == 1 {
self.touchBeginView = view
} else {
self.touchBeginView = nil
}
// End
let viewChangedOwnership = self.ownView(touch, viewToOwn: view)
if !viewChangedOwnership {
self.handleControl(view, controlEvent: .touchDown)
if touch.tapCount > 1 {
// two events, I think this is the correct behavior but I have not tested with an actual UIControl
self.handleControl(view, controlEvent: .touchDownRepeat)
}
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let position = touch.location(in: self)
let oldView = self.touchToView[touch]
let newView = findNearestView(position)
if oldView != newView {
self.handleControl(oldView, controlEvent: .touchDragExit)
let viewChangedOwnership = self.ownView(touch, viewToOwn: newView)
if !viewChangedOwnership {
self.handleControl(newView, controlEvent: .touchDragEnter)
}
else {
self.handleControl(newView, controlEvent: .touchDragInside)
}
}
else {
self.handleControl(oldView, controlEvent: .touchDragInside)
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let view = self.touchToView[touch]
let touchPosition = touch.location(in: self)
if self.bounds.contains(touchPosition) {
// Added by guoc for swiping gesture command
if touches.count == 1 && self.touchBeginView != nil && view != nil {
delegate?.didPan(from: self.touchBeginView!, to: view!)
}
self.touchBeginView = nil
// End
self.handleControl(view, controlEvent: .touchUpInside)
}
else {
self.handleControl(view, controlEvent: .touchCancel)
}
self.touchToView[touch] = nil
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches ?? [] {
let view = self.touchToView[touch]
self.handleControl(view, controlEvent: .touchCancel)
self.touchToView[touch] = nil
}
}
}
| bsd-3-clause |
crazypoo/PTools | PooToolsSource/Core/PTUtils.swift | 1 | 27075 | //
// PTUtils.swift
// Diou
//
// Created by ken lam on 2021/10/8.
// Copyright © 2021 DO. All rights reserved.
//
import UIKit
import AVFoundation
import NotificationBannerSwift
import SwiftDate
@objc public enum PTUrlStringVideoType:Int {
case MP4
case MOV
case ThreeGP
case UNKNOW
}
@objc public enum PTAboutImageType:Int {
case JPEG
case JPEG2000
case PNG
case GIF
case TIFF
case WEBP
case BMP
case ICO
case ICNS
case UNKNOW
}
@objc public enum TemperatureUnit:Int
{
case Fahrenheit
case CentigradeDegree
}
@objcMembers
public class PTUtils: NSObject {
public static let share = PTUtils()
public var timer:DispatchSourceTimer?
//MARK: 类似iPhone点击了Home键
public class func likeTapHome()
{
PTUtils.gcdMain {
UIApplication.shared.perform(#selector(NSXPCConnection.suspend))
}
}
///ALERT真正基类
public class func base_alertVC(title:String? = "",
titleColor:UIColor? = UIColor.black,
titleFont:UIFont? = UIFont.systemFont(ofSize: 15),
msg:String? = "",
msgColor:UIColor? = UIColor.black,
msgFont:UIFont? = UIFont.systemFont(ofSize: 15),
okBtns:[String]? = [String](),
cancelBtn:String? = "",
showIn:UIViewController,
cancelBtnColor:UIColor? = .systemBlue,
doneBtnColors:[UIColor]? = [UIColor](),
alertBGColor:UIColor? = .white,
alertCornerRadius:CGFloat? = 15,
cancel:(()->Void)? = nil,
moreBtn:((_ index:Int,_ title:String)->Void)?)
{
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
if !(cancelBtn!).stringIsEmpty()
{
let cancelAction = UIAlertAction(title: cancelBtn, style: .cancel) { (action) in
if cancel != nil
{
cancel!()
}
}
alert.addAction(cancelAction)
cancelAction.setValue(cancelBtnColor, forKey: "titleTextColor")
}
if (okBtns?.count ?? 0) > 0
{
var dontArrColor = [UIColor]()
if doneBtnColors!.count == 0 || okBtns?.count != doneBtnColors?.count || okBtns!.count > (doneBtnColors?.count ?? 0)
{
if doneBtnColors!.count == 0
{
okBtns?.enumerated().forEach({ (index,value) in
dontArrColor.append(.systemBlue)
})
}
else if okBtns!.count > (doneBtnColors?.count ?? 0)
{
let count = okBtns!.count - (doneBtnColors?.count ?? 0)
dontArrColor = doneBtnColors!
for _ in 0..<(count)
{
dontArrColor.append(.systemBlue)
}
}
else if okBtns!.count < (doneBtnColors?.count ?? 0)
{
let count = (doneBtnColors?.count ?? 0) - okBtns!.count
dontArrColor = doneBtnColors!
for _ in 0..<(count)
{
dontArrColor.removeLast()
}
}
}
else
{
dontArrColor = doneBtnColors!
}
okBtns?.enumerated().forEach({ (index,value) in
let callAction = UIAlertAction(title: value, style: .default) { (action) in
if moreBtn != nil
{
moreBtn!(index,value)
}
}
alert.addAction(callAction)
callAction.setValue(dontArrColor[index], forKey: "titleTextColor")
})
}
// KVC修改系统弹框文字颜色字号
if !(title ?? "").stringIsEmpty()
{
let alertStr = NSMutableAttributedString(string: title!)
let alertStrAttr = [NSAttributedString.Key.foregroundColor: titleColor!, NSAttributedString.Key.font: titleFont!]
alertStr.addAttributes(alertStrAttr, range: NSMakeRange(0, title!.count))
alert.setValue(alertStr, forKey: "attributedTitle")
}
if !(msg ?? "").stringIsEmpty()
{
let alertMsgStr = NSMutableAttributedString(string: msg!)
let alertMsgStrAttr = [NSAttributedString.Key.foregroundColor: msgColor!, NSAttributedString.Key.font: msgFont!]
alertMsgStr.addAttributes(alertMsgStrAttr, range: NSMakeRange(0, msg!.count))
alert.setValue(alertMsgStr, forKey: "attributedMessage")
}
let subview = alert.view.subviews.first! as UIView
let alertContentView = subview.subviews.first! as UIView
if alertBGColor != .white
{
alertContentView.backgroundColor = alertBGColor
}
alertContentView.layer.cornerRadius = alertCornerRadius!
showIn.present(alert, animated: true, completion: nil)
}
public class func base_textfiele_alertVC(title:String? = "",
titleColor:UIColor? = UIColor.black,
titleFont:UIFont? = UIFont.systemFont(ofSize: 15),
okBtn:String,
cancelBtn:String,
showIn:UIViewController,
cancelBtnColor:UIColor? = .black,
doneBtnColor:UIColor? = .systemBlue,
placeHolders:[String],
textFieldTexts:[String],
keyboardType:[UIKeyboardType]?,
textFieldDelegate:Any? = nil,
alertBGColor:UIColor? = .white,
alertCornerRadius:CGFloat? = 15,
cancel:(()->Void)? = nil,
doneBtn:((_ result:[String:String])->Void)?)
{
let alert = UIAlertController(title: title, message: "", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancelBtn, style: .cancel) { (action) in
if cancel != nil
{
cancel!()
}
}
alert.addAction(cancelAction)
cancelAction.setValue(cancelBtnColor, forKey: "titleTextColor")
if placeHolders.count == textFieldTexts.count
{
placeHolders.enumerated().forEach({ (index,value) in
alert.addTextField { (textField : UITextField) -> Void in
textField.placeholder = value
textField.delegate = (textFieldDelegate as! UITextFieldDelegate)
textField.tag = index
textField.text = textFieldTexts[index]
if keyboardType?.count == placeHolders.count
{
textField.keyboardType = keyboardType![index]
}
}
})
}
let doneAction = UIAlertAction(title: okBtn, style: .default) { (action) in
var resultDic = [String:String]()
alert.textFields?.enumerated().forEach({ (index,value) in
resultDic[value.placeholder!] = value.text
})
if doneBtn != nil
{
doneBtn!(resultDic)
}
}
alert.addAction(doneAction)
doneAction.setValue(doneBtnColor, forKey: "titleTextColor")
// KVC修改系统弹框文字颜色字号
if !(title ?? "").stringIsEmpty()
{
let alertStr = NSMutableAttributedString(string: title!)
let alertStrAttr = [NSAttributedString.Key.foregroundColor: titleColor!, NSAttributedString.Key.font: titleFont!]
alertStr.addAttributes(alertStrAttr, range: NSMakeRange(0, title!.count))
alert.setValue(alertStr, forKey: "attributedTitle")
}
let subview = alert.view.subviews.first! as UIView
let alertContentView = subview.subviews.first! as UIView
if alertBGColor != .white
{
alertContentView.backgroundColor = alertBGColor
}
alertContentView.layer.cornerRadius = alertCornerRadius!
showIn.present(alert, animated: true, completion: nil)
}
public class func showNetworkActivityIndicator(_ show:Bool)
{
PTUtils.gcdMain {
UIApplication.shared.isNetworkActivityIndicatorVisible = show
}
}
public class func gcdAfter(time:TimeInterval,
block:@escaping (()->Void))
{
DispatchQueue.main.asyncAfter(deadline: .now() + time, execute: block)
}
public class func gcdMain(block:@escaping (()->Void))
{
DispatchQueue.global(qos: .userInitiated).async {
DispatchQueue.main.sync(execute: block)
}
}
public class func getTimeStamp()->String
{
let date = Date()
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
_ = NSTimeZone.init(name: "Asia/Shanghai")
return String(format: "%.0f", date.timeIntervalSince1970 * 1000)
}
public class func timeRunWithTime_base(customQueName:String,timeInterval:TimeInterval,finishBlock:@escaping ((_ finish:Bool,_ time:Int)->Void))
{
let customQueue = DispatchQueue(label: customQueName)
var newCount = Int(timeInterval) + 1
PTUtils.share.timer = DispatchSource.makeTimerSource(flags: [], queue: customQueue)
PTUtils.share.timer!.schedule(deadline: .now(), repeating: .seconds(1))
PTUtils.share.timer!.setEventHandler {
DispatchQueue.main.async {
newCount -= 1
finishBlock(false,newCount)
if newCount < 1 {
DispatchQueue.main.async {
finishBlock(true,0)
}
PTUtils.share.timer!.cancel()
PTUtils.share.timer = nil
}
}
}
PTUtils.share.timer!.resume()
}
public class func timeRunWithTime(timeInterval:TimeInterval,
sender:UIButton,
originalTitle:String,
canTap:Bool,
timeFinish:(()->Void)?)
{
PTUtils.timeRunWithTime_base(customQueName:"TimeFunction",timeInterval: timeInterval) { finish, time in
if finish
{
sender.setTitle(originalTitle, for: sender.state)
sender.isUserInteractionEnabled = canTap
if timeFinish != nil
{
timeFinish!()
}
}
else
{
let strTime = String.init(format: "%.2d", time)
let buttonTime = String.init(format: "%@", strTime)
sender.setTitle(buttonTime, for: sender.state)
sender.isUserInteractionEnabled = false
}
}
}
public class func contentTypeForUrl(url:String)->PTUrlStringVideoType
{
let pathEX = url.pathExtension.lowercased()
if pathEX.contains("mp4")
{
return .MP4
}
else if pathEX.contains("mov")
{
return .MOV
}
else if pathEX.contains("3gp")
{
return .ThreeGP
}
return .UNKNOW
}
public class func sizeFor(string:String,
font:UIFont,
lineSpacing:CGFloat? = nil,
height:CGFloat,
width:CGFloat)->CGSize
{
var dic = [NSAttributedString.Key.font:font] as! [NSAttributedString.Key:Any]
if lineSpacing != nil
{
let paraStyle = NSMutableParagraphStyle()
paraStyle.lineSpacing = lineSpacing!
dic[NSAttributedString.Key.paragraphStyle] = paraStyle
}
let size = string.boundingRect(with: CGSize.init(width: width, height: height), options: [.usesLineFragmentOrigin,.usesDeviceMetrics], attributes: dic, context: nil).size
return size
}
public class func getCurrentVCFrom(rootVC:UIViewController)->UIViewController
{
var currentVC : UIViewController?
if rootVC is UITabBarController
{
currentVC = PTUtils.getCurrentVCFrom(rootVC: (rootVC as! UITabBarController).selectedViewController!)
}
else if rootVC is UINavigationController
{
currentVC = PTUtils.getCurrentVCFrom(rootVC: (rootVC as! UINavigationController).visibleViewController!)
}
else
{
currentVC = rootVC
}
return currentVC!
}
public class func getCurrentVC(anyClass:UIViewController? = UIViewController())->UIViewController
{
let currentVC = PTUtils.getCurrentVCFrom(rootVC: (AppWindows?.rootViewController ?? anyClass!))
return currentVC
}
public class func returnFrontVC()
{
let vc = PTUtils.getCurrentVC()
if vc.presentingViewController != nil
{
vc.dismiss(animated: true, completion: nil)
}
else
{
vc.navigationController?.popViewController(animated: true, nil)
}
}
public class func cgBaseBundle()->Bundle
{
let bundle = Bundle.init(for: self)
return bundle
}
@available(iOS 11.0, *)
public class func color(name:String,traitCollection:UITraitCollection,bundle:Bundle? = PTUtils.cgBaseBundle())->UIColor
{
return UIColor(named: name, in: bundle!, compatibleWith: traitCollection) ?? .randomColor
}
public class func image(name:String,traitCollection:UITraitCollection,bundle:Bundle? = PTUtils.cgBaseBundle())->UIImage
{
return UIImage(named: name, in: bundle!, compatibleWith: traitCollection) ?? UIColor.randomColor.createImageWithColor()
}
public class func darkModeImage(name:String,bundle:Bundle? = PTUtils.cgBaseBundle())->UIImage
{
return PTUtils.image(name: name, traitCollection: (UIApplication.shared.delegate?.window?!.rootViewController!.traitCollection)!,bundle: bundle!)
}
//MARK:SDWebImage的加载失误图片方式(全局控制)
///SDWebImage的加载失误图片方式(全局控制)
public class func gobalWebImageLoadOption()->SDWebImageOptions
{
#if DEBUG
let userDefaults = UserDefaults.standard.value(forKey: "sdwebimage_option")
let devServer:Bool = userDefaults == nil ? true : (userDefaults as! Bool)
if devServer
{
return .retryFailed
}
else
{
return .lowPriority
}
#else
return .retryFailed
#endif
}
//MARK: 弹出框
class open func gobal_drop(title:String?,titleFont:UIFont? = UIFont.appfont(size: 16),titleColor:UIColor? = .black,subTitle:String? = nil,subTitleFont:UIFont? = UIFont.appfont(size: 16),subTitleColor:UIColor? = .black,bannerBackgroundColor:UIColor? = .white,notifiTap:(()->Void)? = nil)
{
var titleStr = ""
if title == nil || (title ?? "").stringIsEmpty()
{
titleStr = ""
}
else
{
titleStr = title!
}
var subTitleStr = ""
if subTitle == nil || (subTitle ?? "").stringIsEmpty()
{
subTitleStr = ""
}
else
{
subTitleStr = subTitle!
}
let banner = FloatingNotificationBanner(title:titleStr,subtitle: subTitleStr)
banner.duration = 1.5
banner.backgroundColor = bannerBackgroundColor!
banner.subtitleLabel?.textAlignment = PTUtils.sizeFor(string: subTitleStr, font: subTitleFont!, height:44, width: CGFloat(MAXFLOAT)).width > (kSCREEN_WIDTH - 36) ? .left : .center
banner.subtitleLabel?.font = subTitleFont
banner.subtitleLabel?.textColor = subTitleColor!
banner.titleLabel?.textAlignment = PTUtils.sizeFor(string: titleStr, font: titleFont!, height:44, width: CGFloat(MAXFLOAT)).width > (kSCREEN_WIDTH - 36) ? .left : .center
banner.titleLabel?.font = titleFont
banner.titleLabel?.textColor = titleColor!
banner.show(queuePosition: .front, bannerPosition: .top ,cornerRadius: 15)
banner.onTap = {
if notifiTap != nil
{
notifiTap!()
}
}
}
//MARK: 生成CollectionView的Group
@available(iOS 13.0, *)
class open func gobal_collection_gird_layout(data:[AnyObject],
size:CGSize? = CGSize.init(width: (kSCREEN_WIDTH - 10 * 2)/3, height: (kSCREEN_WIDTH - 10 * 2)/3),
originalX:CGFloat? = 10,
mainWidth:CGFloat? = kSCREEN_WIDTH,
cellRowCount:NSInteger? = 3,
sectionContentInsets:NSDirectionalEdgeInsets? = NSDirectionalEdgeInsets.init(top: 0, leading: 0, bottom: 0, trailing: 0),
contentTopAndBottom:CGFloat? = 0,
cellLeadingSpace:CGFloat? = 0,
cellTrailingSpace:CGFloat? = 0)->NSCollectionLayoutGroup
{
let bannerItemSize = NSCollectionLayoutSize.init(widthDimension: NSCollectionLayoutDimension.fractionalWidth(1), heightDimension: NSCollectionLayoutDimension.fractionalHeight(1))
let bannerItem = NSCollectionLayoutItem.init(layoutSize: bannerItemSize)
var bannerGroupSize : NSCollectionLayoutSize
var customers = [NSCollectionLayoutGroupCustomItem]()
var groupH:CGFloat = 0
let itemH = size!.height
let itemW = size!.width
var x:CGFloat = originalX!,y:CGFloat = 0 + contentTopAndBottom!
data.enumerated().forEach { (index,value) in
if index < cellRowCount!
{
let customItem = NSCollectionLayoutGroupCustomItem.init(frame: CGRect.init(x: x, y: y, width: itemW, height: itemH), zIndex: 1000+index)
customers.append(customItem)
x += itemW + cellLeadingSpace!
if index == (data.count - 1)
{
groupH = y + itemH + contentTopAndBottom!
}
}
else
{
x += itemW + cellLeadingSpace!
if index > 0 && (index % cellRowCount! == 0)
{
x = originalX!
y += itemH + cellTrailingSpace!
}
if index == (data.count - 1)
{
groupH = y + itemH + contentTopAndBottom!
}
let customItem = NSCollectionLayoutGroupCustomItem.init(frame: CGRect.init(x: x, y: y, width: itemW, height: itemH), zIndex: 1000+index)
customers.append(customItem)
}
}
bannerItem.contentInsets = sectionContentInsets!
bannerGroupSize = NSCollectionLayoutSize.init(widthDimension: NSCollectionLayoutDimension.absolute(mainWidth!-originalX!*2), heightDimension: NSCollectionLayoutDimension.absolute(groupH))
return NSCollectionLayoutGroup.custom(layoutSize: bannerGroupSize, itemProvider: { layoutEnvironment in
customers
})
}
//MARK: 计算CollectionView的Group高度
class open func gobal_collection_gird_layout_content_height(data:[AnyObject],
size:CGSize? = CGSize.init(width: (kSCREEN_WIDTH - 10 * 2)/3, height: (kSCREEN_WIDTH - 10 * 2)/3),
cellRowCount:NSInteger? = 3,
originalX:CGFloat? = 10,
contentTopAndBottom:CGFloat? = 0,
cellLeadingSpace:CGFloat? = 0,
cellTrailingSpace:CGFloat? = 0)->CGFloat
{
var groupH:CGFloat = 0
let itemH = size!.height
let itemW = size!.width
var x:CGFloat = originalX!,y:CGFloat = 0 + contentTopAndBottom!
data.enumerated().forEach { (index,value) in
if index < cellRowCount!
{
x += itemW + cellLeadingSpace!
if index == (data.count - 1)
{
groupH = y + itemH + contentTopAndBottom!
}
}
else
{
x += itemW + cellLeadingSpace!
if index > 0 && (index % cellRowCount! == 0)
{
x = originalX!
y += itemH + cellTrailingSpace!
}
if index == (data.count - 1)
{
groupH = y + itemH + contentTopAndBottom!
}
}
}
return groupH
}
//MARK: 获取一个输入内最大的一个值
///获取一个输入内最大的一个值
class open func maxOne<T:Comparable>( _ seq:[T]) -> T{
assert(seq.count>0)
return seq.reduce(seq[0]){
max($0, $1)
}
}
//MARK: 华氏摄氏度转普通摄氏度/普通摄氏度转华氏摄氏度
///华氏摄氏度转普通摄氏度/普通摄氏度转华氏摄氏度
class open func temperatureUnitExchangeValue(value:CGFloat,changeToType:TemperatureUnit) ->CGFloat
{
switch changeToType {
case .Fahrenheit:
return 32 + 1.8 * value
case .CentigradeDegree:
return (value - 32) / 1.8
default:
return 0
}
}
//MARK: 判断是否白天
/// 判断是否白天
class open func isNowDayTime()->Bool
{
let date = NSDate()
let cal :NSCalendar = NSCalendar.current as NSCalendar
let components : NSDateComponents = cal.components(.hour, from: date as Date) as NSDateComponents
if components.hour >= 19 || components.hour < 6
{
return false
}
else
{
return true
}
}
class open func findSuperViews(view:UIView)->[UIView]
{
var temp = view.superview
let result = NSMutableArray()
while temp != nil {
result.add(temp!)
temp = temp!.superview
}
return result as! [UIView]
}
class open func findCommonSuperView(firstView:UIView,other:UIView)->[UIView]
{
let result = NSMutableArray()
let sOne = self.findSuperViews(view: firstView)
let sOther = self.findSuperViews(view: other)
var i = 0
while i < min(sOne.count, sOther.count) {
if sOne == sOther
{
result.add(sOne)
i += 1
}
else
{
break
}
}
return result as! [UIView]
}
class open func createNoneInterpolatedUIImage(image:CIImage,imageSize:CGFloat)->UIImage
{
let extent = CGRectIntegral(image.extent)
let scale = min(imageSize / extent.width, imageSize / extent.height)
let width = extent.width * scale
let height = extent.height * scale
let cs = CGColorSpaceCreateDeviceGray()
let bitmapRef:CGContext = CGContext(data: nil , width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: CGImageAlphaInfo.none.rawValue)!
let context = CIContext.init()
let bitmapImage = context.createCGImage(image, from: extent)
bitmapRef.interpolationQuality = .none
bitmapRef.scaleBy(x: scale, y: scale)
bitmapRef.draw(bitmapImage!, in: extent)
let scaledImage = bitmapRef.makeImage()
let newImage = UIImage(cgImage: scaledImage!)
return newImage
}
}
//MARK: OC-FUNCTION
extension PTUtils
{
public class func oc_alert_base(title:String,msg:String,okBtns:[String],cancelBtn:String,showIn:UIViewController,cancel:@escaping (()->Void),moreBtn:@escaping ((_ index:Int,_ title:String)->Void))
{
PTUtils.base_alertVC(title: title, msg: msg, okBtns: okBtns, cancelBtn: cancelBtn, showIn: showIn, cancel: cancel, moreBtn: moreBtn)
}
public class func oc_size(string:String,
font:UIFont,
lineSpacing:CGFloat = CGFloat.ScaleW(w: 3),
height:CGFloat,
width:CGFloat)->CGSize
{
return PTUtils.sizeFor(string: string, font: font,lineSpacing: lineSpacing, height: height, width: width)
}
class open func oc_font(fontSize:CGFloat)->UIFont
{
return UIFont.appfont(size: fontSize)
}
//MARK: 时间
class open func oc_currentTimeFunction(dateFormatter:NSString)->String
{
return String.currentDate(dateFormatterString: dateFormatter as String)
}
class open func oc_currentTimeToTimeInterval(dateFormatter:NSString)->TimeInterval
{
return String.currentDate(dateFormatterString: dateFormatter as String).dateStrToTimeInterval(dateFormat: dateFormatter as String)
}
class open func oc_dateStringFormat(dateString:String,formatString:String)->NSString
{
let regions = Region(calendar: Calendars.republicOfChina,zone: Zones.asiaHongKong,locale: Locales.chineseChina)
return dateString.toDate(formatString,region: regions)!.toString() as NSString
}
class open func oc_dateFormat(date:Date,formatString:String)->String
{
return date.toFormat(formatString)
}
}
| mit |
zarochintsev/MotivationBox | CurrentMotivation/Classes/PresentationLayer/Modules/CurrentMotivation/Module/Router/CurrentMotivationRouterInput.swift | 1 | 1254 | //
// CurrentMotivationRouterInput.swift
//
// MIT License
//
// Copyright (c) 2017 Alex Zarochintsev
//
// 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
protocol CurrentMotivationRouterInput: class {
}
| mit |
iOSDevLog/iOSDevLog | 201. UI Test/Swift/ListerKit/CloudListCoordinator.swift | 1 | 11243 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `CloudListCoordinator` class handles querying for and interacting with lists stored as files in iCloud Drive.
*/
import Foundation
/**
An object that conforms to the `CloudListCoordinator` protocol and is responsible for implementing
entry points in order to communicate with an `ListCoordinatorDelegate`. In the case of Lister,
this is the `ListsController` instance. The main responsibility of a `CloudListCoordinator` is
to track different `NSURL` instances that are important. The iCloud coordinator is responsible for
making sure that the `ListsController` knows about the current set of iCloud documents that are
available.
There are also other responsibilities that an `CloudListCoordinator` must have that are specific
to the underlying storage mechanism of the coordinator. A `CloudListCoordinator` determines whether
or not a new list can be created with a specific name, it removes URLs tied to a specific list, and
it is also responsible for listening for updates to any changes that occur at a specific URL
(e.g. a list document is updated on another device, etc.).
Instances of `CloudListCoordinator` can search for URLs in an asynchronous way. When a new `NSURL`
instance is found, removed, or updated, the `ListCoordinator` instance must make its delegate
aware of the updates. If a failure occured in removing or creating an `NSURL` for a given list,
it must make its delegate aware by calling one of the appropriate error methods defined in the
`ListCoordinatorDelegate` protocol.
*/
public class CloudListCoordinator: ListCoordinator {
// MARK: Properties
public weak var delegate: ListCoordinatorDelegate?
/// Closure executed after the first update provided by the coordinator regarding tracked URLs.
private var firstQueryUpdateHandler: (Void -> Void)?
/// Initialized asynchronously in init(predicate:).
private var _documentsDirectory: NSURL!
public var documentsDirectory: NSURL {
var documentsDirectory: NSURL!
dispatch_sync(documentsDirectoryQueue) {
documentsDirectory = self._documentsDirectory
}
return documentsDirectory
}
private var metadataQuery: NSMetadataQuery
/// A private, local queue to `CloudListCoordinator` that is used to ensure serial accesss to `documentsDirectory`.
private let documentsDirectoryQueue = dispatch_queue_create("com.example.apple-samplecode.lister.cloudlistcoordinator", DISPATCH_QUEUE_CONCURRENT)
// MARK: Initializers
/**
Initializes an `CloudListCoordinator` based on a path extension used to identify files that can be
managed by the app. Also provides a block parameter that can be used to provide actions to be executed
when the coordinator returns its first set of documents. This coordinator monitors the app's iCloud Drive
container.
- parameter pathExtension: The extension that should be used to identify documents of interest to this coordinator.
- parameter firstQueryUpdateHandler: The handler that is executed once the first results are returned.
*/
public convenience init(pathExtension: String, firstQueryUpdateHandler: (Void -> Void)? = nil) {
let predicate = NSPredicate(format: "(%K.pathExtension = %@)", argumentArray: [NSMetadataItemURLKey, pathExtension])
self.init(predicate: predicate, firstQueryUpdateHandler: firstQueryUpdateHandler)
}
/**
Initializes an `CloudListCoordinator` based on a single document used to identify a file that should
be monitored. Also provides a block parameter that can be used to provide actions to be executed when the
coordinator returns its initial result. This coordinator monitors the app's iCloud Drive container.
- parameter lastPathComponent: The file name that should be monitored by this coordinator.
- parameter firstQueryUpdateHandler: The handler that is executed once the first results are returned.
*/
public convenience init(lastPathComponent: String, firstQueryUpdateHandler: (Void -> Void)? = nil) {
let predicate = NSPredicate(format: "(%K.lastPathComponent = %@)", argumentArray: [NSMetadataItemURLKey, lastPathComponent])
self.init(predicate: predicate, firstQueryUpdateHandler: firstQueryUpdateHandler)
}
private init(predicate: NSPredicate, firstQueryUpdateHandler: (Void -> Void)?) {
self.firstQueryUpdateHandler = firstQueryUpdateHandler
metadataQuery = NSMetadataQuery()
// These search scopes search for files in iCloud Drive.
metadataQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope, NSMetadataQueryAccessibleUbiquitousExternalDocumentsScope]
metadataQuery.predicate = predicate
dispatch_barrier_async(documentsDirectoryQueue) {
let cloudContainerURL = NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil)
self._documentsDirectory = cloudContainerURL?.URLByAppendingPathComponent("Documents")
}
// Observe the query.
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "metadataQueryDidFinishGathering:", name: NSMetadataQueryDidFinishGatheringNotification, object: metadataQuery)
notificationCenter.addObserver(self, selector: "metadataQueryDidUpdate:", name: NSMetadataQueryDidUpdateNotification, object: metadataQuery)
}
// MARK: Lifetime
deinit {
// Stop observing the query.
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: NSMetadataQueryDidFinishGatheringNotification, object: metadataQuery)
notificationCenter.removeObserver(self, name: NSMetadataQueryDidUpdateNotification, object: metadataQuery)
}
// MARK: ListCoordinator
public func startQuery() {
// `NSMetadataQuery` should always be started on the main thread.
dispatch_async(dispatch_get_main_queue()) {
self.metadataQuery.startQuery()
return
}
}
public func stopQuery() {
// `NSMetadataQuery` should always be stopped on the main thread.
dispatch_async(dispatch_get_main_queue()) {
self.metadataQuery.stopQuery()
}
}
public func createURLForList(list: List, withName name: String) {
let documentURL = documentURLForName(name)
ListUtilities.createList(list, atURL: documentURL) { error in
if let realError = error {
self.delegate?.listCoordinatorDidFailCreatingListAtURL(documentURL, withError: realError)
}
else {
self.delegate?.listCoordinatorDidUpdateContents(insertedURLs: [documentURL], removedURLs: [], updatedURLs: [])
}
}
}
public func canCreateListWithName(name: String) -> Bool {
if name.isEmpty {
return false
}
let documentURL = documentURLForName(name)
return !NSFileManager.defaultManager().fileExistsAtPath(documentURL.path!)
}
public func copyListFromURL(URL: NSURL, toListWithName name: String) {
let documentURL = documentURLForName(name)
ListUtilities.copyFromURL(URL, toURL: documentURL)
}
public func removeListAtURL(URL: NSURL) {
ListUtilities.removeListAtURL(URL) { error in
if let realError = error {
self.delegate?.listCoordinatorDidFailRemovingListAtURL(URL, withError: realError)
}
else {
self.delegate?.listCoordinatorDidUpdateContents(insertedURLs: [], removedURLs: [URL], updatedURLs: [])
}
}
}
// MARK: NSMetadataQuery Notifications
@objc private func metadataQueryDidFinishGathering(notifcation: NSNotification) {
metadataQuery.disableUpdates()
let metadataItems = metadataQuery.results as! [NSMetadataItem]
let insertedURLs = metadataItems.map { $0.valueForAttribute(NSMetadataItemURLKey) as! NSURL }
delegate?.listCoordinatorDidUpdateContents(insertedURLs: insertedURLs, removedURLs: [], updatedURLs: [])
metadataQuery.enableUpdates()
// Execute the `firstQueryUpdateHandler`, it will contain the closure from initialization on first update.
if let handler = firstQueryUpdateHandler {
handler()
// Set `firstQueryUpdateHandler` to an empty closure so that the handler provided is only run on first update.
firstQueryUpdateHandler = nil
}
}
/**
Private methods that are used with Objective-C for notifications, target / action, etc. should
be marked as @objc.
*/
@objc private func metadataQueryDidUpdate(notification: NSNotification) {
metadataQuery.disableUpdates()
let insertedURLs: [NSURL]
let removedURLs: [NSURL]
let updatedURLs: [NSURL]
let metadataItemToURLTransform: NSMetadataItem -> NSURL = { metadataItem in
return metadataItem.valueForAttribute(NSMetadataItemURLKey) as! NSURL
}
if let insertedMetadataItems = notification.userInfo?[NSMetadataQueryUpdateAddedItemsKey] as? [NSMetadataItem] {
insertedURLs = insertedMetadataItems.map(metadataItemToURLTransform)
}
else {
insertedURLs = []
}
if let removedMetadataItems = notification.userInfo?[NSMetadataQueryUpdateRemovedItemsKey] as? [NSMetadataItem] {
removedURLs = removedMetadataItems.map(metadataItemToURLTransform)
}
else {
removedURLs = []
}
if let updatedMetadataItems = notification.userInfo?[NSMetadataQueryUpdateChangedItemsKey] as? [NSMetadataItem] {
let completelyDownloadedUpdatedMetadataItems = updatedMetadataItems.filter { updatedMetadataItem in
let downloadStatus = updatedMetadataItem.valueForAttribute(NSMetadataUbiquitousItemDownloadingStatusKey) as! String
return downloadStatus == NSMetadataUbiquitousItemDownloadingStatusCurrent
}
updatedURLs = completelyDownloadedUpdatedMetadataItems.map(metadataItemToURLTransform)
}
else {
updatedURLs = []
}
delegate?.listCoordinatorDidUpdateContents(insertedURLs: insertedURLs, removedURLs: removedURLs, updatedURLs: updatedURLs)
metadataQuery.enableUpdates()
}
// MARK: Convenience
private func documentURLForName(name: String) -> NSURL {
let documentURLWithoutExtension = documentsDirectory.URLByAppendingPathComponent(name)
return documentURLWithoutExtension.URLByAppendingPathExtension(AppConfiguration.listerFileExtension)
}
}
| mit |
zjjzmw1/robot | robot/robot/WebVC/WebViewProgressView.swift | 1 | 3964 | //
// WebViewProgressView.swift
// WKWebViewProgressView
//
// Created by LZios on 16/3/3.
// Copyright © 2016年 LZios. All rights reserved.
//
import UIKit
import WebKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
class WebViewProgressView: UIView {
var superWebView: WKWebView?
var topY: CGFloat? = 0
override func willMove(toSuperview newSuperview: UIView?) {
if let webView = newSuperview as? WKWebView {
superWebView = webView
superWebView?.addObserver(self, forKeyPath: "estimatedProgress", options: [.new, .old], context: nil)
superWebView?.scrollView.addObserver(self, forKeyPath: "contentInset", options: [.new, .old], context: nil)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let webView = object as? WKWebView {
if webView == superWebView && keyPath == "estimatedProgress" {
self.animateLayerPosition(keyPath)
}
}
if let scrollView = object as? UIScrollView {
if scrollView == superWebView?.scrollView && keyPath == "contentInset" {
self.animateLayerPosition(keyPath)
}
}
print(superWebView?.estimatedProgress ?? 0.0)
}
override func layoutSubviews() {
}
func animateLayerPosition(_ keyPath: String?) {
if keyPath == "estimatedProgress" {
self.isHidden = false
}else if keyPath == "contentInset" {
topY = superWebView?.scrollView.contentInset.top
}
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in
self.frame = CGRect(x: 0, y: self.topY!, width: (self.superWebView?.bounds.width)! * CGFloat((self.superWebView?.estimatedProgress)!), height: 3)
}, completion: { (finished) -> Void in
if self.superWebView?.estimatedProgress >= 1 {
self.isHidden = true
self.frame = CGRect(x: 0, y: self.topY!, width: 0, height: 3)
}
})
}
deinit {
superWebView?.removeObserver(self, forKeyPath: "estimatedProgress", context: nil)
superWebView?.scrollView.removeObserver(self, forKeyPath: "contentInset", context: nil)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
public let GDBProgressViewTag = 214356312
extension WKWebView {
fileprivate var progressView: UIView? {
get {
let progressView = viewWithTag(GDBProgressViewTag)
return progressView
}
}
public func addProgressView() {
if progressView == nil {
let view = WebViewProgressView()
view.frame = CGRect(x: 0, y: 64, width: 0, height: 3)
view.backgroundColor = UIColor.getMainColorSwift()
view.tag = GDBProgressViewTag
view.autoresizingMask = .flexibleWidth
self.addSubview(view)
}
}
}
| mit |
kagenZhao/cnBeta | iOS/CnBeta/Behavior/Nuke Setup/NukeSetup.swift | 1 | 1516 | //
// ImageLoader.swift
// CnBeta
//
// Created by 赵国庆 on 2017/8/18.
// Copyright © 2017年 Kagen. All rights reserved.
//
import UIKit
import Nuke
import NukeAlamofirePlugin
import NukeGifuPlugin
let ImageLoader = { () -> Nuke.Manager in
let decoder = Nuke.DataDecoderComposition(decoders: [NukeGifuPlugin.AnimatedImageDecoder(), Nuke.DataDecoder()])
let cache = Nuke.Cache().preparedForAnimatedImages()
let loader = Nuke.Loader(loader: NukeAlamofirePlugin.DataLoader(), decoder: decoder)
loader.makeProcessor = { image, request in
image is NukeGifuPlugin.AnimatedImage ? nil : request.processor
}
return Nuke.Manager(loader: loader, cache: cache)
}()
typealias ImageView = NukeGifuPlugin.AnimatedImageView
extension Nuke.Manager {
func loadImage(with str: String, into target: ImageView, placeholder: UIImage? = nil) {
if let url = URL(string: str) {
target.imageView.image = placeholder
ImageLoader.loadImage(with: url, into: target)
} else {
target.imageView.image = UIImage(named: str)
}
}
func loadImage(with str: String, into target: ImageView, placeholder: UIImage? = nil, handler: @escaping Nuke.Manager.Handler) {
if let url = URL(string: str) {
target.imageView.image = placeholder
ImageLoader.loadImage(with: Request(url: url), into: target, handler: handler)
} else {
target.imageView.image = UIImage(named: str)
}
}
}
| mit |
DrGo/LearningSwift | PLAYGROUNDS/ExpressionParser/ExpressionParser/Token.swift | 2 | 7039 | //
// Token.swift
// ExpressionParser
//
// Created by Kyle Oba on 2/5/15.
// Copyright (c) 2015 Pas de Chocolat. All rights reserved.
//
import Foundation
/*---------------------------------------------------------------------/
// Tokens
/---------------------------------------------------------------------*/
public enum Token : Equatable {
case Number(Int)
case Operator(String)
case Reference(String, Int)
case Punctuation(String)
case FunctionName(String)
}
public func ==(lhs: Token, rhs: Token) -> Bool {
switch (lhs,rhs) {
case (.Number(let x), .Number(let y)):
return x == y
case (.Operator(let x), .Operator(let y)):
return x == y
case (.Reference(let row, let column), .Reference(let row1, let column1)):
return row == row1 && column == column1
case (.Punctuation(let x), .Punctuation(let y)):
return x == y
case (.FunctionName (let x), .FunctionName(let y)):
return x == y
default:
return false
}
}
extension Token : Printable {
public var description: String {
switch (self) {
case Number(let x):
return "\(x)"
case .Operator(let o):
return o
case .Reference(let row, let column):
return "\(row)\(column)"
case .Punctuation(let x):
return x
case .FunctionName(let x):
return x
}
}
}
/*---------------------------------------------------------/
// parse - Debug helper
/---------------------------------------------------------*/
public func parse<A>(parser: Parser<Character, A>, input: String) -> A? {
for (result, _) in (parser <* eof()).p(input.slice) {
return result
}
return nil
}
public func parse<A, B>(parser: Parser<A, B>, input: [A]) -> B? {
for (result, _) in (parser <* eof()).p(input[0..<input.count]) {
return result
}
return nil
}
/*---------------------------------------------------------------------/
// const - Takes an arg and constructs a function that always
// (constantly) returns the arg, diregarding the arguments
// sent to the contructed function.
/---------------------------------------------------------------------*/
public func const<A, B>(x: A) -> (y: B) -> A {
return { _ in x }
}
/*---------------------------------------------------------/
// decompose - Required Array extension
/---------------------------------------------------------*/
extension Array {
var decompose: (head: T, tail: [T])? {
return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}
}
/*---------------------------------------------------------/
// tokens - Constructs a parser that consumes all elements
// passed into constructor via array.
/---------------------------------------------------------*/
func tokens<A: Equatable>(input: [A]) -> Parser<A, [A]> {
if let (head, tail) = input.decompose {
return prepend </> token(head) <*> tokens(tail)
} else {
return pure([])
}
}
/*---------------------------------------------------------/
// string - Constructs a parser that parses a string
// given to the constructor.
/---------------------------------------------------------*/
func string(string: String) -> Parser<Character, String> {
return const(string) </> tokens(string.characters)
}
/*---------------------------------------------------------/
// oneOf - Allows combination of parsers in a mutually
// exclusive manner
/---------------------------------------------------------*/
func oneOf<Token, A>(parsers: [Parser<Token, A>]) -> Parser<Token, A> {
return parsers.reduce(fail(), combine: <|>)
}
/*---------------------------------------------------------/
// naturalNumber - Parses natural numbers
/---------------------------------------------------------*/
let pDigit = oneOf(Array(0...9).map { const($0) </> string("\($0)") })
func toNaturalNumber(digits: [Int]) -> Int {
return digits.reduce(0) { $0 * 10 + $1 }
}
let naturalNumber = toNaturalNumber </> oneOrMore(pDigit)
/*---------------------------------------------------------/
// tNumber - Parses natural number and wraps in a Token
/---------------------------------------------------------*/
let tNumber = { Token.Number($0) } </> naturalNumber
/*---------------------------------------------------------/
// tOperator - Parses an operator and wraps in a Token
/---------------------------------------------------------*/
let operatorParsers = ["*", "/", "+", "-", ":"].map { string($0) }
let tOperator = { Token.Operator($0) } </> oneOf (operatorParsers)
/*---------------------------------------------------------/
// capital - For references, parse a single capital letter
/---------------------------------------------------------*/
let capitalSet = NSCharacterSet.uppercaseLetterCharacterSet()
let capital = characterFromSet(capitalSet)
/*---------------------------------------------------------/
// tReference - Capital letter followed by natural number
/---------------------------------------------------------*/
let tReference = curry { Token.Reference(String($0), $1) } </> capital <*> naturalNumber
/*---------------------------------------------------------/
// tPunctuation - Wraps open and close parens in a token
/---------------------------------------------------------*/
let punctuationParsers = ["(", ")"].map { string($0) }
let tPunctuation = { Token.Punctuation($0) } </> oneOf(punctuationParsers)
/*---------------------------------------------------------/
// tName - Function names are one or more capitals
/---------------------------------------------------------*/
let tName = { Token.FunctionName(String($0)) } </> oneOrMore(capital)
/*---------------------------------------------------------/
// ignoreLeadingWhitespace - Ignore whitespace between tokens
/---------------------------------------------------------*/
let whitespaceSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let whitespace = characterFromSet(whitespaceSet)
func ignoreLeadingWhitespace<A>(p: Parser<Character, A>) -> Parser<Character, A> {
return zeroOrMore(whitespace) *> p
}
/*---------------------------------------------------------/
// tokenize - Putting it all together
/---------------------------------------------------------*/
public func tokenize() -> Parser<Character, [Token]> {
let tokenParsers = [tNumber, tOperator, tReference, tPunctuation, tName]
return zeroOrMore(ignoreLeadingWhitespace(oneOf(tokenParsers)))
}
/*---------------------------------------------------------/
// Print tokens
/---------------------------------------------------------*/
public func readToken(t: Token) -> String {
switch t {
case .Number:
return "Number: \(t.description)"
case .Operator:
return "Operator: \(t.description)"
case .Reference:
return "Reference: \(t.description)"
case .Punctuation:
return "Punctuation: \(t.description)"
case .FunctionName:
return "Function Name: \(t.description)"
}
}
public func readTokens(tokens: [Token]) -> String {
return tokens.reduce("") { $0 + "\n\(readToken($1))" }
} | gpl-3.0 |
prolificinteractive/Kumi-iOS | Kumi/Core/Layer/LayerStyle+JSON.swift | 1 | 2119 | //
// LayerStyle+JSON.swift
// Kumi
//
// Created by VIRAKRI JINANGKUL on 6/3/17.
// Copyright © 2017 Prolific Interactive. All rights reserved.
//
import Foundation
extension LayerStyle {
public init?(json: JSON) {
var opacity: Float = 1
var masksToBounds: Bool = false
var isDoubleSided: Bool = true
var cornerRadius: CGFloat = 0
var borderWidth: CGFloat = 0
var borderColor: CGColor?
var backgroundColor: CGColor?
var shadowStyle: ShadowStyle?
var shadowColor: CGColor?
var transform: CATransform3D = CATransform3DIdentity
if let opacityValue = json["opacity"].double {
opacity = Float(opacityValue)
}
if let masksToBoundsValue = json["masksToBounds"].bool {
masksToBounds = masksToBoundsValue
}
if let isDoubleSidedValue = json["isDoubleSided"].bool {
isDoubleSided = isDoubleSidedValue
}
if let cornerRadiusValue = json["cornerRadius"].cgFloat {
cornerRadius = cornerRadiusValue
}
if let borderWidthValue = json["borderWidth"].cgFloat {
borderWidth = borderWidthValue
}
borderColor = UIColor(json: json["borderColor"])?.cgColor
backgroundColor = UIColor(json: json["backgroundColor"])?.cgColor
shadowStyle = ShadowStyle(json: json["shadowStyle"])
shadowColor = UIColor(json: json["shadowColor"])?.cgColor
if let transformValue = CATransform3D(json: json["transform"]) {
transform = transformValue
}
self.init(opacity: opacity,
masksToBounds: masksToBounds,
isDoubleSided: isDoubleSided,
cornerRadius: cornerRadius,
borderWidth: borderWidth,
borderColor: borderColor,
backgroundColor: backgroundColor,
shadowStyle: shadowStyle,
shadowColor: shadowColor,
transform: transform)
}
}
| mit |
newlix/orz-swift | Sources/decodeJWT.swift | 1 | 1102 | //
// jwt.swift
// Orz
//
// Created by newlix on 1/29/16.
// Copyright © 2016 newlix. All rights reserved.
//
import Foundation
public func base64decode(input:String) -> NSData? {
let rem = input.characters.count % 4
var ending = ""
if rem > 0 {
let amount = 4 - rem
ending = String(count: amount, repeatedValue: Character("="))
}
let base64 = input
.stringByReplacingOccurrencesOfString("-", withString: "+")
.stringByReplacingOccurrencesOfString("_", withString: "/") + ending
return NSData(base64EncodedString: base64, options: NSDataBase64DecodingOptions())
}
public func decodeJWT(jwt: String) throws -> [String: AnyObject]? {
let segments = jwt.componentsSeparatedByString(".")
if segments.count != 3 {
throw Error.DecodeJWT(jwt)
}
let payload = segments[1]
if let data = base64decode(payload),
body = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [String: AnyObject]
{
return body
}
throw Error.DecodeJWT(jwt)
}
| mit |
walmartlabs/RxSwift | RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaSearchResult.swift | 11 | 1827 | //
// WikipediaSearchResult.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
struct WikipediaSearchResult: CustomStringConvertible {
let title: String
let description: String
let URL: NSURL
init(title: String, description: String, URL: NSURL) {
self.title = title
self.description = description
self.URL = URL
}
// tedious parsing part
static func parseJSON(json: [AnyObject]) throws -> [WikipediaSearchResult] {
let rootArrayTyped = json.map { $0 as? [AnyObject] }
.filter { $0 != nil }
.map { $0! }
if rootArrayTyped.count != 3 {
throw WikipediaParseError
}
let titleAndDescription = Array(Swift.zip(rootArrayTyped[0], rootArrayTyped[1]))
let titleDescriptionAndUrl: [((AnyObject, AnyObject), AnyObject)] = Array(Swift.zip(titleAndDescription, rootArrayTyped[2]))
let searchResults: [WikipediaSearchResult] = try titleDescriptionAndUrl.map ( { result -> WikipediaSearchResult in
let (first, url) = result
let (title, description) = first
let titleString = title as? String,
descriptionString = description as? String,
urlString = url as? String
if titleString == nil || descriptionString == nil || urlString == nil {
throw WikipediaParseError
}
let URL = NSURL(string: urlString!)
if URL == nil {
throw WikipediaParseError
}
return WikipediaSearchResult(title: titleString!, description: descriptionString!, URL: URL!)
})
return searchResults
}
}
| mit |
vinhdd-rikkei/Training-iOS-2017-HoaLT | Exercise 1/Training iOS HoaLT Exercise 1/Training iOS HoaLT Exercise 1UITests/Training_iOS_HoaLT_Exercise_1UITests.swift | 1 | 1314 | //
// Training_iOS_HoaLT_Exercise_1UITests.swift
// Training iOS HoaLT Exercise 1UITests
//
// Created by Vinh Dang Duc on 7/20/17.
// Copyright © 2017 Vinh Dang Duc. All rights reserved.
//
import XCTest
class Training_iOS_HoaLT_Exercise_1UITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
jeanetienne/Bee | Bee/Architecture/Module.swift | 1 | 559 | //
// Bee
// Copyright © 2017 Jean-Étienne. All rights reserved.
//
import UIKit
typealias ModuleCompletionHandler = (UIViewController) -> ()
extension UIViewController {
static func loadFromStoryboard(withName storyboardName: String = "Main", identifier: String? = nil) -> UIViewController {
let viewIdentifier = (identifier == nil) ? String(describing: self) : identifier!
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
return storyboard.instantiateViewController(withIdentifier: viewIdentifier)
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.