repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
audiokit/AudioKit | Sources/AudioKit/Nodes/Effects/Guitar Processors/DynaRageCompressor.swift | 1 | 5110 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// DynaRage Tube Compressor | Based on DynaRage Tube Compressor RE for Reason
/// by Devoloop Srls
///
public class DynaRageCompressor: Node, AudioUnitContainer, Toggleable {
/// Unique four-letter identifier "dyrc"
public static let ComponentDescription = AudioComponentDescription(effect: "dyrc")
/// Internal type of audio unit for this node
public typealias AudioUnitType = InternalAU
/// Internal audio unit
public private(set) var internalAU: AudioUnitType?
// MARK: - Parameters
/// Specification details for ratio
public static let ratioDef = NodeParameterDef(
identifier: "ratio",
name: "Ratio to compress with, a value > 1 will compress",
address: akGetParameterAddress("DynaRageCompressorParameterRatio"),
range: 1.0 ... 20.0,
unit: .generic,
flags: .default)
/// Ratio to compress with, a value > 1 will compress
@Parameter public var ratio: AUValue
/// Specification details for threshold
public static let thresholdDef = NodeParameterDef(
identifier: "threshold",
name: "Threshold (in dB) 0 = max",
address: akGetParameterAddress("DynaRageCompressorParameterThreshold"),
range: -100.0 ... 0.0,
unit: .decibels,
flags: .default)
/// Threshold (in dB) 0 = max
@Parameter public var threshold: AUValue
/// Specification details for attack duration
public static let attackDurationDef = NodeParameterDef(
identifier: "attackDuration",
name: "Attack Duration",
address: akGetParameterAddress("DynaRageCompressorParameterAttackDuration"),
range: 0.1 ... 500.0,
unit: .seconds,
flags: .default)
/// Attack dration
@Parameter public var attackDuration: AUValue
/// Specification details for release duration
public static let releaseDurationDef = NodeParameterDef(
identifier: "releaseDuration",
name: "Release Duration",
address: akGetParameterAddress("DynaRageCompressorParameterReleaseDuration"),
range: 1.0 ... 20.0,
unit: .seconds,
flags: .default)
/// Release duration
@Parameter public var releaseDuration: AUValue
/// Specification details for rage amount
public static let rageDef = NodeParameterDef(
identifier: "rage",
name: "Rage",
address: akGetParameterAddress("DynaRageCompressorParameterRage"),
range: 0.1 ... 20.0,
unit: .generic,
flags: .default)
/// Rage Amount
@Parameter public var rage: AUValue
/// Specification details for range enabling
public static let rageEnabledDef = NodeParameterDef(
identifier: "rageEnabled",
name: "Rage Enabled",
address: akGetParameterAddress("DynaRageCompressorParameterRageEnabled"),
range: 0.0 ... 1.0,
unit: .boolean,
flags: .default)
/// Rage ON/OFF Switch
@Parameter public var rageEnabled: Bool
// MARK: - Audio Unit
/// Internal audio unit for DynaRageCompressor
public class InternalAU: AudioUnitBase {
/// Get an array of the parameter definitions
/// - Returns: Array of parameter definitions
public override func getParameterDefs() -> [NodeParameterDef] {
[DynaRageCompressor.ratioDef,
DynaRageCompressor.thresholdDef,
DynaRageCompressor.attackDurationDef,
DynaRageCompressor.releaseDurationDef,
DynaRageCompressor.rageDef,
DynaRageCompressor.rageEnabledDef]
}
/// Create the DSP Refence for this node
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
akCreateDSP("DynaRageCompressorDSP")
}
}
// MARK: - Initialization
/// Initialize this compressor node
///
/// - Parameters:
/// - input: Input node to process
/// - ratio: Ratio to compress with, a value > 1 will compress
/// - threshold: Threshold (in dB) 0 = max
/// - attackDuration: Attack duration in seconds
/// - releaseDuration: Release duration in seconds
///
public init(
_ input: Node,
ratio: AUValue = 1,
threshold: AUValue = 0.0,
attackDuration: AUValue = 0.1,
releaseDuration: AUValue = 0.1,
rage: AUValue = 0.1,
rageEnabled: Bool = true
) {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType
self.ratio = ratio
self.threshold = threshold
self.attackDuration = attackDuration
self.releaseDuration = releaseDuration
self.rage = rage
self.rageEnabled = rageEnabled
}
connections.append(input)
}
}
| mit | f00d70f5a502d8d9f776262315838e7a | 31.967742 | 100 | 0.643249 | 4.961165 | false | false | false | false |
CatchChat/Yep | Yep/Extensions/CGImage+Yep.swift | 1 | 1331 | //
// CGImage+Yep.swift
// Yep
//
// Created by nixzhu on 16/1/27.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import Foundation
extension CGImage {
var yep_extendedCanvasCGImage: CGImage {
let width = CGImageGetWidth(self)
let height = CGImageGetHeight(self)
guard width > 0 && height > 0 else {
return self
}
func hasAlpha() -> Bool {
let alpha = CGImageGetAlphaInfo(self)
switch alpha {
case .First, .Last, .PremultipliedFirst, .PremultipliedLast:
return true
default:
return false
}
}
var bitmapInfo = CGBitmapInfo.ByteOrder32Little.rawValue
if hasAlpha() {
bitmapInfo |= CGImageAlphaInfo.PremultipliedFirst.rawValue
} else {
bitmapInfo |= CGImageAlphaInfo.NoneSkipFirst.rawValue
}
guard let context = CGBitmapContextCreate(nil, width, height, 8, 0, CGColorSpaceCreateDeviceRGB(), bitmapInfo) else {
return self
}
CGContextDrawImage(context, CGRect(x: 0, y: 0, width: width, height: height), self)
guard let newCGImage = CGBitmapContextCreateImage(context) else {
return self
}
return newCGImage
}
}
| mit | 40d471c6a356c2aa1f82da9b8b8f7b2f | 24.538462 | 125 | 0.583584 | 5.011321 | false | false | false | false |
cuappdev/tempo | Tempo/Views/LikedPostView.swift | 1 | 7020 | //
// LikedPostView.swift
// Tempo
//
// Created by Logan Allen on 11/18/16.
// Copyright © 2016 CUAppDev. All rights reserved.
//
import UIKit
import MediaPlayer
import Haneke
class LikedPostView: PostView {
fileprivate var tapGestureRecognizer: UITapGestureRecognizer?
fileprivate var longPressGestureRecognizer: UILongPressGestureRecognizer?
let artworkImageLength: CGFloat = 54
let addButtonLength: CGFloat = 20
let padding: CGFloat = 22
let addButtonPadding: CGFloat = 17
let separatorHeight: CGFloat = 1
var labelWidth: CGFloat = 0
var isSpotifyAvailable: Bool = false
var songNameLabel: UILabel?
var songArtistLabel: UILabel?
var albumArtworkImageView: UIImageView?
var addButton: UIButton?
var songStatus: SavedSongStatus = .notSaved
var postViewDelegate: PostViewDelegate!
var playerDelegate: PlayerDelegate!
var playerController: PlayerTableViewController?
override var post: Post? {
didSet {
// update stuff
if let post = post {
songNameLabel?.text = post.song.title
songArtistLabel?.text = post.song.artist
albumArtworkImageView?.hnk_setImageFromURL(post.song.smallArtworkURL ?? URL(fileURLWithPath: ""))
if let _ = User.currentUser.currentSpotifyUser?.savedTracks[post.song.spotifyID] {
songStatus = .saved
}
updateAddButton()
}
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
backgroundColor = .unreadCellColor
albumArtworkImageView = UIImageView(frame: CGRect(x: padding, y: padding, width: artworkImageLength, height: artworkImageLength))
albumArtworkImageView?.center.y = center.y
albumArtworkImageView?.clipsToBounds = true
albumArtworkImageView?.translatesAutoresizingMaskIntoConstraints = true
addSubview(albumArtworkImageView!)
let labelX = (albumArtworkImageView?.frame.maxX)! + padding
let shorterlabelWidth = bounds.width - labelX - addButtonLength - 2*addButtonPadding
let longerLabelWidth = bounds.width - labelX - padding
let currLabelWidth = isSpotifyAvailable ? shorterlabelWidth : longerLabelWidth
songNameLabel = UILabel(frame: CGRect(x: labelX, y: padding, width: currLabelWidth, height: 22))
songNameLabel?.font = UIFont(name: "AvenirNext-Regular", size: 16.0)
songNameLabel?.textColor = .white
songNameLabel?.translatesAutoresizingMaskIntoConstraints = false
addSubview(songNameLabel!)
songArtistLabel = UILabel(frame: CGRect(x: labelX, y: (songNameLabel?.frame.maxY)! + 2, width: currLabelWidth, height: 22))
songArtistLabel?.font = UIFont(name: "AvenirNext-Regular", size: 14.0)
songArtistLabel?.textColor = .paleRed
songArtistLabel?.translatesAutoresizingMaskIntoConstraints = false
addSubview(songArtistLabel!)
addButton = UIButton(frame: CGRect(x: frame.width - addButtonLength - addButtonPadding, y: 34, width: addButtonLength, height: addButtonLength))
addButton?.center.y = center.y
addButton?.setBackgroundImage(#imageLiteral(resourceName: "AddButton"), for: .normal)
addButton?.translatesAutoresizingMaskIntoConstraints = true
addButton?.tag = 1 // this tag makes the hitbox bigger
addButton?.isHidden = !isSpotifyAvailable
addSubview(addButton!)
}
override func updatePlayingStatus() {
updateSongLabel()
updateBackground()
}
override func didMoveToWindow() {
if tapGestureRecognizer == nil {
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(likedPostViewPressed(_:)))
tapGestureRecognizer?.delegate = self
tapGestureRecognizer?.cancelsTouchesInView = false
addGestureRecognizer(tapGestureRecognizer!)
}
if longPressGestureRecognizer == nil {
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(likedPostViewPressed(_:)))
longPressGestureRecognizer?.delegate = self
longPressGestureRecognizer?.minimumPressDuration = 0.5
longPressGestureRecognizer?.cancelsTouchesInView = false
addGestureRecognizer(longPressGestureRecognizer!)
}
isUserInteractionEnabled = true
}
// Customize view to be able to re-use it for search results.
func flagAsSearchResultPost() {
songArtistLabel?.text = "\(post!.song.title) · \(post!.song.album)"
}
func updateAddButton() {
if let _ = post {
if songStatus == .saved {
self.addButton?.setBackgroundImage(#imageLiteral(resourceName: "AddedButton"), for: .normal)
} else {
self.addButton?.setBackgroundImage(#imageLiteral(resourceName: "AddButton"), for: .normal)
}
}
}
func updateSongLabel() {
if let post = post {
let duration = TimeInterval(0.3)
let color: UIColor = post.player.isPlaying ? .tempoRed : .white
let font: UIFont = post.player.isPlaying ? UIFont(name: "AvenirNext-Medium", size: 16.0)! : UIFont(name: "AvenirNext-Regular", size: 16.0)!
guard let label = songNameLabel else { return }
if !label.textColor.isEqual(color) {
UIView.transition(with: label, duration: duration, options: .transitionCrossDissolve, animations: {
label.textColor = color
label.font = font
})
}
}
}
func updateViews() {
if isSpotifyAvailable {
songNameLabel?.frame.size.width = labelWidth
songArtistLabel?.frame.size.width = labelWidth
addButton!.isHidden = false
} else {
let newLabelWidth = bounds.width - (songNameLabel?.frame.minX)! - padding
songNameLabel?.frame.size.width = newLabelWidth
songArtistLabel?.frame.size.width = newLabelWidth
addButton!.isHidden = true
}
}
override func updateBackground() {
if let post = post {
backgroundColor = post.player.isPlaying ? .readCellColor : .unreadCellColor
}
}
func likedPostViewPressed(_ sender: UIGestureRecognizer) {
guard let _ = post else { return }
if sender is UITapGestureRecognizer {
let tapPoint = sender.location(in: self)
let hitView = hitTest(tapPoint, with: nil)
if hitView == addButton {
if songStatus == .notSaved {
SpotifyController.sharedController.saveSpotifyTrack(post!) { success in
if success {
self.songStatus = .saved
self.updateAddButton()
self.playerDelegate.didToggleAdd?()
self.postViewDelegate?.didTapAddButtonForPostView?(true)
}
}
} else if songStatus == .saved {
SpotifyController.sharedController.removeSavedSpotifyTrack(post!) { success in
if success {
self.songStatus = .notSaved
self.updateAddButton()
self.playerDelegate.didToggleAdd?()
self.postViewDelegate?.didTapAddButtonForPostView?(false)
}
}
}
}
}
}
func updateSavedStatus() {
if let selectedPost = post {
if let _ = User.currentUser.currentSpotifyUser?.savedTracks[selectedPost.song.spotifyID] {
songStatus = .saved
} else {
songStatus = .notSaved
}
}
}
func updateAddStatus() {
if let _ = post {
updateSavedStatus()
let image = (songStatus == .saved) ? #imageLiteral(resourceName: "AddedButton") : #imageLiteral(resourceName: "AddButton")
addButton?.setBackgroundImage(image, for: .normal)
}
}
}
| mit | 41162a0693ec2c4827352ab3532dd93a | 31.794393 | 146 | 0.72998 | 4.080233 | false | false | false | false |
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 | 92f33a04acb7571bc9620341d75a5b62 | 24.04878 | 78 | 0.605648 | 3.996109 | false | false | false | false |
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 | d25002753c9d8c562717d46fe07f4f66 | 33.927273 | 114 | 0.704581 | 5.191892 | false | false | false | false |
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 | 4092e166febed347f7c93aea0dbd7716 | 39.353414 | 191 | 0.680832 | 5.594655 | false | false | false | false |
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 | 339949a2ffe466d281e45497e2de5397 | 32.990099 | 97 | 0.708127 | 4.176399 | false | false | false | false |
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 | 2ca1370ddc0dbb7d8514a2292b6cd4ee | 30.373665 | 140 | 0.74569 | 4.202097 | false | true | false | false |
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 | 9f8452bdf7b0da511b12f9e0415e70ef | 35.939698 | 95 | 0.540743 | 4.412365 | false | false | false | false |
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 | 25e389fff6dcb3a600b30dd63e92f9d6 | 36.403061 | 167 | 0.590097 | 5.596183 | false | false | false | false |
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 | 4796642fd2d8aa564987d37f8bec2a43 | 36.869565 | 144 | 0.679104 | 5.409938 | false | false | false | false |
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 | dc0c61ab970af750d4cb57c6604ae1ba | 36.070922 | 177 | 0.595498 | 5.188948 | false | false | false | false |
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 | 4c674aee8baeef5ee2ae594264ab7ab6 | 35.124031 | 159 | 0.655633 | 4.811564 | false | false | false | false |
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 | 66b04375267a6b920ad5dc5231fd7713 | 22.731343 | 65 | 0.506289 | 3.697674 | false | false | false | false |
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 | 1cdf2b79a98649afce61396ad818eefb | 32.624658 | 134 | 0.648631 | 3.826629 | false | false | false | false |
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 | 2e75627dcfaee79280386e3dccc83c68 | 32.801887 | 119 | 0.429648 | 4.112514 | false | false | false | false |
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 | c74b96cf75a6b2eeec64416df6886862 | 29.837838 | 88 | 0.662577 | 3.948097 | false | false | false | false |
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 [email protected]
// 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 | db081b9795ca59e99b93b91c485f0278 | 30.008075 | 310 | 0.605018 | 5.372901 | false | false | false | false |
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 | f7dcc2a7d71e4ff7e0f550bcc9c877e6 | 53.530504 | 118 | 0.626812 | 5.06854 | false | false | false | false |
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 | f01a6b8e1f99e0dbf0ba26f206adf7e2 | 29.259259 | 84 | 0.634027 | 4.615819 | false | false | false | false |
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 | 47e10965e1d9579d2a386804d7637f8c | 30.597884 | 192 | 0.595445 | 5.792435 | false | false | false | false |
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 | 7ac8915bde13a70fbedce5805ac5cadd | 31.630769 | 96 | 0.648515 | 4.898383 | false | false | false | false |
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 | f1856420f2dc1cc6d3cea2cbc77da48c | 36.342105 | 154 | 0.715997 | 4.683168 | false | true | false | false |
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 | a4b9d9d7cf60821b956d40ac4f3d6c67 | 32.956522 | 117 | 0.663252 | 3.323404 | false | false | false | false |
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 | 3e81b86b6c689a8f3ab0e0dea2583cd3 | 23.8125 | 117 | 0.686398 | 4.030457 | false | false | false | false |
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 | 4277c684854eabd78503e5e8965cee83 | 29.390476 | 176 | 0.702131 | 4.070153 | false | false | false | false |
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 | 7642af7e2efb8ec9ff1975173e761e97 | 53.873786 | 187 | 0.743984 | 5.508772 | false | false | false | false |
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 | b8adebc7582c8dc1f96852cf5ab77e7d | 33.28 | 88 | 0.564177 | 5.458599 | false | false | false | false |
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 | ef32ab916a62565449980d1a9a3dc53c | 23.203125 | 90 | 0.607489 | 4.665663 | false | false | false | false |
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 | 907ebb55010c28ac706ff96763d827d8 | 31.105263 | 180 | 0.688525 | 4.576144 | false | false | false | false |
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 | c56f4b9b7404c8cdee3c13aaf9e41b55 | 41.024896 | 176 | 0.649092 | 5.226006 | false | false | false | false |
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 | 60d2f93ef01fb48ce0e18c2b31df288e | 23.206522 | 116 | 0.608891 | 3.591935 | false | false | false | false |
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 | f4a208a7ffaf4d6e8af29bd3d0b79c77 | 40.753247 | 188 | 0.517418 | 4.823706 | false | false | false | false |
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 | 2d8439c20b82205bf81060418e790feb | 36.314815 | 88 | 0.670471 | 4.752358 | false | false | false | false |
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 | 08f90d88a86a4efb4de37595361c074f | 39.184615 | 122 | 0.647014 | 5.032755 | false | false | false | false |
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 | a75c0097ccbaef32352253e49835422c | 32.44 | 121 | 0.619019 | 4.354167 | false | false | false | false |
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 | 7db1b3fd1c20a5a7c3d33e02f0f82a11 | 46.559874 | 182 | 0.430285 | 6.389642 | false | false | false | false |
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 | 42de65cff48940f4146300b6767ce8fa | 40.949654 | 127 | 0.656455 | 5.33691 | false | false | false | false |
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 | 9590505ab462606639f7608e7d26a49c | 35.818182 | 108 | 0.722222 | 3.616071 | false | false | false | false |
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 | 7bc43f9b19464e6261778b9ff30d7611 | 29.690476 | 178 | 0.709077 | 5.293634 | false | false | false | false |
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 | 738f02723cdcd9f7f64e035ae83178e7 | 26 | 94 | 0.607268 | 5.589844 | false | false | false | false |
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 | d7a9a3c1f091e44bacdd4b0fc818c9fa | 36.180723 | 114 | 0.593487 | 4.806854 | false | false | false | false |
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 | f2f0567ee05491dc41959f22ec6a5874 | 26.130435 | 104 | 0.628205 | 4.875 | false | false | false | false |
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 | 70c17b4c3711209fb6e1d2df717fbc85 | 45.21875 | 84 | 0.854632 | 4.979798 | false | false | false | false |
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 | 576a2401dba878f9ff3ee27ecb8d542f | 36.853846 | 177 | 0.69874 | 5.592045 | false | false | false | false |
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 | b7135fc0e08158f7f931b9f77ee7a358 | 31.561404 | 99 | 0.671336 | 5.590361 | false | false | false | false |
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 | c2cddc676bbb38ed4161b539f5b6196d | 26.355556 | 100 | 0.549959 | 4.259516 | false | false | false | false |
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 | 7e94836bb8950d545e2c7c2b2fe20bad | 47.792683 | 209 | 0.64184 | 5.162581 | false | false | false | false |
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 | 2c3d574a26981a983928632f22a61486 | 22.931034 | 80 | 0.596972 | 3.929178 | false | false | false | false |
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 | f25f1a86f9199405300a4d0493543353 | 26.48 | 68 | 0.678311 | 2.792683 | false | false | false | false |
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 | b30eb87029fe5a74e836a9c62c91e695 | 32.639344 | 111 | 0.655945 | 4.932692 | false | false | false | false |
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 | ec4a400a5e2b872ad442e784b789808a | 34.116071 | 215 | 0.568777 | 4.698925 | false | false | false | false |
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 | 5b60b601d310d0cbb7e5f4f7bc743565 | 23.898734 | 98 | 0.514489 | 4.595794 | false | false | false | false |
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 | 4667ebd5f68170fb1810cbca29cff677 | 22.868421 | 87 | 0.624035 | 3.216312 | false | false | false | false |
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 | e887e8a0b59fe9a41e4ef836d5fcbda5 | 37.103774 | 121 | 0.678881 | 6.119697 | false | false | false | false |
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 | 4cb846a94d14451dac8dd4304d6aa02d | 36.732143 | 139 | 0.65523 | 5.048984 | false | false | false | false |
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 | 28db4319b00b943fbaf5c390027e607e | 40.24 | 104 | 0.664403 | 6.325153 | false | false | false | false |
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 | 078bf679900ccc2aab23de2666fdd3ec | 33.3125 | 113 | 0.660109 | 4.456169 | false | false | false | false |
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 | d43607a9817a8cffe0ebd1442060ce90 | 31.097561 | 118 | 0.521277 | 5.157413 | false | false | false | false |
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 | f3882c840fdcd2ed3117f27f82db6836 | 36.963121 | 290 | 0.535832 | 5.102765 | false | false | false | false |
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 | 15606f66684b0b9a29e2fddcfd0b08e1 | 43.43083 | 166 | 0.698247 | 5.726439 | false | false | false | false |
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 | 7457b11e89b5fb6d01aed1d75f7c190a | 31.735537 | 157 | 0.60818 | 4.66 | false | false | false | false |
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 | 86f264fe6a5654cc748a738fd0b954dc | 33.25 | 132 | 0.671533 | 4.106267 | false | false | false | false |
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 | 1a95ebdd272d0be44e068f06e7a5abc6 | 31.146119 | 88 | 0.456315 | 4.898399 | false | false | false | false |
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 | c5737d2cc7d3a3cbab16b4f62faeec4b | 27.621622 | 73 | 0.586874 | 5.544503 | false | false | false | false |
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 | d434bbd2c1dfc43f9b45556b410e7517 | 25.853659 | 121 | 0.641235 | 4.317647 | false | false | false | false |
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 | 279ac60db412f63be24839e0c14f47c9 | 29.45 | 132 | 0.613027 | 4.782723 | false | false | false | false |
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 | d9b09f3043cff9aa43ef2d645a42cf73 | 29.944444 | 125 | 0.725314 | 4.843478 | false | false | false | false |
apstrand/loggy | LoggyTools/Constants.swift | 1 | 1081 | //
// Settings.swift
// Loggy
//
// Created by Peter Strand on 2017-06-30.
// Copyright © 2017 Peter Strand. All rights reserved.
//
import Foundation
public struct SettingName {
public static let Suite = "group.se.nena.loggy"
public static let PowerSave = "power_save"
public static let AutoWaypoint = "auto_waypoint"
public static let SpeedUnit = "speed_unit"
public static let AltitudeUnit = "altitude_unit"
public static let LocationUnit = "location_unit"
public static let BearingUnit = "bearing_unit"
public static let TrackingEnabled = "tracking_enabled"
public static let AutoSaveGen = "auto_save_gen"
}
public enum AppCommand : String {
case StartTracking = "action?startTracking"
case StopTracking = "action?stopTracking"
case StoreWaypoint = "action?storeWaypoint"
}
public struct AppUrl {
public static let AppUrl = "loggy://"
public static func app(cmd : AppCommand) -> URL {
guard let url = URL(string:AppUrl + cmd.rawValue)
else { fatalError("Failed to create appurl for command: \"\(cmd)\"") }
return url
}
}
| mit | 19f9a25507d673a5d078c8ab18a2fc60 | 27.421053 | 77 | 0.712963 | 3.724138 | false | false | false | false |
aryaxt/ScrollPager | ScrollPager/ViewController.swift | 1 | 1543 | //
// ViewController.swift
// ScrollPager
//
// Created by Aryan Ghassemi on 2/22/15.
// Copyright (c) 2015 Aryan Ghassemi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, ScrollPagerDelegate {
@IBOutlet var scrollPager: ScrollPager!
@IBOutlet var secondScrollPager: ScrollPager!
override func viewDidLoad() {
super.viewDidLoad()
let firstView = UILabel()
firstView.backgroundColor = UIColor.white
firstView.text = "first View"
firstView.textAlignment = .center
let secondView = UILabel()
secondView.backgroundColor = UIColor.white
secondView.text = "second view"
secondView.textAlignment = .center
let thirdView = UILabel()
thirdView.backgroundColor = UIColor.white
thirdView.text = "third view"
thirdView.textAlignment = .center
let fourthView = UILabel()
fourthView.backgroundColor = UIColor.white
fourthView.text = "fourth view"
fourthView.textAlignment = .center
scrollPager.delegate = self
scrollPager.addSegmentsWithTitlesAndViews(segments: [
("Home", firstView),
("Public Feed", secondView),
("Profile", thirdView),
("One More", fourthView)
])
secondScrollPager.addSegmentsWithImages(segmentImages: [
UIImage(named: "envelope")!,
UIImage(named: "home")!,
UIImage(named: "like")!,
UIImage(named: "message")!,
UIImage(named: "notes")!
])
}
// MARK: - ScrollPagerDelegate -
func scrollPager(scrollPager: ScrollPager, changedIndex: Int) {
print("scrollPager index changed: \(changedIndex)")
}
}
| mit | cde9f49236775dbfe154bbc82883f63e | 23.492063 | 64 | 0.712897 | 3.691388 | false | false | false | false |
Hukuma23/CS193p | Assignment_1/Calculator/CalculatorBrain.swift | 1 | 4500 | //
// CalculatorBrain.swift
// Calculator
//
// Created by Nikita Litvinov on 12/15/2016.
// Copyright © 2016 Nikita Litvinov. All rights reserved.
//
import Foundation
class CalculatorBrain{
private var accumulator = 0.0
private var descriptionAccumulator = ""
var isPartialResult : Bool { return pending != nil }
private var pending: PendingBinaryOperationInfo?
var result: Double { return accumulator }
var strAccumulator : String { return String(accumulator) }
var description : String {
if let pend = pending {
return pend.descriptionOperation(pend.descriptionOperand, pend.descriptionOperand != descriptionAccumulator ? descriptionAccumulator : "")
} else {
return descriptionAccumulator
}
}
func clear() {
accumulator = 0
descriptionAccumulator = ""
pending = nil
}
func setOperand(_ operand: Double) {
accumulator = operand
descriptionAccumulator = formatter.string(from: NSNumber(value: accumulator)) ?? ""
}
private var operations : [String: Operation] = [
"π": Operation.Constant(M_PI),
"e": Operation.Constant(M_E),
"±": Operation.UnaryOperation({ -$0 }, {"±(" + $0 + ")"}),
"√": Operation.UnaryOperation(sqrt, {"√(" + $0 + ")"}),
"cos": Operation.UnaryOperation(cos, {"cos(" + $0 + ")"}),
"sin": Operation.UnaryOperation(sin, {"sin(" + $0 + ")"}),
"log": Operation.UnaryOperation(log10, {"log(" + $0 + ")"}),
"x⁻¹": Operation.UnaryOperation({1 / $0}, {"(" + $0 + ")⁻¹"}),
"x²": Operation.UnaryOperation({$0 * $0}, {"(" + $0 + ")²"}),
"×": Operation.BinaryOperation({$0 * $1}, {$0 + " × " + $1}),
"÷": Operation.BinaryOperation({$0 / $1}, {$0 + " ÷ " + $1}),
"+": Operation.BinaryOperation({$0 + $1}, {$0 + " + " + $1}),
"−": Operation.BinaryOperation({$0 - $1}, {$0 + " − " + $1}),
"=": Operation.Equals,
"C": Operation.Clear
]
enum Operation{
case Constant(Double)
case UnaryOperation((Double) -> Double, (String) -> String)
case BinaryOperation((Double, Double) -> Double, (String, String) -> String)
case Equals
case Clear
}
func performOperation(_ symbol: String){
if let operation = operations[symbol]{
switch operation {
case .Constant(let value):
descriptionAccumulator = symbol
accumulator = value
case .UnaryOperation(let function, let descriptionFunction):
if pending != nil {
descriptionAccumulator = String(accumulator)
}
descriptionAccumulator = descriptionFunction(descriptionAccumulator)
accumulator = function(accumulator)
case .BinaryOperation(let function, let descriptionFunction):
executeBinaryOperation()
if descriptionAccumulator == "" {
descriptionAccumulator = String(accumulator)
}
pending = PendingBinaryOperationInfo(binaryOperation: function, firstOperand: accumulator, descriptionOperand: descriptionAccumulator, descriptionOperation: descriptionFunction)
case .Equals:
executeBinaryOperation()
case .Clear:
clear()
}
}
}
private func executeBinaryOperation() {
if pending != nil {
accumulator = pending!.binaryOperation(pending!.firstOperand, accumulator)
descriptionAccumulator = pending!.descriptionOperation(pending!.descriptionOperand, descriptionAccumulator)
pending = nil
}
}
private struct PendingBinaryOperationInfo {
var binaryOperation: (Double, Double) -> Double
var firstOperand: Double
var descriptionOperand : String
var descriptionOperation : (String, String) -> String
}
private let formatter : NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 6
formatter.minimumFractionDigits = 0
formatter.notANumberSymbol = "Error"
formatter.groupingSeparator = " "
formatter.locale = Locale.current
return formatter
}()
}
| apache-2.0 | 228e38c1e379b007b1af6647a313c8eb | 35.688525 | 193 | 0.577971 | 4.940397 | false | false | false | false |
gabek/GitYourFeedback | Example/Pods/GRMustache.swift/Sources/ZipFilter.swift | 2 | 3130 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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
let ZipFilter = VariadicFilter { (boxes) in
// Turn collection arguments into iterators. Iterators can be iterated
// all together, and this is what we need.
//
// Other kinds of arguments generate an error.
var zippedIterators: [AnyIterator<MustacheBox>] = []
for box in boxes {
if box.isEmpty {
// Missing collection does not provide anything
} else if let array = box.arrayValue {
// Array
zippedIterators.append(AnyIterator(array.makeIterator()))
} else {
// Error
throw MustacheError(kind: .renderError, message: "Non-enumerable argument in zip filter: `\(box.value)`")
}
}
// Build an array of custom render functions
var renderFunctions: [RenderFunction] = []
while true {
// Extract from all iterators the boxes that should enter the rendering
// context at each iteration.
//
// Given the [1,2,3], [a,b,c] input collections, those boxes would be
// [1,a] then [2,b] and finally [3,c].
var zippedBoxes: [MustacheBox] = []
for iterator in zippedIterators {
var iterator = iterator
if let box = iterator.next() {
zippedBoxes.append(box)
}
}
// All iterators have been enumerated: stop
if zippedBoxes.isEmpty {
break;
}
// Build a render function which extends the rendering context with
// zipped boxes before rendering the tag.
let renderFunction: RenderFunction = { (info) -> Rendering in
var context = zippedBoxes.reduce(info.context) { (context, box) in context.extendedContext(box) }
return try info.tag.render(context)
}
renderFunctions.append(renderFunction)
}
return renderFunctions
}
| mit | 1ee73b5b20e4c0929ce3f799989739ab | 34.556818 | 117 | 0.638543 | 4.873832 | false | false | false | false |
peferron/algo | EPI/Linked Lists/Implement even-odd merge/swift/test.swift | 1 | 1150 | import Darwin
func nodes(_ count: Int) -> [Node] {
let nodes = (0..<count).map { _ in Node() }
for i in 0..<count - 1 {
nodes[i].next = nodes[i + 1]
}
return nodes
}
({
let n = nodes(1)
n[0].merge()
guard n[0].next === nil else {
print("Failed test with 1 nodes")
exit(1)
}
})()
({
let n = nodes(2)
n[0].merge()
guard n[0].next === n[1] && n[1].next == nil else {
print("Failed test with 2 nodes")
exit(1)
}
})()
({
let n = nodes(3)
n[0].merge()
guard n[0].next === n[2] && n[2].next === n[1] && n[1].next == nil else {
print("Failed test with 3 nodes")
exit(1)
}
})()
({
let n = nodes(4)
n[0].merge()
guard n[0].next === n[2] && n[2].next === n[1] && n[1].next === n[3] && n[3].next == nil else {
print("Failed test with 4 nodes")
exit(1)
}
})()
({
let n = nodes(5)
n[0].merge()
guard n[0].next === n[2] && n[2].next === n[4] && n[4].next === n[1] && n[1].next === n[3]
&& n[3].next == nil else {
print("Failed test with 5 nodes")
exit(1)
}
})()
| mit | 029c6b8c2b17b75b43134ee77d20e5b0 | 18.166667 | 99 | 0.436522 | 2.777778 | false | true | false | false |
0416354917/FeedMeIOS | MeTableViewController.swift | 1 | 4476 | //
// MeTableViewController.swift
// FeedMeIOS
//
// Created by Jun Chen on 11/04/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import UIKit
class MeTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setBackground(self)
self.setBar(self)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidAppear(animated: Bool) {
if FeedMe.Variable.userInLoginState == false {
let nextViewController = self.storyboard!.instantiateViewControllerWithIdentifier("sign_in_up")
self.presentViewController(nextViewController, animated: true, completion: nil)
} else {
self.tableView.reloadData()
}
}
// override func viewWillAppear(animated: Bool) {
// if FeedMe.Variable.userInLoginState == false {
// let nextViewController = self.storyboard!.instantiateViewControllerWithIdentifier("sign_in_up")
// self.presentViewController(nextViewController, animated: true, completion: nil)
// }
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return 1
default:
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "MeTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MeTableViewCell
// Configure the cell...
if FeedMe.user == nil {
cell.itemLabel.text = ""
return cell
}
NSLog("user: %@", FeedMe.user!.toJsonString(.None))
switch indexPath.section {
case 0:
cell.itemLabel.text = FeedMe.user!.getEmail()
case 1:
cell.itemLabel.text = "Settings"
default:
cell.itemLabel.text = ""
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| bsd-3-clause | a7ffc5e7f2fbdd1069beb2f35e3057c2 | 32.646617 | 157 | 0.649832 | 5.411125 | false | false | false | false |
mobistix/ios-charts | Charts/Classes/Renderers/TimelineHorizontalAxisRenderer.swift | 1 | 4619 | //
// TimelineHorizontalAxisRenderer.swift
// RoadCheck
//
// Created by Rares Zehan on 03/04/16.
// Copyright © 2016 Realine. All rights reserved.
//
import Foundation
let hourInSeconds: Double = 3600
let dayInHours: Int = 24
public class TimelineHorizontalAxisRenderer: ChartYAxisRendererHorizontalBarChart {
public var showExtended = false
public var topTitleFormatter: ExtendedTitleNumberFormatter?
public override func computeAxisValues(min: Double, max: Double)
{
let range = max - min
guard let yAxis = yAxis else { return }
let yMin = Date(timeIntervalSince1970: min)
_ = Date(timeIntervalSince1970: max)
let hoursCount = Int(range / hourInSeconds)
if hoursCount == 0 { return }
let modItemsCount = hoursCount / yAxis.labelCount
var hoursInterval = modItemsCount < 1 ? 1 : modItemsCount
if viewPortHandler.scaleX < 3 {
hoursInterval = dayInHours
}
var dateComponents = Calendar.utcCalendar().dateComponents([.year, .month, .day, .hour, .minute], from: yMin)
if dateComponents.minute != 0 {
dateComponents.minute = 0
dateComponents.hour = hoursInterval
}
if hoursInterval == dayInHours {
dateComponents.minute = 0
dateComponents.hour = 0
}
let firstHourModulus = Calendar.utcCalendar().date(from: dateComponents)!
yAxis.entries = [Double]()
for i in 0 ..< 48 {
let entry = firstHourModulus.timeIntervalSince1970 + Double(i) * Double(hoursInterval) * hourInSeconds
if entry > max { break }
yAxis.entries += [entry]
}
}
/// draws the y-labels on the specified x-position
public override func drawYLabels(context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat)
{
guard let yAxis = yAxis else { return }
let labelFont = yAxis.labelFont
let labelTextColor = yAxis.labelTextColor
let scaleX = viewPortHandler.scaleX
var prevDay = -1
for i in 0 ..< yAxis.entryCount {
let timelineNumberFormatter = yAxis.valueFormatter as! TimelineNumberFormatter
timelineNumberFormatter.formatterType = scaleX < 3 && showExtended ? .WeekFormatterType : .DayFormatterType
let text = timelineNumberFormatter.string(from: yAxis.entries[i] as NSNumber )
ChartUtils.drawText(context: context,
text: text!,
point: CGPoint(x: positions[i].x, y: fixedPosition - offset),
align: .center,
attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
if (scaleX > 3 && showExtended) {
let currentDate = Date(timeIntervalSince1970: yAxis.entries[i]).localDate()
var dayComps = Calendar.utcCalendar().dateComponents([Calendar.Component.day], from: currentDate)
dayComps.timeZone = TimeZone.utcTimeZone()
let day = dayComps.day
if day != prevDay {
prevDay = day!
ChartUtils.drawText(context: context,
text: text!,
point: CGPoint(x: positions[i].x, y: fixedPosition - offset),
align: .center,
attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
}
}
}
if showExtended && topTitleFormatter != nil {
let titleFont = UIFont(name: "HelveticaNeue", size: 18.0)
topTitleFormatter!.formatterType = scaleX < 3 ? .WeekFormatterType : .DayFormatterType
let millis = yAxis.entries[yAxis.entries.count / 2] as NSNumber
let formattedDate = topTitleFormatter?.string(from: millis)
ChartUtils.drawText(context: context,
text: "\(formattedDate!)",
point: CGPoint(x: viewPortHandler.chartWidth / 2, y: fixedPosition - 40),
align: .center,
attributes: [NSFontAttributeName: titleFont!, NSForegroundColorAttributeName: UIColor.black])
}
}
}
| apache-2.0 | 25f08ac462396a260c881fcbc44e9500 | 38.470085 | 133 | 0.568428 | 5.517324 | false | false | false | false |
jigneshsheth/Datastructures | DataStructure/DataStructure/RetailMeNot/FreeShippingThresold.swift | 1 | 2598 | //
// FreeShippingThresold.swift
// DataStructure
//
// Created by Jigs Sheth on 3/30/16.
// Copyright © 2016 jigneshsheth.com. All rights reserved.
//
import Foundation
/**
Question Given a list of prices on a website, find the two distinct item prices you need to have the lowest shopping cart total
Variations You can start with free shipping at $25 and items of $5, $8, $15, $22.
that meets a free shipping requirement.
There is an n^2 solution that's obvious. n log n that's more efficient. n if you assume all prices are below the free
shipping requirement.
For the O( n ) solution, add the restriction that all items in the catalog are below the free shipping amount and that
there are a huge number of them.
One variation is to say that you can have as many items in the cart as you want to reach the free shipping total.
*/
/**
Optimal solution O(n log n) because of the sort in the middle:
- parameter productPrices:
- parameter freeShippingAmt: Thresold for the free shipping
- returns: touple of 2 values
*/
public func calculateFreeShipping(productPrices:[Int],freeShippingAmt:Int) -> (Int,Int) {
var minFreeShippingDelta = freeShippingAmt
var index1 = 0
var index2 = productPrices.count - 1
var result:(Int,Int) = (-1,-1)
// Below statement do O(log n)
let _productPrices = productPrices.sorted()
// Below statement do O(n) so total complexity of the method is O(n log n)
while index1 < index2 {
let price1 = _productPrices[index1]
let price2 = _productPrices[index2]
let delta = price1 + price2 - freeShippingAmt
if delta > 0 && delta < minFreeShippingDelta {
minFreeShippingDelta = delta
result = (price1,price2)
}
if delta < 0 {
index1 += 1
}else {
index2 -= 1
}
}
return result
}
public func calculateFreeShippingOptimal(productPrices:[Int],freeShippingAmt:Int) -> (Int,Int) {
var minFreeShippingDelta = freeShippingAmt
var index1 = 0
var index2 = productPrices.count - 1
var result:(Int,Int) = (-1,-1)
// Below statement do O(log n)
let _productPrices = productPrices.sorted()
// Below statement do O(n) so total complexity of the method is O(n log n)
while index1 < index2 {
let price1 = _productPrices[index1]
let price2 = _productPrices[index2]
let delta = price1 + price2 - freeShippingAmt
if delta > 0 && delta < minFreeShippingDelta {
minFreeShippingDelta = delta
result = (price1,price2)
}
if delta < 0 {
index1 += 1
}else {
index2 -= 1
}
}
return result
}
| mit | 30d1363ea0ad3b539fcc12aba901f65a | 26.62766 | 128 | 0.683096 | 3.763768 | false | false | false | false |
SonnyBrooks/ProjectEulerSwift | ProjectEulerSwift/Problem29.swift | 1 | 1133 | //
// Problem29.swift
// ProjectEulerSwift
//
// Created by Andrew Budziszek on 1/23/17.
// Copyright © 2017 Andrew Budziszek. All rights reserved.
//
//
/*
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
*/
import Foundation
func p29() -> String {
return "This problem has been done in Python due to max integer restraints. See Problem29.py"
}
private func distinctPowers() -> Int {
var hit:[Int] = []
for i in 2...100{
for j in 2...100{
let currentPow = Int(pow(Double(i), Double(j)))
if !hit.contains(currentPow) {
hit.append(currentPow)
}
}
}
return hit.count
}
| mit | c2440f738345e192ce8a6fefc3761043 | 25.571429 | 125 | 0.600358 | 3.179487 | false | false | false | false |
dinhcong/ALCameraViewController | ALCameraViewController/ViewController/ConfirmViewController.swift | 1 | 8397 | //
// ALConfirmViewController.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/30.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
import Photos
internal class ConfirmViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
let imageView = UIImageView()
@IBOutlet weak var cropOverlay: CropOverlay!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var confirmButton: UIButton!
@IBOutlet weak var centeringView: UIView!
@IBOutlet weak var spinner: UIActivityIndicatorView!
var allowsCropping: Bool = false
var verticalPadding: CGFloat = 30
var horizontalPadding: CGFloat = 30
var onComplete: ALCameraViewCompletion?
var asset: PHAsset!
internal init(asset: PHAsset, allowsCropping: Bool) {
self.allowsCropping = allowsCropping
self.asset = asset
super.init(nibName: "ConfirmViewController", bundle: CameraGlobals.shared.bundle)
commonInit()
}
internal required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func commonInit() {
if UIScreen.mainScreen().bounds.width <= 320 {
horizontalPadding = 15
}
}
internal override func prefersStatusBarHidden() -> Bool {
return true
}
internal override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
return UIStatusBarAnimation.Slide
}
internal override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blackColor()
scrollView.addSubview(imageView)
scrollView.delegate = self
scrollView.maximumZoomScale = 1
cropOverlay.hidden = true
guard let asset = asset else {
return
}
spinner.startAnimating()
SingleImageFetcher()
.setAsset(asset)
.setTargetSize(largestPhotoSize())
.onSuccess { image in
self.configureWithImage(image)
self.spinner.stopAnimating()
}
.onFailure { error in
self.spinner.stopAnimating()
}
.fetch()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let scale = calculateMinimumScale(view.frame.size)
let frame = allowsCropping ? cropOverlay.frame : view.bounds
scrollView.contentInset = calculateScrollViewInsets(frame)
scrollView.minimumZoomScale = scale
scrollView.zoomScale = scale
centerScrollViewContents()
centerImageViewOnRotate()
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let scale = calculateMinimumScale(size)
var frame = view.bounds
if allowsCropping {
frame = cropOverlay.frame
let centeringFrame = centeringView.frame
var origin: CGPoint
if size.width > size.height { // landscape
let offset = (size.width - centeringFrame.height)
let expectedX = (centeringFrame.height/2 - frame.height/2) + offset
origin = CGPoint(x: expectedX, y: frame.origin.x)
} else {
let expectedY = (centeringFrame.width/2 - frame.width/2)
origin = CGPoint(x: frame.origin.y, y: expectedY)
}
frame.origin = origin
} else {
frame.size = size
}
coordinator.animateAlongsideTransition({ context in
self.scrollView.contentInset = self.calculateScrollViewInsets(frame)
self.scrollView.minimumZoomScale = scale
self.scrollView.zoomScale = scale
self.centerScrollViewContents()
self.centerImageViewOnRotate()
}, completion: nil)
}
private func configureWithImage(image: UIImage) {
if allowsCropping {
cropOverlay.hidden = false
} else {
cropOverlay.hidden = true
}
buttonActions()
imageView.image = image
imageView.sizeToFit()
view.setNeedsLayout()
}
private func calculateMinimumScale(size: CGSize) -> CGFloat {
var _size = size
if allowsCropping {
_size = cropOverlay.frame.size
}
guard let image = imageView.image else {
return 1
}
let scaleWidth = _size.width / image.size.width
let scaleHeight = _size.height / image.size.height
var scale: CGFloat
if allowsCropping {
scale = max(scaleWidth, scaleHeight)
} else {
scale = min(scaleWidth, scaleHeight)
}
return scale
}
private func calculateScrollViewInsets(frame: CGRect) -> UIEdgeInsets {
let bottom = view.frame.height - (frame.origin.y + frame.height)
let right = view.frame.width - (frame.origin.x + frame.width)
let insets = UIEdgeInsets(top: frame.origin.y, left: frame.origin.x, bottom: bottom, right: right)
return insets
}
private func centerImageViewOnRotate() {
if allowsCropping {
let size = allowsCropping ? cropOverlay.frame.size : scrollView.frame.size
let scrollInsets = scrollView.contentInset
let imageSize = imageView.frame.size
var contentOffset = CGPoint(x: -scrollInsets.left, y: -scrollInsets.top)
contentOffset.x -= (size.width - imageSize.width) / 2
contentOffset.y -= (size.height - imageSize.height) / 2
scrollView.contentOffset = contentOffset
}
}
private func centerScrollViewContents() {
let size = allowsCropping ? cropOverlay.frame.size : scrollView.frame.size
let imageSize = imageView.frame.size
var imageOrigin = CGPoint.zero
if imageSize.width < size.width {
imageOrigin.x = (size.width - imageSize.width) / 2
}
if imageSize.height < size.height {
imageOrigin.y = (size.height - imageSize.height) / 2
}
imageView.frame.origin = imageOrigin
}
private func buttonActions() {
confirmButton.addTarget(self, action: "confirmPhoto", forControlEvents: UIControlEvents.TouchUpInside)
cancelButton.addTarget(self, action: "cancel", forControlEvents: UIControlEvents.TouchUpInside)
}
internal func cancel() {
onComplete?(nil)
}
internal func confirmPhoto() {
imageView.hidden = true
spinner.startAnimating()
let fetcher = SingleImageFetcher()
.onSuccess { image in
self.onComplete?(image)
self.spinner.stopAnimating()
}
.onFailure { error in
self.spinner.stopAnimating()
}
.setAsset(asset)
if allowsCropping {
var cropRect = cropOverlay.frame
cropRect.origin.x += scrollView.contentOffset.x
cropRect.origin.y += scrollView.contentOffset.y
let normalizedX = cropRect.origin.x / imageView.frame.width
let normalizedY = cropRect.origin.y / imageView.frame.height
let normalizedWidth = cropRect.width / imageView.frame.width
let normalizedHeight = cropRect.height / imageView.frame.height
let rect = normalizedRect(CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight), orientation: imageView.image!.imageOrientation)
fetcher.setCropRect(rect)
}
fetcher.fetch()
}
internal func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
internal func scrollViewDidZoom(scrollView: UIScrollView) {
centerScrollViewContents()
}
} | mit | aea11e0c5453b77178ac18e7ef375375 | 31.804688 | 175 | 0.600333 | 5.413926 | false | false | false | false |
omise/omise-ios | OmiseSDK/FPXBankChooserViewController.swift | 1 | 4557 | import UIKit
import os
@objc(OMSFPXBankChooserViewController)
class FPXBankChooserViewController: AdaptableDynamicTableViewController<Capability.Backend.Bank>, PaymentSourceChooser, PaymentChooserUI {
var email: String?
var flowSession: PaymentCreatorFlowSession?
private let defaultImage: String = "FPX/unknown"
private let message = NSLocalizedString(
"fpx.bank-chooser.no-banks-available.text",
bundle: .module,
value: "Cannot retrieve list of banks.\nPlease try again later.",
comment: "A descriptive text telling the user when there's no banks available"
)
override var showingValues: [Capability.Backend.Bank] {
didSet {
os_log("FPX Bank Chooser: Showing options - %{private}@",
log: uiLogObject,
type: .info,
showingValues.map { $0.name }.joined(separator: ", "))
}
}
@IBInspectable var preferredPrimaryColor: UIColor? {
didSet {
applyPrimaryColor()
}
}
@IBInspectable var preferredSecondaryColor: UIColor? {
didSet {
applySecondaryColor()
}
}
override func viewDidLoad() {
super.viewDidLoad()
applyPrimaryColor()
applySecondaryColor()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
if showingValues.isEmpty {
displayEmptyMessage()
} else {
restore()
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if let cell = cell as? PaymentOptionTableViewCell {
cell.separatorView.backgroundColor = currentSecondaryColor
}
let bank = showingValues[indexPath.row]
cell.accessoryView?.tintColor = currentSecondaryColor
cell.textLabel?.text = bank.name
cell.imageView?.image = bankImage(bank: bank.code)
cell.textLabel?.textColor = currentPrimaryColor
if !bank.isActive {
disableCell(cell: cell)
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else {
return
}
let selectedBank = element(forUIIndexPath: indexPath)
let paymentInformation = PaymentInformation.FPX(bank: selectedBank.code, email: email)
tableView.deselectRow(at: indexPath, animated: true)
os_log("FPX Banking Chooser: %{private}@ was selected", log: uiLogObject, type: .info, selectedBank.name)
let oldAccessoryView = cell.accessoryView
let loadingIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray)
loadingIndicator.color = currentSecondaryColor
cell.accessoryView = loadingIndicator
loadingIndicator.startAnimating()
view.isUserInteractionEnabled = false
flowSession?.requestCreateSource(.fpx(paymentInformation)) { _ in
cell.accessoryView = oldAccessoryView
self.view.isUserInteractionEnabled = true
}
}
private func applyPrimaryColor() {
guard isViewLoaded else {
return
}
}
private func applySecondaryColor() {
}
private func bankImage(bank: String) -> UIImage? {
if let image = UIImage(named: "FPX/" + bank, in: .module, compatibleWith: nil) {
return image
} else {
return UIImage(named: defaultImage, in: .module, compatibleWith: nil)
}
}
private func disableCell(cell: UITableViewCell) {
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.contentView.alpha = 0.5
cell.isUserInteractionEnabled = false
}
private func displayEmptyMessage() {
let label = UILabel(
frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height)
)
label.text = message
label.textColor = currentPrimaryColor
label.numberOfLines = 0
label.textAlignment = .center
label.sizeToFit()
tableView.backgroundView = label
tableView.separatorStyle = .none
}
private func restore() {
tableView.backgroundView = nil
tableView.separatorStyle = .singleLine
}
}
| mit | 05c5b8b3a0e6c20621b37f219f355f01 | 32.262774 | 138 | 0.640114 | 5.057714 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/ConfigurationMessageCell/ConversationMessageActionController.swift | 1 | 7076 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireDataModel
import WireCommonComponents
final class ConversationMessageActionController {
enum Context: Int {
case content, collection
}
let message: ZMConversationMessage
let context: Context
weak var responder: MessageActionResponder?
weak var view: UIView!
init(responder: MessageActionResponder?,
message: ZMConversationMessage,
context: Context,
view: UIView) {
self.responder = responder
self.message = message
self.context = context
self.view = view
}
// MARK: - List of Actions
private var allPerformableMessageAction: [MessageAction] {
return MessageAction.allCases
.filter(canPerformAction)
}
func allMessageMenuElements() -> [UIAction] {
weak var responder = self.responder
weak var message = self.message
unowned let targetView: UIView = self.view
return allPerformableMessageAction.compactMap { messageAction in
guard let title = messageAction.title else { return nil }
let handler: UIActionHandler = { _ in
responder?.perform(action: messageAction,
for: message,
view: targetView)
}
return UIAction(title: title,
image: messageAction.systemIcon(),
handler: handler)
}
}
// MARK: - UI menu
static var allMessageActions: [UIMenuItem] {
return MessageAction.allCases.compactMap {
guard let selector = $0.selector,
let title = $0.title else { return nil }
return UIMenuItem(title: title, action: selector)
}
}
func canPerformAction(action: MessageAction) -> Bool {
switch action {
case .copy:
return message.canBeCopied
case .digitallySign:
return message.canBeDigitallySigned
case .reply:
return message.canBeQuoted
case .openDetails:
return message.areMessageDetailsAvailable
case .edit:
return message.canBeEdited
case .delete:
return message.canBeDeleted
case .save:
return message.canBeSaved
case .cancel:
return message.canCancelDownload
case .download:
return message.canBeDownloaded
case .forward:
return message.canBeForwarded
case .like:
return message.canBeLiked && !message.liked
case .unlike:
return message.canBeLiked && message.liked
case .resend:
return message.canBeResent
case .showInConversation:
return context == .collection
case .sketchDraw,
.sketchEmoji:
return message.isImage
case .present,
.openQuote,
.resetSession:
return false
}
}
func canPerformAction(_ selector: Selector) -> Bool {
guard let action = MessageAction.allCases.first(where: {
$0.selector == selector
}) else { return false }
return canPerformAction(action: action)
}
func makeAccessibilityActions() -> [UIAccessibilityCustomAction] {
return ConversationMessageActionController.allMessageActions
.filter { self.canPerformAction($0.action) }
.map { menuItem in
UIAccessibilityCustomAction(name: menuItem.title, target: self, selector: menuItem.action)
}
}
@available(iOS, introduced: 9.0, deprecated: 13.0, message: "UIViewControllerPreviewing is deprecated. Please use UIContextMenuInteraction.")
var previewActionItems: [UIPreviewAction] {
return allPerformableMessageAction.compactMap { messageAction in
guard let title = messageAction.title else { return nil }
return UIPreviewAction(title: title,
style: .default) { [weak self] _, _ in
self?.perform(action: messageAction)
}
}
}
// MARK: - Single Tap Action
func performSingleTapAction() {
guard let singleTapAction = singleTapAction else { return }
perform(action: singleTapAction)
}
var singleTapAction: MessageAction? {
if message.isImage, message.imageMessageData?.isDownloaded == true {
return .present
} else if message.isFile, !message.isAudio, let transferState = message.fileMessageData?.transferState {
switch transferState {
case .uploaded:
return .present
default:
return nil
}
}
return nil
}
// MARK: - Double Tap Action
func performDoubleTapAction() {
guard let doubleTapAction = doubleTapAction else { return }
perform(action: doubleTapAction)
}
var doubleTapAction: MessageAction? {
return message.canBeLiked ? .like : nil
}
// MARK: - Handler
private func perform(action: MessageAction) {
responder?.perform(action: action,
for: message,
view: view)
}
@objc func digitallySignMessage() {
perform(action: .digitallySign)
}
@objc func copyMessage() {
perform(action: .copy)
}
@objc func editMessage() {
perform(action: .edit)
}
@objc func quoteMessage() {
perform(action: .reply)
}
@objc func openMessageDetails() {
perform(action: .openDetails)
}
@objc func cancelDownloadingMessage() {
perform(action: .cancel)
}
@objc func downloadMessage() {
perform(action: .download)
}
@objc func saveMessage() {
perform(action: .save)
}
@objc func forwardMessage() {
perform(action: .forward)
}
@objc func likeMessage() {
perform(action: .like)
}
@objc func unlikeMessage() {
perform(action: .like)
}
@objc func deleteMessage() {
perform(action: .delete)
}
@objc func resendMessage() {
perform(action: .resend)
}
@objc func revealMessage() {
perform(action: .showInConversation)
}
}
| gpl-3.0 | d245256df0d04da39792c256ce633baf | 27.647773 | 145 | 0.599067 | 5.022001 | false | false | false | false |
michaelvu812/MVFetchedResultsController | MVFetchedResultsController/ViewController.swift | 1 | 1140 | //
// ViewController.swift
// MVFetchedResultsController
//
// Created by Michael on 1/7/14.
// Copyright (c) 2014 Michael Vu. All rights reserved.
//
import UIKit
class ViewController: MVFetchedResultsController {
var canInsert = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
self.entityName = "Entity"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let entity = self.fetchedResultsController.objectAtIndexPath(indexPath) as Entity
super.tableView(tableView, cellForRowAtIndexPath: indexPath)
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil)
let text = entity.name
cell.textLabel.text = text
return cell
}
}
| mit | 8ccb90842907d563b9052894b1c347eb | 31.571429 | 121 | 0.677193 | 5.181818 | false | false | false | false |
nab0y4enko/PrettyKeyboardHelper | PrettyKeyboardHelper/UIScrollView+PrettyKeyboardHelper.swift | 1 | 1460 | //
// UIScrollView+PrettyKeyboardHelper.swift
// PrettyKeyboardHelper
//
// Created by Oleksii Naboichenko on 12/7/16.
// Copyright © 2016 Oleksii Naboichenko. All rights reserved.
//
import UIKit
public extension UIScrollView {
final func updateBottomInset(with keyboardInfo: PrettyKeyboardInfo, defaultBottomInset: CGFloat = 0.0, safeAreaInsets: UIEdgeInsets? = nil, completion: ((Bool) -> Swift.Void)? = nil) {
var bottomContentInset = keyboardInfo.estimatedKeyboardHeight + defaultBottomInset
if let bottomSafeAreaInset = safeAreaInsets?.bottom, keyboardInfo.keyboardState == .willBeShown {
bottomContentInset -= bottomSafeAreaInset
}
UIView.animate(
withDuration: keyboardInfo.duration,
delay: 0,
options: keyboardInfo.animationOptions,
animations: { [weak self] in
guard let self = self else {
return
}
var contentInset = self.contentInset
contentInset.bottom = bottomContentInset
self.contentInset = contentInset
var verticalScrollIndicatorInsets = self.verticalScrollIndicatorInsets
verticalScrollIndicatorInsets.bottom = bottomContentInset
self.verticalScrollIndicatorInsets = verticalScrollIndicatorInsets
},
completion: completion
)
}
}
| mit | 385a500839a246a056a9f83e9f4927ee | 35.475 | 188 | 0.642221 | 5.859438 | false | false | false | false |
greycats/Greycats.swift | Greycats/Camera.swift | 1 | 4321 | import AVFoundation
import GreycatsCore
import GreycatsGraphics
import UIKit
open class Camera {
var session: AVCaptureSession!
var previewLayer: AVCaptureVideoPreviewLayer!
var stillCameraOutput: AVCaptureStillImageOutput!
public init() {
session = AVCaptureSession()
stillCameraOutput = AVCaptureStillImageOutput()
session.sessionPreset = AVCaptureSession.Preset.photo
previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
if let input = backCameraInput() {
if session.canAddInput(input) {
session.addInput(input)
}
}
if session.canAddOutput(stillCameraOutput) {
session.addOutput(stillCameraOutput)
}
}
fileprivate func backCameraDevice() -> AVCaptureDevice? {
let availableCameraDevices = AVCaptureDevice.devices(for: AVMediaType.video)
for device in availableCameraDevices {
if device.position == .back {
return device
}
}
return nil
}
open func containerDidUpdate(_ container: UIView) {
if previewLayer.superlayer == nil {
container.layer.addSublayer(previewLayer)
}
UIView.setAnimationsEnabled(false)
previewLayer.frame = container.bounds
UIView.setAnimationsEnabled(true)
}
open func start() {
foreground {
self.checkPermission {[weak self] in
self?.session.startRunning()
}
}
}
open func capture(_ next: @escaping (UIImage?) -> Void) {
if let connection = stillCameraOutput.connection(with: AVMediaType.video) {
if connection.isVideoOrientationSupported {
connection.videoOrientation = .portrait
}
if !connection.isEnabled || !connection.isActive {
next(nil)
return
}
stillCameraOutput.captureStillImageAsynchronously(from: connection) { [weak self] buffer, _ in
self?.stop()
if let buffer = buffer {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
let image = UIImage(data: imageData!)?.fixedOrientation()
foreground {
next(image)
}
} else {
next(nil)
}
}
} else {
next(nil)
}
}
open func stop() {
session.stopRunning()
}
open func toggleFlash() -> AVCaptureDevice.FlashMode? {
if let device = backCameraDevice() {
do {
try device.lockForConfiguration()
if device.flashMode == .off {
device.flashMode = .on
} else {
device.flashMode = .off
}
device.unlockForConfiguration()
} catch {
}
return device.flashMode
}
return nil
}
fileprivate func backCameraInput() -> AVCaptureDeviceInput? {
if let device = backCameraDevice() {
return try? AVCaptureDeviceInput(device: device)
}
return nil
}
fileprivate func checkPermission(_ next: @escaping () -> Void) {
let authorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch authorizationStatus {
case .notDetermined:
// permission dialog not yet presented, request authorization
AVCaptureDevice.requestAccess(for: AVMediaType.video) { granted in
if granted {
foreground {
next()
}
} else {
// user denied, nothing much to do
}
}
case .authorized:
next()
case .denied, .restricted:
// the user explicitly denied camera usage or is not allowed to access the camera devices
return
@unknown default:
return
}
}
}
| mit | d819f619098cf4d704332908d1cb3135 | 31.984733 | 106 | 0.545476 | 6.043357 | false | false | false | false |
isnine/HutHelper-Open | HutHelper/SwiftApp/Third/FWPopupView/FWMenuView.swift | 1 | 21181 | //
// FWMenuView.swift
// FWPopupView
//
// Created by xfg on 2018/5/19.
// Copyright © 2018年 xfg. All rights reserved.
// 仿QQ、微信菜单
/** ************************************************
github地址:https://github.com/choiceyou/FWPopupView
bug反馈、交流群:670698309
***************************************************
*/
import Foundation
import UIKit
class FWMenuViewTableViewCell: UITableViewCell {
var iconImgView: UIImageView!
var titleLabel: UILabel!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.clear
self.iconImgView = UIImageView()
self.iconImgView.contentMode = .center
self.iconImgView.backgroundColor = UIColor.clear
self.contentView.addSubview(self.iconImgView)
self.titleLabel = UILabel()
self.titleLabel.backgroundColor = UIColor.clear
self.contentView.addSubview(self.titleLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupContent(title: String?, image: UIImage?, property: FWMenuViewProperty) {
self.selectionStyle = property.selectionStyle
if image != nil {
self.iconImgView.isHidden = false
self.iconImgView.image = image
self.iconImgView.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(property.letfRigthMargin)
make.centerY.equalToSuperview()
make.size.equalTo(image!.size)
}
} else {
self.iconImgView.isHidden = true
}
if title != nil {
self.titleLabel.textAlignment = property.textAlignment
let attributedString = NSAttributedString(string: title!, attributes: property.titleTextAttributes)
self.titleLabel.attributedText = attributedString
self.titleLabel.snp.makeConstraints { (make) in
if image != nil {
make.left.equalTo(self.iconImgView.snp.right).offset(property.commponentMargin)
} else {
make.left.equalToSuperview().offset(property.letfRigthMargin)
}
make.right.equalToSuperview().offset(-property.letfRigthMargin)
make.top.equalToSuperview().offset(property.topBottomMargin)
make.bottom.equalToSuperview().offset(-property.topBottomMargin)
}
}
}
}
open class FWMenuView: FWPopupView, UITableViewDelegate, UITableViewDataSource {
/// 外部传入的标题数组
@objc public var itemTitleArray: [String]? {
didSet {
self.setNeedsLayout()
self.setNeedsDisplay()
}
}
/// 外部传入的图片数组
@objc public var itemImageArray: [UIImage]? {
didSet {
self.setNeedsLayout()
self.setNeedsDisplay()
}
}
/// 当前选中下标
private var selectedIndex: Int = 0
/// 最大的那一项的size
private var maxItemSize: CGSize = CGSize.zero
/// 保存点击回调
private var popupItemClickedBlock: FWPopupItemClickedBlock?
/// 有箭头时:当前layer的mask
private var maskLayer: CAShapeLayer?
/// 有箭头时:当前layer的border
private var borderLayer: CAShapeLayer?
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.register(FWMenuViewTableViewCell.self, forCellReuseIdentifier: "cellId")
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = UIColor.clear
self.addSubview(tableView)
return tableView
}()
/// 类初始化方法1
///
/// - Parameters:
/// - itemTitles: 标题
/// - itemBlock: 点击回调
/// - Returns: self
@objc open class func menu(itemTitles: [String], itemBlock: FWPopupItemClickedBlock? = nil) -> FWMenuView {
return self.menu(itemTitles: itemTitles, itemImageNames: nil, itemBlock: itemBlock, property: nil)
}
/// 类初始化方法2
///
/// - Parameters:
/// - itemTitles: 标题
/// - itemBlock: 点击回调
/// - property: 可设置参数
/// - Returns: self
@objc open class func menu(itemTitles: [String], itemBlock: FWPopupItemClickedBlock? = nil, property: FWMenuViewProperty?) -> FWMenuView {
return self.menu(itemTitles: itemTitles, itemImageNames: nil, itemBlock: itemBlock, property: property)
}
/// 类初始化方法3
///
/// - Parameters:
/// - itemTitles: 标题
/// - itemImageNames: 图片
/// - itemBlock: 点击回调
/// - property: 可设置参数
/// - Returns: self
@objc open class func menu(itemTitles: [String]?, itemImageNames: [UIImage]?, itemBlock: FWPopupItemClickedBlock? = nil, property: FWMenuViewProperty?) -> FWMenuView {
let popupMenu = FWMenuView()
popupMenu.setupUI(itemTitles: itemTitles, itemImageNames: itemImageNames, itemBlock: itemBlock, property: property)
return popupMenu
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.vProperty = FWMenuViewProperty()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 刷新当前视图及数据
@objc open func refreshData() {
self.setupFrame(property: self.vProperty as! FWMenuViewProperty)
self.tableView.reloadData()
}
}
extension FWMenuView {
private func setupUI(itemTitles: [String]?, itemImageNames: [UIImage]?, itemBlock: FWPopupItemClickedBlock? = nil, property: FWMenuViewProperty?) {
if itemTitles == nil && itemImageNames == nil {
return
}
if property != nil {
self.vProperty = property!
} else {
self.vProperty = FWMenuViewProperty()
}
self.clipsToBounds = true
self.itemTitleArray = itemTitles
self.itemImageArray = itemImageNames
self.popupItemClickedBlock = itemBlock
let property = self.vProperty as! FWMenuViewProperty
self.tableView.separatorInset = property.separatorInset
self.tableView.layoutMargins = property.separatorInset
self.tableView.separatorColor = property.separatorColor
self.tableView.bounces = property.bounces
self.maxItemSize = self.measureMaxSize()
self.setupFrame(property: property)
var tableViewY: CGFloat = 0
if property.popupArrowStyle == .none {
self.layer.cornerRadius = self.vProperty.cornerRadius
self.layer.borderColor = self.vProperty.splitColor.cgColor
self.layer.borderWidth = self.vProperty.splitWidth
} else {
tableViewY = property.popupArrowSize.height
}
// 箭头方向
var isUpArrow = true
switch property.popupCustomAlignment {
case .bottomLeft, .bottomRight, .bottomCenter:
isUpArrow = false
break
default:
isUpArrow = true
break
}
// 用来隐藏多余的线条,不想自定义线条
let footerViewHeight: CGFloat = 1
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: footerViewHeight))
footerView.backgroundColor = UIColor.clear
self.tableView.tableFooterView = footerView
self.tableView.snp.remakeConstraints { (make) in
make.top.equalToSuperview().offset(isUpArrow ? tableViewY : 0)
make.left.right.equalToSuperview()
make.bottom.equalToSuperview().offset(-((isUpArrow ? 0 : tableViewY ) - footerViewHeight))
}
}
private func setupFrame(property: FWMenuViewProperty) {
var tableViewY: CGFloat = 0
switch property.popupArrowStyle {
case .none:
tableViewY = 0
break
case .round, .triangle:
tableViewY = property.popupArrowSize.height
break
}
var tmpMaxHeight: CGFloat = 0.0
if self.superview != nil {
tmpMaxHeight = self.vProperty.popupViewMaxHeightRate * self.superview!.frame.size.height
} else {
tmpMaxHeight = self.vProperty.popupViewMaxHeightRate * UIScreen.main.bounds.height
}
var selfSize: CGSize = CGSize.zero
if property.popupViewSize.width > 0 && property.popupViewSize.height > 0 {
selfSize = property.popupViewSize
} else if self.vProperty.popupViewMaxHeightRate > 0 && self.maxItemSize.height * CGFloat(self.itemsCount()) > tmpMaxHeight {
selfSize = CGSize(width: self.maxItemSize.width, height: tmpMaxHeight)
} else {
selfSize = CGSize(width: self.maxItemSize.width, height: self.maxItemSize.height * CGFloat(self.itemsCount()))
}
selfSize.height += tableViewY
self.frame = CGRect(x: 0, y: tableViewY, width: selfSize.width, height: selfSize.height)
self.finalSize = selfSize
self.setupMaskLayer(property: property)
}
private func setupMaskLayer(property: FWMenuViewProperty) {
// 绘制箭头
if property.popupArrowStyle != .none {
if self.maskLayer != nil {
self.layer.mask = nil
self.maskLayer?.removeFromSuperlayer()
self.maskLayer = nil
}
if self.borderLayer != nil {
self.borderLayer?.removeFromSuperlayer()
self.borderLayer = nil
}
// 圆角值
let cornerRadius = property.cornerRadius
/// 箭头的尺寸
let arrowSize = property.popupArrowSize
if property.popupArrowVertexScaleX > 1 {
property.popupArrowVertexScaleX = 1
} else if property.popupArrowVertexScaleX < 0 {
property.popupArrowVertexScaleX = 0
}
// 箭头方向
var isUpArrow = true
switch property.popupCustomAlignment {
case .bottomLeft, .bottomRight, .bottomCenter:
isUpArrow = false
break
default:
isUpArrow = true
break
}
// 弹窗箭头顶点坐标
let arrowPoint = CGPoint(x: (self.frame.width - arrowSize.width - cornerRadius * 2) * property.popupArrowVertexScaleX + arrowSize.width/2 + cornerRadius, y: isUpArrow ? 0 : self.frame.height)
// 顶部Y值
let maskTop = isUpArrow ? arrowSize.height : 0
// 底部Y值
let maskBottom = isUpArrow ? self.frame.height : self.frame.height - arrowSize.height
// 开始画贝塞尔曲线
let maskPath = UIBezierPath()
// 左上圆角
maskPath.move(to: CGPoint(x: 0, y: cornerRadius + maskTop))
maskPath.addArc(withCenter: CGPoint(x: cornerRadius, y: cornerRadius + maskTop), radius: cornerRadius, startAngle: self.degreesToRadians(angle: 180), endAngle: self.degreesToRadians(angle: 270), clockwise: true)
// 箭头向上时的箭头位置
if isUpArrow {
maskPath.addLine(to: CGPoint(x: arrowPoint.x - arrowSize.width/2, y: arrowSize.height))
if property.popupArrowStyle == .triangle { // 菱角箭头
maskPath.addLine(to: arrowPoint)
maskPath.addLine(to: CGPoint(x: arrowPoint.x + arrowSize.width/2, y: arrowSize.height))
} else { // 圆角箭头
maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x - property.popupArrowCornerRadius, y: property.popupArrowCornerRadius), controlPoint: CGPoint(x: arrowPoint.x - arrowSize.width/2 + property.popupArrowBottomCornerRadius, y: arrowSize.height))
maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x + property.popupArrowCornerRadius, y: property.popupArrowCornerRadius), controlPoint: arrowPoint)
maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x + arrowSize.width/2, y: arrowSize.height), controlPoint: CGPoint(x: arrowPoint.x + arrowSize.width/2 - property.popupArrowBottomCornerRadius, y: arrowSize.height))
}
}
// 右上圆角
maskPath.addLine(to: CGPoint(x: self.frame.width - cornerRadius, y: maskTop))
maskPath.addArc(withCenter: CGPoint(x: self.frame.width - cornerRadius, y: maskTop + cornerRadius), radius: cornerRadius, startAngle: self.degreesToRadians(angle: 270), endAngle: self.degreesToRadians(angle: 0), clockwise: true)
// 右下圆角
maskPath.addLine(to: CGPoint(x: self.frame.width, y: maskBottom - cornerRadius))
maskPath.addArc(withCenter: CGPoint(x: self.frame.width - cornerRadius, y: maskBottom - cornerRadius), radius: cornerRadius, startAngle: self.degreesToRadians(angle: 0), endAngle: self.degreesToRadians(angle: 90), clockwise: true)
// 箭头向下时的箭头位置
if !isUpArrow {
maskPath.addLine(to: CGPoint(x: arrowPoint.x + arrowSize.width/2, y: self.frame.height - arrowSize.height))
if property.popupArrowStyle == .triangle { // 菱角箭头
maskPath.addLine(to: arrowPoint)
maskPath.addLine(to: CGPoint(x: arrowPoint.x - arrowSize.width/2, y: self.frame.height - arrowSize.height))
} else { // 圆角箭头
maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x + property.popupArrowCornerRadius, y: self.frame.height - property.popupArrowCornerRadius), controlPoint: CGPoint(x: arrowPoint.x + arrowSize.width/2 - property.popupArrowBottomCornerRadius, y: self.frame.height - arrowSize.height))
maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x - property.popupArrowCornerRadius, y: self.frame.height - property.popupArrowCornerRadius), controlPoint: arrowPoint)
maskPath.addQuadCurve(to: CGPoint(x: arrowPoint.x - arrowSize.width/2, y: self.frame.height - arrowSize.height), controlPoint: CGPoint(x: arrowPoint.x - arrowSize.width/2 + property.popupArrowBottomCornerRadius, y: self.frame.height - arrowSize.height))
}
}
// 左下圆角
maskPath.addLine(to: CGPoint(x: cornerRadius, y: maskBottom))
maskPath.addArc(withCenter: CGPoint(x: cornerRadius, y: maskBottom - cornerRadius), radius: cornerRadius, startAngle: self.degreesToRadians(angle: 90), endAngle: self.degreesToRadians(angle: 180), clockwise: true)
maskPath.close()
// 截取圆角和箭头
self.maskLayer = CAShapeLayer()
self.maskLayer?.frame = self.bounds
self.maskLayer?.path = maskPath.cgPath
self.layer.mask = self.maskLayer
// 边框
self.borderLayer = CAShapeLayer()
self.borderLayer?.frame = self.bounds
self.borderLayer?.path = maskPath.cgPath
self.borderLayer?.lineWidth = 1
self.borderLayer?.fillColor = UIColor.clear.cgColor
self.borderLayer?.strokeColor = property.splitColor.cgColor
self.layer.addSublayer(self.borderLayer!)
}
}
}
extension FWMenuView {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.itemsCount()
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.maxItemSize.height
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! FWMenuViewTableViewCell
cell.setupContent(title: (self.itemTitleArray != nil) ? self.itemTitleArray![indexPath.row] : nil, image: (self.itemImageArray != nil) ? self.itemImageArray![indexPath.row] : nil, property: self.vProperty as! FWMenuViewProperty)
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.hide()
if self.popupItemClickedBlock != nil {
self.popupItemClickedBlock!(self, indexPath.row, (self.itemTitleArray != nil) ? self.itemTitleArray![indexPath.row] : nil)
}
}
}
extension FWMenuView {
/// 计算控件的最大宽度、高度
///
/// - Returns: CGSize
fileprivate func measureMaxSize() -> CGSize {
if self.itemTitleArray == nil && self.itemImageArray == nil {
return CGSize.zero
}
let property = self.vProperty as! FWMenuViewProperty
var titleSize = CGSize.zero
var imageSize = CGSize.zero
var totalMaxSize = CGSize.zero
let titleAttrs = property.titleTextAttributes
if self.itemTitleArray != nil {
var tmpSize = CGSize.zero
var index = 0
for title: String in self.itemTitleArray! {
titleSize = (title as NSString).size(withAttributes: titleAttrs)
if self.itemImageArray != nil && self.itemImageArray!.count == self.itemTitleArray!.count {
let image = self.itemImageArray![index]
imageSize = image.size
}
tmpSize = CGSize(width: titleSize.width + imageSize.width, height: titleSize.height + imageSize.height)
totalMaxSize.width = max(totalMaxSize.width, tmpSize.width)
totalMaxSize.height = max(totalMaxSize.height, tmpSize.height)
index += 1
}
} else if self.itemTitleArray == nil && self.itemImageArray != nil {
for image: UIImage in self.itemImageArray! {
imageSize = image.size
totalMaxSize.width = max(totalMaxSize.width, imageSize.width)
totalMaxSize.height = max(totalMaxSize.height, imageSize.height)
}
}
totalMaxSize.width += property.letfRigthMargin * 2
if self.itemTitleArray != nil && self.itemImageArray != nil {
totalMaxSize.width += property.commponentMargin
}
totalMaxSize.height += property.topBottomMargin * 2
var width = min(ceil(totalMaxSize.width), property.popupViewMaxWidth)
width = max(width, property.popupViewMinWidth)
totalMaxSize.width = width
if property.popupViewItemHeight > 0 {
totalMaxSize.height = property.popupViewItemHeight
} else {
totalMaxSize.height = ceil(totalMaxSize.height)
}
return totalMaxSize
}
/// 计算总计行数
///
/// - Returns: 行数
fileprivate func itemsCount() -> Int {
if self.itemTitleArray != nil {
return self.itemTitleArray!.count
} else if self.itemImageArray != nil {
return self.itemImageArray!.count
} else {
return 0
}
}
/// 角度转换
///
/// - Parameter angle: 传入的角度值
/// - Returns: CGFloat
fileprivate func degreesToRadians(angle: CGFloat) -> CGFloat {
return angle * CGFloat(Double.pi) / 180
}
}
/// FWMenuView的相关属性,请注意其父类中还有很多公共属性
open class FWMenuViewProperty: FWPopupViewProperty {
/// 弹窗大小,如果没有设置,将按照统一的计算方式
@objc public var popupViewSize = CGSize.zero
/// 指定行高优先级 > 自动计算的优先级
@objc public var popupViewItemHeight: CGFloat = 0
/// 未选中时按钮字体属性
@objc public var titleTextAttributes: [NSAttributedString.Key: Any]!
/// 文字位置
@objc public var textAlignment: NSTextAlignment = .left
/// 内容位置
@objc public var contentHorizontalAlignment: UIControl.ContentHorizontalAlignment = .left
/// 选中风格
@objc public var selectionStyle: UITableViewCell.SelectionStyle = .none
/// 分割线颜色
@objc public var separatorColor: UIColor = kPV_RGBA(r: 231, g: 231, b: 231, a: 1)
/// 分割线偏移量
@objc public var separatorInset: UIEdgeInsets = UIEdgeInsets.zero
/// 是否开启tableview回弹效果
@objc public var bounces: Bool = false
/// 弹窗的最大宽度
@objc open var popupViewMaxWidth: CGFloat = UIScreen.main.bounds.width * 0.6
/// 弹窗的最小宽度
@objc open var popupViewMinWidth: CGFloat = 20
public override func reSetParams() {
super.reSetParams()
self.titleTextAttributes = [NSAttributedString.Key.foregroundColor: self.itemNormalColor, NSAttributedString.Key.backgroundColor: UIColor.clear, NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.buttonFontSize)]
self.letfRigthMargin = 20
self.popupViewMaxHeightRate = 0.7
}
}
| lgpl-2.1 | f01503e74f9e561fa26ec6fb96167280 | 36.777778 | 303 | 0.628775 | 4.57707 | false | false | false | false |
therealbnut/swift | benchmark/single-source/Walsh.swift | 5 | 2354 | //===--- Walsh.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
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Darwin
func IsPowerOfTwo(_ x: Int) -> Bool { return (x & (x - 1)) == 0 }
// Fast Walsh Hadamard Transform
func WalshTransform(_ data: inout [Double]) {
assert(IsPowerOfTwo(data.count), "Not a power of two")
var temp = [Double](repeating: 0, count: data.count)
var ret = WalshImpl(&data, &temp, 0, data.count)
for i in 0..<data.count {
data[i] = ret[i]
}
}
func Scale(_ data: inout [Double], _ scalar : Double) {
for i in 0..<data.count {
data[i] = data[i] * scalar
}
}
func InverseWalshTransform(_ data: inout [Double]) {
WalshTransform(&data)
Scale(&data, Double(1)/Double(data.count))
}
func WalshImpl(_ data: inout [Double], _ temp: inout [Double], _ start: Int, _ size: Int) -> [Double] {
if (size == 1) { return data }
let stride = size/2
for i in 0..<stride {
temp[start + i] = data[start + i + stride] + data[start + i]
temp[start + i + stride] = data[start + i] - data[start + i + stride]
}
_ = WalshImpl(&temp, &data, start, stride)
return WalshImpl(&temp, &data, start + stride, stride)
}
func checkCorrectness() {
var In : [Double] = [1,0,1,0,0,1,1,0]
var Out : [Double] = [4,2,0,-2,0,2,0,2]
var data : [Double] = In
WalshTransform(&data)
var mid = data
InverseWalshTransform(&data)
for i in 0..<In.count {
// Check encode.
CheckResults(abs(data[i] - In[i]) < 0.0001, "Incorrect results in Walsh.")
// Check decode.
CheckResults(abs(mid[i] - Out[i]) < 0.0001, "Incorrect results in Walsh.")
}
}
@inline(never)
public func run_Walsh(_ N: Int) {
checkCorrectness()
// Generate data.
var data2 : [Double] = []
for i in 0..<1024 {
data2.append(Double(sin(Float(i))))
}
// Transform back and forth.
for _ in 1...10*N {
WalshTransform(&data2)
InverseWalshTransform(&data2)
}
}
| apache-2.0 | 009baecea8d337fe3c8040f6dc5bab7d | 27.361446 | 103 | 0.593033 | 3.339007 | false | false | false | false |
ytakzk/Fusuma | Example/FusumaExample/ViewController.swift | 1 | 4106 | //
// ViewController.swift
// Fusuma
//
// Created by ytakzk on 01/31/2016.
// Copyright (c) 2016 ytakzk. All rights reserved.
//
import UIKit
class ViewController: UIViewController, FusumaDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var showButton: UIButton!
@IBOutlet weak var fileUrlLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
showButton.layer.cornerRadius = 2.0
fileUrlLabel.text = ""
}
@IBAction func showButtonPressed(_ sender: AnyObject) {
// Show Fusuma
let fusuma = FusumaViewController()
fusuma.delegate = self
fusuma.cropHeightRatio = 1.0
fusuma.allowMultipleSelection = false
fusuma.availableModes = [.library, .video, .camera]
fusuma.photoSelectionLimit = 4
fusumaSavesImage = true
present(fusuma, animated: true, completion: nil)
}
// MARK: FusumaDelegate Protocol
func fusumaImageSelected(_ image: UIImage, source: FusumaMode) {
switch source {
case .camera:
print("Image captured from Camera")
case .library:
print("Image selected from Camera Roll")
default:
print("Image selected")
}
imageView.image = image
}
func fusumaMultipleImageSelected(_ images: [UIImage], source: FusumaMode) {
print("Number of selection images: \(images.count)")
var count: Double = 0
for image in images {
DispatchQueue.main.asyncAfter(deadline: .now() + (3.0 * count)) {
self.imageView.image = image
print("w: \(image.size.width) - h: \(image.size.height)")
}
count += 1
}
}
func fusumaImageSelected(_ image: UIImage, source: FusumaMode, metaData: ImageMetadata) {
print("Image mediatype: \(metaData.mediaType)")
print("Source image size: \(metaData.pixelWidth)x\(metaData.pixelHeight)")
print("Creation date: \(String(describing: metaData.creationDate))")
print("Modification date: \(String(describing: metaData.modificationDate))")
print("Video duration: \(metaData.duration)")
print("Is favourite: \(metaData.isFavourite)")
print("Is hidden: \(metaData.isHidden)")
print("Location: \(String(describing: metaData.location))")
}
func fusumaVideoCompleted(withFileURL fileURL: URL) {
print("video completed and output to file: \(fileURL)")
self.fileUrlLabel.text = "file output to: \(fileURL.absoluteString)"
}
func fusumaDismissedWithImage(_ image: UIImage, source: FusumaMode) {
switch source {
case .camera:
print("Called just after dismissed FusumaViewController using Camera")
case .library:
print("Called just after dismissed FusumaViewController using Camera Roll")
default:
print("Called just after dismissed FusumaViewController")
}
}
func fusumaCameraRollUnauthorized() {
print("Camera roll unauthorized")
let alert = UIAlertController(title: "Access Requested",
message: "Saving image needs to access your photo album",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Settings", style: .default) { (action) -> Void in
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(url)
}
})
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
})
guard let vc = UIApplication.shared.delegate?.window??.rootViewController, let presented = vc.presentedViewController else {
return
}
presented.present(alert, animated: true, completion: nil)
}
func fusumaClosed() {
print("Called when the FusumaViewController disappeared")
}
func fusumaWillClosed() {
print("Called when the close button is pressed")
}
}
| mit | 30a40936e4c32f7c07dc7154b0aff354 | 32.382114 | 132 | 0.620312 | 4.941035 | false | false | false | false |
jokechat/swift3-novel | swift_novels/Pods/SnapKit/Source/Constraint.swift | 15 | 11168 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class Constraint {
internal let sourceLocation: (String, UInt)
internal let label: String?
private let from: ConstraintItem
private let to: ConstraintItem
private let relation: ConstraintRelation
private let multiplier: ConstraintMultiplierTarget
private var constant: ConstraintConstantTarget {
didSet {
self.updateConstantAndPriorityIfNeeded()
}
}
private var priority: ConstraintPriorityTarget {
didSet {
self.updateConstantAndPriorityIfNeeded()
}
}
private var layoutConstraints: [LayoutConstraint]
// MARK: Initialization
internal init(from: ConstraintItem,
to: ConstraintItem,
relation: ConstraintRelation,
sourceLocation: (String, UInt),
label: String?,
multiplier: ConstraintMultiplierTarget,
constant: ConstraintConstantTarget,
priority: ConstraintPriorityTarget) {
self.from = from
self.to = to
self.relation = relation
self.sourceLocation = sourceLocation
self.label = label
self.multiplier = multiplier
self.constant = constant
self.priority = priority
self.layoutConstraints = []
// get attributes
let layoutFromAttributes = self.from.attributes.layoutAttributes
let layoutToAttributes = self.to.attributes.layoutAttributes
// get layout from
let layoutFrom: ConstraintView = self.from.view!
// get relation
let layoutRelation = self.relation.layoutRelation
for layoutFromAttribute in layoutFromAttributes {
// get layout to attribute
let layoutToAttribute: NSLayoutAttribute
#if os(iOS) || os(tvOS)
if layoutToAttributes.count > 0 {
if self.from.attributes == .edges && self.to.attributes == .margins {
switch layoutFromAttribute {
case .left:
layoutToAttribute = .leftMargin
case .right:
layoutToAttribute = .rightMargin
case .top:
layoutToAttribute = .topMargin
case .bottom:
layoutToAttribute = .bottomMargin
default:
fatalError()
}
} else if self.from.attributes == .margins && self.to.attributes == .edges {
switch layoutFromAttribute {
case .leftMargin:
layoutToAttribute = .left
case .rightMargin:
layoutToAttribute = .right
case .topMargin:
layoutToAttribute = .top
case .bottomMargin:
layoutToAttribute = .bottom
default:
fatalError()
}
} else if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else {
layoutToAttribute = layoutToAttributes[0]
}
} else {
layoutToAttribute = layoutFromAttribute
}
#else
if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else if layoutToAttributes.count > 0 {
layoutToAttribute = layoutToAttributes[0]
} else {
layoutToAttribute = layoutFromAttribute
}
#endif
// get layout constant
let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute)
// get layout to
var layoutTo: AnyObject? = self.to.target
// use superview if possible
if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height {
layoutTo = layoutFrom.superview
}
// create layout constraint
let layoutConstraint = LayoutConstraint(
item: layoutFrom,
attribute: layoutFromAttribute,
relatedBy: layoutRelation,
toItem: layoutTo,
attribute: layoutToAttribute,
multiplier: self.multiplier.constraintMultiplierTargetValue,
constant: layoutConstant
)
// set label
layoutConstraint.label = self.label
// set priority
layoutConstraint.priority = self.priority.constraintPriorityTargetValue
// set constraint
layoutConstraint.constraint = self
// append
self.layoutConstraints.append(layoutConstraint)
}
}
// MARK: Public
@available(*, deprecated:3.0, message:"Use activate().")
public func install() {
self.activate()
}
@available(*, deprecated:3.0, message:"Use deactivate().")
public func uninstall() {
self.deactivate()
}
public func activate() {
self.activateIfNeeded()
}
public func deactivate() {
self.deactivateIfNeeded()
}
@discardableResult
public func update(offset: ConstraintOffsetTarget) -> Constraint {
self.constant = offset.constraintOffsetTargetValue
return self
}
@discardableResult
public func update(inset: ConstraintInsetTarget) -> Constraint {
self.constant = inset.constraintInsetTargetValue
return self
}
@discardableResult
public func update(priority: ConstraintPriorityTarget) -> Constraint {
self.priority = priority.constraintPriorityTargetValue
return self
}
@available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.")
public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) }
@available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.")
public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) }
@available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityRequired() -> Void {}
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
// MARK: Internal
internal func updateConstantAndPriorityIfNeeded() {
for layoutConstraint in self.layoutConstraints {
let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute)
layoutConstraint.priority = self.priority.constraintPriorityTargetValue
}
}
internal func activateIfNeeded(updatingExisting: Bool = false) {
guard let view = self.from.view else {
print("WARNING: SnapKit failed to get from view from constraint. Activate will be a no-op.")
return
}
let layoutConstraints = self.layoutConstraints
let existingLayoutConstraints = view.snp.constraints.map({ $0.layoutConstraints }).reduce([]) { $0 + $1 }
if updatingExisting {
for layoutConstraint in layoutConstraints {
let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint }
guard let updateLayoutConstraint = existingLayoutConstraint else {
fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)")
}
let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute
updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute)
}
} else {
NSLayoutConstraint.activate(layoutConstraints)
view.snp.add(constraints: [self])
}
}
internal func deactivateIfNeeded() {
guard let view = self.from.view else {
print("WARNING: SnapKit failed to get from view from constraint. Deactivate will be a no-op.")
return
}
let layoutConstraints = self.layoutConstraints
NSLayoutConstraint.deactivate(layoutConstraints)
view.snp.remove(constraints: [self])
}
}
| apache-2.0 | 0159cdf44467ebd3f891e1e9241e6d36 | 40.671642 | 184 | 0.607808 | 6.033495 | false | false | false | false |
acchou/RxGmail | Example/RxGmail/Data+Base64URL.swift | 1 | 1990 | // Data+Base64URL.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension Data {
init?(base64URLEncoded string: String) {
let base64Encoded = string
.replacingOccurrences(of: "_", with: "/")
.replacingOccurrences(of: "-", with: "+")
// iOS can't handle base64 encoding without padding. Add manually
let padLength = (4 - (base64Encoded.characters.count % 4)) % 4
let base64EncodedWithPadding = base64Encoded + String(repeating: "=", count: padLength)
self.init(base64Encoded: base64EncodedWithPadding)
}
func base64URLEncodedString() -> String {
// use URL safe encoding and remove padding
return self.base64EncodedString()
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "=", with: "")
}
}
| mit | 771a261deb060c0be3ddd8f3a1fcff41 | 45.27907 | 95 | 0.699497 | 4.595843 | false | false | false | false |
wilzh40/SoundSieve | SwiftSkeleton/LFTPulseAnimation.swift | 1 | 3615 |
//
// LFTPulseAnimation.swift
//
// Created by Christoffer Tews on 18.12.14.
// Copyright (c) 2014 Christoffer Tews. All rights reserved.
//
// Swift clone of: https://github.com/shu223/PulsingHalo/blob/master/PulsingHalo/PulsingHaloLayer.m
import UIKit
class LFTPulseAnimation: CALayer {
var radius: CGFloat = 200.0
var fromValueForRadius: Float = 0.0
var fromValueForAlpha: Float = 0.45
var keyTimeForHalfOpacity: Float = 0.2
var animationDuration: NSTimeInterval = 3.0
var pulseInterval: NSTimeInterval = 0.0
var useTimingFunction: Bool = true
var animationGroup: CAAnimationGroup = CAAnimationGroup()
var repetitions: Float = Float.infinity
// Need to implement that, because otherwise it can't find
// the constructor init(layer:AnyObject!)
// Doesn't seem to look in the super class
override init!(layer: AnyObject!) {
super.init(layer: layer)
}
init(repeatCount: Float=Float.infinity, radius: CGFloat, position: CGPoint) {
super.init()
self.contentsScale = UIScreen.mainScreen().scale
self.opacity = 0.0
self.backgroundColor = UIColor.whiteColor().CGColor
self.radius = radius;
self.repetitions = repeatCount;
self.position = position
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
self.setupAnimationGroup()
self.setPulseRadius(self.radius)
if (self.pulseInterval != Double.infinity) {
dispatch_async(dispatch_get_main_queue(), {
self.addAnimation(self.animationGroup, forKey: "pulse")
})
}
})}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setPulseRadius(radius: CGFloat) {
self.radius = radius
var tempPos = self.position
var diameter = self.radius * 2
self.bounds = CGRect(x: 0.0, y: 0.0, width: diameter, height: diameter)
self.cornerRadius = self.radius
self.position = tempPos
}
func setupAnimationGroup() {
self.animationGroup = CAAnimationGroup()
self.animationGroup.duration = self.animationDuration + self.pulseInterval
self.animationGroup.repeatCount = self.repetitions
self.animationGroup.removedOnCompletion = false
if self.useTimingFunction {
var defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
self.animationGroup.timingFunction = defaultCurve
}
self.animationGroup.animations = [createScaleAnimation(), createOpacityAnimation()]
}
func createScaleAnimation() -> CABasicAnimation {
var scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
scaleAnimation.fromValue = NSNumber(float: self.fromValueForRadius)
scaleAnimation.toValue = NSNumber(float: 1.0)
scaleAnimation.duration = self.animationDuration
return scaleAnimation
}
func createOpacityAnimation() -> CAKeyframeAnimation {
var opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.duration = self.animationDuration
opacityAnimation.values = [self.fromValueForAlpha, 0.8, 0]
opacityAnimation.keyTimes = [0, self.keyTimeForHalfOpacity, 1]
opacityAnimation.removedOnCompletion = false
return opacityAnimation
}
} | mit | 8ad81a8f7c80b6444aacd2b8a1cc3cd7 | 35.525253 | 100 | 0.647026 | 4.885135 | false | false | false | false |
getSenic/nuimo-swift-demo-osx | Pods/NuimoSwift/SDK/BLEDiscoveryManager.swift | 1 | 8426 | //
// BLEDiscoveryManager.swift
// Nuimo
//
// Created by Lars Blumberg on 12/10/15.
// Copyright © 2015 Senic. All rights reserved.
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
import CoreBluetooth
/**
Allows for easy discovering bluetooth devices.
Automatically re-starts discovery if bluetooth was disabled for a previous discovery.
*/
public class BLEDiscoveryManager: NSObject {
public private(set) lazy var centralManager: CBCentralManager = self.discovery.centralManager
public weak var delegate: BLEDiscoveryManagerDelegate?
private let options: [String : AnyObject]
private lazy var discovery: BLEDiscoveryManagerPrivate = BLEDiscoveryManagerPrivate(discovery: self, options: self.options)
public init(delegate: BLEDiscoveryManagerDelegate? = nil, options: [String : AnyObject] = [:]) {
self.delegate = delegate
self.options = options
super.init()
}
/// If detectUnreachableDevices is set to true, it will invalidate devices if they stop advertising. Consumes more energy since `CBCentralManagerScanOptionAllowDuplicatesKey` is set to true.
public func startDiscovery(discoverServiceUUIDs: [CBUUID], detectUnreachableDevices: Bool = false) {
discovery.startDiscovery(discoverServiceUUIDs, detectUnreachableDevices: detectUnreachableDevices)
}
public func stopDiscovery() {
discovery.stopDiscovery()
}
internal func invalidateDevice(device: BLEDevice) {
discovery.invalidateDevice(device)
}
}
@objc public protocol BLEDiscoveryManagerDelegate: class {
func bleDiscoveryManager(discovery: BLEDiscoveryManager, deviceWithPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject]?) -> BLEDevice?
func bleDiscoveryManager(discovery: BLEDiscoveryManager, didDiscoverDevice device: BLEDevice)
func bleDiscoveryManager(discovery: BLEDiscoveryManager, didRestoreDevice device: BLEDevice)
optional func bleDiscoveryManagerDidStartDiscovery(discovery: BLEDiscoveryManager)
optional func bleDiscoveryManagerDidStopDiscovery(discovery: BLEDiscoveryManager)
}
/**
Private implementation of BLEDiscoveryManager.
Hides implementation of CBCentralManagerDelegate.
*/
private class BLEDiscoveryManagerPrivate: NSObject, CBCentralManagerDelegate {
let discovery: BLEDiscoveryManager
let options: [String : AnyObject]
lazy var centralManager: CBCentralManager = CBCentralManager(delegate: self, queue: nil, options: self.options)
var discoverServiceUUIDs = [CBUUID]()
var detectUnreachableDevices = false
var shouldStartDiscoveryWhenPowerStateTurnsOn = false
var deviceForPeripheral = [CBPeripheral : BLEDevice]()
var restoredConnectedPeripherals: [CBPeripheral]?
private var isScanning = false
init(discovery: BLEDiscoveryManager, options: [String : AnyObject]) {
self.discovery = discovery
self.options = options
super.init()
}
func startDiscovery(discoverServiceUUIDs: [CBUUID], detectUnreachableDevices: Bool) {
self.discoverServiceUUIDs = discoverServiceUUIDs
self.detectUnreachableDevices = detectUnreachableDevices
self.shouldStartDiscoveryWhenPowerStateTurnsOn = true
guard centralManager.state == .PoweredOn else { return }
startDiscovery()
}
private func startDiscovery() {
var options = self.options
options[CBCentralManagerScanOptionAllowDuplicatesKey] = detectUnreachableDevices
centralManager.scanForPeripheralsWithServices(discoverServiceUUIDs, options: options)
isScanning = true
discovery.delegate?.bleDiscoveryManagerDidStartDiscovery?(discovery)
}
func stopDiscovery() {
shouldStartDiscoveryWhenPowerStateTurnsOn = false
guard isScanning else { return }
centralManager.stopScan()
isScanning = false
discovery.delegate?.bleDiscoveryManagerDidStopDiscovery?(discovery)
}
func invalidateDevice(device: BLEDevice) {
device.invalidate()
// Remove all peripherals associated with controller (there should be only one)
deviceForPeripheral
.filter{ $0.1 == device }
.forEach { deviceForPeripheral.removeValueForKey($0.0) }
// Restart discovery if the device was connected before and if we are not receiving duplicate discovery events for the same peripheral – otherwise we wouldn't detect this invalidated peripheral when it comes back online. iOS and tvOS only report duplicate discovery events if the app is active (i.e. independently from the "allow duplicates" flag) – this said, we don't need to restart the discovery if the app is active and we're already getting duplicate discovery events for the same peripheral
#if os(iOS) || os(tvOS)
let appIsActive = UIApplication.sharedApplication().applicationState == .Active
#else
let appIsActive = true
#endif
if isScanning && device.didInitiateConnection && !(appIsActive && detectUnreachableDevices) { startDiscovery() }
}
@objc func centralManager(central: CBCentralManager, willRestoreState state: [String : AnyObject]) {
//TODO: Should work on OSX as well. http://stackoverflow.com/q/33210078/543875
#if os(iOS) || os(tvOS)
restoredConnectedPeripherals = (state[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral])?.filter{ $0.state == .Connected }
#endif
}
@objc func centralManagerDidUpdateState(central: CBCentralManager) {
switch central.state {
case .PoweredOn:
restoredConnectedPeripherals?.forEach{ centralManager(central, didRestorePeripheral: $0) }
restoredConnectedPeripherals = nil
// When bluetooth turned on and discovery start had already been triggered before, start discovery now
shouldStartDiscoveryWhenPowerStateTurnsOn
? startDiscovery()
: ()
default:
// Invalidate all connections as bluetooth state is .PoweredOff or below
deviceForPeripheral.values.forEach(invalidateDevice)
}
}
@objc func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
// Prevent devices from being discovered multiple times. iOS devices in peripheral role are also discovered multiple times.
var device: BLEDevice?
if let knownDevice = deviceForPeripheral[peripheral] {
if detectUnreachableDevices {
device = knownDevice
}
}
else if let discoveredDevice = discovery.delegate?.bleDiscoveryManager(discovery, deviceWithPeripheral: peripheral, advertisementData: advertisementData) {
deviceForPeripheral[peripheral] = discoveredDevice
discovery.delegate?.bleDiscoveryManager(discovery, didDiscoverDevice: discoveredDevice)
device = discoveredDevice
}
device?.didAdvertise(advertisementData, RSSI: RSSI, willReceiveSuccessiveAdvertisingData: detectUnreachableDevices)
}
func centralManager(central: CBCentralManager, didRestorePeripheral peripheral: CBPeripheral) {
guard let device = discovery.delegate?.bleDiscoveryManager(discovery, deviceWithPeripheral: peripheral, advertisementData: nil) else { return }
deviceForPeripheral[peripheral] = device
device.didRestore()
discovery.delegate?.bleDiscoveryManager(discovery, didRestoreDevice: device)
}
@objc func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
guard let device = self.deviceForPeripheral[peripheral] else { return }
device.didConnect()
}
@objc func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
guard let device = self.deviceForPeripheral[peripheral] else { return }
device.didFailToConnect(error)
}
@objc func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
guard let device = self.deviceForPeripheral[peripheral] else { return }
device.didDisconnect(error)
invalidateDevice(device)
}
}
| mit | dab134029b2d8799d3df678e63df8bc9 | 47.396552 | 505 | 0.731623 | 5.166258 | false | false | false | false |
fancymax/12306ForMac | 12306ForMac/Model/AutoSubmitParams.swift | 1 | 1544 | //
// autoSubmitParams.swift
// 12306ForMac
//
// Created by fancymax on 2016/12/13.
// Copyright © 2016年 fancy. All rights reserved.
//
import Foundation
struct AutoSubmitParams{
init(with ticket:QueryLeftNewDTO, purposeCode:String,passengerTicket:String,oldPassenger:String) {
secretStr = ticket.SecretStr!
train_date = ticket.trainDateStr
purpose_codes = purposeCode
query_from_station_name = ticket.FromStationName!
query_to_station_name = ticket.ToStationName!
passengerTicketStr = passengerTicket
oldPassengerStr = oldPassenger
}
var secretStr = ""
var train_date = ""
let tour_flag = "dc"
var purpose_codes = "ADULT"
var query_from_station_name = ""
var query_to_station_name = ""
let cancel_flag = "2"
let bed_level_order_num = "000000000000000000000000000000"
var passengerTicketStr = ""
var oldPassengerStr = ""
func ToPostParams()->[String:String]{
return [
"secretStr":secretStr,
"train_date":train_date,//2015-11-17
"tour_flag":tour_flag,
"purpose_codes":purpose_codes,
"query_from_station_name":query_from_station_name,
"query_to_station_name":query_to_station_name,
"cancel_flag":cancel_flag,
"bed_level_order_num":bed_level_order_num,
"passengerTicketStr":passengerTicketStr,
"oldPassengerStr":oldPassengerStr]
}
}
| mit | c3a2a3be822ef20451e47c45f249be97 | 26.517857 | 102 | 0.613238 | 3.891414 | false | false | false | false |
leleks/TextFieldEffects | TextFieldEffects/TextFieldEffects/IsaoTextField.swift | 1 | 5298 | //
// IsaoTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 29/01/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
@IBDesignable public class IsaoTextField: TextFieldEffects {
@IBInspectable public var inactiveColor: UIColor? {
didSet {
updateBorder()
}
}
@IBInspectable public var activeColor: UIColor? {
didSet {
updateBorder()
}
}
override public var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override public var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
private let borderThickness: (active: CGFloat, inactive: CGFloat) = (4, 2)
private let placeholderInsets = CGPoint(x: 6, y: 6)
private let textFieldInsets = CGPoint(x: 6, y: 6)
private let borderLayer = CALayer()
override func drawViewsForRect(rect: CGRect) {
let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font)
updateBorder()
updatePlaceholder()
layer.addSublayer(borderLayer)
addSubview(placeholderLabel)
delegate = self
}
private func updateBorder() {
borderLayer.frame = rectForBorder(frame)
borderLayer.backgroundColor = isFirstResponder() ? activeColor?.CGColor : inactiveColor?.CGColor
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = inactiveColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder() {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.7)
return smallerFont
}
private func rectForBorder(bounds: CGRect) -> CGRect {
var newRect:CGRect
if isFirstResponder() {
newRect = CGRect(x: 0, y: bounds.size.height - font.lineHeight + textFieldInsets.y - borderThickness.active, width: bounds.size.width, height: borderThickness.active)
} else {
newRect = CGRect(x: 0, y: bounds.size.height - font.lineHeight + textFieldInsets.y - borderThickness.inactive, width: bounds.size.width, height: borderThickness.inactive)
}
return newRect
}
private func layoutPlaceholderInTextRect() {
if !text.isEmpty {
return
}
let textRect = textRectForBounds(bounds)
var originX = textRect.origin.x
switch textAlignment {
case .Center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .Right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height,
width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height)
}
override func animateViewsForTextEntry() {
updateBorder()
if let activeColor = activeColor {
performPlacerholderAnimationWithColor(activeColor)
}
}
override func animateViewsForTextDisplay() {
updateBorder()
if let inactiveColor = inactiveColor {
performPlacerholderAnimationWithColor(inactiveColor)
}
}
private func performPlacerholderAnimationWithColor(color: UIColor) {
let yOffset:CGFloat = 4
UIView.animateWithDuration(0.15, animations: { () -> Void in
self.placeholderLabel.transform = CGAffineTransformMakeTranslation(0, -yOffset)
self.placeholderLabel.alpha = 0
}) { (completed) -> Void in
self.placeholderLabel.transform = CGAffineTransformIdentity
self.placeholderLabel.transform = CGAffineTransformMakeTranslation(0, yOffset)
UIView.animateWithDuration(0.15, animations: {
self.placeholderLabel.textColor = color
self.placeholderLabel.transform = CGAffineTransformIdentity
self.placeholderLabel.alpha = 1
})
}
}
// MARK: - Overrides
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
}
| mit | 37406da2255615cc593ff85e571e6c40 | 32.738854 | 182 | 0.617897 | 5.38313 | false | false | false | false |
suragch/MongolAppDevelopment-iOS | Mongol App ComponantsTests/MongolUnicodeRendererTests.swift | 1 | 19699 |
import XCTest
@testable import Mongol_App_Componants
class MongolUnicodeRendererTests: XCTestCase {
func testUnicodeToGlyphs_emptyString_returnEmptyString() {
// Arrange
let unicode = ""
let expected = ""
let renderer = MongolUnicodeRenderer()
// Act
let result = renderer.unicodeToGlyphs(unicode)
// Assert
XCTAssertEqual(result, expected)
}
func testUnicodeToGlyphs_nonMongolString_returnSame() {
// Arrange
let unicode = "abc"
let expected = unicode
let renderer = MongolUnicodeRenderer()
// Act
let result = renderer.unicodeToGlyphs(unicode)
// Assert
XCTAssertEqual(result, expected)
}
func testUnicodeToGlyphs_IsolateI_returnGlyph() {
// Arrange
let unicode = "ᠢ"
let expected = ""
let renderer = MongolUnicodeRenderer()
// Act
let result = renderer.unicodeToGlyphs(unicode)
// Assert
XCTAssertEqual(result, expected)
}
func testUnicodeToGlyphs_InitialMedialFinalNom_returnGlyph() {
// Arrange
let unicode = "ᠨᠣᠮ"
let expected = ""
let renderer = MongolUnicodeRenderer()
// Act
let result = renderer.unicodeToGlyphs(unicode)
// Assert
XCTAssertEqual(result, expected)
}
func testUnicodeToGlyphs_MVS_returnGlyphs() {
// Arrange
let baina = "ᠪᠠᠢᠨᠠ"
let minggan = "ᠮᠢᠩᠭᠡᠨ"
let na = "ᠨᠡ"
let ngqa = "ᠩᠬᠡ"
let ngga = "ᠩᠭᠡ"
let qa = "ᠬᠡ"
let ga = "ᠭᠡ"
let ma = "ᠮᠡ"
let la = "ᠯᠡ"
let ya = "ᠶᠡ" // y
let wa = "ᠸᠡ"
let ia = "ᠢᠡ" // i
let ra = "ᠷᠡ"
let bainaExpected = ""
let mingganExpected = ""
let naExpected = ""
let ngqaExpected = ""
let nggaExpected = ""
let qaExpected = ""
let gaExpected = ""
let maExpected = ""
let laExpected = ""
let yaExpected = "" // y
let waExpected = ""
let iaExpected = "" // i
let raExpected = ""
let renderer = MongolUnicodeRenderer()
// Assert
XCTAssertEqual(renderer.unicodeToGlyphs(baina), bainaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(minggan), mingganExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(na), naExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(ngqa), ngqaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(ngga), nggaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(qa), qaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(ga), gaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(ma), maExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(la), laExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(ya), yaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(wa), waExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(ia), iaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(ra), raExpected)
}
// TODO: make more tests
func testUnicodeToGlyphs_YiRuleNamayi_returnGlyphs() {
// Arrange
let unicode = "ᠨᠠᠮᠠᠶᠢ"
let expected = ""
let renderer = MongolUnicodeRenderer()
// Act
let result = renderer.unicodeToGlyphs(unicode)
// Assert
XCTAssertEqual(result, expected)
// show
print("Unicode: \(unicode), Rendered: \(result)")
}
// Words from "A Study of Traditional Mongolian Script Encodings and Rendering"
func testUnicodeToGlyphs_wordList1_returnGlyphs() {
// Arrange
let biqig = "ᠪᠢᠴᠢᠭ"
let egshig_inu = "ᠡᠭᠡᠰᠢᠭ ᠢᠨᠦ"
let bujig_i_ben_yugen = "ᠪᠦᠵᠢᠭ ᠢ ᠪᠡᠨ ᠶᠦᠭᠡᠨ"
let chirig_mini = "ᠴᠢᠷᠢᠭ ᠮᠠᠨᠢ"
let egche = "ᠡᠭᠴᠡ"
let hugjim_dur_iyen_degen = "ᠬᠦᠭᠵᠢᠮ ᠳᠦᠷ ᠢᠶᠡᠨ ᠳᠡᠭᠡᠨ"
let buridgel_iyen = "ᠪᠦᠷᠢᠳᠭᠡᠯ ᠢᠶᠡᠨ"
let sedgil_mini = "ᠰᠡᠳᠬᠢᠯ ᠮᠢᠨᠢ"
let uiledburi_du = "ᠦᠢᠯᠠᠳᠪᠦᠷᠢ ᠳᠦ"
let jeligudgen_u = "ᠵᠡᠯᠢᠭᠦᠳᠭᠡᠨ ᠦ"
let manggal_dur_iyen_dagan = "ᠮᠠᠩᠭᠠᠯ ᠳᠤᠷ ᠢᠶᠠᠨ ᠳᠠᠭᠠᠨ"
let dung_i = "ᠳ᠋ᠦᠩ ᠢ"
let sodnam_acha_ban_achagan = "ᠰᠣᠳᠨᠠᠮ ᠠᠴᠠ ᠪᠠᠨ ᠠᠴᠠᠭᠠᠨ"
let lhagba_luga = "ᡀᠠᠭᠪᠠ ᠯᠤᠭᠠ"
let cement_tayigan = "ᠼᠧᠮᠧᠨ᠋ᠲ ᠲᠠᠶᠢᠭᠠᠨ" // should't have FVS1 according to Unicode 8.0 draft
let chebegmed_luge = "ᠴᠡᠪᠡᠭᠮᠡᠳ ᠯᠦᠭᠡ"
let uniye_teyigen = "ᠦᠨᠢᠶᠡ ᠲᠡᠶᠢᠭᠡᠨ"
let hoyina = "ᠬᠣᠶᠢᠨᠠ"
let angna = "ᠠᠩᠨᠠ" // missing gliph in font
let biqigExpected = ""
let egshig_inuExpected = " "
let bujig_i_ben_yugenExpected = " "
let chirig_miniExpected = " "
let egcheExpected = ""
let hugjim_dur_iyen_degenExpected = " "
let buridgel_iyenExpected = " "
let sedgil_miniExpected = " "
let uiledburi_duExpected = " "
let jeligudgen_uExpected = " "
let manggal_dur_iyen_daganExpected = " "
let dung_iExpected = " "
let sodnam_acha_ban_achaganExpected = " "
let lhagba_lugaExpected = " "
let cement_tayiganExpected = " "
let chebegmed_lugeExpected = " "
let uniye_teyigenExpected = " "
let hoyinaExpected = ""
let angnaExpected = ""
let renderer = MongolUnicodeRenderer()
// Assert
XCTAssertEqual(renderer.unicodeToGlyphs(biqig), biqigExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(egshig_inu), egshig_inuExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(bujig_i_ben_yugen), bujig_i_ben_yugenExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(chirig_mini), chirig_miniExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(egche), egcheExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(hugjim_dur_iyen_degen), hugjim_dur_iyen_degenExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(buridgel_iyen), buridgel_iyenExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(sedgil_mini), sedgil_miniExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(uiledburi_du), uiledburi_duExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(jeligudgen_u), jeligudgen_uExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(manggal_dur_iyen_dagan), manggal_dur_iyen_daganExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(dung_i), dung_iExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(sodnam_acha_ban_achagan), sodnam_acha_ban_achaganExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(lhagba_luga), lhagba_lugaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(cement_tayigan), cement_tayiganExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(chebegmed_luge), chebegmed_lugeExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(uniye_teyigen), uniye_teyigenExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(hoyina), hoyinaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(angna), angnaExpected)
// show
print("Unicode: \(biqig), Rendered: \(renderer.unicodeToGlyphs(biqig))")
print("Unicode: \(egshig_inu), Rendered: \(renderer.unicodeToGlyphs(egshig_inu))")
print("Unicode: \(bujig_i_ben_yugen), Rendered: \(renderer.unicodeToGlyphs(bujig_i_ben_yugen))")
print("Unicode: \(chirig_mini), Rendered: \(renderer.unicodeToGlyphs(chirig_mini))")
print("Unicode: \(egche), Rendered: \(renderer.unicodeToGlyphs(egche))")
print("Unicode: \(hugjim_dur_iyen_degen), Rendered: \(renderer.unicodeToGlyphs(hugjim_dur_iyen_degen))")
print("Unicode: \(buridgel_iyen), Rendered: \(renderer.unicodeToGlyphs(buridgel_iyen))")
print("Unicode: \(sedgil_mini), Rendered: \(renderer.unicodeToGlyphs(sedgil_mini))")
print("Unicode: \(uiledburi_du), Rendered: \(renderer.unicodeToGlyphs(uiledburi_du))")
print("Unicode: \(jeligudgen_u), Rendered: \(renderer.unicodeToGlyphs(jeligudgen_u))")
print("Unicode: \(manggal_dur_iyen_dagan), Rendered: \(renderer.unicodeToGlyphs(manggal_dur_iyen_dagan))")
print("Unicode: \(dung_i), Rendered: \(renderer.unicodeToGlyphs(dung_i))")
print("Unicode: \(sodnam_acha_ban_achagan), Rendered: \(renderer.unicodeToGlyphs(sodnam_acha_ban_achagan))")
print("Unicode: \(lhagba_luga), Rendered: \(renderer.unicodeToGlyphs(lhagba_luga))")
print("Unicode: \(cement_tayigan), Rendered: \(renderer.unicodeToGlyphs(cement_tayigan))")
print("Unicode: \(chebegmed_luge), Rendered: \(renderer.unicodeToGlyphs(chebegmed_luge))")
print("Unicode: \(uniye_teyigen), Rendered: \(renderer.unicodeToGlyphs(uniye_teyigen))")
print("Unicode: \(hoyina), Rendered: \(renderer.unicodeToGlyphs(hoyina))")
print("Unicode: \(angna), Rendered: \(renderer.unicodeToGlyphs(angna))")
}
// Additional words
func testUnicodeToGlyphs_wordList2_returnGlyphs() {
// TODO: sort these out into different tests based on rules
// Arrange
let chingalahu = "ᠴᠢᠩᠭᠠᠯᠠᠬᠤ"
let taljiyagsan = "ᠳᠠᠯᠵᠢᠶᠭᠰᠠᠨ"
let ilbigchi = "ᠢᠯᠪᠢᠭᠴᠢ"
let bichigchi = "ᠪᠢᠴᠢᠭᠴᠢ"
let shigshiglehu = "ᠰᠢᠭᠰᠢᠭᠯᠡᠬᠦ"
let tiglimsigsen = "ᠳᠢᠭᠯᠢᠮᠰᠢᠭᠰᠡᠨ"
let chigiglig = "ᠴᠢᠭᠢᠭᠯᠢᠭ"
let gram = "ᠭᠷᠠᠮ" // g+non-vowel words
let mingga = "ᠮᠢᠩᠭᠠ"
let minggan = "ᠮᠢᠩᠭᠠᠨ"
let naima = "ᠨᠠᠢ᠌ᠮᠠ"
let baina = "ᠪᠠᠢᠨᠠ"
let bayina = "ᠪᠠᠶᠢᠨᠠ"
let buu = "ᠪᠦᠦ"
let huu = "ᠬᠦᠦ"
let heuhed = "ᠬᠡᠦᠬᠡᠳ"
let angli = "ᠠᠩᠭᠯᠢ"
let soyol = "ᠰᠤᠶᠤᠯ"
let saihan = "ᠰᠠᠢᠬᠠᠨ" // beautiful
let sayihan = "ᠰᠠᠶ᠋ᠢᠬᠠᠨ" // recently
let sayi = "ᠰᠠᠶᠢ" // old form - straight Y
let sayiHooked = "ᠰᠠᠶ᠋ᠢ" // hooked y
let naranGerel = "ᠨᠠᠷᠠᠨᠭᠡᠷᠡᠯ"
let cholmonOdo = "ᠴᠣᠯᠮᠣᠨ᠍ᠣ᠋ᠳᠣ"
//let sodoBilig = "ᠰᠣᠳᠣᠪᠢᠯᠢᠭ" // TODO: final g unspecified
let sodoBilig2 = "ᠰᠣᠳᠣᠪᠢᠯᠢᠭ᠌" // final g is specified
let erdeniTana = "ᠡᠷᠳᠡᠨᠢᠲ᠋ᠠᠨᠠ" // two-part name, with second medial TA form
let engheBold = "ᠡᠩᠬᠡᠪᠣᠯᠣᠳ"
let bayanUnder = "ᠪᠠᠶᠠᠨ᠍ᠦ᠌ᠨᠳᠦᠷ"
let biburie = "ᠪᠢᠪᠦᠷᠢᠡ" // i-e as an alternate to y-e
let asiglaju = "ᠠᠰᠢᠭᠯᠠᠵᠤ" // ig
let eimu = "ᠡᠢᠮᠣ"
let namayi = "ᠨᠠᠮᠠᠶᠢ"
let heduin = "ᠬᠡᠳᠦᠢᠨ"
let chingalahuExpected = ""
let taljiyagsanExpected = ""
let ilbigchiExpected = ""
let bichigchiExpected = ""
let shigshiglehuExpected = ""
let tiglimsigsenExpected = ""
let chigigligExpected = ""
let gramExpected = ""
let minggaExpected = ""
let mingganExpected = ""
let naimaExpected = ""
let bainaExpected = ""
let bayinaExpected = ""
let buuExpected = ""
let huuExpected = ""
let heuhedExpected = ""
let angliExpected = ""
let soyolExpected = ""
let saihanExpected = ""
let sayihanExpected = ""
let sayiExpected = ""
let sayiHookedExpected = ""
let naranGerelExpected = ""
let cholmonOdoExpected = ""
//let sodoBiligExpected = ""
let sodoBilig2Expected = ""
let erdeniTanaExpected = ""
let engheBoldExpected = ""
let bayanUnderExpected = ""
let biburieExpected = ""
let asiglajuExpected = ""
let eimuExpected = ""
let namayiExpected = ""
let heduinExpected = ""
let renderer = MongolUnicodeRenderer()
// Assert
XCTAssertEqual(renderer.unicodeToGlyphs(chingalahu), chingalahuExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(taljiyagsan), taljiyagsanExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(ilbigchi), ilbigchiExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(bichigchi), bichigchiExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(shigshiglehu), shigshiglehuExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(tiglimsigsen), tiglimsigsenExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(chigiglig), chigigligExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(gram), gramExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(mingga), minggaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(minggan), mingganExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(naima), naimaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(baina), bainaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(bayina), bayinaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(buu), buuExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(huu), huuExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(heuhed), heuhedExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(angli), angliExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(soyol), soyolExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(saihan), saihanExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(sayihan), sayihanExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(sayi), sayiExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(sayiHooked), sayiHookedExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(naranGerel), naranGerelExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(cholmonOdo), cholmonOdoExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(sodoBilig2), sodoBilig2Expected)
XCTAssertEqual(renderer.unicodeToGlyphs(erdeniTana), erdeniTanaExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(engheBold), engheBoldExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(bayanUnder), bayanUnderExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(biburie), biburieExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(asiglaju), asiglajuExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(eimu), eimuExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(namayi), namayiExpected)
XCTAssertEqual(renderer.unicodeToGlyphs(heduin), heduinExpected)
// show
print("Unicode: \(chingalahu), Rendered: \(renderer.unicodeToGlyphs(chingalahu))")
print("Unicode: \(taljiyagsan), Rendered: \(renderer.unicodeToGlyphs(taljiyagsan))")
print("Unicode: \(ilbigchi), Rendered: \(renderer.unicodeToGlyphs(ilbigchi))")
print("Unicode: \(bichigchi), Rendered: \(renderer.unicodeToGlyphs(bichigchi))")
print("Unicode: \(shigshiglehu), Rendered: \(renderer.unicodeToGlyphs(shigshiglehu))")
print("Unicode: \(tiglimsigsen), Rendered: \(renderer.unicodeToGlyphs(tiglimsigsen))")
print("Unicode: \(chigiglig), Rendered: \(renderer.unicodeToGlyphs(chigiglig))")
print("Unicode: \(gram), Rendered: \(renderer.unicodeToGlyphs(gram))")
print("Unicode: \(mingga), Rendered: \(renderer.unicodeToGlyphs(mingga))")
print("Unicode: \(minggan), Rendered: \(renderer.unicodeToGlyphs(minggan))")
print("Unicode: \(naima), Rendered: \(renderer.unicodeToGlyphs(naima))")
print("Unicode: \(baina), Rendered: \(renderer.unicodeToGlyphs(baina))")
print("Unicode: \(bayina), Rendered: \(renderer.unicodeToGlyphs(bayina))")
print("Unicode: \(buu), Rendered: \(renderer.unicodeToGlyphs(buu))")
print("Unicode: \(huu), Rendered: \(renderer.unicodeToGlyphs(huu))")
print("Unicode: \(heuhed), Rendered: \(renderer.unicodeToGlyphs(heuhed))")
print("Unicode: \(angli), Rendered: \(renderer.unicodeToGlyphs(angli))")
print("Unicode: \(soyol), Rendered: \(renderer.unicodeToGlyphs(soyol))")
print("Unicode: \(saihan), Rendered: \(renderer.unicodeToGlyphs(saihan))")
print("Unicode: \(sayihan), Rendered: \(renderer.unicodeToGlyphs(sayihan))")
print("Unicode: \(sayi), Rendered: \(renderer.unicodeToGlyphs(sayi))")
print("Unicode: \(sayiHooked), Rendered: \(renderer.unicodeToGlyphs(sayiHooked))")
print("Unicode: \(naranGerel), Rendered: \(renderer.unicodeToGlyphs(naranGerel))")
print("Unicode: \(cholmonOdo), Rendered: \(renderer.unicodeToGlyphs(cholmonOdo))")
//print("Unicode: \(sodoBilig), Rendered: \(renderer.unicodeToGlyphs(sodoBilig))")
print("Unicode: \(sodoBilig2), Rendered: \(renderer.unicodeToGlyphs(sodoBilig2))")
print("Unicode: \(erdeniTana), Rendered: \(renderer.unicodeToGlyphs(erdeniTana))")
print("Unicode: \(engheBold), Rendered: \(renderer.unicodeToGlyphs(engheBold))")
print("Unicode: \(bayanUnder), Rendered: \(renderer.unicodeToGlyphs(bayanUnder))")
print("Unicode: \(biburie), Rendered: \(renderer.unicodeToGlyphs(biburie))")
print("Unicode: \(asiglaju), Rendered: \(renderer.unicodeToGlyphs(asiglaju))")
print("Unicode: \(eimu), Rendered: \(renderer.unicodeToGlyphs(eimu))")
print("Unicode: \(namayi), Rendered: \(renderer.unicodeToGlyphs(namayi))")
print("Unicode: \(heduin), Rendered: \(renderer.unicodeToGlyphs(heduin))")
}
}
| mit | a146f435ecde26ea5d421d6672b96310 | 46.647849 | 116 | 0.630465 | 2.43375 | false | false | false | false |
velvetroom/columbus | Source/View/CreateSave/VCreateSaveStatusError+Factory.swift | 1 | 6286 | import UIKit
extension VCreateSaveStatusError
{
//MARK: private
private func factoryTitle() -> NSAttributedString
{
let attributes:[NSAttributedStringKey:Any] = [
NSAttributedStringKey.font : UIFont.medium(size:VCreateSaveStatusError.Constants.titleFontSize),
NSAttributedStringKey.foregroundColor : UIColor.white]
let string:String = String.localizedView(key:"VCreateSaveStatusError_labelTitle")
let attributedString:NSAttributedString = NSAttributedString(
string:string,
attributes:attributes)
return attributedString
}
private func factoryDescr() -> NSAttributedString
{
let attributes:[NSAttributedStringKey:Any] = [
NSAttributedStringKey.font : UIFont.regular(size:VCreateSaveStatusError.Constants.descrFontSize),
NSAttributedStringKey.foregroundColor : UIColor(white:1, alpha:0.8)]
let string:String = String.localizedView(key:"VCreateSaveStatusError_labelDescr")
let attributedString:NSAttributedString = NSAttributedString(
string:string,
attributes:attributes)
return attributedString
}
private func factoryInfo() -> NSAttributedString
{
let title:NSAttributedString = factoryTitle()
let descr:NSAttributedString = factoryDescr()
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(title)
mutableString.append(descr)
return mutableString
}
//MARK: internal
func factoryViews()
{
let info:NSAttributedString = factoryInfo()
let colourTop:UIColor = UIColor(
red:1,
green:0.4352941176470589,
blue:0.5686274509803924,
alpha:1)
let viewGradient:VGradient = VGradient.vertical(
colourTop:colourTop,
colourBottom:UIColor.colourFail)
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.center
label.numberOfLines = 0
label.attributedText = info
let buttonCancel:UIButton = UIButton()
buttonCancel.translatesAutoresizingMaskIntoConstraints = false
buttonCancel.setTitleColor(
UIColor(white:1, alpha:0.9),
for:UIControlState.normal)
buttonCancel.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
buttonCancel.setTitle(
String.localizedView(key:"VCreateSaveStatusError_buttonCancel"),
for:UIControlState.normal)
buttonCancel.titleLabel!.font = UIFont.regular(
size:VCreateSaveStatusError.Constants.cancelFontSize)
buttonCancel.addTarget(
self,
action:#selector(selectorCancel(sender:)),
for:UIControlEvents.touchUpInside)
let buttonRetry:UIButton = UIButton()
buttonRetry.translatesAutoresizingMaskIntoConstraints = false
buttonRetry.setTitleColor(
UIColor.white,
for:UIControlState.normal)
buttonRetry.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
buttonRetry.setTitle(
String.localizedView(key:"VCreateSaveStatusError_buttonRetry"),
for:UIControlState.normal)
buttonRetry.titleLabel!.font = UIFont.bold(
size:VCreateSaveStatusError.Constants.retryFontSize)
buttonRetry.addTarget(
self,
action:#selector(selectorRetry(sender:)),
for:UIControlEvents.touchUpInside)
let image:UIImageView = UIImageView()
image.isUserInteractionEnabled = false
image.translatesAutoresizingMaskIntoConstraints = false
image.clipsToBounds = true
image.contentMode = UIViewContentMode.center
image.image = #imageLiteral(resourceName: "assetGenericError").withRenderingMode(UIImageRenderingMode.alwaysTemplate)
image.tintColor = UIColor.white
addSubview(viewGradient)
addSubview(label)
addSubview(buttonCancel)
addSubview(buttonRetry)
addSubview(image)
NSLayoutConstraint.equals(
view:viewGradient,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:label,
toView:self,
constant:VCreateSaveStatusError.Constants.labelBottom)
NSLayoutConstraint.height(
view:label,
constant:VCreateSaveStatusError.Constants.labelHeight)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self)
NSLayoutConstraint.topToBottom(
view:buttonCancel,
toView:buttonRetry)
NSLayoutConstraint.height(
view:buttonCancel,
constant:VCreateSaveStatusError.Constants.buttonHeight)
layoutCancelLeft = NSLayoutConstraint.leftToLeft(
view:buttonCancel,
toView:self)
NSLayoutConstraint.width(
view:buttonCancel,
constant:VCreateSaveStatusError.Constants.buttonWidth)
NSLayoutConstraint.topToBottom(
view:buttonRetry,
toView:label)
NSLayoutConstraint.height(
view:buttonRetry,
constant:VCreateSaveStatusError.Constants.buttonHeight)
layoutRetryLeft = NSLayoutConstraint.leftToLeft(
view:buttonRetry,
toView:self)
NSLayoutConstraint.width(
view:buttonRetry,
constant:VCreateSaveStatusError.Constants.buttonWidth)
NSLayoutConstraint.bottomToTop(
view:image,
toView:label)
NSLayoutConstraint.height(
view:image,
constant:VCreateSaveStatusError.Constants.imageHeight)
NSLayoutConstraint.equalsHorizontal(
view:image,
toView:self)
}
}
| mit | 0e9ec0c9600c0531937f337c1eb25b9a | 35.126437 | 125 | 0.639039 | 5.858341 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Managers/DatabaseManager.swift | 1 | 6271 | //
// DatabaseManager.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 01/09/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
import Realm
/**
This keys are used to store all servers and
database information to each server user is
connected to.
*/
struct ServerPersistKeys {
// Server controls
static let servers = "kServers"
static let selectedIndex = "kSelectedIndex"
// Database
static let databaseName = "kDatabaseName"
// Authentication information
static let token = "kAuthToken"
static let serverURL = "kAuthServerURL"
static let serverVersion = "kAuthServerVersion"
static let userId = "kUserId"
// Display information
static let serverIconURL = "kServerIconURL"
static let serverName = "kServerName"
// Two-way SSL certificate & password
static let sslClientCertificatePath = "kSSLClientCertificatePath"
static let sslClientCertificatePassword = "kSSLClientCertificatePassword"
}
struct DatabaseManager {
/**
- returns: The selected database index.
*/
static var selectedIndex: Int {
return UserDefaults.group.value(forKey: ServerPersistKeys.selectedIndex) as? Int ?? 0
}
/**
- returns: All servers stored locally into the app.
*/
static var servers: [[String: String]]? {
return UserDefaults.group.value(forKey: ServerPersistKeys.servers) as? [[String: String]]
}
/**
- parameter index: The database index user wants to select.
*/
static func selectDatabase(at index: Int) {
UserDefaults.group.set(index, forKey: ServerPersistKeys.selectedIndex)
}
/**
- parameter index: The database index that needs to be updated.
*/
static func updateSSLClientInformation(for index: Int, path: URL, password: String) {
guard
var servers = self.servers,
servers.count > index
else {
return
}
// Update SSL Client Certificate information
var server = servers[index]
server[ServerPersistKeys.sslClientCertificatePath] = path.absoluteString
server[ServerPersistKeys.sslClientCertificatePassword] = password
servers[index] = server
UserDefaults.group.set(servers, forKey: ServerPersistKeys.servers)
}
/**
Remove selected server and select the
first one.
*/
static func removeSelectedDatabase() {
removeDatabase(at: selectedIndex)
selectDatabase(at: 0)
}
/**
Removes server information at some index.
parameter index: The database index user wants to delete.
*/
static func removeDatabase(at index: Int) {
if var servers = self.servers, servers.count > index {
servers.remove(at: index)
UserDefaults.group.set(servers, forKey: ServerPersistKeys.servers)
}
}
/**
This method cleans the servers that doesn't have
authentication information.
*/
static func cleanInvalidDatabases() {
let servers = self.servers ?? []
var validServers: [[String: String]] = []
for (index, server) in servers.enumerated() {
guard
server[ServerPersistKeys.token] != nil,
server[ServerPersistKeys.userId] != nil,
server[ServerPersistKeys.databaseName] != nil,
server[ServerPersistKeys.serverURL] != nil,
let realmConfiguration = databaseConfiguration(index: index),
(try? Realm(configuration: realmConfiguration)) != nil
else {
continue
}
validServers.append(server)
}
if selectedIndex > validServers.count - 1 {
selectDatabase(at: 0)
}
UserDefaults.group.set(validServers, forKey: ServerPersistKeys.servers)
}
/**
This method will create a new database before user
even authenticated into the server. This is used
so we can populate the authentication information
when user logins.
- parameter serverURL: The server URL.
*/
@discardableResult
static func createNewDatabaseInstance(serverURL: String) -> Int {
let defaults = UserDefaults.group
var servers = self.servers ?? []
servers.append([
ServerPersistKeys.databaseName: "\(String.random()).realm",
ServerPersistKeys.serverURL: serverURL
])
let index = servers.count - 1
defaults.set(servers, forKey: ServerPersistKeys.servers)
defaults.set(index, forKey: ServerPersistKeys.selectedIndex)
return index
}
/**
This method gets the realm associated with this server
*/
static func databaseInstace(index: Int) -> Realm? {
guard let configuration = databaseConfiguration(index: index) else { return nil }
return try? Realm(configuration: configuration)
}
/**
This method returns the realm configuration associated with this server
*/
static func databaseConfiguration(index: Int? = nil) -> Realm.Configuration? {
guard
let server = AuthManager.selectedServerInformation(index: index),
let databaseName = server[ServerPersistKeys.databaseName],
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppGroup.identifier)
else {
return nil
}
#if DEBUG
Log.debug("Realm path: \(url.appendingPathComponent(databaseName))")
#endif
return Realm.Configuration(
fileURL: url.appendingPathComponent(databaseName),
deleteRealmIfMigrationNeeded: true
)
}
}
extension DatabaseManager {
/**
This method returns an index for the server with this URL if it already exists.
- parameter serverUrl: The URL of the server
*/
static func serverIndexForUrl(_ serverUrl: URL) -> Int? {
return servers?.index {
guard let url = URL(string: $0[ServerPersistKeys.serverURL] ?? "") else {
return false
}
return url.host == serverUrl.host
}
}
}
| mit | 15b4ff46a7a97a85bae919ec74451760 | 29.735294 | 114 | 0.63748 | 4.960443 | false | true | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClientUnitTests/Spec/User/NewCreatorRequestSpec.swift | 1 | 2834 | //
// NewCreatorRequestSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Quick
import Nimble
@testable import CreatubblesAPIClient
class NewCreatorRequestSpec: QuickSpec {
override func spec() {
describe("New creator request") {
let name = "TestCreatorName"
let displayName = "TestCreatorDisplayName"
let birthYear = 2_000
let birthMonth = 10
let countryCode = "PL"
let gender = Gender.male
var creatorRequest: NewCreatorRequest {
return NewCreatorRequest(name: name, displayName: displayName,
birthYear: birthYear, birthMonth: birthMonth,
countryCode: countryCode, gender: gender)
}
it("Should have proper endpoint") {
let request = creatorRequest
expect(request.endpoint) == "creators"
}
it("Should have proper method") {
let request = creatorRequest
expect(request.method) == RequestMethod.post
}
it("Should have proper parameters") {
let request = creatorRequest
let params = request.parameters
expect(params["name"] as? String) == name
expect(params["display_name"] as? String) == displayName
expect(params["birth_year"] as? Int) == birthYear
expect(params["birth_month"] as? Int) == birthMonth
expect(params["country"] as? String) == countryCode
expect(params["gender"] as? Int) == gender.rawValue
}
}
}
}
| mit | 5c21affe8772b2d4b4b23c5ff246b66c | 41.298507 | 86 | 0.627029 | 4.945899 | false | false | false | false |
emilstahl/swift | stdlib/public/core/ArrayBuffer.swift | 9 | 16801 | //===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
//
// This is the class that implements the storage and object management for
// Swift Array.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
internal typealias _ArrayBridgeStorage
= _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCoreType>
public struct _ArrayBuffer<Element> : _ArrayBufferType {
/// Create an empty buffer.
public init() {
_storage = _ArrayBridgeStorage(native: _emptyArrayStorage)
}
public init(nsArray: _NSArrayCoreType) {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_storage = _ArrayBridgeStorage(objC: nsArray)
}
/// Returns an `_ArrayBuffer<U>` containing the same elements.
///
/// - Requires: The elements actually have dynamic type `U`, and `U`
/// is a class or `@objc` existential.
@warn_unused_result
func castToBufferOf<U>(_: U.Type) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
return _ArrayBuffer<U>(storage: _storage)
}
/// The spare bits that are set when a native array needs deferred
/// element type checking.
var deferredTypeCheckMask : Int { return 1 }
/// Returns an `_ArrayBuffer<U>` containing the same elements,
/// deffering checking each element's `U`-ness until it is accessed.
///
/// - Requires: `U` is a class or `@objc` existential derived from `Element`.
@warn_unused_result
func downcastToBufferWithDeferredTypeCheckOf<U>(
_: U.Type
) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
// FIXME: can't check that U is derived from Element pending
// <rdar://problem/19915280> generic metatype casting doesn't work
// _sanityCheck(U.self is Element.Type)
return _ArrayBuffer<U>(
storage: _ArrayBridgeStorage(
native: _native._storage, bits: deferredTypeCheckMask))
}
var needsElementTypeCheck: Bool {
// NSArray's need an element typecheck when the element type isn't AnyObject
return !_isNativeTypeChecked && !(AnyObject.self is Element.Type)
}
//===--- private --------------------------------------------------------===//
internal init(storage: _ArrayBridgeStorage) {
_storage = storage
}
internal var _storage: _ArrayBridgeStorage
}
extension _ArrayBuffer {
/// Adopt the storage of `source`.
public init(_ source: NativeBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
_storage = _ArrayBridgeStorage(native: source._storage)
}
var arrayPropertyIsNative : Bool {
return _isNative
}
/// `true`, if the array is native and does not need a deferred type check.
var arrayPropertyIsNativeTypeChecked : Bool {
return _isNativeTypeChecked
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
@warn_unused_result
mutating func isUniquelyReferenced() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferenced_native_noSpareBits()
}
return _storage.isUniquelyReferencedNative() && _isNative
}
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned.
@warn_unused_result
mutating func isUniquelyReferencedOrPinned() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferencedOrPinned_native_noSpareBits()
}
return _storage.isUniquelyReferencedOrPinnedNative() && _isNative
}
/// Convert to an NSArray.
///
/// - Precondition: `_isBridgedToObjectiveC(Element.self)`.
/// O(1) if the element type is bridged verbatim, O(N) otherwise.
@warn_unused_result
public func _asCocoaArray() -> _NSArrayCoreType {
_sanityCheck(
_isBridgedToObjectiveC(Element.self),
"Array element type is not bridged to Objective-C")
return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative
}
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the self
/// buffer store minimumCapacity elements, returns that buffer.
/// Otherwise, returns `nil`.
@warn_unused_result
public mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int)
-> NativeBuffer?
{
if _fastPath(isUniquelyReferenced()) {
let b = _native
if _fastPath(b.capacity >= minimumCapacity) {
return b
}
}
return nil
}
@warn_unused_result
public mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
@warn_unused_result
public mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@warn_unused_result
public func requestNativeBuffer() -> NativeBuffer? {
if !_isClassOrObjCExistential(Element.self) {
return _native
}
return _fastPath(_storage.isNative) ? _native : nil
}
// We have two versions of type check: one that takes a range and the other
// checks one element. The reason for this is that the ARC optimizer does not
// handle loops atm. and so can get blocked by the presence of a loop (over
// the range). This loop is not necessary for a single element access.
@inline(never)
internal func _typeCheckSlowPath(index: Int) {
if _fastPath(_isNative) {
let element: AnyObject = castToBufferOf(AnyObject.self)._native[index]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
}
else {
let ns = _nonNative
_precondition(
ns.objectAtIndex(index) is Element,
"NSArray element failed to match the Swift Array Element type")
}
}
func _typeCheck(subRange: Range<Int>) {
if !_isClassOrObjCExistential(Element.self) {
return
}
if _slowPath(needsElementTypeCheck) {
// Could be sped up, e.g. by using
// enumerateObjectsAtIndexes:options:usingBlock: in the
// non-native case.
for i in subRange {
_typeCheckSlowPath(i)
}
}
}
/// Copy the given subRange of this buffer into uninitialized memory
/// starting at target. Return a pointer past-the-end of the
/// just-initialized memory.
@inline(never) // The copy loop blocks retain release matching.
public func _uninitializedCopy(
subRange: Range<Int>, target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_typeCheck(subRange)
if _fastPath(_isNative) {
return _native._uninitializedCopy(subRange, target: target)
}
let nonNative = _nonNative
let nsSubRange = SwiftShims._SwiftNSRange(
location:subRange.startIndex,
length: subRange.endIndex - subRange.startIndex)
let buffer = UnsafeMutablePointer<AnyObject>(target)
// Copies the references out of the NSArray without retaining them
nonNative.getObjects(buffer, range: nsSubRange)
// Make another pass to retain the copied objects
var result = target
for _ in subRange {
result.initialize(result.memory)
++result
}
return result
}
/// Return a `_SliceBuffer` containing the given `subRange` of values
/// from this buffer.
public subscript(subRange: Range<Int>) -> _SliceBuffer<Element> {
get {
_typeCheck(subRange)
if _fastPath(_isNative) {
return _native[subRange]
}
// Look for contiguous storage in the NSArray
let nonNative = self._nonNative
let cocoa = _CocoaArrayWrapper(nonNative)
let cocoaStorageBaseAddress = cocoa.contiguousStorage(self.indices)
if cocoaStorageBaseAddress != nil {
return _SliceBuffer(
owner: nonNative,
subscriptBaseAddress: UnsafeMutablePointer(cocoaStorageBaseAddress),
indices: subRange,
hasNativeBuffer: false)
}
// No contiguous storage found; we must allocate
let subRangeCount = subRange.count
let result = _ContiguousArrayBuffer<Element>(
count: subRangeCount, minimumCapacity: 0)
// Tell Cocoa to copy the objects into our storage
cocoa.buffer.getObjects(
UnsafeMutablePointer(result.firstElementAddress),
range: _SwiftNSRange(
location: subRange.startIndex,
length: subRangeCount))
return _SliceBuffer(result, shiftedToStartIndex: subRange.startIndex)
}
set {
fatalError("not implemented")
}
}
public var _unconditionalMutableSubscriptBaseAddress:
UnsafeMutablePointer<Element> {
_sanityCheck(_isNative, "must be a native buffer")
return _native.firstElementAddress
}
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
public var firstElementAddress: UnsafeMutablePointer<Element> {
if (_fastPath(_isNative)) {
return _native.firstElementAddress
}
return nil
}
/// The number of elements the buffer stores.
public var count: Int {
@inline(__always)
get {
return _fastPath(_isNative) ? _native.count : _nonNative.count
}
set {
_sanityCheck(_isNative, "attempting to update count of Cocoa array")
_native.count = newValue
}
}
/// Traps if an inout violation is detected or if the buffer is
/// native and the subscript is out of range.
///
/// wasNative == _isNative in the absence of inout violations.
/// Because the optimizer can hoist the original check it might have
/// been invalidated by illegal user code.
internal func _checkInoutAndNativeBounds(index: Int, wasNative: Bool) {
_precondition(
_isNative == wasNative,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNative) {
_native._checkValidSubscript(index)
}
}
// TODO: gyb this
/// Traps if an inout violation is detected or if the buffer is
/// native and typechecked and the subscript is out of range.
///
/// wasNativeTypeChecked == _isNativeTypeChecked in the absence of
/// inout violations. Because the optimizer can hoist the original
/// check it might have been invalidated by illegal user code.
internal func _checkInoutAndNativeTypeCheckedBounds(
index: Int, wasNativeTypeChecked: Bool
) {
_precondition(
_isNativeTypeChecked == wasNativeTypeChecked,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNativeTypeChecked) {
_native._checkValidSubscript(index)
}
}
/// The number of elements the buffer can store without reallocation.
public var capacity: Int {
return _fastPath(_isNative) ? _native.capacity : _nonNative.count
}
@inline(__always)
@warn_unused_result
func getElement(i: Int, wasNativeTypeChecked: Bool) -> Element {
if _fastPath(wasNativeTypeChecked) {
return _nativeTypeChecked[i]
}
return unsafeBitCast(_getElementSlowPath(i), Element.self)
}
@inline(never)
@warn_unused_result
func _getElementSlowPath(i: Int) -> AnyObject {
_sanityCheck(
_isClassOrObjCExistential(Element.self),
"Only single reference elements can be indexed here.")
let element: AnyObject
if _isNative {
// _checkInoutAndNativeTypeCheckedBounds does no subscript
// checking for the native un-typechecked case. Therefore we
// have to do it here.
_native._checkValidSubscript(i)
element = castToBufferOf(AnyObject.self)._native[i]
_precondition(
element is Element,
"Down-casted Array element failed to match the target type")
} else {
// ObjC arrays do their own subscript checking.
element = _nonNative.objectAtIndex(i)
_precondition(
element is Element,
"NSArray element failed to match the Swift Array Element type")
}
return element
}
/// Get or set the value of the ith element.
public subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
}
nonmutating set {
if _fastPath(_isNative) {
_native[i] = newValue
}
else {
var refCopy = self
refCopy.replace(
subRange: i...i, with: 1, elementsOf: CollectionOfOne(newValue))
}
}
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
public func withUnsafeBufferPointer<R>(
@noescape body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
if _fastPath(_isNative) {
defer { _fixLifetime(self) }
return try body(UnsafeBufferPointer(start: firstElementAddress,
count: count))
}
return try ContiguousArray(self).withUnsafeBufferPointer(body)
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Requires: Such contiguous storage exists or the buffer is empty.
public mutating func withUnsafeMutableBufferPointer<R>(
@noescape body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
_sanityCheck(
firstElementAddress != nil || count == 0,
"Array is bridging an opaque NSArray; can't get a pointer to the elements"
)
defer { _fixLifetime(self) }
return try body(
UnsafeMutableBufferPointer(start: firstElementAddress, count: count))
}
/// An object that keeps the elements stored in this buffer alive.
public var owner: AnyObject {
return _fastPath(_isNative) ? _native._storage : _nonNative
}
/// An object that keeps the elements stored in this buffer alive.
///
/// - Requires: This buffer is backed by a `_ContiguousArrayBuffer`.
public var nativeOwner: AnyObject {
_sanityCheck(_isNative, "Expect a native array")
return _native._storage
}
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
public var identity: UnsafePointer<Void> {
if _isNative {
return _native.identity
}
else {
return unsafeAddressOf(_nonNative)
}
}
//===--- CollectionType conformance -------------------------------------===//
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Int {
return count
}
//===--- private --------------------------------------------------------===//
typealias Storage = _ContiguousArrayStorage<Element>
public typealias NativeBuffer = _ContiguousArrayBuffer<Element>
var _isNative: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
}
else {
return _storage.isNative
}
}
/// `true`, if the array is native and does not need a deferred type check.
var _isNativeTypeChecked: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
}
else {
return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask)
}
}
/// Our native representation.
///
/// - Requires: `_isNative`.
var _native: NativeBuffer {
return NativeBuffer(
_isClassOrObjCExistential(Element.self)
? _storage.nativeInstance : _storage.nativeInstance_noSpareBits)
}
/// Fast access to the native representation.
///
/// - Requires: `_isNativeTypeChecked`.
var _nativeTypeChecked: NativeBuffer {
return NativeBuffer(_storage.nativeInstance_noSpareBits)
}
var _nonNative: _NSArrayCoreType {
@inline(__always)
get {
_sanityCheck(_isClassOrObjCExistential(Element.self))
return _storage.objCInstance
}
}
}
#endif
| apache-2.0 | 7c595ecff59db6fe3e27ad257d054bdb | 31.309615 | 80 | 0.666746 | 4.778441 | false | false | false | false |
TouchInstinct/LeadKit | Sources/Structures/DrawingOperations/PaddingDrawingOperation.swift | 1 | 2163 | //
// Copyright (c) 2017 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import CoreGraphics
struct PaddingDrawingOperation: DrawingOperation {
private let image: CGImage
private let imageSize: CGSize
private let padding: CGFloat
public init(image: CGImage, imageSize: CGSize, padding: CGFloat) {
self.image = image
self.imageSize = imageSize
self.padding = padding
}
public var contextSize: CGContextSize {
let width = Int(ceil(imageSize.width + padding * 2))
let height = Int(ceil(imageSize.height + padding * 2))
return (width: width, height: height)
}
public func apply(in context: CGContext) {
// Draw the image in the center of the context, leaving a gap around the edges
let imageLocation = CGRect(x: padding,
y: padding,
width: imageSize.width,
height: imageSize.height)
context.addRect(imageLocation)
context.clip()
context.draw(image, in: imageLocation)
}
}
| apache-2.0 | ce6688125787421fb90ff3bcb8bb931c | 37.625 | 86 | 0.679149 | 4.661638 | false | false | false | false |
davidpaul0880/ChristiansSongs | christiansongs/BMAddTableViewController.swift | 1 | 6766 | //
// BMAddTableViewController.swift
// christiansongs
//
// Created by jijo on 3/11/15.
// Copyright (c) 2015 jeesmon. All rights reserved.
//
import UIKit
import CoreData
class BMAddTableViewController: UITableViewController , FolderSelection{
var newBM : Dictionary<String, AnyObject>?
var folder : Folder!
var editingBookMark : BookMarks?
@IBAction func cancelBM(sender: UIBarButtonItem?) {
if editingBookMark != nil {
self.navigationController?.popViewControllerAnimated(true);
}else{
self.dismissViewControllerAnimated(true, completion: nil)
}
}
@IBAction func saveBM(sender: UIBarButtonItem) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContextUserData!
let entity1 = NSEntityDescription.entityForName("BookMarks", inManagedObjectContext: managedObjectContext)
let newBMTemp = BookMarks(entity: entity1!, insertIntoManagedObjectContext: managedObjectContext)
//managedObjectContext.insertObject(newBM!)
newBMTemp.createddate = NSDate()
newBMTemp.folder = self.folder!
newBMTemp.songtitle = newBM!["songtitle"]! as! String
newBMTemp.song_id = newBM!["song_id"]! as! NSNumber
var error: NSError?
do {
try managedObjectContext.save()
} catch let error1 as NSError {
error = error1
}
if let err = error {
print("\(error)")
} else {
//("success")
}
self.cancelBM(nil)
}
func updatedBM(){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContextUserData!
editingBookMark!.folder = self.folder
var error: NSError?
do {
try managedObjectContext.save()
} catch let error1 as NSError {
error = error1
}
if let _ = error {
print("\(error)")
} else {
//("success")
}
self.cancelBM(nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
if editingBookMark != nil {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: Selector("updatedBM"))
self.navigationItem.title = "Edit Bookmark"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var ident = "CellTitle"
if indexPath.section == 1 {
ident = "FolderCell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(ident, forIndexPath: indexPath)
if indexPath.section == 0 {
if editingBookMark != nil {
cell.textLabel?.text = editingBookMark!.songtitle
}else{
cell.textLabel?.text = newBM!["songtitle"] as? String
}
}else{
cell.textLabel?.text = self.folder!.folder_label
cell.imageView?.image = UIImage(named: "folder.png")
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if segue.identifier == "SelectFolder" {
let controller = segue.destinationViewController as! FolderSelectionTableViewController
controller.delegate = self
}
}
// MARK: protocol FolderSelection
func folderSelected(selectedFolder : Folder) {
self.folder = selectedFolder
self.folder.lastaccessed = NSDate()
self.tableView.reloadData()
}
}
| gpl-2.0 | 433610f02431b2e51d895fb2d5334f2f | 31.84466 | 162 | 0.621194 | 5.647746 | false | false | false | false |
carlynorama/learningSwift | Playgrounds/SimpleInfoChecking_iOS10.playground/Contents.swift | 1 | 2258 | //Array, Dictionary Scratch Pad, Swift Xcode 8 Beta 6
//2016. 08
//carlynorama, license: CC0
//https://www.udemy.com/complete-ios-10-developer-course/
//https://developer.apple.com/reference/swift/dictionary
//https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch
import UIKit
let stringVar:String? = nil
stringVar ?? "a default string" // if string var is not nill return stringVar, else return default
enum UserProfileError: Error {
case UserNotFound
case BadPass
case NietherSupplied
case OneNotSupplied
}
//SCOPE!!! These must be outside do to be used also by the catches.
let enteredUser = "GeorgeJettson"
let enteredPassword = "partparty"
func checkUser(user: String, withPassword password: String) throws -> String {
guard !password.isEmpty && !user.isEmpty else { throw UserProfileError.NietherSupplied }
guard !password.isEmpty || !user.isEmpty else { throw UserProfileError.OneNotSupplied }
var userVerified = Bool()
var passwordVerified = Bool()
if user == "GeorgeJettson" { userVerified = true; } else { userVerified = false }
//if password == "partyparty" { passwordVerified = true } else { passwordVerified = false }
//a >= 0 ? doThis(): doThat()
password == "partyparty" ? (passwordVerified = true) : (passwordVerified = false)
guard userVerified else { throw UserProfileError.UserNotFound }
guard passwordVerified else { throw UserProfileError.BadPass }
//let welcomeMessage =
return "Welcome \(enteredUser). Please enjoy the show."}
do {
defer { print("Shutting the door.") }
let verificationMessage = try checkUser(user: enteredUser, withPassword: enteredPassword)
print(verificationMessage)
//other stuff
} catch UserProfileError.UserNotFound {
print("I don't recognize you.")
} catch UserProfileError.BadPass {
let message = String(format: "I'm sorry %@ that password was not correct", enteredUser)
print(message)
} catch UserProfileError.NietherSupplied {
print("I'm sorry I didn't hear anything")
} catch UserProfileError.OneNotSupplied {
print("I'm sorry, could you make sure you entered BOTH a username and password?")
} catch {
print("Something went wrong!")
}
| unlicense | ffdaaf49c3cdebfebfeedc41b247d9a6 | 33.212121 | 99 | 0.713906 | 3.968366 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.