repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rduan8/Aerial | refs/heads/master | Aerial/Source/Views/AerialView.swift | mit | 1 | //
// AerialView.swift
// Aerial
//
// Created by John Coates on 10/22/15.
// Copyright © 2015 John Coates. All rights reserved.
//
import Foundation
import ScreenSaver
import AVFoundation
import AVKit
@objc(AerialView) class AerialView : ScreenSaverView {
// var playerView: AVPlayerView!
var playerLayer:AVPlayerLayer!
var preferencesController:PreferencesWindowController?
static var players:[AVPlayer] = [AVPlayer]()
static var previewPlayer:AVPlayer?
static var previewView:AerialView?
var player:AVPlayer?
static let defaults:NSUserDefaults = ScreenSaverDefaults(forModuleWithName: "com.JohnCoates.Aerial")! as ScreenSaverDefaults
static var sharingPlayers:Bool {
defaults.synchronize();
return !defaults.boolForKey("differentDisplays");
}
static var sharedViews:[AerialView] = []
// MARK: - Shared Player
static var singlePlayerAlreadySetup:Bool = false;
class var sharedPlayer: AVPlayer {
struct Static {
static let instance: AVPlayer = AVPlayer();
static var _player:AVPlayer?;
static var player:AVPlayer {
if let activePlayer = _player {
return activePlayer;
}
_player = AVPlayer();
return _player!;
}
}
return Static.player;
}
// MARK: - Init / Setup
override init?(frame: NSRect, isPreview: Bool) {
super.init(frame: frame, isPreview: isPreview)
self.animationTimeInterval = 1.0 / 30.0
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
deinit {
debugLog("deinit AerialView");
NSNotificationCenter.defaultCenter().removeObserver(self);
// set player item to nil if not preview player
if player != AerialView.previewPlayer {
player?.rate = 0;
player?.replaceCurrentItemWithPlayerItem(nil);
}
guard let player = self.player else {
return;
}
// Remove from player index
let indexMaybe = AerialView.players.indexOf(player)
guard let index = indexMaybe else {
return;
}
AerialView.players.removeAtIndex(index);
}
func setupPlayerLayer(withPlayer player:AVPlayer) {
self.layer = CALayer()
guard let layer = self.layer else {
NSLog("Aerial Errror: Couldn't create CALayer");
return;
}
self.wantsLayer = true
layer.backgroundColor = NSColor.blackColor().CGColor
layer.delegate = self;
layer.needsDisplayOnBoundsChange = true;
layer.frame = self.bounds
// layer.backgroundColor = NSColor.greenColor().CGColor
debugLog("setting up player layer with frame: \(self.bounds) / \(self.frame)");
playerLayer = AVPlayerLayer(player: player);
if #available(OSX 10.10, *) {
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
};
playerLayer.autoresizingMask = [CAAutoresizingMask.LayerWidthSizable, CAAutoresizingMask.LayerHeightSizable]
playerLayer.frame = layer.bounds;
layer.addSublayer(playerLayer);
}
func setup() {
var localPlayer:AVPlayer?
if (!self.preview) {
// check if we should share preview's player
if (AerialView.players.count == 0) {
if AerialView.previewPlayer != nil {
localPlayer = AerialView.previewPlayer;
}
}
}
else {
AerialView.previewView = self;
}
if AerialView.sharingPlayers {
AerialView.sharedViews.append(self);
}
if localPlayer == nil {
if AerialView.sharingPlayers {
if AerialView.previewPlayer != nil {
localPlayer = AerialView.previewPlayer
}
else {
localPlayer = AerialView.sharedPlayer;
}
}
else {
localPlayer = AVPlayer();
}
}
guard let player = localPlayer else {
NSLog("Aerial Error: Couldn't create AVPlayer!");
return;
}
self.player = player;
if (self.preview) {
AerialView.previewPlayer = player;
}
else if (AerialView.sharingPlayers == false) {
// add to player list
AerialView.players.append(player);
}
setupPlayerLayer(withPlayer: player);
if (AerialView.sharingPlayers == true && AerialView.singlePlayerAlreadySetup) {
self.playerLayer.player = AerialView.sharedViews[0].player
return;
}
AerialView.singlePlayerAlreadySetup = true;
ManifestLoader.instance.addCallback { (videos:[AerialVideo]) -> Void in
self.playNextVideo();
};
}
// MARK: - AVPlayerItem Notifications
func playerItemFailedtoPlayToEnd(aNotification: NSNotification) {
NSLog("AVPlayerItemFailedToPlayToEndTimeNotification \(aNotification)");
playNextVideo();
}
func playerItemNewErrorLogEntryNotification(aNotification: NSNotification) {
NSLog("AVPlayerItemNewErrorLogEntryNotification \(aNotification)");
}
func playerItemPlaybackStalledNotification(aNotification: NSNotification) {
NSLog("AVPlayerItemPlaybackStalledNotification \(aNotification)");
}
func playerItemDidReachEnd(aNotification: NSNotification) {
debugLog("played did reach end");
debugLog("notification: \(aNotification)");
playNextVideo()
debugLog("playing next video for player \(player)");
}
// MARK: - Playing Videos
func playNextVideo() {
let notificationCenter = NSNotificationCenter.defaultCenter()
// remove old entries
notificationCenter.removeObserver(self);
let player = AVPlayer()
// play another video
let oldPlayer = self.player
self.player = player
self.playerLayer.player = self.player
if self.preview {
AerialView.previewPlayer = player
}
debugLog("Setting player for all player layers in \(AerialView.sharedViews)");
for view in AerialView.sharedViews {
view.playerLayer.player = player
}
if (oldPlayer == AerialView.previewPlayer) {
AerialView.previewView?.playerLayer.player = self.player
}
let randomVideo = ManifestLoader.instance.randomVideo();
guard let video = randomVideo else {
NSLog("Aerial: Error grabbing random video!");
return;
}
let videoURL = video.url;
let asset = CachedOrCachingAsset(videoURL)
// let asset = AVAsset(URL: videoURL);
let item = AVPlayerItem(asset: asset);
player.replaceCurrentItemWithPlayerItem(item);
debugLog("playing video: \(video.url)");
if player.rate == 0 {
player.play();
}
guard let currentItem = player.currentItem else {
NSLog("Aerial Error: No current item!");
return;
}
debugLog("observing current item \(currentItem)");
notificationCenter.addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: currentItem);
notificationCenter.addObserver(self, selector: "playerItemNewErrorLogEntryNotification:", name: AVPlayerItemNewErrorLogEntryNotification, object: currentItem);
notificationCenter.addObserver(self, selector: "playerItemFailedtoPlayToEnd:", name: AVPlayerItemFailedToPlayToEndTimeNotification, object: currentItem);
notificationCenter.addObserver(self, selector: "playerItemPlaybackStalledNotification:", name: AVPlayerItemPlaybackStalledNotification, object: currentItem);
player.actionAtItemEnd = AVPlayerActionAtItemEnd.None;
}
// MARK: - Preferences
override func hasConfigureSheet() -> Bool {
return true;
}
override func configureSheet() -> NSWindow? {
if let controller = preferencesController {
return controller.window
}
let controller = PreferencesWindowController(windowNibName: "PreferencesWindow");
preferencesController = controller;
return controller.window;
}
} | 71190ca3c6a70edc2781b7ab0dddab77 | 30.333333 | 167 | 0.592564 | false | false | false | false |
dminones/reddit-ios-client | refs/heads/master | RedditIOSClient/Client/Listing.swift | mit | 1 | //
// Listing.swift
// RedditIOSClient
//
// Created by Dario Miñones on 4/5/17.
// Copyright © 2017 Dario Miñones. All rights reserved.
//
import Foundation
class Listing: NSObject, NSCoding {
var before: String?
var after: String?
var children = [Link]()
override init(){
super.init()
}
//MARK: NSCoding protocol methods
func encode(with aCoder: NSCoder){
aCoder.encode(self.before, forKey: "before")
aCoder.encode(self.after, forKey: "after")
aCoder.encode(self.children, forKey: "children")
}
required init(coder decoder: NSCoder) {
if let before = decoder.decodeObject(forKey: "before") as? String{
self.before = before
}
if let after = decoder.decodeObject(forKey: "after") as? String{
self.after = after
}
if let children = decoder.decodeObject(forKey: "children") as? [Link]{
self.children = children
}
}
init?(json: [String: Any]) {
if let after = json["after"] as? String? {
self.after = after
}
if let before = json["before"] as? String? {
self.before = before
}
if let children : [NSDictionary] = json["children"] as? [NSDictionary] {
var links = [Link]()
for item in children {
if let link = Link(json: item as! [String : Any]) {
links.append(link)
}
}
self.children = links
}
}
func addAfter(_ after: Listing) {
self.after = after.after
self.children.append(contentsOf: after.children)
}
}
| e8a18942b7ee7a056c1e9d010e474442 | 24.865672 | 80 | 0.533756 | false | false | false | false |
SwiftyMagic/Magic | refs/heads/master | Magic/Magic/UIKit/UITableViewControllerExtension.swift | mit | 1 | //
// UITableViewControllerExtension.swift
// Magic
//
// Created by Broccoli on 2016/9/22.
// Copyright © 2016年 broccoliii. All rights reserved.
//
import Foundation
public extension UITableViewController {
// /**
// Adds activity indicator to the table view.
// http://stackoverflow.com/questions/29912852/how-to-show-activity-indicator-while-tableview-loads
// - returns: Returns an instance of the activity indicator that is centered.
// */
// // move to UICollectionView
// var activityIndicatorView: UIActivityIndicatorView? {
// get {
// return view.viewWithTag(3000) as? UIActivityIndicatorView
// }
//
// set {
// newValue?.tag = 3000
// newValue?.center = self.view.center
// newValue?.hidesWhenStopped = true
// guard newValue != nil else {
// return
// }
// self.view.addSubview(newValue!)
// }
// }
//
// func setupActivityIndicator(
// viewStyle: UIActivityIndicatorViewStyle = .gray,
// color: UIColor = UIColor.gray) {
// if self.activityIndicatorView == nil {
// self.activityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
// }
// self.activityIndicatorView?.activityIndicatorViewStyle = viewStyle
// self.activityIndicatorView?.color = color
//
// self.activityIndicatorView?.startAnimating()
//
// }
}
| c05f43d0e89f1c6bf87ae9ce6261c0ae | 33.108696 | 120 | 0.583811 | false | false | false | false |
saraheolson/TechEmpathy-iOS | refs/heads/master | TechEmpathy/TechEmpathy/Models/Story.swift | apache-2.0 | 1 | //
// Story.swift
// TechEmpathy
//
// Created by Sarah Olson on 4/15/17.
// Copyright © 2017 SarahEOlson. All rights reserved.
//
import Foundation
enum StoryType: String {
case exclusion = "exclusion"
case inclusion = "inclusion"
case all = "all"
}
struct JSONKeys {
static let uuid = "uuid"
static let dateAdded = "dateAdded"
static let storyName = "storyName"
static let user = "user"
static let color = "color"
static let storyType = "storyType"
static let storyText = "storyText"
static let isApproved = "isApproved"
static let audio = "audio"
static let image = "image"
}
struct Story {
let key: String
let uuid: String
var user: String
let dateAdded: Date
var storyName: String
var color: String
var storyType: StoryType
let isApproved: Bool
var audio: String?
var image: String?
var storyText: String?
var isLampLit = false
/// Populating an existing story from JSON
init?(key: String, JSON: [String: Any?]) {
guard let nickname = JSON[JSONKeys.storyName] as? String,
let user = JSON[JSONKeys.user] as? String,
let color = JSON[JSONKeys.color] as? String,
let storyTypeString = JSON[JSONKeys.storyType] as? String,
let storyType = StoryType(rawValue: storyTypeString)
else {
return nil
}
self.key = key
self.storyName = nickname
self.user = user
self.color = color
self.storyType = storyType
if let dateAddedString = JSON[JSONKeys.dateAdded] as? String,
let dateAdded = Date.firebaseDate(fromString: dateAddedString) {
self.dateAdded = dateAdded
} else {
self.dateAdded = Date()
}
if let uuid = JSON[JSONKeys.uuid] as? String {
self.uuid = uuid
} else {
self.uuid = UUID().uuidString
}
if let approved = JSON[JSONKeys.isApproved] as? Bool {
self.isApproved = approved
} else {
self.isApproved = false
}
if let audio = JSON[JSONKeys.audio] as? String {
self.audio = audio
}
if let image = JSON[JSONKeys.image] as? String {
self.image = image
}
if let storyText = JSON[JSONKeys.storyText] as? String {
self.storyText = storyText
}
}
/// Creating a new story
init( key: String,
storyName: String,
user: String,
color: String,
storyType: StoryType,
audio: String?,
image: String?,
storyText: String?) {
self.key = key
self.dateAdded = Date()
self.storyName = storyName
self.user = user
self.color = color
self.storyType = storyType
self.audio = audio
self.image = image
self.storyText = storyText
self.uuid = UUID().uuidString
self.isApproved = false
}
func toJSON() -> [String: [String: Any]] {
return [key :
[JSONKeys.uuid: self.uuid,
JSONKeys.dateAdded: self.dateAdded.firebaseDateString(),
JSONKeys.storyName : self.storyName,
JSONKeys.user: self.user,
JSONKeys.color: self.color,
JSONKeys.storyType: storyType.rawValue,
JSONKeys.isApproved: self.isApproved,
JSONKeys.audio: audio ?? "",
JSONKeys.image: image ?? "",
JSONKeys.storyText: storyText ?? ""]]
}
}
| 339a638a5ce672df469a57036acfce68 | 27.873016 | 75 | 0.561847 | false | false | false | false |
salmojunior/TMDb | refs/heads/master | TMDb/TMDb/Source/Infrastructure/Extensions/ReachabilityExtension.swift | mit | 1 | //
// ReachabilityExtension.swift
// TMDb
//
// Created by SalmoJunior on 13/05/17.
// Copyright © 2017 Salmo Junior. All rights reserved.
//
import Reachability
extension Reachability {
// MARK: - Private Computed Properties
private static let defaultHost = "www.google.com"
private static var reachability = Reachability(hostName: defaultHost)
// MARK: - Public Functions
/// True value if there is a stable network connection
static var isConnected: Bool {
guard let reachability = Reachability.reachability else { return false }
return reachability.currentReachabilityStatus() != .NotReachable
}
/// Current network status based on enum NetworkStatus
static var status: NetworkStatus {
guard let reachability = Reachability.reachability else { return .NotReachable }
return reachability.currentReachabilityStatus()
}
}
| 035a24dca2a60b0e9e5c98ea1fbde5dc | 29.129032 | 88 | 0.690578 | false | false | false | false |
remaerd/Keys | refs/heads/master | Keys/Hash.swift | bsd-3-clause | 1 | //
// Hash.swift
// Keys
//
// Created by Sean Cheng on 8/9/15.
//
//
import Foundation
import CommonCrypto
public extension Data {
var MD2: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_MD2_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_MD2(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_MD2_DIGEST_LENGTH))
}
var MD4: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_MD4_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_MD4(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_MD4_DIGEST_LENGTH))
}
var MD5: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_MD5(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_MD5_DIGEST_LENGTH))
}
var SHA1: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA1(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA1_DIGEST_LENGTH))
}
var SHA224: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA224_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA224(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA224_DIGEST_LENGTH))
}
var SHA256: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA256(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA256_DIGEST_LENGTH))
}
var SHA384: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA384_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA384(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA384_DIGEST_LENGTH))
}
var SHA512: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
var pointer : UnsafeRawPointer? = nil
withUnsafeBytes({ (ptr) in pointer = ptr.baseAddress })
CC_SHA512(pointer, CC_LONG(count), &hash)
return Data(bytes: pointer!, count: Int(CC_SHA512_DIGEST_LENGTH))
}
}
public extension String {
var MD2: String? {
return String(digestData: hashData?.MD2, length: CC_MD2_DIGEST_LENGTH)
}
var MD4: String? {
return String(digestData: hashData?.MD4, length: CC_MD4_DIGEST_LENGTH)
}
var MD5: String? {
return String(digestData: hashData?.MD5, length: CC_MD5_DIGEST_LENGTH)
}
var SHA1: String? {
return String(digestData: hashData?.SHA1, length: CC_SHA1_DIGEST_LENGTH)
}
var SHA224: String? {
return String(digestData: hashData?.SHA224, length: CC_SHA224_DIGEST_LENGTH)
}
var SHA256: String? {
return String(digestData: hashData?.SHA256, length: CC_SHA256_DIGEST_LENGTH)
}
var SHA384: String? {
return String(digestData: hashData?.SHA384, length: CC_SHA384_DIGEST_LENGTH)
}
var SHA512: String? {
return String(digestData: hashData?.SHA512, length: CC_SHA512_DIGEST_LENGTH)
}
fileprivate var hashData: Data?
{
return data(using: String.Encoding.utf8, allowLossyConversion: false)
}
fileprivate init?(digestData: Data?, length: Int32) {
guard let digestData = digestData else { return nil }
var digest = [UInt8](repeating: 0, count: Int(length))
(digestData as NSData).getBytes(&digest, length: Int(length) * MemoryLayout<UInt8>.size)
var string = ""
for i in 0..<length {
string += String(format: "%02x", digest[Int(i)])
}
self.init(string)
}
}
| 61be190ba750ab86d4f546bf81620cc3 | 26.598639 | 92 | 0.663544 | false | false | false | false |
CodePath-Parse/MiAR | refs/heads/master | MiAR/ARNodes/FocusSquare.swift | apache-2.0 | 2 | //
// FocusSquare.swift
// MiAR
//
// Created by Oscar Bonilla on 10/23/17.
// Copyright © 2017 MiAR. All rights reserved.
//
import Foundation
import ARKit
class FocusSquare: SCNNode {
enum State {
case initializing
case featuresDetected(anchorPosition: float3, camera: ARCamera?)
case planeDetected(anchorPosition: float3, planeAnchor: ARPlaneAnchor, camera: ARCamera?)
}
// MARK: - Configuration Properties
// Original size of the focus square in meters.
static let size: Float = 0.17
// Thickness of the focus square lines in meters.
static let thickness: Float = 0.018
// Scale factor for the focus square when it is closed, w.r.t. the original size.
static let scaleForClosedSquare: Float = 0.97
// Side length of the focus square segments when it is open (w.r.t. to a 1x1 square).
static let sideLengthForOpenSegments: CGFloat = 0.2
// Duration of the open/close animation
static let animationDuration = 0.7
static let primaryColor = #colorLiteral(red: 1, green: 0.8, blue: 0, alpha: 1)
// Color of the focus square fill.
static let fillColor = #colorLiteral(red: 1, green: 0.9254901961, blue: 0.4117647059, alpha: 1)
// MARK: - Properties
/// The most recent position of the focus square based on the current state.
var lastPosition: float3? {
switch state {
case .initializing: return nil
case .featuresDetected(let anchorPosition, _): return anchorPosition
case .planeDetected(let anchorPosition, _, _): return anchorPosition
}
}
var state: State = .initializing {
didSet {
guard state != oldValue else { return }
switch state {
case .initializing:
displayAsBillboard()
case .featuresDetected(let anchorPosition, let camera):
displayAsOpen(at: anchorPosition, camera: camera)
case .planeDetected(let anchorPosition, let planeAnchor, let camera):
displayAsClosed(at: anchorPosition, planeAnchor: planeAnchor, camera: camera)
}
}
}
/// Indicates whether the segments of the focus square are disconnected.
private var isOpen = false
/// Indicates if the square is currently being animated.
private var isAnimating = false
/// The focus square's most recent positions.
private var recentFocusSquarePositions: [float3] = []
/// Previously visited plane anchors.
private var anchorsOfVisitedPlanes: Set<ARAnchor> = []
/// List of the segments in the focus square.
private var segments: [FocusSquare.Segment] = []
/// The primary node that controls the position of other `FocusSquare` nodes.
private let positioningNode = SCNNode()
// MARK: - Initialization
override init() {
super.init()
opacity = 0.0
/*
The focus square consists of eight segments as follows, which can be individually animated.
s1 s2
_ _
s3 | | s4
s5 | | s6
- -
s7 s8
*/
let s1 = Segment(name: "s1", corner: .topLeft, alignment: .horizontal)
let s2 = Segment(name: "s2", corner: .topRight, alignment: .horizontal)
let s3 = Segment(name: "s3", corner: .topLeft, alignment: .vertical)
let s4 = Segment(name: "s4", corner: .topRight, alignment: .vertical)
let s5 = Segment(name: "s5", corner: .bottomLeft, alignment: .vertical)
let s6 = Segment(name: "s6", corner: .bottomRight, alignment: .vertical)
let s7 = Segment(name: "s7", corner: .bottomLeft, alignment: .horizontal)
let s8 = Segment(name: "s8", corner: .bottomRight, alignment: .horizontal)
segments = [s1, s2, s3, s4, s5, s6, s7, s8]
let sl: Float = 0.5 // segment length
let c: Float = FocusSquare.thickness / 2 // correction to align lines perfectly
s1.simdPosition += float3(-(sl / 2 - c), -(sl - c), 0)
s2.simdPosition += float3(sl / 2 - c, -(sl - c), 0)
s3.simdPosition += float3(-sl, -sl / 2, 0)
s4.simdPosition += float3(sl, -sl / 2, 0)
s5.simdPosition += float3(-sl, sl / 2, 0)
s6.simdPosition += float3(sl, sl / 2, 0)
s7.simdPosition += float3(-(sl / 2 - c), sl - c, 0)
s8.simdPosition += float3(sl / 2 - c, sl - c, 0)
positioningNode.eulerAngles.x = .pi / 2 // Horizontal
positioningNode.simdScale = float3(FocusSquare.size * FocusSquare.scaleForClosedSquare)
for segment in segments {
positioningNode.addChildNode(segment)
}
positioningNode.addChildNode(fillPlane)
// Always render focus square on top of other content.
displayNodeHierarchyOnTop(true)
addChildNode(positioningNode)
// Start the focus square as a billboard.
displayAsBillboard()
}
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
// MARK: - Appearance
/// Hides the focus square.
func hide() {
guard action(forKey: "hide") == nil else { return }
displayNodeHierarchyOnTop(false)
runAction(.fadeOut(duration: 0.5), forKey: "hide")
}
/// Unhides the focus square.
func unhide() {
guard action(forKey: "unhide") == nil else { return }
displayNodeHierarchyOnTop(true)
runAction(.fadeIn(duration: 0.5), forKey: "unhide")
}
/// Displays the focus square parallel to the camera plane.
private func displayAsBillboard() {
eulerAngles.x = -.pi / 2
simdPosition = float3(0, 0, -0.8)
unhide()
performOpenAnimation()
}
/// Called when a surface has been detected.
private func displayAsOpen(at position: float3, camera: ARCamera?) {
performOpenAnimation()
recentFocusSquarePositions.append(position)
updateTransform(for: position, camera: camera)
}
/// Called when a plane has been detected.
private func displayAsClosed(at position: float3, planeAnchor: ARPlaneAnchor, camera: ARCamera?) {
performCloseAnimation(flash: !anchorsOfVisitedPlanes.contains(planeAnchor))
anchorsOfVisitedPlanes.insert(planeAnchor)
recentFocusSquarePositions.append(position)
updateTransform(for: position, camera: camera)
}
// MARK: Helper Methods
/// Update the transform of the focus square to be aligned with the camera.
private func updateTransform(for position: float3, camera: ARCamera?) {
simdTransform = matrix_identity_float4x4
// Average using several most recent positions.
recentFocusSquarePositions = Array(recentFocusSquarePositions.suffix(10))
// Move to average of recent positions to avoid jitter.
let average = recentFocusSquarePositions.reduce(float3(0), { $0 + $1 }) / Float(recentFocusSquarePositions.count)
self.simdPosition = average
self.simdScale = float3(scaleBasedOnDistance(camera: camera))
// Correct y rotation of camera square.
guard let camera = camera else { return }
let tilt = abs(camera.eulerAngles.x)
let threshold1: Float = .pi / 2 * 0.65
let threshold2: Float = .pi / 2 * 0.75
let yaw = atan2f(camera.transform.columns.0.x, camera.transform.columns.1.x)
var angle: Float = 0
switch tilt {
case 0..<threshold1:
angle = camera.eulerAngles.y
case threshold1..<threshold2:
let relativeInRange = abs((tilt - threshold1) / (threshold2 - threshold1))
let normalizedY = normalize(camera.eulerAngles.y, forMinimalRotationTo: yaw)
angle = normalizedY * (1 - relativeInRange) + yaw * relativeInRange
default:
angle = yaw
}
eulerAngles.y = angle
}
private func normalize(_ angle: Float, forMinimalRotationTo ref: Float) -> Float {
// Normalize angle in steps of 90 degrees such that the rotation to the other angle is minimal
var normalized = angle
while abs(normalized - ref) > .pi / 4 {
if angle > ref {
normalized -= .pi / 2
} else {
normalized += .pi / 2
}
}
return normalized
}
/**
Reduce visual size change with distance by scaling up when close and down when far away.
These adjustments result in a scale of 1.0x for a distance of 0.7 m or less
(estimated distance when looking at a table), and a scale of 1.2x
for a distance 1.5 m distance (estimated distance when looking at the floor).
*/
private func scaleBasedOnDistance(camera: ARCamera?) -> Float {
guard let camera = camera else { return 1.0 }
let distanceFromCamera = simd_length(simdWorldPosition - camera.transform.translation)
if distanceFromCamera < 0.7 {
return distanceFromCamera / 0.7
} else {
return 0.25 * distanceFromCamera + 0.825
}
}
// MARK: Animations
private func performOpenAnimation() {
guard !isOpen, !isAnimating else { return }
isOpen = true
isAnimating = true
// Open animation
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
positioningNode.opacity = 1.0
for segment in segments {
segment.open()
}
SCNTransaction.completionBlock = {
self.positioningNode.runAction(pulseAction(), forKey: "pulse")
// This is a safe operation because `SCNTransaction`'s completion block is called back on the main thread.
self.isAnimating = false
}
SCNTransaction.commit()
// Add a scale/bounce animation.
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
positioningNode.simdScale = float3(FocusSquare.size)
SCNTransaction.commit()
}
private func performCloseAnimation(flash: Bool = false) {
guard isOpen, !isAnimating else { return }
isOpen = false
isAnimating = true
positioningNode.removeAction(forKey: "pulse")
positioningNode.opacity = 1.0
// Close animation
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 2
positioningNode.opacity = 0.99
SCNTransaction.completionBlock = {
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
for segment in self.segments {
segment.close()
}
SCNTransaction.completionBlock = { self.isAnimating = false }
SCNTransaction.commit()
}
SCNTransaction.commit()
// Scale/bounce animation
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.x"), forKey: "transform.scale.x")
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.y"), forKey: "transform.scale.y")
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.z"), forKey: "transform.scale.z")
if flash {
let waitAction = SCNAction.wait(duration: FocusSquare.animationDuration * 0.75)
let fadeInAction = SCNAction.fadeOpacity(to: 0.25, duration: FocusSquare.animationDuration * 0.125)
let fadeOutAction = SCNAction.fadeOpacity(to: 0.0, duration: FocusSquare.animationDuration * 0.125)
fillPlane.runAction(SCNAction.sequence([waitAction, fadeInAction, fadeOutAction]))
let flashSquareAction = flashAnimation(duration: FocusSquare.animationDuration * 0.25)
for segment in segments {
segment.runAction(.sequence([waitAction, flashSquareAction]))
}
}
}
// MARK: Convenience Methods
private func scaleAnimation(for keyPath: String) -> CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: keyPath)
let easeOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
let easeInOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let linear = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let size = FocusSquare.size
let ts = FocusSquare.size * FocusSquare.scaleForClosedSquare
let values = [size, size * 1.15, size * 1.15, ts * 0.97, ts]
let keyTimes: [NSNumber] = [0.00, 0.25, 0.50, 0.75, 1.00]
let timingFunctions = [easeOut, linear, easeOut, easeInOut]
scaleAnimation.values = values
scaleAnimation.keyTimes = keyTimes
scaleAnimation.timingFunctions = timingFunctions
scaleAnimation.duration = FocusSquare.animationDuration
return scaleAnimation
}
/// Sets the rendering order of the `positioningNode` to show on top or under other scene content.
func displayNodeHierarchyOnTop(_ isOnTop: Bool) {
// Recursivley traverses the node's children to update the rendering order depending on the `isOnTop` parameter.
func updateRenderOrder(for node: SCNNode) {
node.renderingOrder = isOnTop ? 2 : 0
for material in node.geometry?.materials ?? [] {
material.readsFromDepthBuffer = !isOnTop
}
for child in node.childNodes {
updateRenderOrder(for: child)
}
}
updateRenderOrder(for: positioningNode)
}
private lazy var fillPlane: SCNNode = {
let correctionFactor = FocusSquare.thickness / 2 // correction to align lines perfectly
let length = CGFloat(1.0 - FocusSquare.thickness * 2 + correctionFactor)
let plane = SCNPlane(width: length, height: length)
let node = SCNNode(geometry: plane)
node.name = "fillPlane"
node.opacity = 0.0
let material = plane.firstMaterial!
material.diffuse.contents = FocusSquare.fillColor
material.isDoubleSided = true
material.ambient.contents = UIColor.black
material.lightingModel = .constant
material.emission.contents = FocusSquare.fillColor
return node
}()
}
// MARK: - Animations and Actions
private func pulseAction() -> SCNAction {
let pulseOutAction = SCNAction.fadeOpacity(to: 0.4, duration: 0.5)
let pulseInAction = SCNAction.fadeOpacity(to: 1.0, duration: 0.5)
pulseOutAction.timingMode = .easeInEaseOut
pulseInAction.timingMode = .easeInEaseOut
return SCNAction.repeatForever(SCNAction.sequence([pulseOutAction, pulseInAction]))
}
private func flashAnimation(duration: TimeInterval) -> SCNAction {
let action = SCNAction.customAction(duration: duration) { (node, elapsedTime) -> Void in
// animate color from HSB 48/100/100 to 48/30/100 and back
let elapsedTimePercentage = elapsedTime / CGFloat(duration)
let saturation = 2.8 * (elapsedTimePercentage - 0.5) * (elapsedTimePercentage - 0.5) + 0.3
if let material = node.geometry?.firstMaterial {
material.diffuse.contents = UIColor(hue: 0.1333, saturation: saturation, brightness: 1.0, alpha: 1.0)
}
}
return action
}
extension FocusSquare.State: Equatable {
static func ==(lhs: FocusSquare.State, rhs: FocusSquare.State) -> Bool {
switch (lhs, rhs) {
case (.initializing, .initializing):
return true
case (.featuresDetected(let lhsPosition, let lhsCamera),
.featuresDetected(let rhsPosition, let rhsCamera)):
return lhsPosition == rhsPosition && lhsCamera == rhsCamera
case (.planeDetected(let lhsPosition, let lhsPlaneAnchor, let lhsCamera),
.planeDetected(let rhsPosition, let rhsPlaneAnchor, let rhsCamera)):
return lhsPosition == rhsPosition
&& lhsPlaneAnchor == rhsPlaneAnchor
&& lhsCamera == rhsCamera
default:
return false
}
}
}
| 50c6425909dc646544bfa8a73367681e | 37.108295 | 121 | 0.646291 | false | false | false | false |
luowei/Swift-Samples | refs/heads/master | LWPickerLabel/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// LWPickerLabel
//
// Created by luowei on 16/8/5.
// Copyright © 2016年 wodedata. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var textLabel: LWAddressLabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//let text = NSMutableAttributedString(string: "aaabbbb")
var main_string = "Hello World aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa aaaaaaaaa bbbb aaaaaaaaa aaaaaaaaa"
var string_to_color = "bbbb"
var range = (main_string as NSString).rangeOfString(string_to_color)
var attributedString = NSMutableAttributedString(string:main_string)
// attributedString.addAttribute(
// NSForegroundColorAttributeName, value: UIColor.redColor() , range: NSRange(location: 0,length: 5))
attributedString.addAttributes([
NSForegroundColorAttributeName : UIColor.redColor(),
NSFontAttributeName : UIFont.systemFontOfSize(21)
], range: NSRange(location: 0,length: 5))
attributedString.addAttributes([
NSForegroundColorAttributeName : UIColor.redColor(),
NSFontAttributeName : UIFont.systemFontOfSize(30)
], range: range)
textLabel.attributedText = attributedString
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| a673d3f66a486754b52428650ef305e8 | 33.673913 | 134 | 0.672727 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | CredentialProvider/CredentialWelcomeViewController.swift | mpl-2.0 | 2 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
import Shared
protocol CredentialWelcomeViewControllerDelegate: AnyObject {
func credentialWelcomeViewControllerDidCancel()
func credentialWelcomeViewControllerDidProceed()
}
class CredentialWelcomeViewController: UIViewController {
var delegate: CredentialWelcomeViewControllerDelegate?
lazy private var logoImageView: UIImageView = {
let image = UIImageView(image: UIImage(named: "logo-glyph"))
image.translatesAutoresizingMaskIntoConstraints = false
return image
}()
lazy private var titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = .LoginsWelcomeViewTitle2
label.font = UIFont.systemFont(ofSize: 32, weight: .bold)
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
lazy private var taglineLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = .LoginsWelcomeViewTagline
label.font = UIFont.systemFont(ofSize: 20)
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
lazy private var cancelButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(.CancelString, for: .normal)
button.addTarget(self, action: #selector(self.cancelButtonTapped(_:)), for: .touchUpInside)
return button
}()
lazy private var proceedButton: UIButton = {
let button = UIButton(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.Photon.Blue50
button.layer.cornerRadius = 8
button.setTitle(String.LoginsWelcomeTurnOnAutoFillButtonTitle, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)
button.addTarget(self, action: #selector(proceedButtonTapped), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.CredentialProvider.welcomeScreenBackgroundColor
view.addSubviews(cancelButton, logoImageView, titleLabel, taglineLabel, proceedButton)
NSLayoutConstraint.activate([
cancelButton.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 10),
cancelButton.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -20),
logoImageView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
logoImageView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, multiplier: 0.4),
titleLabel.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 40),
titleLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
titleLabel.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 35, priority: .defaultHigh),
titleLabel.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -35, priority: .defaultHigh),
titleLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 440),
taglineLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 20),
taglineLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
taglineLabel.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 35, priority: .defaultHigh),
taglineLabel.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -35, priority: .defaultHigh),
taglineLabel.widthAnchor.constraint(lessThanOrEqualToConstant: 440),
proceedButton.bottomAnchor.constraint(equalTo: self.view.layoutMarginsGuide.bottomAnchor, constant: -20),
proceedButton.heightAnchor.constraint(equalToConstant: 44),
proceedButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
proceedButton.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 35, priority: .defaultHigh),
proceedButton.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -35, priority: .defaultHigh),
proceedButton.widthAnchor.constraint(lessThanOrEqualToConstant: 360)
])
}
@objc func cancelButtonTapped(_ sender: UIButton) {
delegate?.credentialWelcomeViewControllerDidCancel()
}
@objc func proceedButtonTapped(_ sender: UIButton) {
delegate?.credentialWelcomeViewControllerDidProceed()
}
}
| 2fce0a40b1d374cffa0b5a84fedd638b | 47.776699 | 146 | 0.725717 | false | false | false | false |
tkremenek/swift | refs/heads/master | test/refactoring/ConvertAsync/basic.swift | apache-2.0 | 1 | // RUN: %empty-directory(%t)
enum CustomError: Error {
case invalid
case insecure
}
typealias SomeCallback = (String) -> Void
typealias SomeResultCallback = (Result<String, CustomError>) -> Void
typealias NestedAliasCallback = SomeCallback
// 1. Check various functions for having/not having async alternatives
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+4):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s
// RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+3):6 | %FileCheck -check-prefix=ASYNC-SIMPLE %s
// RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):12 | %FileCheck -check-prefix=ASYNC-SIMPLE %s
// RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):13 | %FileCheck -check-prefix=ASYNC-SIMPLE %s
func simple(completion: (String) -> Void) { }
// ASYNC-SIMPLE: basic.swift [[# @LINE-1]]:1 -> [[# @LINE-1]]:1
// ASYNC-SIMPLE-NEXT: @available(*, deprecated, message: "Prefer async alternative instead")
// ASYNC-SIMPLE-EMPTY:
// ASYNC-SIMPLE-NEXT: basic.swift [[# @LINE-4]]:43 -> [[# @LINE-4]]:46
// ASYNC-SIMPLE-NEXT: {
// ASYNC-SIMPLE-NEXT: Task {
// ASYNC-SIMPLE-NEXT: let result = await simple()
// ASYNC-SIMPLE-NEXT: completion(result)
// ASYNC-SIMPLE-NEXT: }
// ASYNC-SIMPLE-NEXT: }
// ASYNC-SIMPLE-EMPTY:
// ASYNC-SIMPLE-NEXT: basic.swift [[# @LINE-12]]:46 -> [[# @LINE-12]]:46
// ASYNC-SIMPLE-EMPTY:
// ASYNC-SIMPLE-EMPTY:
// ASYNC-SIMPLE-EMPTY:
// ASYNC-SIMPLE-NEXT: basic.swift [[# @LINE-16]]:46 -> [[# @LINE-16]]:46
// ASYNC-SIMPLE-NEXT: func simple() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLENOLABEL %s
func simpleWithoutLabel(_ completion: (String) -> Void) { }
// ASYNC-SIMPLENOLABEL: {
// ASYNC-SIMPLENOLABEL-NEXT: Task {
// ASYNC-SIMPLENOLABEL-NEXT: let result = await simpleWithoutLabel()
// ASYNC-SIMPLENOLABEL-NEXT: completion(result)
// ASYNC-SIMPLENOLABEL-NEXT: }
// ASYNC-SIMPLENOLABEL-NEXT: }
// ASYNC-SIMPLENOLABEL: func simpleWithoutLabel() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLEWITHARG %s
func simpleWithArg(a: Int, completion: (String) -> Void) { }
// ASYNC-SIMPLEWITHARG: {
// ASYNC-SIMPLEWITHARG-NEXT: Task {
// ASYNC-SIMPLEWITHARG-NEXT: let result = await simpleWithArg(a: a)
// ASYNC-SIMPLEWITHARG-NEXT: completion(result)
// ASYNC-SIMPLEWITHARG-NEXT: }
// ASYNC-SIMPLEWITHARG-NEXT: }
// ASYNC-SIMPLEWITHARG: func simpleWithArg(a: Int) async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-MULTIPLERESULTS %s
func multipleResults(completion: (String, Int) -> Void) { }
// ASYNC-MULTIPLERESULTS: {
// ASYNC-MULTIPLERESULTS-NEXT: Task {
// ASYNC-MULTIPLERESULTS-NEXT: let result = await multipleResults()
// ASYNC-MULTIPLERESULTS-NEXT: completion(result.0, result.1)
// ASYNC-MULTIPLERESULTS-NEXT: }
// ASYNC-MULTIPLERESULTS-NEXT: }
// ASYNC-MULTIPLERESULTS: func multipleResults() async -> (String, Int) { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-NONOPTIONALERROR %s
func nonOptionalError(completion: (String, Error) -> Void) { }
// ASYNC-NONOPTIONALERROR: {
// ASYNC-NONOPTIONALERROR-NEXT: Task {
// ASYNC-NONOPTIONALERROR-NEXT: let result = await nonOptionalError()
// ASYNC-NONOPTIONALERROR-NEXT: completion(result.0, result.1)
// ASYNC-NONOPTIONALERROR-NEXT: }
// ASYNC-NONOPTIONALERROR-NEXT: }
// ASYNC-NONOPTIONALERROR: func nonOptionalError() async -> (String, Error) { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-NOPARAMS %s
func noParams(completion: () -> Void) { }
// ASYNC-NOPARAMS: {
// ASYNC-NOPARAMS-NEXT: Task {
// ASYNC-NOPARAMS-NEXT: await noParams()
// ASYNC-NOPARAMS-NEXT: completion()
// ASYNC-NOPARAMS-NEXT: }
// ASYNC-NOPARAMS-NEXT: }
// ASYNC-NOPARAMS: func noParams() async { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERROR %s
func error(completion: (String?, Error?) -> Void) { }
// ASYNC-ERROR: {
// ASYNC-ERROR-NEXT: Task {
// ASYNC-ERROR-NEXT: do {
// ASYNC-ERROR-NEXT: let result = try await error()
// ASYNC-ERROR-NEXT: completion(result, nil)
// ASYNC-ERROR-NEXT: } catch {
// ASYNC-ERROR-NEXT: completion(nil, error)
// ASYNC-ERROR-NEXT: }
// ASYNC-ERROR-NEXT: }
// ASYNC-ERROR: func error() async throws -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERRORONLY %s
func errorOnly(completion: (Error?) -> Void) { }
// ASYNC-ERRORONLY: {
// ASYNC-ERRORONLY-NEXT: Task {
// ASYNC-ERRORONLY-NEXT: do {
// ASYNC-ERRORONLY-NEXT: try await errorOnly()
// ASYNC-ERRORONLY-NEXT: completion(nil)
// ASYNC-ERRORONLY-NEXT: } catch {
// ASYNC-ERRORONLY-NEXT: completion(error)
// ASYNC-ERRORONLY-NEXT: }
// ASYNC-ERRORONLY-NEXT: }
// ASYNC-ERRORONLY-NEXT: }
// ASYNC-ERRORONLY: func errorOnly() async throws { }
// RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERRORNONOPTIONALRESULT %s
func errorNonOptionalResult(completion: (String, Error?) -> Void) { }
// ASYNC-ERRORNONOPTIONALRESULT: {
// ASYNC-ERRORNONOPTIONALRESULT-NEXT: Task {
// ASYNC-ERRORNONOPTIONALRESULT-NEXT: do {
// ASYNC-ERRORNONOPTIONALRESULT-NEXT: let result = try await errorNonOptionalResult()
// ASYNC-ERRORNONOPTIONALRESULT-NEXT: completion(result, nil)
// ASYNC-ERRORNONOPTIONALRESULT-NEXT: } catch {
// ASYNC-ERRORNONOPTIONALRESULT-NEXT: completion(<#String#>, error)
// ASYNC-ERRORNONOPTIONALRESULT-NEXT: }
// ASYNC-ERRORNONOPTIONALRESULT-NEXT: }
// ASYNC-ERRORNONOPTIONALRESULT-NEXT: }
// ASYNC-ERRORNONOPTIONALRESULT: func errorNonOptionalResult() async throws -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-CUSTOMERROR %s
func customError(completion: (String?, CustomError?) -> Void) { }
// ASYNC-CUSTOMERROR: {
// ASYNC-CUSTOMERROR-NEXT: Task {
// ASYNC-CUSTOMERROR-NEXT: do {
// ASYNC-CUSTOMERROR-NEXT: let result = try await customError()
// ASYNC-CUSTOMERROR-NEXT: completion(result, nil)
// ASYNC-CUSTOMERROR-NEXT: } catch {
// ASYNC-CUSTOMERROR-NEXT: completion(nil, error as! CustomError)
// ASYNC-CUSTOMERROR-NEXT: }
// ASYNC-CUSTOMERROR-NEXT: }
// ASYNC-CUSTOMERROR-NEXT: }
// ASYNC-CUSTOMERROR: func customError() async throws -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ALIAS %s
func alias(completion: SomeCallback) { }
// ASYNC-ALIAS: {
// ASYNC-ALIAS-NEXT: Task {
// ASYNC-ALIAS-NEXT: let result = await alias()
// ASYNC-ALIAS-NEXT: completion(result)
// ASYNC-ALIAS-NEXT: }
// ASYNC-ALIAS-NEXT: }
// ASYNC-ALIAS: func alias() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-NESTEDALIAS %s
func nestedAlias(completion: NestedAliasCallback) { }
// ASYNC-NESTEDALIAS: {
// ASYNC-NESTEDALIAS-NEXT: Task {
// ASYNC-NESTEDALIAS-NEXT: let result = await nestedAlias()
// ASYNC-NESTEDALIAS-NEXT: completion(result)
// ASYNC-NESTEDALIAS-NEXT: }
// ASYNC-NESTEDALIAS-NEXT: }
// ASYNC-NESTEDALIAS: func nestedAlias() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLERESULT %s
func simpleResult(completion: (Result<String, Never>) -> Void) { }
// ASYNC-SIMPLERESULT: {
// ASYNC-SIMPLERESULT-NEXT: Task {
// ASYNC-SIMPLERESULT-NEXT: let result = await simpleResult()
// ASYNC-SIMPLERESULT-NEXT: completion(.success(result))
// ASYNC-SIMPLERESULT-NEXT: }
// ASYNC-SIMPLERESULT-NEXT: }
// ASYNC-SIMPLERESULT: func simpleResult() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERRORRESULT %s
func errorResult(completion: (Result<String, Error>) -> Void) { }
// ASYNC-ERRORRESULT: {
// ASYNC-ERRORRESULT-NEXT: Task {
// ASYNC-ERRORRESULT-NEXT: do {
// ASYNC-ERRORRESULT-NEXT: let result = try await errorResult()
// ASYNC-ERRORRESULT-NEXT: completion(.success(result))
// ASYNC-ERRORRESULT-NEXT: } catch {
// ASYNC-ERRORRESULT-NEXT: completion(.failure(error))
// ASYNC-ERRORRESULT-NEXT: }
// ASYNC-ERRORRESULT-NEXT: }
// ASYNC-ERRORRESULT-NEXT: }
// ASYNC-ERRORRESULT: func errorResult() async throws -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-CUSTOMERRORRESULT %s
func customErrorResult(completion: (Result<String, CustomError>) -> Void) { }
// ASYNC-CUSTOMERRORRESULT: {
// ASYNC-CUSTOMERRORRESULT-NEXT: Task {
// ASYNC-CUSTOMERRORRESULT-NEXT: do {
// ASYNC-CUSTOMERRORRESULT-NEXT: let result = try await customErrorResult()
// ASYNC-CUSTOMERRORRESULT-NEXT: completion(.success(result))
// ASYNC-CUSTOMERRORRESULT-NEXT: } catch {
// ASYNC-CUSTOMERRORRESULT-NEXT: completion(.failure(error as! CustomError))
// ASYNC-CUSTOMERRORRESULT-NEXT: }
// ASYNC-CUSTOMERRORRESULT-NEXT: }
// ASYNC-CUSTOMERRORRESULT-NEXT: }
// ASYNC-CUSTOMERRORRESULT: func customErrorResult() async throws -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ALIASRESULT %s
func aliasedResult(completion: SomeResultCallback) { }
// ASYNC-ALIASRESULT: {
// ASYNC-ALIASRESULT-NEXT: Task {
// ASYNC-ALIASRESULT-NEXT: do {
// ASYNC-ALIASRESULT-NEXT: let result = try await aliasedResult()
// ASYNC-ALIASRESULT-NEXT: completion(.success(result))
// ASYNC-ALIASRESULT-NEXT: } catch {
// ASYNC-ALIASRESULT-NEXT: completion(.failure(error as! CustomError))
// ASYNC-ALIASRESULT-NEXT: }
// ASYNC-ALIASRESULT-NEXT: }
// ASYNC-ALIASRESULT-NEXT: }
// ASYNC-ALIASRESULT: func aliasedResult() async throws -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MANY %s
func many(_ completion: (String, Int) -> Void) { }
// MANY: {
// MANY-NEXT: Task {
// MANY-NEXT: let result = await many()
// MANY-NEXT: completion(result.0, result.1)
// MANY-NEXT: }
// MANY-NEXT: }
// MANY: func many() async -> (String, Int) { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-SINGLE %s
func optionalSingle(completion: (String?) -> Void) { }
// OPTIONAL-SINGLE: {
// OPTIONAL-SINGLE-NEXT: Task {
// OPTIONAL-SINGLE-NEXT: let result = await optionalSingle()
// OPTIONAL-SINGLE-NEXT: completion(result)
// OPTIONAL-SINGLE-NEXT: }
// OPTIONAL-SINGLE-NEXT: }
// OPTIONAL-SINGLE: func optionalSingle() async -> String? { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MANY-OPTIONAL %s
func manyOptional(_ completion: (String?, Int?) -> Void) { }
// MANY-OPTIONAL: {
// MANY-OPTIONAL-NEXT: Task {
// MANY-OPTIONAL-NEXT: let result = await manyOptional()
// MANY-OPTIONAL-NEXT: completion(result.0, result.1)
// MANY-OPTIONAL-NEXT: }
// MANY-OPTIONAL-NEXT: }
// MANY-OPTIONAL: func manyOptional() async -> (String?, Int?) { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MIXED %s
func mixed(_ completion: (String?, Int) -> Void) { }
// MIXED: {
// MIXED-NEXT: Task {
// MIXED-NEXT: let result = await mixed()
// MIXED-NEXT: completion(result.0, result.1)
// MIXED-NEXT: }
// MIXED-NEXT: }
// MIXED: func mixed() async -> (String?, Int) { }
// RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
func mixedOptionalError(_ completion: (String?, Int, Error?) -> Void) { }
// MIXED-OPTIONAL-ERROR: {
// MIXED-OPTIONAL-ERROR-NEXT: Task {
// MIXED-OPTIONAL-ERROR-NEXT: do {
// MIXED-OPTIONAL-ERROR-NEXT: let result = try await mixedOptionalError()
// MIXED-OPTIONAL-ERROR-NEXT: completion(result.0, result.1, nil)
// MIXED-OPTIONAL-ERROR-NEXT: } catch {
// MIXED-OPTIONAL-ERROR-NEXT: completion(nil, <#Int#>, error)
// MIXED-OPTIONAL-ERROR-NEXT: }
// MIXED-OPTIONAL-ERROR-NEXT: }
// MIXED-OPTIONAL-ERROR-NEXT: }
// MIXED-OPTIONAL-ERROR: func mixedOptionalError() async throws -> (String, Int) { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MIXED-ERROR %s
func mixedError(_ completion: (String?, Int, Error) -> Void) { }
// MIXED-ERROR: {
// MIXED-ERROR-NEXT: Task {
// MIXED-ERROR-NEXT: let result = await mixedError()
// MIXED-ERROR-NEXT: completion(result.0, result.1, result.2)
// MIXED-ERROR-NEXT: }
// MIXED-ERROR-NEXT: }
// MIXED-ERROR: func mixedError() async -> (String?, Int, Error) { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=GENERIC %s
func generic<T, R>(completion: (T, R) -> Void) { }
// GENERIC: {
// GENERIC-NEXT: Task {
// GENERIC-NEXT: let result: (T, R) = await generic()
// GENERIC-NEXT: completion(result.0, result.1)
// GENERIC-NEXT: }
// GENERIC-NEXT: }
// GENERIC: func generic<T, R>() async -> (T, R) { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=GENERIC-RESULT %s
func genericResult<T>(completion: (T?, Error?) -> Void) where T: Numeric { }
// GENERIC-RESULT: {
// GENERIC-RESULT-NEXT: Task {
// GENERIC-RESULT-NEXT: do {
// GENERIC-RESULT-NEXT: let result: T = try await genericResult()
// GENERIC-RESULT-NEXT: completion(result, nil)
// GENERIC-RESULT-NEXT: } catch {
// GENERIC-RESULT-NEXT: completion(nil, error)
// GENERIC-RESULT-NEXT: }
// GENERIC-RESULT-NEXT: }
// GENERIC-RESULT-NEXT: }
// GENERIC-RESULT: func genericResult<T>() async throws -> T where T: Numeric { }
// FIXME: This doesn't compile after refactoring because we aren't using the generic argument `E` in the async method (SR-14560)
// RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=GENERIC-ERROR %s
func genericError<E>(completion: (String?, E?) -> Void) where E: Error { }
// GENERIC-ERROR: {
// GENERIC-ERROR-NEXT: Task {
// GENERIC-ERROR-NEXT: do {
// GENERIC-ERROR-NEXT: let result: String = try await genericError()
// GENERIC-ERROR-NEXT: completion(result, nil)
// GENERIC-ERROR-NEXT: } catch {
// GENERIC-ERROR-NEXT: completion(nil, error as! E)
// GENERIC-ERROR-NEXT: }
// GENERIC-ERROR-NEXT: }
// GENERIC-ERROR-NEXT: }
// GENERIC-ERROR: func genericError<E>() async throws -> String where E: Error { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OTHER-NAME %s
func otherName(execute: (String) -> Void) { }
// OTHER-NAME: {
// OTHER-NAME-NEXT: Task {
// OTHER-NAME-NEXT: let result = await otherName()
// OTHER-NAME-NEXT: execute(result)
// OTHER-NAME-NEXT: }
// OTHER-NAME-NEXT: }
// OTHER-NAME: func otherName() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT_ARGS %s
func defaultArgs(a: Int, b: Int = 10, completion: (String) -> Void) { }
// DEFAULT_ARGS: {
// DEFAULT_ARGS-NEXT: Task {
// DEFAULT_ARGS-NEXT: let result = await defaultArgs(a: a, b: b)
// DEFAULT_ARGS-NEXT: completion(result)
// DEFAULT_ARGS-NEXT: }
// DEFAULT_ARGS-NEXT: }
// DEFAULT_ARGS: func defaultArgs(a: Int, b: Int = 10) async -> String { }
struct MyStruct {
var someVar: (Int) -> Void {
get {
return {_ in }
}
// RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):5
set (completion) {
}
}
init() { }
// RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):3
init(completion: (String) -> Void) { }
func retSelf() -> MyStruct { return self }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):10 | %FileCheck -check-prefix=MODIFIERS %s
public func publicMember(completion: (String) -> Void) { }
// MODIFIERS: public func publicMember() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=STATIC %s
static func staticMember(completion: (String) -> Void) { }
// STATIC: static func staticMember() async -> String { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):11 | %FileCheck -check-prefix=DEPRECATED %s
@available(*, deprecated, message: "Deprecated")
private func deprecated(completion: (String) -> Void) { }
// DEPRECATED: @available(*, deprecated, message: "Deprecated")
// DEPRECATED-NEXT: private func deprecated() async -> String { }
}
func retStruct() -> MyStruct { return MyStruct() }
protocol MyProtocol {
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=PROTO-MEMBER %s
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=PROTO-MEMBER %s
func protoMember(completion: (String) -> Void)
// PROTO-MEMBER: func protoMember() async -> String{{$}}
}
// RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-COMPLETION %s
func nonCompletion(a: Int) { }
// NON-COMPLETION: func nonCompletion(a: Int) async { }
// RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MULTIPLE-RESULTS %s
func multipleResults(completion: (Result<String, Error>, Result<String, Error>) -> Void) { }
// MULTIPLE-RESULTS: func multipleResults(completion: (Result<String, Error>, Result<String, Error>) -> Void) async { }
// RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NOT-LAST %s
func completionNotLast(completion: (String) -> Void, a: Int) { }
// NOT-LAST: func completionNotLast(completion: (String) -> Void, a: Int) async { }
// RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-VOID %s
func nonVoid(completion: (String) -> Void) -> Int { return 0 }
// NON-VOID: func nonVoid(completion: (String) -> Void) async -> Int { return 0 }
// RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=COMPLETION-NON-VOID %s
func completionNonVoid(completion: (String) -> Int) -> Void { }
// COMPLETION-NON-VOID: func completionNonVoid(completion: (String) -> Int) async -> Void { }
// RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1
func alreadyThrows(completion: (String) -> Void) throws { }
// RUN: not %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+2):1
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=AUTO-CLOSURE %s
func noParamAutoclosure(completion: @autoclosure () -> Void) { }
// AUTO-CLOSURE: func noParamAutoclosure(completion: @autoclosure () -> Void) async { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix BLOCK-CONVENTION %s
func blockConvention(completion: @convention(block) () -> Void) { }
// BLOCK-CONVENTION: func blockConvention() async { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix C-CONVENTION %s
func cConvention(completion: @convention(c) () -> Void) { }
// C-CONVENTION: func cConvention() async { }
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-HANDLER %s
func voidCompletion(completion: (Void) -> Void) {}
// VOID-HANDLER: {
// VOID-HANDLER-NEXT: Task {
// VOID-HANDLER-NEXT: await voidCompletion()
// VOID-HANDLER-NEXT: completion(())
// VOID-HANDLER-NEXT: }
// VOID-HANDLER-NEXT: }
// VOID-HANDLER: func voidCompletion() async {}
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix OPT-VOID-AND-ERROR-HANDLER %s
func optVoidAndErrorCompletion(completion: (Void?, Error?) -> Void) {}
// OPT-VOID-AND-ERROR-HANDLER: {
// OPT-VOID-AND-ERROR-HANDLER-NEXT: Task {
// OPT-VOID-AND-ERROR-HANDLER-NEXT: do {
// OPT-VOID-AND-ERROR-HANDLER-NEXT: try await optVoidAndErrorCompletion()
// OPT-VOID-AND-ERROR-HANDLER-NEXT: completion((), nil)
// OPT-VOID-AND-ERROR-HANDLER-NEXT: } catch {
// OPT-VOID-AND-ERROR-HANDLER-NEXT: completion(nil, error)
// OPT-VOID-AND-ERROR-HANDLER-NEXT: }
// OPT-VOID-AND-ERROR-HANDLER-NEXT: }
// OPT-VOID-AND-ERROR-HANDLER-NEXT: }
// OPT-VOID-AND-ERROR-HANDLER: func optVoidAndErrorCompletion() async throws {}
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix TOO-MUCH-VOID-AND-ERROR-HANDLER %s
func tooMuchVoidAndErrorCompletion(completion: (Void?, Void?, Error?) -> Void) {}
// TOO-MUCH-VOID-AND-ERROR-HANDLER: {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: Task {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: do {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: try await tooMuchVoidAndErrorCompletion()
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: completion((), (), nil)
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } catch {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: completion(nil, nil, error)
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: }
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: }
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: }
// TOO-MUCH-VOID-AND-ERROR-HANDLER: func tooMuchVoidAndErrorCompletion() async throws {}
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-PROPER-AND-ERROR-HANDLER %s
func tooVoidProperAndErrorCompletion(completion: (Void?, String?, Error?) -> Void) {}
// VOID-PROPER-AND-ERROR-HANDLER: {
// VOID-PROPER-AND-ERROR-HANDLER-NEXT: Task {
// VOID-PROPER-AND-ERROR-HANDLER-NEXT: do {
// VOID-PROPER-AND-ERROR-HANDLER-NEXT: let result = try await tooVoidProperAndErrorCompletion()
// VOID-PROPER-AND-ERROR-HANDLER-NEXT: completion((), result.1, nil)
// VOID-PROPER-AND-ERROR-HANDLER-NEXT: } catch {
// VOID-PROPER-AND-ERROR-HANDLER-NEXT: completion(nil, nil, error)
// VOID-PROPER-AND-ERROR-HANDLER-NEXT: }
// VOID-PROPER-AND-ERROR-HANDLER-NEXT: }
// VOID-PROPER-AND-ERROR-HANDLER-NEXT: }
// VOID-PROPER-AND-ERROR-HANDLER: func tooVoidProperAndErrorCompletion() async throws -> (Void, String) {}
// RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
func voidAndErrorCompletion(completion: (Void, Error?) -> Void) {}
// VOID-AND-ERROR-HANDLER: {
// VOID-AND-ERROR-HANDLER-NEXT: Task {
// VOID-AND-ERROR-HANDLER-NEXT: do {
// VOID-AND-ERROR-HANDLER-NEXT: try await voidAndErrorCompletion()
// VOID-AND-ERROR-HANDLER-NEXT: completion((), nil)
// VOID-AND-ERROR-HANDLER-NEXT: } catch {
// VOID-AND-ERROR-HANDLER-NEXT: completion((), error)
// VOID-AND-ERROR-HANDLER-NEXT: }
// VOID-AND-ERROR-HANDLER-NEXT: }
// VOID-AND-ERROR-HANDLER-NEXT: }
// VOID-AND-ERROR-HANDLER: func voidAndErrorCompletion() async throws {}
// 2. Check that the various ways to call a function (and the positions the
// refactoring is called from) are handled correctly
class MyClass {}
func simpleClassParam(completion: (MyClass) -> Void) { }
// TODO: We cannot check that the refactored code compiles because 'simple' and
// friends aren't refactored when only invoking the refactoring on this function.
// TODO: When changing this line to %refactor-check-compiles, 'swift-refactor'
// is crashing in '-dump-rewritten'. This is because
// 'swift-refactor -dump-rewritten' is removing 'RUN' lines. After removing
// those lines, we are trying to remove the function body, using its length
// before the 'RUN' lines were removed, thus pointing past the end of the
// rewritten buffer.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL %s
func testSimple() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+4):3 | %FileCheck -check-prefix=CALL %s
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):10
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):24
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):28
simple(completion: { str in
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):5
print("with label")
})
}
// CALL: let str = await simple(){{$}}
// CALL-NEXT: //
// CALL-NEXT: {{^}} print("with label")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NOLABEL %s
func testSimpleWithoutLabel() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=CALL-NOLABEL %s
simpleWithoutLabel({ str in
print("without label")
})
}
// CALL-NOLABEL: let str = await simpleWithoutLabel(){{$}}
// CALL-NOLABEL-NEXT: {{^}}print("without label")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-WRAPPED %s
func testWrapped() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=CALL-WRAPPED %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 | %FileCheck -check-prefix=CALL-WRAPPED %s
((simple))(completion: { str in
print("wrapped call")
})
}
// CALL-WRAPPED: let str = await ((simple))(){{$}}
// CALL-WRAPPED-NEXT: {{^}}print("wrapped call")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TRAILING %s
func testTrailing() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=TRAILING %s
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):12
simple { str in
print("trailing")
}
}
// TRAILING: let str = await simple(){{$}}
// TRAILING-NEXT: {{^}}print("trailing")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TRAILING-PARENS %s
func testTrailingParens() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=TRAILING-PARENS %s
simple() { str in
print("trailing with parens")
}
}
// TRAILING-PARENS: let str = await simple(){{$}}
// TRAILING-PARENS-NEXT: {{^}}print("trailing with parens")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=TRAILING-WRAPPED %s
func testTrailingWrapped() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):5 | %FileCheck -check-prefix=TRAILING-WRAPPED %s
((simple)) { str in
print("trailing with wrapped call")
}
}
// TRAILING-WRAPPED: let str = await ((simple))(){{$}}
// TRAILING-WRAPPED-NEXT: {{^}}print("trailing with wrapped call")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-ARG %s
func testCallArg() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):3 | %FileCheck -check-prefix=CALL-ARG %s
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):17
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):20
simpleWithArg(a: 10) { str in
print("with arg")
}
}
// CALL-ARG: let str = await simpleWithArg(a: 10){{$}}
// CALL-ARG-NEXT: {{^}}print("with arg")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=MANY-CALL %s
func testMany() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MANY-CALL %s
many { str, num in
print("many")
}
}
// MANY-CALL: let (str, num) = await many(){{$}}
// MANY-CALL-NEXT: {{^}}print("many")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MEMBER-CALL %s
func testMember() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):15 | %FileCheck -check-prefix=MEMBER-CALL %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MEMBER-CALL %s
retStruct().publicMember { str in
print("call on member")
}
}
// MEMBER-CALL: let str = await retStruct().publicMember(){{$}}
// MEMBER-CALL-NEXT: {{^}}print("call on member")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MEMBER-CALL2 %s
func testMember2() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):25 | %FileCheck -check-prefix=MEMBER-CALL2 %s
retStruct().retSelf().publicMember { str in
print("call on member 2")
}
}
// MEMBER-CALL2: let str = await retStruct().retSelf().publicMember(){{$}}
// MEMBER-CALL2-NEXT: {{^}}print("call on member 2")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MEMBER-PARENS %s
func testMemberParens() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):3 | %FileCheck -check-prefix=MEMBER-PARENS %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):5 | %FileCheck -check-prefix=MEMBER-PARENS %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):15 | %FileCheck -check-prefix=MEMBER-PARENS %s
(((retStruct().retSelf()).publicMember)) { str in
print("call on member parens")
}
}
// MEMBER-PARENS: let str = await (((retStruct().retSelf()).publicMember))(){{$}}
// MEMBER-PARENS-NEXT: {{^}}print("call on member parens")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=SKIP-ASSIGN-FUNC %s
func testSkipAssign() {
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):13
let _: Void = simple { str in
print("assigned")
}
}
// SKIP-ASSIGN-FUNC: {{^}}func testSkipAssign() async {
// SKIP-ASSIGN-FUNC: let _: Void = simple { str in{{$}}
// SKIP-ASSIGN-FUNC-NEXT: print("assigned"){{$}}
// SKIP-ASSIGN-FUNC-NEXT: }{{$}}
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=SKIP-AUTOCLOSURE-FUNC %s
func testSkipAutoclosure() {
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3
noParamAutoclosure(completion: print("autoclosure"))
}
// SKIP-AUTOCLOSURE-FUNC: {{^}}func testSkipAutoclosure() async {
// SKIP-AUTOCLOSURE-FUNC: noParamAutoclosure(completion: print("autoclosure")){{$}}
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=EMPTY-CAPTURE %s
func testEmptyCapture() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=EMPTY-CAPTURE %s
simple { [] str in
print("closure with empty capture list")
}
}
// EMPTY-CAPTURE: let str = await simple(){{$}}
// EMPTY-CAPTURE-NEXT: {{^}}print("closure with empty capture list")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CAPTURE %s
func testCapture() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=CAPTURE %s
let myClass = MyClass()
simpleClassParam { [unowned myClass] str in
print("closure with capture list \(myClass)")
}
}
// CAPTURE: let str = await simpleClassParam(){{$}}
// CAPTURE-NEXT: {{^}}print("closure with capture list \(myClass)")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefixes=NOT-HANDLER-FUNC %s
func testNotCompletionHandler() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NOT-HANDLER %s
otherName(execute: { str in
print("otherName")
})
}
// NOT-HANDLER-FUNC: otherName(execute: { str in{{$}}
// NOT-HANDLER-FUNC-NEXT: print("otherName"){{$}}
// NOT-HANDLER-FUNC-NEXT: }){{$}}
// NOT-HANDLER: let str = await otherName(){{$}}
// NOT-HANDLER-NEXT: {{^}}print("otherName")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT-ARGS-MISSING %s
func testDefaultArgsMissing() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=DEFAULT-ARGS-MISSING %s
defaultArgs(a: 1) { str in
print("defaultArgs missing")
}
}
// DEFAULT-ARGS-MISSING: let str = await defaultArgs(a: 1){{$}}
// DEFAULT-ARGS-MISSING-NEXT: {{^}}print("defaultArgs missing")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT-ARGS-CALL %s
func testDefaultArgs() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=DEFAULT-ARGS-CALL %s
defaultArgs(a: 1, b: 2) { str in
print("defaultArgs")
}
}
// DEFAULT-ARGS-CALL: let str = await defaultArgs(a: 1, b: 2){{$}}
// DEFAULT-ARGS-CALL-NEXT: {{^}}print("defaultArgs")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=BLOCK-CONVENTION-CALL %s
func testBlockConvention() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BLOCK-CONVENTION-CALL %s
blockConvention {
print("blockConvention")
}
}
// BLOCK-CONVENTION-CALL: await blockConvention(){{$}}
// BLOCK-CONVENTION-CALL-NEXT: {{^}}print("blockConvention")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=C-CONVENTION-CALL %s
func testCConvention() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=C-CONVENTION-CALL %s
cConvention {
print("cConvention")
}
}
// C-CONVENTION-CALL: await cConvention(){{$}}
// C-CONVENTION-CALL-NEXT: {{^}}print("cConvention")
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL %s
func testVoidAndError() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL %s
optVoidAndErrorCompletion { v, err in
print("opt void and error completion \(v)")
}
}
// VOID-AND-ERROR-CALL: try await optVoidAndErrorCompletion(){{$}}
// VOID-AND-ERROR-CALL-NEXT: {{^}}print("opt void and error completion \(<#v#>)"){{$}}
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL2 %s
func testVoidAndError2() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL2 %s
optVoidAndErrorCompletion { _, err in
print("opt void and error completion 2")
}
}
// VOID-AND-ERROR-CALL2: try await optVoidAndErrorCompletion(){{$}}
// VOID-AND-ERROR-CALL2-NEXT: {{^}}print("opt void and error completion 2"){{$}}
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL3 %s
func testVoidAndError3() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL3 %s
tooMuchVoidAndErrorCompletion { v, v1, err in
print("void and error completion 3")
}
}
// VOID-AND-ERROR-CALL3: try await tooMuchVoidAndErrorCompletion(){{$}}
// VOID-AND-ERROR-CALL3-NEXT: {{^}}print("void and error completion 3"){{$}}
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL4 %s
func testVoidAndError4() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=VOID-AND-ERROR-CALL4 %s
voidAndErrorCompletion { v, err in
print("void and error completion \(v)")
}
}
// VOID-AND-ERROR-CALL4: try await voidAndErrorCompletion(){{$}}
// VOID-AND-ERROR-CALL4-NEXT: {{^}}print("void and error completion \(<#v#>)"){{$}}
func testPreserveComments() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=PRESERVE-COMMENTS %s
simpleWithArg(/*hello*/ a: /*a*/5) { str in
// b1
// b2
print("1")
// c
print("2") /*
d1
d2
*/
if .random() {
// e
}
/* f1 */
/* f2 */} // don't pick this up
}
// PRESERVE-COMMENTS: let str = await simpleWithArg(/*hello*/ a: /*a*/5)
// PRESERVE-COMMENTS-NEXT: // b1
// PRESERVE-COMMENTS-NEXT: // b2
// PRESERVE-COMMENTS-NEXT: print("1")
// PRESERVE-COMMENTS-NEXT: // c
// PRESERVE-COMMENTS-NEXT: print("2")
// PRESERVE-COMMENTS-NEXT: /*
// PRESERVE-COMMENTS-NEXT: d1
// PRESERVE-COMMENTS-NEXT: d2
// PRESERVE-COMMENTS-NEXT: */
// PRESERVE-COMMENTS-NEXT: if .random() {
// PRESERVE-COMMENTS-NEXT: // e
// PRESERVE-COMMENTS-NEXT: }
// PRESERVE-COMMENTS-NEXT: /* f1 */
// PRESERVE-COMMENTS-NEXT: /* f2 */{{$}}
// PRESERVE-COMMENTS-NOT: }{{$}}
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=PRESERVE-COMMENTS-ERROR %s
func testPreserveComments2() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=PRESERVE-COMMENTS-ERROR %s
errorOnly { err in
// a
if err != nil {
// b
print("oh no") // c
/* d */
return /* e */
}
if err != nil {
// f
print("fun")
// g
}
// h
print("good times") // i
}
}
// PRESERVE-COMMENTS-ERROR: do {
// PRESERVE-COMMENTS-ERROR-NEXT: try await errorOnly()
// PRESERVE-COMMENTS-ERROR-NEXT: // a
// PRESERVE-COMMENTS-ERROR-NEXT: // h
// PRESERVE-COMMENTS-ERROR-NEXT: print("good times")
// PRESERVE-COMMENTS-ERROR-NEXT: // i
// PRESERVE-COMMENTS-ERROR: } catch let err {
// PRESERVE-COMMENTS-ERROR-NEXT: // b
// PRESERVE-COMMENTS-ERROR-NEXT: print("oh no")
// PRESERVE-COMMENTS-ERROR-NEXT: // c
// PRESERVE-COMMENTS-ERROR-NEXT: /* d */
// PRESERVE-COMMENTS-ERROR-NEXT: /* e */
// PRESERVE-COMMENTS-ERROR-NEXT: // f
// PRESERVE-COMMENTS-ERROR-NEXT: print("fun")
// PRESERVE-COMMENTS-ERROR-NEXT: // g
// PRESERVE-COMMENTS-ERROR-NEXT: {{ }}
// PRESERVE-COMMENTS-ERROR-NEXT: }
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=PRESERVE-TRAILING-COMMENT-FN %s
func testPreserveComments3() {
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=PRESERVE-TRAILING-COMMENT-CALL %s
simple { s in
print(s)
}
// make sure we pickup this trailing comment if we're converting the function, but not the call
}
// PRESERVE-TRAILING-COMMENT-FN: func testPreserveComments3() async {
// PRESERVE-TRAILING-COMMENT-FN-NEXT: //
// PRESERVE-TRAILING-COMMENT-FN-NEXT: let s = await simple()
// PRESERVE-TRAILING-COMMENT-FN-NEXT: print(s)
// PRESERVE-TRAILING-COMMENT-FN-NEXT: // make sure we pickup this trailing comment if we're converting the function, but not the call
// PRESERVE-TRAILING-COMMENT-FN-NEXT: }
// PRESERVE-TRAILING-COMMENT-CALL: let s = await simple()
// PRESERVE-TRAILING-COMMENT-CALL-NEXT: print(s)
// PRESERVE-TRAILING-COMMENT-CALL-NOT: // make sure we pickup this trailing comment if we're converting the function, but not the call
class TestConvertFunctionWithCallToFunctionsWithSpecialName {
required init() {}
subscript(index: Int) -> Int { return index }
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):3
static func example() -> Self {
let x = self.init()
_ = x[1]
return x
}
}
// rdar://78781061
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOR-IN-WHERE %s
func testForInWhereRefactoring() {
let arr: [String] = []
for str in arr where str.count != 0 {
simple { res in
print(res)
}
}
}
// FOR-IN-WHERE: func testForInWhereRefactoring() async {
// FOR-IN-WHERE-NEXT: let arr: [String] = []
// FOR-IN-WHERE-NEXT: for str in arr where str.count != 0 {
// FOR-IN-WHERE-NEXT: let res = await simple()
// FOR-IN-WHERE-NEXT: print(res)
// FOR-IN-WHERE-NEXT: }
// FOR-IN-WHERE-NEXT: }
| 37291d190b7969c46c0c1077fa1b9f5a | 48.090183 | 165 | 0.692696 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/Interpreter/SDK/Foundation_bridge.swift | apache-2.0 | 17 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift %s -import-objc-header %S/Inputs/Foundation_bridge.h -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
// CHECK: 17 bridges to 17
do {
var i = 17
let obj = _bridgeAnythingToObjectiveC(i)
print("\(i) bridges to \(obj.description!)")
}
// CHECK: 3.14159 bridges to 3.14159
do {
var d = 3.14159
let obj = _bridgeAnythingToObjectiveC(d)
print("\(d) bridges to \(obj.description!)")
}
// CHECK: Hello, world! bridges to Hello, world!
do {
var s = "Hello, world!"
let obj = _bridgeAnythingToObjectiveC(s)
print("\(s) bridges to \(obj.description!)")
}
// CHECK: int array bridges to (
// CHECK: 1
// CHECK: 2
// CHECK: 3
// CHECK: )
do {
var a = [1, 2, 3]
let obj = _bridgeAnythingToObjectiveC(a)
print("int array bridges to \(obj.description!)")
}
// CHECK: uint array bridges to (
// CHECK: 1
// CHECK: 2
// CHECK: 3
// CHECK: )
do {
var aui: [UInt] = [1, 2, 3]
let obj = _bridgeAnythingToObjectiveC(aui)
print("uint array bridges to \(obj.description!)")
}
// CHECK: float array bridges to (
// CHECK: 1.5
// CHECK: 2.5
// CHECK: 3.5
// CHECK: )
do {
var af: [Float] = [1.5, 2.5, 3.5]
let obj = _bridgeAnythingToObjectiveC(af)
print("float array bridges to \(obj.description!)")
}
// CHECK: double array bridges to (
// CHECK: 1.5
// CHECK: 2.5
// CHECK: 3.5
// CHECK: )
do {
var ad = [1.5, 2.5, 3.5]
let obj = _bridgeAnythingToObjectiveC(ad)
print("double array bridges to \(obj.description!)")
}
// CHECK: string array bridges to (
// CHECK: Hello
// CHECK: Swift
// CHECK: World
// CHECK: )
do {
var a2 = ["Hello", "Swift", "World"]
let obj = _bridgeAnythingToObjectiveC(a2)
print("string array bridges to \(obj.description!)")
}
// CHECK: bool array bridges to (
// CHECK: 0
// CHECK: 1
// CHECK: 0
// CHECK: )
do {
var ab = [false, true, false]
let obj = _bridgeAnythingToObjectiveC(ab)
print("bool array bridges to \(obj.description!)")
}
// CHECK: tuple array bridges to (
// CHECK: (1, 1)
// CHECK: (1, 1)
// CHECK: (1, 2)
// CHECK: )
do {
var a3 = [(1, 1), (1, 1), (1, 2)]
let obj = _bridgeAnythingToObjectiveC(a3)
print("tuple array bridges to \(obj.description!)")
}
// CHECK: dictionary bridges to {
// CHECK-NEXT: 2 = World;
// CHECK-NEXT: 1 = Hello;
// CHECK-NEXT: }
do {
var dict: Dictionary<NSNumber, NSString> = [1: "Hello", 2: "World"]
let obj = _bridgeAnythingToObjectiveC(dict)
print("dictionary bridges to \(obj.description!)")
}
// CHECK: dictionary bridges to {
// CHECK-NEXT: 2 = World;
// CHECK-NEXT: 1 = Hello;
// CHECK-NEXT: }
do {
var dict2 = [1: "Hello", 2: "World"]
let obj = _bridgeAnythingToObjectiveC(dict2)
print("dictionary bridges to \(obj.description!)")
}
// CHECK: dictionary bridges to {
// CHECK-NEXT: 2 = "(\"World\", 2)";
// CHECK-NEXT: 1 = "(\"Hello\", 1)";
// CHECK-NEXT: }
do {
var dict3 = [1: ("Hello", 1), 2: ("World", 2)]
let obj = _bridgeAnythingToObjectiveC(dict3)
print("dictionary bridges to \(obj)")
}
// Check dictionary bridging.
var propListStr: NSString = "\"Hello\" = 1;\n\n\"World\" = 2;"
var dict4 = propListStr.propertyListFromStringsFileFormat()!
var hello: NSString = "Hello"
var world: NSString = "World"
// Print out the keys. We only check one of these because the order is
// nondeterministic.
// CHECK: Hello
for key in dict4.keys {
print(key.description)
}
// CHECK: Hello: 1
print("Hello: \(dict4[hello]!)")
// CHECK: World: 2
print("World: \(dict4[world]!)")
// <rdar://problem/17035548> bridging array of blocks.
class Foo: NSObject {
func foo() { print("Foo.foo()") }
lazy var closures: [(@convention(block) () -> Void)] = [self.foo]
func invoke() {
closures[0]()
}
}
// CHECK: Foo.foo()
Foo().invoke()
// <rdar://problem/19734621> Dealing with APIs that have been updated not to return nil in newer SDKs
// CHECK: getNullable: nil
print("getNullable: \(getNullable())")
// CHECK: getNonnull: []
print("getNonnull: \(getNonnull())")
// CHECK: final
print("final")
| e18e6391086b5073a36c80ddfb62ee90 | 23.005682 | 101 | 0.613254 | false | false | false | false |
volodg/iAsync.utils | refs/heads/master | Sources/Extensions/Data+ToString.swift | mit | 1 | //
// Data+ToString.swift
// iAsync_utils
//
// Created by Vladimir Gorbenko on 06.06.14.
// Copyright © 2014 EmbeddedSources. All rights reserved.
//
import Foundation
extension Data {
public func toString() -> String? {
return withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: count)
buffer.assign(from: bytes, count: count)
let result = String(bytesNoCopy: buffer, length: count, encoding: .utf8, freeWhenDone: true)
return result
}
}
func hexString() -> String {
let bytesPointer = self.withUnsafeBytes { bytes in
return UnsafeBufferPointer<UInt8>(start: UnsafePointer(bytes), count: self.count)
}
let hexBytes = bytesPointer.map { return String(format: "%02hhx", $0) }
return hexBytes.joined()
}
public func apnsToString() -> String {
let result = hexString()
return result
}
}
| ef8aa4519d6fc3bafa9caf864d5baedd | 25.447368 | 104 | 0.625871 | false | false | false | false |
cloudofpoints/Pachinko | refs/heads/master | Pachinko/Model/Feature/FeatureVersion.swift | bsd-3-clause | 1 | //
// FeatureVersion.swift
// Pachinko
//
// Created by Tim Antrobus on 15/11/2015.
// Copyright © 2015 cloudofpoints. All rights reserved.
//
import Foundation
public func ==(lhs: FeatureVersion, rhs: FeatureVersion) -> Bool {
return lhs.hashValue == rhs.hashValue
}
public func <(lhs: FeatureVersion, rhs: FeatureVersion) -> Bool {
return lhs.major < rhs.major && lhs.minor < rhs.minor && lhs.patch < rhs.patch
}
public struct FeatureVersion: Hashable, Comparable {
public let major: Int
public let minor: Int
public let patch: Int
public var hashValue: Int {
return (31 &* major.hashValue) &+ minor.hashValue &+ patch.hashValue
}
public init(major: Int, minor: Int, patch: Int) {
self.major = major
self.minor = minor
self.patch = patch
}
public init?(version: String){
guard let versionTokens: [String] = version.componentsSeparatedByString(".") else {
return nil
}
if versionTokens.count != 3 {
return nil
}
guard let majorNum = Int(versionTokens[0]),
minorNum = Int(versionTokens[1]),
patchNum = Int(versionTokens[2]) else {
return nil
}
self.major = majorNum
self.minor = minorNum
self.patch = patchNum
}
public init?(major: String, minor: String, patch: String) {
if let majorNum = Int(major), minorNum = Int(minor), patchNum = Int(patch) {
self.major = majorNum
self.minor = minorNum
self.patch = patchNum
} else {
return nil
}
}
public func description() -> String {
return "\(major).\(minor).\(patch)"
}
} | d43fb79a86d0b654625e958c86e5a6ce | 25.761194 | 91 | 0.569196 | false | false | false | false |
RamonGilabert/Wall | refs/heads/master | Source/Models/Post.swift | mit | 2 | import Foundation
public protocol PostConvertible {
var wallModel: Post { get }
}
public class Post {
public var id = 0
public var publishDate = ""
public var text = ""
public var liked = false
public var seen = false
public var group = ""
public var likeCount = 0
public var seenCount = 0
public var commentCount = 0
public var author: Author?
public var reusableIdentifier = PostTableViewCell.reusableIdentifier
public var media: [Media]
// MARK: - Initialization
public init(id: Int, text: String = "", publishDate: String, author: Author? = nil,
media: [Media] = [], reusableIdentifier: String? = nil) {
self.id = id
self.text = text
self.publishDate = publishDate
self.author = author
self.media = media
if let reusableIdentifier = reusableIdentifier {
self.reusableIdentifier = reusableIdentifier
}
}
}
// MARK: - PostConvertible
extension Post: PostConvertible {
public var wallModel: Post {
return self
}
}
| 07c5acf149ec91514eec31be38de7940 | 20.702128 | 85 | 0.671569 | false | false | false | false |
Agarunov/FetchKit | refs/heads/master | Tests/QueryProtocolTests.swift | bsd-2-clause | 1 | //
// QueryProtocolTests.swift
// FetchKit
//
// Created by Anton Agarunov on 15.06.17.
//
//
import CoreData
@testable import FetchKit
import XCTest
// swiftlint:disable force_cast force_try force_unwrapping
internal class QueryProtocolTests: FetchKitTests {
func testFindFirst() {
let user = try! User.findFirst()
.sorted(by: #keyPath(User.firstName))
.execute(in: context)
XCTAssertEqual(user!.id, 3)
XCTAssertEqual(user!.firstName, "Alex")
XCTAssertEqual(user!.lastName, "Finch")
}
func testFindAll() {
let all = try! User.findAll().execute(in: context)
XCTAssertEqual(all.count, 5)
}
func testFindRange() {
let users = try! User.findRange(0..<2)
.sorted(by: #keyPath(User.firstName))
.sorted(by: #keyPath(User.lastName))
.execute(in: context)
let alex = users[0]
let ivan = users[1]
XCTAssertEqual(alex.id, 3)
XCTAssertEqual(alex.firstName, "Alex")
XCTAssertEqual(alex.lastName, "Finch")
XCTAssertEqual(ivan.id, 0)
XCTAssertEqual(ivan.firstName, "Ivan")
XCTAssertEqual(ivan.lastName, "Ivanov")
}
func testDeleteAll() {
let deleteCount = try! User.deleteAll()
.where(#keyPath(User.firstName), equals: "John")
.execute(in: context)
let newCount = try! User.getCount().execute(in: context)
XCTAssertEqual(deleteCount, 2)
XCTAssertEqual(newCount, 3)
}
func testAggregate() {
let result = try! User.aggregate(property: #keyPath(User.id), function: "min:")
.execute(in: context)
XCTAssertEqual(result as! Int64, 0)
}
func testGetMin() {
let result = try! User.getMin(property: #keyPath(User.id))
.execute(in: context)
XCTAssertEqual(result as! Int64, 0)
}
func testGetMax() {
let result = try! User.getMax(property: #keyPath(User.id))
.execute(in: context)
XCTAssertEqual(result as! Int64, 4)
}
func testGetDistinct() {
let result = try! User.getDistinct()
.propertiesToFetch([\User.firstName])
.group(by: \User.firstName)
.execute(in: context)
let nsdicts = result.map { NSDictionary(dictionary: $0) }
let expected: [NSDictionary] =
[["firstName": "Alex"], ["firstName": "Ivan"], ["firstName": "Joe"], ["firstName": "John"]]
XCTAssertEqual(nsdicts, expected)
}
func testFetchResults() {
let resultsController = try! User.fetchResults()
.group(by: #keyPath(User.firstName))
.sorted(by: #keyPath(User.firstName))
.sorted(by: #keyPath(User.lastName))
.execute(in: context)
XCTAssertEqual(resultsController.fetchedObjects!.count, 5)
XCTAssertEqual(resultsController.sections!.count, 4)
}
}
| 83272feeb403c04b41b64f2b0d37d7b1 | 29.414141 | 103 | 0.58718 | false | true | false | false |
tzongw/ReactiveCocoa | refs/heads/master | ReactiveCocoa/Swift/Flatten.swift | mit | 1 | //
// Flatten.swift
// ReactiveCocoa
//
// Created by Neil Pankey on 11/30/15.
// Copyright © 2015 GitHub. All rights reserved.
//
import enum Result.NoError
/// Describes how multiple producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The producers should be merged, so that any value received on any of the
/// input producers will be forwarded immediately to the output producer.
///
/// The resulting producer will complete only when all inputs have completed.
case Merge
/// The producers should be concatenated, so that their values are sent in the
/// order of the producers themselves.
///
/// The resulting producer will complete only when all inputs have completed.
case Concat
/// Only the events from the latest input producer should be considered for
/// the output. Any producers received before that point will be disposed of.
///
/// The resulting producer will complete only when the producer-of-producers and
/// the latest producer has completed.
case Latest
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` or an active inner producer fails, the returned signal will
/// forward that failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalType where Value: SignalProducerType, Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If an active inner producer fails, the returned signal will forward that
/// failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalType where Value: SignalProducerType, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalType where Value: SignalProducerType, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Flattens the inner producers sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` or an active inner producer fails, the returned producer will
/// forward that failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If an active inner producer fails, the returned producer will forward that
/// failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerType where Value: SignalProducerType, Error == NoError, Value.Error == NoError {
/// Flattens the inner producers sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalProducerType where Value: SignalProducerType, Value.Error == NoError {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalType where Value: SignalType, Error == Value.Error {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` or an active inner signal emits an error, the returned
/// signal will forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalType where Value: SignalType, Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If an active inner signal emits an error, the returned signal will
/// forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalType where Value: SignalType, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalType where Value: SignalType, Value.Error == NoError {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward
/// that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalProducerType where Value: SignalType, Error == Value.Error {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` or an active inner signal emits an error, the returned
/// producer will forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerType where Value: SignalType, Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If an active inner signal emits an error, the returned producer will
/// forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.promoteErrors(Value.Error.self)
.flatten(strategy)
}
}
extension SignalProducerType where Value: SignalType, Error == NoError, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> {
return self
.map(SignalProducer.init)
.flatten(strategy)
}
}
extension SignalProducerType where Value: SignalType, Value.Error == NoError {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` emits an error, the returned producer will forward that
/// error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.flatMap(strategy) { $0.promoteErrors(Error.self) }
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal which sends all the values from producer signal emitted from
/// `signal`, waiting until each inner producer completes before beginning to
/// send the values from the next inner producer.
///
/// If any of the inner producers fail, the returned signal will forward
/// that failure immediately
///
/// The returned signal completes only when `signal` and all producers
/// emitted from `signal` complete.
private func concat() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeConcat(relayObserver, relayDisposable)
return disposable
}
}
private func observeConcat(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? {
let state = ConcatState(observer: observer, disposable: disposable)
return self.observe { event in
switch event {
case let .Next(value):
state.enqueueSignalProducer(value.producer)
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
// Add one last producer to the queue, whose sole job is to
// "turn out the lights" by completing `observer`.
state.enqueueSignalProducer(SignalProducer.empty.on(completed: {
observer.sendCompleted()
}))
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Returns a producer which sends all the values from each producer emitted from
/// `producer`, waiting until each inner producer completes before beginning to
/// send the values from the next inner producer.
///
/// If any of the inner producers emit an error, the returned producer will emit
/// that error.
///
/// The returned producer completes only when `producer` and all producers
/// emitted from `producer` complete.
private func concat() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
signal.observeConcat(observer, disposable)
}
}
}
}
extension SignalProducerType {
/// `concat`s `next` onto `self`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func concat(next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer<SignalProducer<Value, Error>, Error>(values: [ self.producer, next ]).flatten(.Concat)
}
}
private final class ConcatState<Value, Error: ErrorType> {
/// The observer of a started `concat` producer.
let observer: Observer<Value, Error>
/// The top level disposable of a started `concat` producer.
let disposable: CompositeDisposable?
/// The active producer, if any, and the producers waiting to be started.
let queuedSignalProducers: Atomic<[SignalProducer<Value, Error>]> = Atomic([])
init(observer: Signal<Value, Error>.Observer, disposable: CompositeDisposable?) {
self.observer = observer
self.disposable = disposable
}
func enqueueSignalProducer(producer: SignalProducer<Value, Error>) {
if let d = disposable where d.disposed {
return
}
var shouldStart = true
queuedSignalProducers.modify {
// An empty queue means the concat is idle, ready & waiting to start
// the next producer.
var queue = $0
shouldStart = queue.isEmpty
queue.append(producer)
return queue
}
if shouldStart {
startNextSignalProducer(producer)
}
}
func dequeueSignalProducer() -> SignalProducer<Value, Error>? {
if let d = disposable where d.disposed {
return nil
}
var nextSignalProducer: SignalProducer<Value, Error>?
queuedSignalProducers.modify {
// Active producers remain in the queue until completed. Since
// dequeueing happens at completion of the active producer, the
// first producer in the queue can be removed.
var queue = $0
if !queue.isEmpty { queue.removeAtIndex(0) }
nextSignalProducer = queue.first
return queue
}
return nextSignalProducer
}
/// Subscribes to the given signal producer.
func startNextSignalProducer(signalProducer: SignalProducer<Value, Error>) {
signalProducer.startWithSignal { signal, disposable in
let handle = self.disposable?.addDisposable(disposable) ?? nil
signal.observe { event in
switch event {
case .Completed, .Interrupted:
handle?.remove()
if let nextSignalProducer = self.dequeueSignalProducer() {
self.startNextSignalProducer(nextSignalProducer)
}
case .Next, .Failed:
self.observer.action(event)
}
}
}
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer
/// added earlier. Returns a Signal that will forward events from the inner producers as they arrive.
private func merge() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
let disposable = CompositeDisposable()
let relayDisposable = CompositeDisposable()
disposable += relayDisposable
disposable += self.observeMerge(relayObserver, relayDisposable)
return disposable
}
}
private func observeMerge(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable) -> Disposable? {
let inFlight = Atomic(1)
let decrementInFlight = {
let orig = inFlight.modify { $0 - 1 }
if orig == 1 {
observer.sendCompleted()
}
}
return self.observe { event in
switch event {
case let .Next(producer):
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 + 1 }
let handle = disposable.addDisposable(innerDisposable)
innerSignal.observe { event in
switch event {
case .Completed, .Interrupted:
handle.remove()
decrementInFlight()
case .Next, .Failed:
observer.action(event)
}
}
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
decrementInFlight()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer
/// added earlier. Returns a Signal that will forward events from the inner producers as they arrive.
private func merge() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { relayObserver, disposable in
self.startWithSignal { signal, signalDisposable in
disposable.addDisposable(signalDisposable)
signal.observeMerge(relayObserver, disposable)
}
}
}
}
extension SignalType {
/// Merges the given signals into a single `Signal` that will emit all values
/// from each of them, and complete when all of them have completed.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public static func merge<Seq: SequenceType, S: SignalType where S.Value == Value, S.Error == Error, Seq.Generator.Element == S>(signals: Seq) -> Signal<Value, Error> {
let producer = SignalProducer<S, Error>(values: signals)
var result: Signal<Value, Error>!
producer.startWithSignal { signal, _ in
result = signal.flatten(.Merge)
}
return result
}
/// Merges the given signals into a single `Signal` that will emit all values
/// from each of them, and complete when all of them have completed.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public static func merge<S: SignalType where S.Value == Value, S.Error == Error>(signals: S...) -> Signal<Value, Error> {
return Signal.merge(signals)
}
}
extension SignalProducerType {
/// Merges the given producers into a single `SignalProducer` that will emit all values
/// from each of them, and complete when all of them have completed.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public static func merge<Seq: SequenceType, S: SignalProducerType where S.Value == Value, S.Error == Error, Seq.Generator.Element == S>(producers: Seq) -> SignalProducer<Value, Error> {
return SignalProducer(values: producers).flatten(.Merge)
}
/// Merges the given producers into a single `SignalProducer` that will emit all values
/// from each of them, and complete when all of them have completed.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public static func merge<S: SignalProducerType where S.Value == Value, S.Error == Error>(producers: S...) -> SignalProducer<Value, Error> {
return SignalProducer.merge(producers)
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
private func switchToLatest() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
let composite = CompositeDisposable()
let serial = SerialDisposable()
composite += serial
composite += self.observeSwitchToLatest(observer, serial)
return composite
}
}
private func observeSwitchToLatest(observer: Observer<Value.Value, Error>, _ latestInnerDisposable: SerialDisposable) -> Disposable? {
let state = Atomic(LatestState<Value, Error>())
return self.observe { event in
switch event {
case let .Next(innerProducer):
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify {
// When we replace the disposable below, this prevents the
// generated Interrupted event from doing any work.
var state = $0
state.replacingInnerSignal = true
return state
}
latestInnerDisposable.innerDisposable = innerDisposable
state.modify {
var state = $0
state.replacingInnerSignal = false
state.innerSignalComplete = false
return state
}
innerSignal.observe { event in
switch event {
case .Interrupted:
// If interruption occurred as a result of a new producer
// arriving, we don't want to notify our observer.
let original = state.modify {
var state = $0
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return state
}
if !original.replacingInnerSignal && original.outerSignalComplete {
observer.sendCompleted()
}
case .Completed:
let original = state.modify {
var state = $0
state.innerSignalComplete = true
return state
}
if original.outerSignalComplete {
observer.sendCompleted()
}
case .Next, .Failed:
observer.action(event)
}
}
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
let original = state.modify {
var state = $0
state.outerSignalComplete = true
return state
}
if original.innerSignalComplete {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
private func switchToLatest() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
let latestInnerDisposable = SerialDisposable()
disposable.addDisposable(latestInnerDisposable)
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
disposable += signal.observeSwitchToLatest(observer, latestInnerDisposable)
}
}
}
}
private struct LatestState<Value, Error: ErrorType> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
extension SignalType {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created producers fail, the returned signal
/// will forward that failure immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` fails, the returned signal will forward that failure
/// immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created signals emit an error, the returned
/// signal will forward that error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` emits an error, the returned signal will forward that
/// error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, NoError>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalType where Error == NoError {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U, E>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned signal
/// will forward that error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U, E>(strategy: FlattenStrategy, transform: Value -> Signal<U, E>) -> Signal<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, NoError>) -> Signal<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerType {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created producers fail, the returned producer
/// will forward that failure immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` fails, the returned producer will forward that failure
/// immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created signals emit an error, the returned
/// producer will forward that error immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` emits an error, the returned producer will forward that
/// error immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, NoError>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerType where Error == NoError {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created producers fail, the returned producer will
/// forward that failure immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U, E>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If any of the created signals emit an error, the returned
/// producer will forward that error immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U, E>(strategy: FlattenStrategy, transform: Value -> Signal<U, E>) -> SignalProducer<U, E> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, NoError>) -> SignalProducer<U, NoError> {
return map(transform).flatten(strategy)
}
}
extension SignalType {
/// Catches any failure that may occur on the input signal, mapping to a new producer
/// that starts in its place.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> Signal<Value, F> {
return Signal { observer in
self.observeFlatMapError(handler, observer, SerialDisposable())
}
}
private func observeFlatMapError<F>(handler: Error -> SignalProducer<Value, F>, _ observer: Observer<Value, F>, _ serialDisposable: SerialDisposable) -> Disposable? {
return self.observe { event in
switch event {
case let .Next(value):
observer.sendNext(value)
case let .Failed(error):
handler(error).startWithSignal { signal, disposable in
serialDisposable.innerDisposable = disposable
signal.observe(observer)
}
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType {
/// Catches any failure that may occur on the input producer, mapping to a new producer
/// that starts in its place.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> SignalProducer<Value, F> {
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable.addDisposable(serialDisposable)
self.startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
signal.observeFlatMapError(handler, observer, serialDisposable)
}
}
}
}
| 06e688ee4c71c6ee74efec7660535382 | 36.312771 | 186 | 0.721089 | false | false | false | false |
LawrenceHan/Games | refs/heads/master | ZombieConga/ZombieConga/MyUtils.swift | mit | 1 | //
// MyUtils.swift
// ZombieConga
//
// Created by Hanguang on 3/28/16.
// Copyright © 2016 Hanguang. All rights reserved.
//
import Foundation
import CoreGraphics
import AVFoundation
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
func += (inout left: CGPoint, right: CGPoint) {
left = left + right
}
func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
func -= (inout left: CGPoint, right: CGPoint) {
left = left - right
}
func * (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x * right.x, y: left.y * right.y)
}
func *= (inout left: CGPoint, right: CGPoint) {
left = left * right
}
func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
func *= (inout point: CGPoint, scalar: CGFloat) {
point = point * scalar
}
func / (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x / right.x, y: left.y / right.y)
}
func /= (inout left: CGPoint, right: CGPoint) {
left = left / right
}
func / (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x / scalar, y: point.y / scalar)
}
func /= (inout point: CGPoint, scalar: CGFloat) {
point = point / scalar
}
#if !(arch(x86_64) || arch(arm64))
func atan2(y: CGFloat, x: CGFloat) -> CGFloat {
return CGFloat(atan2f(Float(y), Float(x)))
}
func sqrt(a: CGFloat) -> CGFloat {
return CGFloat(sqrtf(Float(a)))
}
#endif
extension CGPoint {
func length() -> CGFloat {
return sqrt(x*x + y*y)
}
func normalized() -> CGPoint {
return self / length()
}
var angle: CGFloat {
return atan2(y, x)
}
}
let π = CGFloat(M_PI)
func shortestAngleBetween(angle1: CGFloat, angle2: CGFloat) -> CGFloat {
let twoπ = π * 2.0
var angle = (angle2 - angle1) % twoπ
if (angle >= π) {
angle = angle - twoπ
}
if (angle <= -π) {
angle = angle + twoπ
}
return angle
}
extension CGFloat {
func sign() -> CGFloat {
return (self >= 0.0) ? 1.0 : -1.0
}
}
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(Float(arc4random()) / Float(UInt32.max))
}
static func random(min min: CGFloat, max: CGFloat) -> CGFloat {
assert(min < max)
return CGFloat.random() * (max - min) + min
}
}
var backgroundMusicPlayer: AVAudioPlayer!
func playBackgroundMusic(fileName: String) {
let resourceUrl = NSBundle.mainBundle().URLForResource(fileName, withExtension: nil)
guard let url = resourceUrl else {
print("Could not find file: \(fileName)")
return
}
do {
try backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url)
backgroundMusicPlayer.numberOfLoops = 1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
} catch {
print("Could not create audio player!")
return
}
}
| 283d375b5400504f01975bd914148e3c | 21.536232 | 88 | 0.600322 | false | false | false | false |
hrscy/TodayNews | refs/heads/master | News/News/Classes/Home/Controller/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// News
//
// Created by 杨蒙 on 2018/1/23.
// Copyright © 2018年 hrscy. All rights reserved.
//
import UIKit
import SGPagingView
import RxSwift
import RxCocoa
class HomeViewController: UIViewController {
/// 标题和内容
private var pageTitleView: SGPageTitleView?
private var pageContentView: SGPageContentView?
/// 自定义导航栏
private lazy var navigationBar = HomeNavigationView.loadViewFromNib()
private lazy var disposeBag = DisposeBag()
/// 添加频道按钮
private lazy var addChannelButton: UIButton = {
let addChannelButton = UIButton(frame: CGRect(x: screenWidth - newsTitleHeight, y: 0, width: newsTitleHeight, height: newsTitleHeight))
addChannelButton.theme_setImage("images.add_channel_titlbar_thin_new_16x16_", forState: .normal)
let separatorView = UIView(frame: CGRect(x: 0, y: newsTitleHeight - 1, width: newsTitleHeight, height: 1))
separatorView.theme_backgroundColor = "colors.separatorViewColor"
addChannelButton.addSubview(separatorView)
return addChannelButton
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.keyWindow?.theme_backgroundColor = "colors.windowColor"
// 设置状态栏属性
navigationController?.navigationBar.barStyle = .black
navigationController?.setNavigationBarHidden(false, animated: animated)
navigationController?.navigationBar.setBackgroundImage(UIImage(named: "navigation_background" + (UserDefaults.standard.bool(forKey: isNight) ? "_night" : "")), for: .default)
}
override func viewDidLoad() {
super.viewDidLoad()
// 设置 UI
setupUI()
// 点击事件
clickAction()
}
}
// MARK: - 导航栏按钮点击
extension HomeViewController {
/// 设置 UI
private func setupUI() {
view.theme_backgroundColor = "colors.cellBackgroundColor"
// 设置自定义导航栏
navigationItem.titleView = navigationBar
// 添加频道
view.addSubview(addChannelButton)
// 首页顶部新闻标题的数据
NetworkTool.loadHomeNewsTitleData {
// 向数据库中插入数据
NewsTitleTable().insert($0)
let configuration = SGPageTitleViewConfigure()
configuration.titleColor = .black
configuration.titleSelectedColor = .globalRedColor()
configuration.indicatorColor = .clear
// 标题名称的数组
self.pageTitleView = SGPageTitleView(frame: CGRect(x: 0, y: 0, width: screenWidth - newsTitleHeight, height: newsTitleHeight), delegate: self, titleNames: $0.compactMap({ $0.name }), configure: configuration)
self.pageTitleView!.backgroundColor = .clear
self.view.addSubview(self.pageTitleView!)
// 设置子控制器
_ = $0.compactMap({ (newsTitle) -> () in
switch newsTitle.category {
case .video: // 视频
let videoTableVC = VideoTableViewController()
videoTableVC.newsTitle = newsTitle
videoTableVC.setupRefresh(with: .video)
self.addChildViewController(videoTableVC)
case .essayJoke: // 段子
let essayJokeVC = HomeJokeViewController()
essayJokeVC.isJoke = true
essayJokeVC.setupRefresh(with: .essayJoke)
self.addChildViewController(essayJokeVC)
case .imagePPMM: // 街拍
let imagePPMMVC = HomeJokeViewController()
imagePPMMVC.isJoke = false
imagePPMMVC.setupRefresh(with: .imagePPMM)
self.addChildViewController(imagePPMMVC)
case .imageFunny: // 趣图
let imagePPMMVC = HomeJokeViewController()
imagePPMMVC.isJoke = false
imagePPMMVC.setupRefresh(with: .imageFunny)
self.addChildViewController(imagePPMMVC)
case .photos: // 图片,组图
let homeImageVC = HomeImageViewController()
homeImageVC.setupRefresh(with: .photos)
self.addChildViewController(homeImageVC)
case .jinritemai: // 特卖
let temaiVC = TeMaiViewController()
temaiVC.url = "https://m.maila88.com/mailaIndex?mailaAppKey=GDW5NMaKQNz81jtW2Yuw2P"
self.addChildViewController(temaiVC)
default :
let homeTableVC = HomeRecommendController()
homeTableVC.setupRefresh(with: newsTitle.category)
self.addChildViewController(homeTableVC)
}
})
// 内容视图
self.pageContentView = SGPageContentView(frame: CGRect(x: 0, y: newsTitleHeight, width: screenWidth, height: self.view.height - newsTitleHeight), parentVC: self, childVCs: self.childViewControllers)
self.pageContentView!.delegatePageContentView = self
self.view.addSubview(self.pageContentView!)
}
}
/// 点击事件
private func clickAction() {
// 搜索按钮点击
navigationBar.didSelectSearchButton = {
}
// 头像按钮点击
navigationBar.didSelectAvatarButton = { [weak self] in
self!.navigationController?.pushViewController(MineViewController(), animated: true)
}
// 相机按钮点击
navigationBar.didSelectCameraButton = {
}
/// 添加频道点击
addChannelButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in
let homeAddCategoryVC = HomeAddCategoryController.loadStoryboard()
homeAddCategoryVC.modalSize = (width: .full, height: .custom(size: Float(screenHeight - (isIPhoneX ? 44 : 20))))
self!.present(homeAddCategoryVC, animated: true, completion: nil)
})
.disposed(by: disposeBag)
}
}
// MARK: - SGPageTitleViewDelegate
extension HomeViewController: SGPageTitleViewDelegate, SGPageContentViewDelegate {
/// 联动 pageContent 的方法
func pageTitleView(_ pageTitleView: SGPageTitleView!, selectedIndex: Int) {
self.pageContentView!.setPageContentViewCurrentIndex(selectedIndex)
}
/// 联动 SGPageTitleView 的方法
func pageContentView(_ pageContentView: SGPageContentView!, progress: CGFloat, originalIndex: Int, targetIndex: Int) {
self.pageTitleView!.setPageTitleViewWithProgress(progress, originalIndex: originalIndex, targetIndex: targetIndex)
}
}
| 3171df1290c2f64b37ae83add98684a4 | 42.379085 | 220 | 0.62257 | false | false | false | false |
devinross/curry | refs/heads/master | Examples/Examples/TextViewViewController.swift | mit | 1 | //
// TextViewViewController.swift
// Created by Devin Ross on 5/5/17.
//
/*
curry || https://github.com/devinross/curry
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import curry
class TextViewViewController: UIViewController {
var textView : TKTextView!
var insetSlider : UISlider!
var textSizeSlider : UISlider!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
self.edgesForExtendedLayout = .left
let textView = TKTextView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: 200).insetBy(dx: 10, dy: 10))
textView.placeholder = "Placeholder"
textView.backgroundColor = UIColor.white
self.textView = textView
self.view.addSubview(textView)
let slider = UISlider(frame: CGRect(x: 0, y: textView.maxY + 10, width: self.view.width, height: 30).insetBy(dx: 20, dy: 0))
self.textSizeSlider = slider
slider.minimumValue = 10
slider.maximumValue = 30
slider.addEventHandler({ (sender) in
self.textView.font = UIFont.systemFont(ofSize: CGFloat(self.textSizeSlider.value))
}, for: .valueChanged)
self.view.addSubview(slider)
let insetSlider = UISlider(frame: CGRect(x: 0, y: slider.maxY + 10, width: self.view.width, height: 30).insetBy(dx: 20, dy: 0))
insetSlider.minimumValue = 0
insetSlider.maximumValue = 12
insetSlider.addEventHandler({ (sender) in
let inset = CGFloat(self.insetSlider.value)
self.textView.textContainerInset = UIEdgeInsets.init(top: inset, left: inset, bottom: inset, right: inset)
}, for: .valueChanged)
self.insetSlider = insetSlider
self.view.addSubview(self.insetSlider)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.textView.becomeFirstResponder()
}
}
| bf5ea31580e1e12f4c59a6244e3d02eb | 34.139241 | 129 | 0.753602 | false | false | false | false |
coach-plus/ios | refs/heads/master | Pods/YPImagePicker/Source/Pages/Gallery/LibraryMediaManager.swift | mit | 1 | //
// LibraryMediaManager.swift
// YPImagePicker
//
// Created by Sacha DSO on 26/01/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
import Photos
class LibraryMediaManager {
weak var v: YPLibraryView?
var collection: PHAssetCollection?
internal var fetchResult: PHFetchResult<PHAsset>!
internal var previousPreheatRect: CGRect = .zero
internal var imageManager: PHCachingImageManager?
internal var exportTimer: Timer?
internal var currentExportSessions: [AVAssetExportSession] = []
func initialize() {
imageManager = PHCachingImageManager()
resetCachedAssets()
}
func resetCachedAssets() {
imageManager?.stopCachingImagesForAllAssets()
previousPreheatRect = .zero
}
func updateCachedAssets(in collectionView: UICollectionView) {
let size = UIScreen.main.bounds.width/4 * UIScreen.main.scale
let cellSize = CGSize(width: size, height: size)
var preheatRect = collectionView.bounds
preheatRect = preheatRect.insetBy(dx: 0.0, dy: -0.5 * preheatRect.height)
let delta = abs(preheatRect.midY - previousPreheatRect.midY)
if delta > collectionView.bounds.height / 3.0 {
var addedIndexPaths: [IndexPath] = []
var removedIndexPaths: [IndexPath] = []
previousPreheatRect.differenceWith(rect: preheatRect, removedHandler: { removedRect in
let indexPaths = collectionView.aapl_indexPathsForElementsInRect(removedRect)
removedIndexPaths += indexPaths
}, addedHandler: { addedRect in
let indexPaths = collectionView.aapl_indexPathsForElementsInRect(addedRect)
addedIndexPaths += indexPaths
})
let assetsToStartCaching = fetchResult.assetsAtIndexPaths(addedIndexPaths)
let assetsToStopCaching = fetchResult.assetsAtIndexPaths(removedIndexPaths)
imageManager?.startCachingImages(for: assetsToStartCaching,
targetSize: cellSize,
contentMode: .aspectFill,
options: nil)
imageManager?.stopCachingImages(for: assetsToStopCaching,
targetSize: cellSize,
contentMode: .aspectFill,
options: nil)
previousPreheatRect = preheatRect
}
}
func fetchVideoUrlAndCrop(for videoAsset: PHAsset, cropRect: CGRect, callback: @escaping (URL) -> Void) {
let videosOptions = PHVideoRequestOptions()
videosOptions.isNetworkAccessAllowed = true
videosOptions.deliveryMode = .highQualityFormat
imageManager?.requestAVAsset(forVideo: videoAsset, options: videosOptions) { asset, _, _ in
do {
guard let asset = asset else { print("⚠️ PHCachingImageManager >>> Don't have the asset"); return }
let assetComposition = AVMutableComposition()
let trackTimeRange = CMTimeRangeMake(start: CMTime.zero, duration: asset.duration)
// 1. Inserting audio and video tracks in composition
guard let videoTrack = asset.tracks(withMediaType: AVMediaType.video).first,
let videoCompositionTrack = assetComposition
.addMutableTrack(withMediaType: .video,
preferredTrackID: kCMPersistentTrackID_Invalid) else {
print("⚠️ PHCachingImageManager >>> Problems with video track")
return
}
if let audioTrack = asset.tracks(withMediaType: AVMediaType.audio).first,
let audioCompositionTrack = assetComposition
.addMutableTrack(withMediaType: AVMediaType.audio,
preferredTrackID: kCMPersistentTrackID_Invalid) {
try audioCompositionTrack.insertTimeRange(trackTimeRange, of: audioTrack, at: CMTime.zero)
}
try videoCompositionTrack.insertTimeRange(trackTimeRange, of: videoTrack, at: CMTime.zero)
// Layer Instructions
let layerInstructions = AVMutableVideoCompositionLayerInstruction(assetTrack: videoCompositionTrack)
var transform = videoTrack.preferredTransform
transform.tx -= cropRect.minX
transform.ty -= cropRect.minY
layerInstructions.setTransform(transform, at: CMTime.zero)
// CompositionInstruction
let mainInstructions = AVMutableVideoCompositionInstruction()
mainInstructions.timeRange = trackTimeRange
mainInstructions.layerInstructions = [layerInstructions]
// Video Composition
let videoComposition = AVMutableVideoComposition(propertiesOf: asset)
videoComposition.instructions = [mainInstructions]
videoComposition.renderSize = cropRect.size // needed?
// 5. Configuring export session
let exportSession = AVAssetExportSession(asset: assetComposition,
presetName: YPConfig.video.compression)
exportSession?.outputFileType = YPConfig.video.fileType
exportSession?.shouldOptimizeForNetworkUse = true
exportSession?.videoComposition = videoComposition
exportSession?.outputURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingUniquePathComponent(pathExtension: YPConfig.video.fileType.fileExtension)
// 6. Exporting
DispatchQueue.main.async {
self.exportTimer = Timer.scheduledTimer(timeInterval: 0.1,
target: self,
selector: #selector(self.onTickExportTimer),
userInfo: exportSession,
repeats: true)
}
self.currentExportSessions.append(exportSession!)
exportSession?.exportAsynchronously(completionHandler: {
DispatchQueue.main.async {
if let url = exportSession?.outputURL, exportSession?.status == .completed {
callback(url)
if let index = self.currentExportSessions.firstIndex(of:exportSession!) {
self.currentExportSessions.remove(at: index)
}
} else {
let error = exportSession?.error
print("error exporting video \(String(describing: error))")
}
}
})
} catch let error {
print("⚠️ PHCachingImageManager >>> \(error)")
}
}
}
@objc func onTickExportTimer(sender: Timer) {
if let exportSession = sender.userInfo as? AVAssetExportSession {
if let v = v {
if exportSession.progress > 0 {
v.updateProgress(exportSession.progress)
}
}
if exportSession.progress > 0.99 {
sender.invalidate()
v?.updateProgress(0)
self.exportTimer = nil
}
}
}
func forseCancelExporting() {
for s in self.currentExportSessions {
s.cancelExport()
}
}
}
| fd269f643be1cc19884acb65586b562e | 46 | 116 | 0.543343 | false | false | false | false |
muukii/PhotosPicker | refs/heads/master | PhotosPicker/Sources/PhotosPickerAssetsSectionView.swift | mit | 2 | // PhotosPickerAssetsSectionView
//
// Copyright (c) 2015 muukii
//
// 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
public class PhotosPickerAssetsSectionView: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
self.setAppearance()
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public class func sizeForSection(#collectionView: UICollectionView) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 30)
}
public weak var sectionTitleLabel: UILabel?
public var section: DayPhotosPickerAssets? {
get {
return _section
}
set {
_section = newValue
if let section = newValue {
struct Static {
static var formatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.ShortStyle
return formatter
}()
}
self.sectionTitleLabel?.text = Static.formatter.stringFromDate(section.date)
}
}
}
public func setup() {
let sectionTitleLabel = UILabel()
sectionTitleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(sectionTitleLabel)
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.sectionTitleLabel = sectionTitleLabel
let views = [
"sectionTitleLabel": sectionTitleLabel
]
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"|-(10)-[sectionTitleLabel]-(10)-|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: views
)
)
self.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-[sectionTitleLabel]-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: views
)
)
}
public func setAppearance() {
self.backgroundColor = UIColor.whiteColor()
}
private var _section: DayPhotosPickerAssets?
}
| 81b8658d9f06dc46ff1aaf5970f5b0dc | 32.980198 | 120 | 0.638695 | false | false | false | false |
lightbluefox/rcgapp | refs/heads/master | IOS App/RCGApp/RCGApp/AppDelegate.swift | gpl-2.0 | 1 | //
// AppDelegate.swift
// RCGApp
//
// Created by iFoxxy on 12.05.15.
// Copyright (c) 2015 LightBlueFox. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true);
var itemsReceiver = NewsAndVacanciesReceiver()
//itemsReceiver.getAllNews();
//itemsReceiver.getAllVacancies();
var newsStack = itemsReceiver.newsStack;
var vacStack = itemsReceiver.vacStack
let navBarFont = UIFont(name: "Roboto-Regular", size: 17.0) ?? UIFont.systemFontOfSize(17.0);
var navBar = UINavigationBar.appearance();
var tabBar = UITabBar.appearance();
//UITabBar.appearance().backgroundImage = UIImage(named: "selectedItemImage");
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) //Для iOS 7 и старше
{
navBar.barTintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
tabBar.barTintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
tabBar.tintColor = UIColor.whiteColor();
}
else //ниже iOS 7
{
navBar.tintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
tabBar.tintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
}
//Стиль заголовка
navBar.titleTextAttributes = [NSFontAttributeName: navBarFont, NSForegroundColorAttributeName: UIColor.whiteColor()];
//Чтобы избавиться от стандартного выделения выбранного таба, используем такой костыль.
tabBar.selectionIndicatorImage = UIImage(named: "selectedItemImage");
//Mark: Регистрация на пуш-уведомления
//IOS 7 -
UIApplication.sharedApplication().registerForRemoteNotificationTypes(UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound);
//IOS 8 +
//UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert);
//UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings: UIUserNotificationSettings.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 15a29b5e619c1654b77a04e4beba4716 | 49.54023 | 285 | 0.712304 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformKit/Coincore/Account/Fiat/PaymentMethodAccount.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import MoneyKit
import RxSwift
import ToolKit
// swiftformat:disable all
/// A type that represents a payment method as a `BlockchainAccount`.
public final class PaymentMethodAccount: FiatAccount {
public let paymentMethodType: PaymentMethodType
public let paymentMethod: PaymentMethod
public let priceService: PriceServiceAPI
public let accountType: AccountType
public init(
paymentMethodType: PaymentMethodType,
paymentMethod: PaymentMethod,
priceService: PriceServiceAPI = resolve()
) {
self.paymentMethodType = paymentMethodType
self.paymentMethod = paymentMethod
self.priceService = priceService
accountType = paymentMethod.isCustodial ? .trading : .nonCustodial
}
public let isDefault: Bool = false
public var activity: AnyPublisher<[ActivityItemEvent], Error> {
.just([]) // no activity to report
}
public var fiatCurrency: FiatCurrency {
guard let fiatCurrency = paymentMethodType.currency.fiatCurrency else {
impossible("Payment Method Accounts should always be denominated in fiat.")
}
return fiatCurrency
}
public var canWithdrawFunds: Single<Bool> {
.just(false)
}
public var identifier: AnyHashable {
paymentMethodType.id
}
public var label: String {
paymentMethodType.label
}
public var isFunded: AnyPublisher<Bool, Error> {
.just(true)
}
public var balance: AnyPublisher<MoneyValue, Error> {
.just(paymentMethodType.balance)
}
public func can(perform action: AssetAction) -> AnyPublisher<Bool, Error>{
.just(action == .buy)
}
public var pendingBalance: AnyPublisher<MoneyValue, Error> {
balance
}
public var actionableBalance: AnyPublisher<MoneyValue, Error> {
balance
}
public var receiveAddress: AnyPublisher<ReceiveAddress, Error> {
.failure(ReceiveAddressError.notSupported)
}
public func balancePair(
fiatCurrency: FiatCurrency,
at time: PriceTime
) -> AnyPublisher<MoneyValuePair, Error> {
balancePair(
priceService: priceService,
fiatCurrency: fiatCurrency,
at: time
)
}
public func invalidateAccountBalance() {
// NO-OP
}
}
| b355f7c2aeaea0db45455ec5174d8881 | 25.290323 | 87 | 0.667485 | false | false | false | false |
CoderYLiu/30DaysOfSwift | refs/heads/master | Project 18 - LimitCharacters/LimitCharacters/ViewController.swift | mit | 1 | //
// ViewController.swift
// LimitCharacters <https://github.com/DeveloperLY/30DaysOfSwift>
//
// Created by Liu Y on 16/4/24.
// Copyright © 2016年 DeveloperLY. All rights reserved.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {
@IBOutlet weak var tweetTextView: UITextView!
@IBOutlet weak var bottomUIView: UIView!
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var characterCountLabel: UILabel!
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
tweetTextView.delegate = self
avatarImageView.layer.cornerRadius = avatarImageView.frame.width / 2
tweetTextView.backgroundColor = UIColor.clear
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyBoardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyBoardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let myTextViewString = tweetTextView.text
characterCountLabel.text = "\(140 - (myTextViewString?.characters.count)!)"
if range.length > 140{
return false
}
let newLength = (myTextViewString?.characters.count)! + range.length
return newLength < 140
}
func keyBoardWillShow(_ note:Notification) {
let userInfo = note.userInfo
let keyBoardBounds = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let deltaY = keyBoardBounds.size.height
let animations:(() -> Void) = {
self.bottomUIView.transform = CGAffineTransform(translationX: 0,y: -deltaY)
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
}else {
animations()
}
}
func keyBoardWillHide(_ note:Notification) {
let userInfo = note.userInfo
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animations:(() -> Void) = {
self.bottomUIView.transform = CGAffineTransform.identity
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
}else{
animations()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
}
| 9de51dc92dbd380a1759541a5148ad7b | 31.747826 | 167 | 0.629315 | false | false | false | false |
MasterSwift/Amaze | refs/heads/master | Sources/AmazeCore/Edge/EZAEdge.swift | bsd-3-clause | 1 | //
// EZAEdge.swift
// Amaze
//
// Created by Muhammad Tahir Vali on 2/25/18.
//
import Foundation
struct EZAEdge : Edgeable {
var index: EdgeIndex
var weight: Double
var tag: String? = nil
var description: String? = nil
static func ==(lhs: EZAEdge, rhs: EZAEdge) -> Bool {
return lhs.index == rhs.index && lhs.weight == rhs.weight
}
init(index : EdgeIndex, weight: Double ) {
self.index = index
self.weight = weight
}
init(index : EdgeIndex, weight: Double, tag : String?, description: String?) {
self.index = index
self.weight = weight
self.tag = tag
self.description = description
}
}
| b5406de1aae814a7a4648b23b8e5d4ed | 20.636364 | 82 | 0.578431 | false | false | false | false |
BelledonneCommunications/linphone-iphone | refs/heads/master | Classes/Swift/Conference/Views/ICSBubbleView.swift | gpl-3.0 | 1 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* 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 Foundation
import linphonesw
import EventKit
import EventKitUI
@objc class ICSBubbleView: UIView, EKEventEditViewDelegate {
let corner_radius = 7.0
let border_width = 2.0
let rows_spacing = 6.0
let inner_padding = 8.0
let forward_reply_title_height = 10.0
let indicator_y = 3.0
let share_size = 25
let join_share_width = 150.0
let inviteTitle = StyledLabel(VoipTheme.conference_invite_title_font, VoipTexts.conference_invite_title)
let inviteCancelled = StyledLabel(VoipTheme.conference_cancelled_title_font, VoipTexts.conference_cancel_title)
let inviteUpdated = StyledLabel(VoipTheme.conference_updated_title_font, VoipTexts.conference_update_title)
let subject = StyledLabel(VoipTheme.conference_invite_subject_font)
let participants = StyledLabel(VoipTheme.conference_invite_desc_font)
let date = StyledLabel(VoipTheme.conference_invite_desc_font)
let timeDuration = StyledLabel(VoipTheme.conference_invite_desc_font)
let descriptionTitle = StyledLabel(VoipTheme.conference_invite_desc_title_font, VoipTexts.conference_description_title)
let descriptionValue = StyledLabel(VoipTheme.conference_invite_desc_font)
let joinShare = UIStackView()
let join = FormButton(title:VoipTexts.conference_invite_join.uppercased(), backgroundStateColors: VoipTheme.button_green_background)
let share = UIImageView(image:UIImage(named:"voip_export")?.tinted(with: VoipTheme.primaryTextColor.get()))
var conferenceData: ScheduledConferenceData? = nil {
didSet {
if let data = conferenceData {
subject.text = data.subject.value
participants.text = VoipTexts.conference_invite_participants_count.replacingOccurrences(of: "%d", with: String(data.conferenceInfo.participants.count+1))
participants.addIndicatorIcon(iconName: "conference_schedule_participants_default",padding : 0.0, y: -indicator_y, trailing: false)
date.text = TimestampUtils.dateToString(date: data.rawDate)
date.addIndicatorIcon(iconName: "conference_schedule_calendar_default", padding: 0.0, y:-indicator_y, trailing:false)
timeDuration.text = "\(data.time.value)" + (data.duration.value != nil ? " ( \(data.duration.value) )" : "")
timeDuration.addIndicatorIcon(iconName: "conference_schedule_time_default",padding : 0.0, y: -indicator_y, trailing: false)
descriptionTitle.isHidden = data.description.value == nil || data.description.value!.count == 0
descriptionValue.isHidden = descriptionTitle.isHidden
descriptionValue.text = data.description.value
inviteTitle.isHidden = [.Cancelled,.Updated].contains(data.conferenceInfo.state)
inviteCancelled.isHidden = data.conferenceInfo.state != .Cancelled
inviteUpdated.isHidden = data.conferenceInfo.state != .Updated
join.isEnabled = data.isConferenceCancelled.value != true
}
}
}
init() {
super.init(frame:.zero)
layer.cornerRadius = corner_radius
clipsToBounds = true
backgroundColor = VoipTheme.voip_light_gray
let rows = UIStackView()
rows.axis = .vertical
rows.spacing = rows_spacing
addSubview(rows)
rows.addArrangedSubview(inviteTitle)
rows.addArrangedSubview(inviteCancelled)
rows.addArrangedSubview(inviteUpdated)
rows.addArrangedSubview(subject)
rows.addArrangedSubview(participants)
rows.addArrangedSubview(date)
rows.addArrangedSubview(timeDuration)
rows.addArrangedSubview(descriptionTitle)
rows.addArrangedSubview(descriptionValue)
descriptionValue.numberOfLines = 5
addSubview(joinShare)
joinShare.axis = .horizontal
joinShare.spacing = rows_spacing
joinShare.addArrangedSubview(share)
share.square(share_size).done()
joinShare.addArrangedSubview(join)
rows.matchParentSideBorders(insetedByDx: inner_padding).alignParentTop(withMargin: inner_padding).done()
joinShare.alignParentBottom(withMargin: inner_padding).width(join_share_width).alignParentRight(withMargin: inner_padding).done()
join.onClick {
let view : ConferenceWaitingRoomFragment = self.VIEW(ConferenceWaitingRoomFragment.compositeViewDescription())
PhoneMainView.instance().changeCurrentView(view.compositeViewDescription())
view.setDetails(subject: (self.conferenceData?.subject.value)!, url: (self.conferenceData?.address.value)!)
}
share.onClick {
let eventStore = EKEventStore()
eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
DispatchQueue.main.async {
if (granted) && (error == nil) {
let event = EKEvent(eventStore: eventStore)
event.title = self.conferenceData?.subject.value
event.startDate = self.conferenceData?.rawDate
if let duration = self.conferenceData?.conferenceInfo.duration, duration > 0 {
event.endDate = event.startDate.addingTimeInterval(TimeInterval(duration*60))
} else {
event.endDate = event.startDate.addingTimeInterval(TimeInterval(3600))
}
event.calendar = eventStore.defaultCalendarForNewEvents
if let description = self.conferenceData?.description.value, description.count > 0 {
event.notes = description + "\n\n"
}
event.notes = (event.notes != nil ? event.notes! : "") + "\(VoipTexts.call_action_participants_list):\n\(self.conferenceData?.participantsExpanded.value)"
if let urlString = self.conferenceData?.conferenceInfo.uri?.asStringUriOnly() {
event.url = URL(string:urlString)
}
let addController = EKEventEditViewController()
addController.event = event
addController.eventStore = eventStore
PhoneMainView.instance().present(addController, animated: false)
addController.editViewDelegate = self;
} else {
VoipDialog.toast(message: VoipTexts.conference_unable_to_share_via_calendar)
}
}
})
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func setFromChatMessage(cmessage: OpaquePointer) {
let message = ChatMessage.getSwiftObject(cObject: cmessage)
message.contents.forEach { content in
if (content.isIcalendar) {
if let conferenceInfo = try? Factory.Instance.createConferenceInfoFromIcalendarContent(content: content) {
self.conferenceData = ScheduledConferenceData(conferenceInfo: conferenceInfo)
}
}
}
}
@objc static func isConferenceInvitationMessage(cmessage: OpaquePointer) -> Bool {
var isConferenceInvitationMessage = false
let message = ChatMessage.getSwiftObject(cObject: cmessage)
message.contents.forEach { content in
if (content.isIcalendar) {
isConferenceInvitationMessage = true
}
}
return isConferenceInvitationMessage
}
@objc func setLayoutConstraints(view:UIView) {
matchBordersWith(view: view, insetedByDx: inner_padding).done()
}
@objc func updateTopLayoutConstraints(view:UIView, replyOrForward: Bool) {
updateTopBorderWith(view: view, inset: inner_padding + (replyOrForward ? forward_reply_title_height : 0.0)).done()
}
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
controller.dismiss(animated: true, completion: nil)
}
@objc static func getSubjectFromContent(cmessage: OpaquePointer) -> String {
let message = ChatMessage.getSwiftObject(cObject: cmessage)
var subject = ""
message.contents.forEach { content in
if (content.isIcalendar) {
if let conferenceInfo = try? Factory.Instance.createConferenceInfoFromIcalendarContent(content: content) {
subject = conferenceInfo.subject
}
}
}
return subject
}
@objc static func getDescriptionHeightFromContent(cmessage: OpaquePointer) -> CGFloat {
let message = ChatMessage.getSwiftObject(cObject: cmessage)
var height = 0.0
message.contents.forEach { content in
if (content.isIcalendar) {
if let conferenceInfo = try? Factory.Instance.createConferenceInfoFromIcalendarContent(content: content) {
let description = NSString(string: conferenceInfo.description)
if (description.length > 0) {
let dummyTitle = StyledLabel(VoipTheme.conference_invite_desc_title_font, VoipTexts.conference_description_title)
let dummyLabel = StyledLabel(VoipTheme.conference_invite_desc_font)
let rect = CGSize(width: CGFloat(CONFERENCE_INVITATION_WIDTH-80), height: CGFloat.greatestFiniteMagnitude)
height = dummyTitle.intrinsicContentSize.height + description.boundingRect(with: rect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: dummyLabel.font!], context: nil).height
}
}
}
}
return height
}
}
| f634f7133b5b466326dc35971e7b169a | 41.642202 | 228 | 0.755379 | false | false | false | false |
Corotata/CRWeiBo | refs/heads/master | CRWeiBo/CRWeiBo/Classes/Modules/Main/CRTabBar.swift | mit | 1 | //
// CRTabBar.swift
// CRWeiBo
//
// Created by Corotata on 16/2/17.
// Copyright © 2016年 Corotata. All rights reserved.
//
import UIKit
class CRTabBar: UITabBar {
override init(frame: CGRect) {
super.init(frame: frame)
let image = UIImage(named: "tabbar_background")
backgroundColor = UIColor.init(patternImage: image!)
addSubview(composeButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var composeButton:UIButton = {
let button = UIButton()
button.coro_image("tabbar_compose_icon_add")
button.coro_highlightedImage("tabbar_compose_icon_add_highlighted")
button.coro_backgroundImage("tabbar_compose_button")
button.coro_highlightedBackgroundImage("tabbar_compose_button_highlighted")
button.frame.size = button.currentBackgroundImage!.size
return button
}()
override func layoutSubviews() {
let width = frame.size.width
let height = frame.size.height
composeButton.center = CGPoint(x: width/2, y: height/2)
let buttonY = CGFloat(0);
let buttonW = CGFloat(width / 5);
let buttonH = height;
var index = 0;
for button in subviews{
if !button .isKindOfClass(UIControl) || button == composeButton{
continue;
}
let buttonX = buttonW * CGFloat(index > 1 ? index + 1 :index) ;
button.frame = CGRect(x: buttonX, y: buttonY, width: buttonW, height: buttonH)
index = index + 1 ;
}
}
}
| 722857e82481ef4962ea9d2428633719 | 26.238095 | 90 | 0.587995 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/API/Requests/Message/GetMessageRequest.swift | mit | 1 | //
// GetMessageRequest.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 10/04/19.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
final class GetMessageRequest: APIRequest {
typealias APIResourceType = GetMessageResource
let requiredVersion = Version(0, 47, 0)
let method: HTTPMethod = .get
let path = "/api/v1/chat.getMessage"
var query: String?
init(msgId: String) {
self.query = "msgId=\(msgId)"
}
}
final class GetMessageResource: APIResource {
var message: Message? {
if let object = raw?["message"] {
let message = Message()
message.map(object, realm: nil)
return message
}
return nil
}
var success: Bool {
return raw?["success"].boolValue ?? false
}
}
| da352788104acd21ed552083cf5ccec1 | 19.380952 | 54 | 0.620327 | false | false | false | false |
ls1intum/proceed-storytellr | refs/heads/master | Prototyper/Classes/ScenarioInfoStepView.swift | mit | 1 | //
// ScenarioInfoStepView.swift
// StoryTellr
//
// Created by Lara Marie Reimer on 27.05.17.
// Copyright © 2017 Lara Marie Reimer. All rights reserved.
//
import UIKit
class ScenarioInfoStepView: ScenarioInfoView {
// MARK: Initialization
convenience init() {
self.init(scenarioStep: nil)
}
init(scenarioStep: ScenarioStep?) {
super.init(frame: CGRect.zero)
self.currentStep = scenarioStep
self.questions = nil
if let step = currentStep {
currentStepLabel.text = String(describing: step.stepNumber)
titleLabel.text = step.stepDescription
} else {
currentStepLabel.text = "0"
titleLabel.text = "There is no scenario step for this screen available"
}
self.setConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Autolayout
func setConstraints() {
backgroundView.addSubview(stepView)
backgroundView.addSubview(bottomView)
stepView.addSubview(currentStepLabel)
let viewsDictionary = ["step": stepView, "stepLabel": currentStepLabel, "title": titleLabel, "bottom": bottomView] as [String : Any]
//position constraints in background
let titleConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[title]-20-|",options: NSLayoutFormatOptions(rawValue: 0),metrics: nil, views: viewsDictionary)
let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[step(50)]-40@999-[title]-40@999-[bottom]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let vConstraintsStep = NSLayoutConstraint.constraints(withVisualFormat: "[step(50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let centerStepX = NSLayoutConstraint(item: self.stepView, attribute:.centerX, relatedBy:.equal, toItem: self.backgroundView, attribute:.centerX, multiplier: 1.0, constant: 0.0)
let centerButtonX = NSLayoutConstraint(item: self.bottomView, attribute:.centerX, relatedBy:.equal, toItem: self.backgroundView, attribute:.centerX, multiplier: 1.0, constant: 0.0)
let centerTitleX = NSLayoutConstraint(item: self.titleLabel, attribute:.centerX, relatedBy:.equal, toItem: self.backgroundView, attribute:.centerX, multiplier: 1.0, constant: 0.0)
backgroundView.addConstraint(centerStepX)
backgroundView.addConstraint(centerButtonX)
backgroundView.addConstraint(centerTitleX)
backgroundView.addConstraints(titleConstraint)
backgroundView.addConstraints(vConstraints)
backgroundView.addConstraints(vConstraintsStep)
//position constraints in stepView
let centerX = NSLayoutConstraint(item: currentStepLabel, attribute:.centerX, relatedBy:.equal, toItem: stepView, attribute:.centerX, multiplier: 1.0, constant: 0.0)
let centerY = NSLayoutConstraint(item: currentStepLabel, attribute:.centerY, relatedBy:.equal, toItem: stepView, attribute:.centerY, multiplier: 1.0, constant: 0.0)
stepView.addConstraint(centerX)
stepView.addConstraint(centerY)
}
// MARK: Getters
var stepView : UIView = {
let view = UIView()
view.backgroundColor = PrototypeUI.ButtonColor
view.layer.cornerRadius = 25.0
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var currentStepLabel : UILabel = {
let stepLabel = UILabel()
stepLabel.translatesAutoresizingMaskIntoConstraints = false
stepLabel.font = UIFont.boldSystemFont(ofSize: 30.0)
stepLabel.textColor = UIColor.white
stepLabel.text = "0"
return stepLabel
}()
var bottomView : UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = PrototypeUI.ButtonColor
button.layer.cornerRadius = 15.0
button.setImage(UIImage(named: "check"), for: .normal)
button.setTitle("OKAY", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
button.contentEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
button.addTarget(self, action: #selector(didTapOkay), for: .touchUpInside)
return button
}()
// MARK: Actions
@objc func didTapOkay(sender: UIButton) {
guard let delegate = self.delegate else { return }
delegate.didPressBottomButton(_: sender, withAnswer: nil, isLastFeedback: nil)
print("Tap received")
}
}
| ab1d8edd3a6d2b4e5d90f7e866d0ad94 | 41.087719 | 209 | 0.670905 | false | false | false | false |
boxenjim/SwiftyFaker | refs/heads/master | SwiftyFaker/Random.swift | mit | 1 | //
// RandomNumbers.swift
// SwiftyFaker
//
// Created by Jim Schultz on 9/23/15.
// Copyright © 2015 Jim Schultz. All rights reserved.
//
import Foundation
/**
Arc Random for Double and Float
*/
func arc4random <T: ExpressibleByIntegerLiteral> (_ type: T.Type) -> T {
var r: T = 0
arc4random_buf(&r, MemoryLayout<T>.size)
return r
}
extension UInt64 {
static func random(_ lower: UInt64 = min, upper: UInt64 = max) -> UInt64 {
var m: UInt64
let u = upper - lower
var r = arc4random(UInt64.self)
if u > UInt64(Int64.max) {
m = 1 + ~u
} else {
m = ((max - (u * 2)) + 1) % u
}
while r < m {
r = arc4random(UInt64.self)
}
return (r % u) + lower
}
}
extension Int64 {
static func random(_ lower: Int64 = min, upper: Int64 = max) -> Int64 {
let (s, overflow) = upper.subtractingReportingOverflow(lower)
let u = overflow ? UInt64.max - UInt64(~s) : UInt64(s)
let r = UInt64.random(upper: u)
if r > UInt64(Int64.max) {
return Int64(r - (UInt64(~lower) + 1))
} else {
return Int64(r) + lower
}
}
}
extension UInt32 {
static func random(_ lower: UInt32 = min, upper: UInt32 = max) -> UInt32 {
return arc4random_uniform(upper - lower) + lower
}
}
extension Int32 {
static func random(_ lower: Int32 = min, upper: Int32 = max) -> Int32 {
let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower)))
return Int32(Int64(r) + Int64(lower))
}
}
extension UInt {
static func random(_ lower: UInt = min, upper: UInt = max) -> UInt {
switch (__WORDSIZE) {
case 32: return UInt(UInt32.random(UInt32(lower), upper: UInt32(upper)))
case 64: return UInt(UInt64.random(UInt64(lower), upper: UInt64(upper)))
default: return lower
}
}
}
extension Int {
static func random(_ lower: Int = min, upper: Int = max) -> Int {
switch (__WORDSIZE) {
case 32: return Int(Int32.random(Int32(lower), upper: Int32(upper)))
case 64: return Int(Int64.random(Int64(lower), upper: Int64(upper)))
default: return lower
}
}
}
public extension Int {
public static func random(_ range: Range<Int>) -> Int {
let offset = range.lowerBound < 0 ? abs(range.lowerBound) : 0
let min = UInt32(range.lowerBound + offset)
let max = UInt32(range.upperBound + offset)
return Int(min + arc4random_uniform(max - min)) - offset
}
public static func random(_ digits: Int) -> Int {
let min = getMin(digits)
let max = getMax(digits)
return Int.random(min, upper: max)
}
fileprivate static func getMin(_ digits: Int) -> Int {
var strng = "1"
let absMax = UInt.max
let maxCount = "\(absMax)".characters.count
let adjCount = digits > maxCount ? maxCount : digits
for _ in 1..<adjCount {
strng += "0"
}
return Int(strng)!
}
fileprivate static func getMax(_ digits: Int) -> Int {
var strng = ""
let absMax = UInt.max
if digits >= "\(absMax)".characters.count {
strng = "\(UInt.max)"
} else {
for _ in 0..<digits {
strng += "9"
}
}
return Int(strng)!
}
}
public extension Double {
public static func random(_ min: Double = 0.0, max: Double = 1.0) -> Double {
let offset = min < 0.0 ? Swift.abs(min) : 0.0
let low = min + offset
let high = max + offset
let r = Double(arc4random(UInt64.self)) / Double(UInt64.max)
return ((r * (high - low)) + low) - offset
}
}
public extension Float {
public static func random(_ min: Float = 0.0, max: Float = 1.0) -> Float {
let offset = min < 0.0 ? Swift.abs(min) : Float(0.0)
let low = min + offset
let high = max + offset
let r = Float(arc4random(UInt32.self)) / Float(UInt32.max)
return ((r * (high - low)) + low) - offset
}
}
public extension Array {
public func random() -> Element {
let randInt = Int.random(0..<self.count)
let obj = self[randInt]
return obj
}
}
| eadfff852fffc0a608b87d2e3bc11be9 | 27.392157 | 81 | 0.546961 | false | false | false | false |
andrebocchini/SwiftChattyOSX | refs/heads/master | Pods/SwiftChatty/SwiftChatty/Requests/Threads/GetThreadPostIdsRequest.swift | mit | 1 | //
// GetThreadPostIdsRequest.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/17/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
/// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451666
public struct GetThreadPostIdsRequest: Request {
public let endpoint: ApiEndpoint = .GetThreadPostIds
public var parameters: [String : AnyObject] = [:]
public init(withThreadIds ids: [Int]) {
if ids.count > 0 {
var concatenatedIds: String = ""
for i in 0...(ids.count - 1) {
if i == 0 {
concatenatedIds += String(ids[i])
} else {
concatenatedIds += ("," + String(ids[i]))
}
}
self.parameters["id"] = concatenatedIds
}
}
}
| 83f4382a4ba64aafb8f416d5120e2565 | 27.034483 | 61 | 0.544895 | false | false | false | false |
yanagiba/swift-transform | refs/heads/master | Sources/swift-transform/Option.swift | apache-2.0 | 1 | /*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
func computeFormats(
_ dotYanagibaTransform: DotYanagibaTransform?,
_ formatsOption: [String: Any]?
) -> [String: Any]? {
var formats: [String: Any]?
if let dotYanagibaTransform = dotYanagibaTransform, let customFormats = dotYanagibaTransform.formats {
formats = customFormats
}
if let customFormats = formatsOption {
formats = customFormats
}
return formats
}
enum OutputOption {
case standardOutput
case fileOutput(String)
}
func computeOutput(
_ dotYanagibaTransform: DotYanagibaTransform?,
_ outputPathOption: String?
) -> OutputOption {
var outputPath: String?
if let dotYanagibaTransform = dotYanagibaTransform, let outputPathOption = dotYanagibaTransform.outputPath {
outputPath = outputPathOption
}
if let outputPathOption = outputPathOption {
outputPath = outputPathOption
}
if let fileOutput = outputPath {
return .fileOutput(fileOutput)
}
return .standardOutput
}
| 37a8416ae403da06b1b4862920b6b13d | 28.5 | 110 | 0.750157 | false | false | false | false |
sfaxon/PyxisServer | refs/heads/master | Sources/HTTPResponse.swift | mit | 1 | //
// HTTPResponse.swift
// PyxisRouter
//
// Created by Seth Faxon on 8/23/15.
// Copyright © 2015 SlashAndBurn. All rights reserved.
//
public protocol HttpResponseProtocol {
var statusCode: Int { get set }
var headers: [String: String] { get set }
var body: String { get set }
}
public class HttpResponse: HttpResponseProtocol {
public var statusCode: Int = 200
public var headers: [String: String] = [:]
public var body: String = ""
// resp_body - the response body, by default is an empty string. It is set to nil after the response is set, except for test connections.
// resp_charset - the response charset, defaults to “utf-8”
// resp_cookies - the response cookies with their name and options
// resp_headers - the response headers as a dict, by default cache-control is set to "max-age=0, private, must-revalidate"
// status - the response status
public var description: String {
// HTTP/1.1 200 OK
// Content-Length: 27
//
// hello world for the request
let headerString = headers.map { "\($0): \($1)" }.joinWithSeparator("\n")
return "HTTP/1.1 \(statusCode) OK\n\(headerString)\nContent-Length: xx\n\n\(body)"
}
}
//public enum HttpResponseBody {
// case HTML(String)
// case RAW(String)
//
// var data: String {
// switch self {
// case .HTML(let body):
// return "<html><body>\(body)</body></html>"
// case .RAW(let body):
// return body
// }
// }
//}
//
//public protocol HttpResponse {
// var statusCode: Int { get }
// var headers: [String: String] { get }
// var body: String { get }
//}
//
//public protocol HTTPResponder {
// func call(request: HttpRequest, response: HttpResponse) -> HttpResponse
//}
//
//public struct BaseResponse: HttpResponse, HTTPResponder {
// public var statusCode: Int = 200
// public var headers: [String: String] = [:]
// public var body: String = ""
//
// private var request: HttpRequest
// public init(request: HttpRequest) {
// self.request = request
// }
//
// public func call(request: HttpRequest, response: HttpResponse) -> HttpResponse {
// var newResponse = BaseResponse(request: request)
// newResponse.statusCode = self.statusCode
// newResponse.headers = self.headers
// newResponse.body = self.body
//
// return self
// }
//}
//
//public struct HTTPPipeline: HTTPResponder {
// public var responders: [HTTPResponder] = []
//
// public init(responders: [HTTPResponder]) {
// self.responders = responders
// }
//
// public func call(request: HttpRequest, response: HttpResponse) -> HttpResponse {
// var response = BaseResponse(request: request) as HttpResponse
// for (index, responder) in self.responders.enumerate() {
// print("index: \(index) response: \(response)")
// response = responder.call(request, response: response)
// }
// print("final: \(response)")
// return response
// }
//}
//
//
| 88143d4ebfb35b21d1f8f9bf2a3205dc | 30.81 | 148 | 0.598554 | false | false | false | false |
elpassion/el-space-ios | refs/heads/master | ELSpaceTests/TestCases/ViewControllers/LoginViewControllerSpec.swift | gpl-3.0 | 1 | import Quick
import Nimble
import GoogleSignIn
import RxTest
@testable import ELSpace
class LoginViewControllerSpec: QuickSpec {
override func spec() {
describe("LoginViewController") {
var sut: LoginViewController!
var navigationController: UINavigationController!
var viewControllerPresenterSpy: ViewControllerPresenterSpy!
var googleUserManagerSpy: GoogleUserManagerSpy!
afterEach {
sut = nil
navigationController = nil
viewControllerPresenterSpy = nil
googleUserManagerSpy = nil
}
context("when try to initialize with init coder") {
it("should throw fatalError") {
expect { sut = LoginViewController(coder: NSCoder()) }.to(throwAssertion())
}
}
context("after initialize") {
beforeEach {
viewControllerPresenterSpy = ViewControllerPresenterSpy()
googleUserManagerSpy = GoogleUserManagerSpy()
sut = LoginViewController(googleUserManager: googleUserManagerSpy,
alertFactory: AlertFactoryFake(),
viewControllerPresenter: viewControllerPresenterSpy,
googleUserMapper: GoogleUSerMapperFake())
navigationController = UINavigationController(rootViewController: sut)
}
describe("view") {
it("should be kind of LoginView") {
expect(sut.view as? LoginView).toNot(beNil())
}
context("when appear") {
beforeEach {
sut.viewWillAppear(true)
}
it("should set navigation bar hidden") {
expect(navigationController.isNavigationBarHidden).to(beTrue())
}
}
}
context("when viewDidAppear") {
beforeEach {
sut.viewDidAppear(true)
}
it("should call autoSignIn") {
expect(googleUserManagerSpy.didCallAutoSignIn).to(beTrue())
}
}
context("when viewWillAppear") {
beforeEach {
sut.viewWillAppear(true)
}
it("should set navigation bar to hidden") {
expect(navigationController.isNavigationBarHidden).to(beTrue())
}
}
it("should have correct preferredStatusBarStyle") {
expect(sut.preferredStatusBarStyle == .lightContent).to(beTrue())
}
context("when tap sign in button and sign in with success") {
var resultToken: String!
beforeEach {
sut.googleTooken = { token in
resultToken = token
}
googleUserManagerSpy.resultUser = GIDGoogleUser()
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should sign in on correct view controller") {
expect(googleUserManagerSpy.viewController).to(equal(sut))
}
it("should get correct token") {
expect(resultToken).to(equal("fake_token"))
}
}
context("when tap sign in button and sign in with ValidationError emialFormat") {
beforeEach {
googleUserManagerSpy.resultError = EmailValidator.EmailValidationError.emailFormat
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should present error on correct view controller") {
expect(viewControllerPresenterSpy.presenter).to(equal(sut))
}
}
context("when tap sign in button and sign in with ValidationError incorrectDomain") {
beforeEach {
googleUserManagerSpy.resultError = EmailValidator.EmailValidationError.incorrectDomain
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should present error on correct view controller") {
expect(viewControllerPresenterSpy.presenter).to(equal(sut))
}
}
context("when tap sign in button and sign in with unkown error") {
beforeEach {
googleUserManagerSpy.resultError = NSError(domain: "fake_domain",
code: 999,
userInfo: nil)
sut.loginView.loginButton.sendActions(for: .touchUpInside)
}
it("should NOT present error") {
expect(viewControllerPresenterSpy.presenter).to(beNil())
}
}
}
}
}
}
| cfdc10090e4a6de252c1ed09b87c9d56 | 38.692857 | 110 | 0.478316 | false | false | false | false |
sundeepgupta/chord | refs/heads/master | chord/BeaconId.swift | apache-2.0 | 1 | typealias BeaconId = [String: NSObject]
extension Dictionary where Key: StringLiteralConvertible, Value: NSObject {
var uuid: String {
get {
return self["uuid"] as! String
}
}
var major: NSNumber {
get {
return self["major"] as! NSNumber
}
}
var minor: NSNumber {
get {
return self["minor"] as! NSNumber
}
}
}
import CoreLocation
extension CLBeacon {
func toBeaconId() -> BeaconId {
return [
DictionaryKey.uuid: self.proximityUUID.UUIDString,
DictionaryKey.major: self.major,
DictionaryKey.minor: self.minor
]
}
}
extension SequenceType where Generator.Element == BeaconId {
func includes (element: Generator.Element) -> Bool {
return self.contains { myElement -> Bool in
return myElement == element
}
}
} | 6b32dc1107a996b151588c93bdd9520f | 20.090909 | 75 | 0.567422 | false | false | false | false |
LuAndreCast/iOS_WatchProjects | refs/heads/master | watchOS2/Heart Rate/v3 Heart Rate Stream/HealthWatchExample/MainViewController.swift | mit | 1 | //
// MainViewController.swift
// HealthWatchExample
//
// Created by Luis Castillo on 8/2/16.
// Copyright © 2016 LC. All rights reserved.
//
import UIKit
import HealthKit
class MainViewController: UIViewController,watchMessengerDelegate
{
//watch messenger
let wMessenger = WatchMessenger()
//heart Rate
let hrPermission = HeartRatePermission()
let healthStore = HKHealthStore()
@IBOutlet weak var startEndMonitoringButton: UIButton!
@IBOutlet weak var messageLabel: UILabel!
//MARK: - View
override func viewDidLoad() {
super.viewDidLoad()
self.wMessenger.delegate = self
self.wMessenger.start()
}//eom
override func viewDidAppear(_ animated: Bool)
{
self.requestHeartRatePermission()
}//eom
//MARK: - Actions
@IBAction func startEndMonitoring(_ sender: AnyObject)
{
if self.startEndMonitoringButton.isSelected
{
self.startEndMonitoringButton.isSelected = false
self.end()
}
else
{
self.startEndMonitoringButton.isSelected = true
self.start()
}
}//eom
//MARK: Start / End Monitoring
func start()
{
let messageFromPhone = [ keys.command.toString() : command.startMonitoring.toString() ]
wMessenger.sendMessage(messageFromPhone as [String : AnyObject])
{ (reply:[String : Any]?, error:Error?) in
if error != nil
{
self.startEndMonitoringButton.isSelected = false
self.updateUI()
//show error
}
else
{
}
}
}//eom
func end()
{
let messageFromPhone = [ keys.command.toString() : command.endMonitoring.toString() ]
wMessenger.sendMessage(messageFromPhone as [String : AnyObject])
{ (reply:[String : Any]?, error:Error?) in
if error != nil
{
self.startEndMonitoringButton.isSelected = true
self.updateUI()
//show error
}
else
{
}
}
}//eom
fileprivate func updateUI()
{
if self.startEndMonitoringButton.isSelected
{
self.messageLabel.text = "Started Monitoring"
self.startEndMonitoringButton.setTitle("End Monitoring", for: UIControlState())
}
else
{
self.messageLabel.text = "Ended Monitoring"
self.startEndMonitoringButton.setTitle("Start Monitoring", for: UIControlState())
}
}//eom
//MARK: - Messenger Delegates
func watchMessenger_didReceiveMessage(_ message: [String : AnyObject])
{
DispatchQueue.main.async {
//reponses
if let commandReceived:String = message[keys.response.toString()] as? String
{
switch commandReceived
{
case response.startedMonitoring.toString():
self.startEndMonitoringButton.isSelected = true
self.updateUI()
break
case response.endedMonitoring.toString():
self.startEndMonitoringButton.isSelected = false
self.updateUI()
break
case response.data.toString():
let hrValue:Double? = message[keys.heartRate.toString()] as? Double
let hrTime:String? = message[keys.time.toString()] as? String
let hrDate:String? = message[keys.date.toString()] as? String
if hrValue != nil && hrTime != nil && hrDate != nil
{
self.messageLabel.text = "Heart rate Data:\n \(hrValue!) \n at \(hrTime!) \n on \(hrDate!)"
}
break
case response.errorHealthKit.toString():
self.messageLabel.text = "Error with HealthKit"
break
case response.errorMonitoring.toString():
self.messageLabel.text = "Error with Monitoring"
break
default:
self.messageLabel.text = "Unknown response received"
break
}
}
else
{
self.messageLabel.text = "Unknown received"
}
}
}//eom
func watchMessenger_startResults(_ started: Bool, error: NSError?)
{
if error != nil
{
self.messageLabel.text = error?.localizedDescription
}
}//eom
//MARK: - Request Heart Rate Permission
func requestHeartRatePermission()
{
hrPermission.requestPermission(healthStore)
{ (success:Bool, error:NSError?) in
}
}//eom
}//eoc
| d2e83b8e7f8324e904bfc7e7b2654466 | 28.977143 | 119 | 0.506291 | false | false | false | false |
wilfreddekok/Antidote | refs/heads/master | Antidote/ErrorHandling.swift | mpl-2.0 | 1 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
enum ErrorHandlerType {
case CannotLoadHTML
case CreateOCTManager
case ToxSetInfoCodeName
case ToxSetInfoCodeStatusMessage
case ToxAddFriend
case RemoveFriend
case CallToChat
case ExportProfile
case DeleteProfile
case PasswordIsEmpty
case WrongOldPassword
case PasswordsDoNotMatch
case AnswerCall
case RouteAudioToSpeaker
case EnableVideoSending
case CallSwitchCamera
case ConvertImageToPNG
case ChangeAvatar
case SendFileToFriend
case AcceptIncomingFile
case CancelFileTransfer
case PauseFileTransfer
}
/**
Show alert for given error.
- Parameters:
- type: Type of error to handle.
- error: Optional erro to get code from.
- retryBlock: If set user will be asked to retry request once again.
*/
func handleErrorWithType(type: ErrorHandlerType, error: NSError? = nil, retryBlock: (Void -> Void)? = nil) {
switch type {
case .CannotLoadHTML:
UIAlertController.showErrorWithMessage(String(localized: "error_internal_message"), retryBlock: retryBlock)
case .CreateOCTManager:
let (title, message) = OCTManagerInitError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .ToxSetInfoCodeName:
let (title, message) = OCTToxErrorSetInfoCode(rawValue: error!.code)!.nameStrings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .ToxSetInfoCodeStatusMessage:
let (title, message) = OCTToxErrorSetInfoCode(rawValue: error!.code)!.statusMessageStrings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .ToxAddFriend:
let (title, message) = OCTToxErrorFriendAdd(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .RemoveFriend:
let (title, message) = OCTToxErrorFriendDelete(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .CallToChat:
let (title, message) = OCTToxAVErrorCall(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .ExportProfile:
UIAlertController.showWithTitle(String(localized: "error_title"), message: error!.localizedDescription, retryBlock: retryBlock)
case .DeleteProfile:
UIAlertController.showWithTitle(String(localized: "error_title"), message: error!.localizedDescription, retryBlock: retryBlock)
case .PasswordIsEmpty:
UIAlertController.showWithTitle(String(localized: "password_is_empty_error"), retryBlock: retryBlock)
case .WrongOldPassword:
UIAlertController.showWithTitle(String(localized: "wrong_old_password"), retryBlock: retryBlock)
case .PasswordsDoNotMatch:
UIAlertController.showWithTitle(String(localized: "passwords_do_not_match"), retryBlock: retryBlock)
case .AnswerCall:
let (title, message) = OCTToxAVErrorAnswer(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .RouteAudioToSpeaker:
UIAlertController.showWithTitle(String(localized: "error_title"), message: String(localized: "error_internal_message"), retryBlock: retryBlock)
case .EnableVideoSending:
UIAlertController.showWithTitle(String(localized: "error_title"), message: String(localized: "error_internal_message"), retryBlock: retryBlock)
case .CallSwitchCamera:
UIAlertController.showWithTitle(String(localized: "error_title"), message: String(localized: "error_internal_message"), retryBlock: retryBlock)
case .ConvertImageToPNG:
UIAlertController.showWithTitle(String(localized: "error_title"), message: String(localized: "change_avatar_error_convert_image"), retryBlock: retryBlock)
case .ChangeAvatar:
let (title, message) = OCTSetUserAvatarError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .SendFileToFriend:
let (title, message) = OCTSendFileError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .AcceptIncomingFile:
let (title, message) = OCTAcceptFileError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .CancelFileTransfer:
let (title, message) = OCTFileTransferError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
case .PauseFileTransfer:
let (title, message) = OCTFileTransferError(rawValue: error!.code)!.strings()
UIAlertController.showWithTitle(title, message: message, retryBlock: retryBlock)
}
}
extension OCTManagerInitError {
func strings() -> (title: String, message: String) {
switch self {
case .PassphraseFailed:
return (String(localized: "error_wrong_password_title"),
String(localized: "error_wrong_password_message"))
case .CannotImportToxSave:
return (String(localized: "error_import_not_exist_title"),
String(localized: "error_import_not_exist_message"))
case .DatabaseKeyCannotCreateKey:
fallthrough
case .DatabaseKeyCannotReadKey:
fallthrough
case .DatabaseKeyMigrationToEncryptedFailed:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .ToxFileDecryptNull:
fallthrough
case .DatabaseKeyDecryptNull:
return (String(localized: "error_decrypt_title"),
String(localized: "error_decrypt_empty_data_message"))
case .ToxFileDecryptBadFormat:
fallthrough
case .DatabaseKeyDecryptBadFormat:
return (String(localized: "error_decrypt_title"),
String(localized: "error_decrypt_bad_format_message"))
case .ToxFileDecryptFailed:
fallthrough
case .DatabaseKeyDecryptFailed:
return (String(localized: "error_decrypt_title"),
String(localized: "error_decrypt_wrong_password_message"))
case .CreateToxUnknown:
return (String(localized: "error_title"),
String(localized: "error_general_unknown_message"))
case .CreateToxMemoryError:
return (String(localized: "error_title"),
String(localized: "error_general_no_memory_message"))
case .CreateToxPortAlloc:
return (String(localized: "error_title"),
String(localized: "error_general_bind_port_message"))
case .CreateToxProxyBadType:
return (String(localized: "error_proxy_title"),
String(localized: "error_internal_message"))
case .CreateToxProxyBadHost:
return (String(localized: "error_proxy_title"),
String(localized: "error_proxy_invalid_address_message"))
case .CreateToxProxyBadPort:
return (String(localized: "error_proxy_title"),
String(localized: "error_proxy_invalid_port_message"))
case .CreateToxProxyNotFound:
return (String(localized: "error_proxy_title"),
String(localized: "error_proxy_host_not_resolved_message"))
case .CreateToxEncrypted:
return (String(localized: "error_title"),
String(localized: "error_general_profile_encrypted_message"))
case .CreateToxBadFormat:
return (String(localized: "error_title"),
String(localized: "error_general_bad_format_message"))
}
}
}
extension OCTToxErrorSetInfoCode {
func nameStrings() -> (title: String, message: String) {
switch self {
case .Unknow:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .TooLong:
return (String(localized: "error_title"),
String(localized: "error_name_too_long"))
}
}
func statusMessageStrings() -> (title: String, message: String) {
switch self {
case .Unknow:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .TooLong:
return (String(localized: "error_title"),
String(localized: "error_status_message_too_long"))
}
}
}
extension OCTToxErrorFriendAdd {
func strings() -> (title: String, message: String) {
switch self {
case .TooLong:
return (String(localized: "error_title"),
String(localized: "error_contact_request_too_long"))
case .NoMessage:
return (String(localized: "error_title"),
String(localized: "error_contact_request_no_message"))
case .OwnKey:
return (String(localized: "error_title"),
String(localized: "error_contact_request_own_key"))
case .AlreadySent:
return (String(localized: "error_title"),
String(localized: "error_contact_request_already_sent"))
case .BadChecksum:
return (String(localized: "error_title"),
String(localized: "error_contact_request_bad_checksum"))
case .SetNewNospam:
return (String(localized: "error_title"),
String(localized: "error_contact_request_new_nospam"))
case .Malloc:
fallthrough
case .Unknown:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTToxErrorFriendDelete {
func strings() -> (title: String, message: String) {
switch self {
case .NotFound:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTToxAVErrorCall {
func strings() -> (title: String, message: String) {
switch self {
case .AlreadyInCall:
return (String(localized: "error_title"),
String(localized: "call_error_already_in_call"))
case .FriendNotConnected:
return (String(localized: "error_title"),
String(localized: "call_error_contact_is_offline"))
case .FriendNotFound:
fallthrough
case .InvalidBitRate:
fallthrough
case .Malloc:
fallthrough
case .Sync:
fallthrough
case .Unknown:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTToxAVErrorAnswer {
func strings() -> (title: String, message: String) {
switch self {
case .FriendNotCalling:
return (String(localized: "error_title"),
String(localized: "call_error_no_active_call"))
case .CodecInitialization:
fallthrough
case .Sync:
fallthrough
case .InvalidBitRate:
fallthrough
case .Unknown:
fallthrough
case .FriendNotFound:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTSetUserAvatarError {
func strings() -> (title: String, message: String) {
switch self {
case .TooBig:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
extension OCTSendFileError {
func strings() -> (title: String, message: String) {
switch self {
case .InternalError:
fallthrough
case .CannotReadFile:
fallthrough
case .CannotSaveFileToUploads:
fallthrough
case .NameTooLong:
fallthrough
case .FriendNotFound:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .FriendNotConnected:
return (String(localized: "error_title"),
String(localized: "error_contact_not_connected"))
case .TooMany:
return (String(localized: "error_title"),
String(localized: "error_too_many_files"))
}
}
}
extension OCTAcceptFileError {
func strings() -> (title: String, message: String) {
switch self {
case .InternalError:
fallthrough
case .CannotWriteToFile:
fallthrough
case .FriendNotFound:
fallthrough
case .WrongMessage:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
case .FriendNotConnected:
return (String(localized: "error_title"),
String(localized: "error_contact_not_connected"))
}
}
}
extension OCTFileTransferError {
func strings() -> (title: String, message: String) {
switch self {
case .WrongMessage:
return (String(localized: "error_title"),
String(localized: "error_internal_message"))
}
}
}
| ed87761991e27b841120482867ba63e8 | 43.260479 | 166 | 0.596225 | false | false | false | false |
JGiola/swift-corelibs-foundation | refs/heads/master | Foundation/URLSession/NativeProtocol.swift | apache-2.0 | 2 | // Foundation/URLSession/NativeProtocol.swift - NSURLSession & libcurl
//
// 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// This file has the common implementation of Native protocols like HTTP,FTP,Data
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: NSURLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
internal let enableLibcurlDebugOutput: Bool = {
return ProcessInfo.processInfo.environment["URLSessionDebugLibcurl"] != nil
}()
internal let enableDebugOutput: Bool = {
return ProcessInfo.processInfo.environment["URLSessionDebug"] != nil
}()
internal class _NativeProtocol: URLProtocol, _EasyHandleDelegate {
internal var easyHandle: _EasyHandle!
internal lazy var tempFileURL: URL = {
let fileName = NSTemporaryDirectory() + NSUUID().uuidString + ".tmp"
_ = FileManager.default.createFile(atPath: fileName, contents: nil)
return URL(fileURLWithPath: fileName)
}()
public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
self.internalState = .initial
super.init(request: task.originalRequest!, cachedResponse: cachedResponse, client: client)
self.task = task
self.easyHandle = _EasyHandle(delegate: self)
}
public required init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
self.internalState = .initial
super.init(request: request, cachedResponse: cachedResponse, client: client)
self.easyHandle = _EasyHandle(delegate: self)
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
resume()
}
override func stopLoading() {
if task?.state == .suspended {
suspend()
} else {
self.internalState = .transferFailed
guard let error = self.task?.error else { fatalError() }
completeTask(withError: error)
}
}
var internalState: _InternalState {
// We manage adding / removing the easy handle and pausing / unpausing
// here at a centralized place to make sure the internal state always
// matches up with the state of the easy handle being added and paused.
willSet {
if !internalState.isEasyHandlePaused && newValue.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
if internalState.isEasyHandleAddedToMultiHandle && !newValue.isEasyHandleAddedToMultiHandle {
task?.session.remove(handle: easyHandle)
}
}
didSet {
if !oldValue.isEasyHandleAddedToMultiHandle && internalState.isEasyHandleAddedToMultiHandle {
task?.session.add(handle: easyHandle)
}
if oldValue.isEasyHandlePaused && !internalState.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
}
}
func didReceive(data: Data) -> _EasyHandle._Action {
guard case .transferInProgress(var ts) = internalState else {
fatalError("Received body data, but no transfer in progress.")
}
if let response = validateHeaderComplete(transferState:ts) {
ts.response = response
}
notifyDelegate(aboutReceivedData: data)
internalState = .transferInProgress(ts.byAppending(bodyData: data))
return .proceed
}
func validateHeaderComplete(transferState: _TransferState) -> URLResponse? {
guard transferState.isHeaderComplete else {
fatalError("Received body data, but the header is not complete, yet.")
}
return nil
}
fileprivate func notifyDelegate(aboutReceivedData data: Data) {
guard let t = self.task else {
fatalError("Cannot notify")
}
if case .taskDelegate(let delegate) = t.session.behaviour(for: self.task!),
let dataDelegate = delegate as? URLSessionDataDelegate,
let task = self.task as? URLSessionDataTask {
// Forward to the delegate:
guard let s = self.task?.session as? URLSession else {
fatalError()
}
s.delegateQueue.addOperation {
dataDelegate.urlSession(s, dataTask: task, didReceive: data)
}
} else if case .taskDelegate(let delegate) = t.session.behaviour(for: self.task!),
let downloadDelegate = delegate as? URLSessionDownloadDelegate,
let task = self.task as? URLSessionDownloadTask {
guard let s = self.task?.session as? URLSession else {
fatalError()
}
let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL)
_ = fileHandle.seekToEndOfFile()
fileHandle.write(data)
task.countOfBytesReceived += Int64(data.count)
s.delegateQueue.addOperation {
downloadDelegate.urlSession(s, downloadTask: task, didWriteData: Int64(data.count), totalBytesWritten: task.countOfBytesReceived,
totalBytesExpectedToWrite: task.countOfBytesExpectedToReceive)
}
if task.countOfBytesExpectedToReceive == task.countOfBytesReceived {
fileHandle.closeFile()
self.properties[.temporaryFileURL] = self.tempFileURL
}
}
}
fileprivate func notifyDelegate(aboutUploadedData count: Int64) {
guard let task = self.task as? URLSessionUploadTask,
let session = self.task?.session as? URLSession,
case .taskDelegate(let delegate) = session.behaviour(for: task) else { return }
task.countOfBytesSent += count
session.delegateQueue.addOperation {
delegate.urlSession(session, task: task, didSendBodyData: count,
totalBytesSent: task.countOfBytesSent, totalBytesExpectedToSend: task.countOfBytesExpectedToSend)
}
}
func didReceive(headerData data: Data, contentLength: Int64) -> _EasyHandle._Action {
NSRequiresConcreteImplementation()
}
func fill(writeBuffer buffer: UnsafeMutableBufferPointer<Int8>) -> _EasyHandle._WriteBufferResult {
guard case .transferInProgress(let ts) = internalState else {
fatalError("Requested to fill write buffer, but transfer isn't in progress.")
}
guard let source = ts.requestBodySource else {
fatalError("Requested to fill write buffer, but transfer state has no body source.")
}
switch source.getNextChunk(withLength: buffer.count) {
case .data(let data):
copyDispatchData(data, infoBuffer: buffer)
let count = data.count
assert(count > 0)
notifyDelegate(aboutUploadedData: Int64(count))
return .bytes(count)
case .done:
return .bytes(0)
case .retryLater:
// At this point we'll try to pause the easy handle. The body source
// is responsible for un-pausing the handle once data becomes
// available.
return .pause
case .error:
return .abort
}
}
func transferCompleted(withError error: NSError?) {
// At this point the transfer is complete and we can decide what to do.
// If everything went well, we will simply forward the resulting data
// to the delegate. But in case of redirects etc. we might send another
// request.
guard case .transferInProgress(let ts) = internalState else {
fatalError("Transfer completed, but it wasn't in progress.")
}
guard let request = task?.currentRequest else {
fatalError("Transfer completed, but there's no current request.")
}
guard error == nil else {
internalState = .transferFailed
failWith(error: error!, request: request)
return
}
if let response = task?.response {
var transferState = ts
transferState.response = response
}
guard let response = ts.response else {
fatalError("Transfer completed, but there's no response.")
}
internalState = .transferCompleted(response: response, bodyDataDrain: ts.bodyDataDrain)
let action = completionAction(forCompletedRequest: request, response: response)
switch action {
case .completeTask:
completeTask()
case .failWithError(let errorCode):
internalState = .transferFailed
let error = NSError(domain: NSURLErrorDomain, code: errorCode,
userInfo: [NSLocalizedDescriptionKey: "Completion failure"])
failWith(error: error, request: request)
case .redirectWithRequest(let newRequest):
redirectFor(request: newRequest)
}
}
func redirectFor(request: URLRequest) {
NSRequiresConcreteImplementation()
}
func completeTask() {
guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = self.internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete.")
}
task?.response = response
// We don't want a timeout to be triggered after this. The timeout timer needs to be cancelled.
easyHandle.timeoutTimer = nil
// because we deregister the task with the session on internalState being set to taskCompleted
// we need to do the latter after the delegate/handler was notified/invoked
if case .inMemory(let bodyData) = bodyDataDrain {
var data = Data()
if let body = bodyData {
data = Data(bytes: body.bytes, count: body.length)
}
self.client?.urlProtocol(self, didLoad: data)
self.internalState = .taskCompleted
}
if case .toFile(let url, let fileHandle?) = bodyDataDrain {
self.properties[.temporaryFileURL] = url
fileHandle.closeFile()
}
self.client?.urlProtocolDidFinishLoading(self)
self.internalState = .taskCompleted
}
func completionAction(forCompletedRequest request: URLRequest, response: URLResponse) -> _CompletionAction {
return .completeTask
}
func seekInputStream(to position: UInt64) throws {
// We will reset the body source and seek forward.
NSUnimplemented()
}
func updateProgressMeter(with propgress: _EasyHandle._Progress) {
//TODO: Update progress. Note that a single URLSessionTask might
// perform multiple transfers. The values in `progress` are only for
// the current transfer.
}
/// The data drain.
///
/// This depends on what the delegate / completion handler need.
fileprivate func createTransferBodyDataDrain() -> _DataDrain {
guard let task = task else {
fatalError()
}
let s = task.session as! URLSession
switch s.behaviour(for: task) {
case .noDelegate:
return .ignore
case .taskDelegate:
// Data will be forwarded to the delegate as we receive it, we don't
// need to do anything about it.
return .ignore
case .dataCompletionHandler:
// Data needs to be concatenated in-memory such that we can pass it
// to the completion handler upon completion.
return .inMemory(nil)
case .downloadCompletionHandler:
// Data needs to be written to a file (i.e. a download task).
let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL)
return .toFile(self.tempFileURL, fileHandle)
}
}
func createTransferState(url: URL, workQueue: DispatchQueue) -> _TransferState {
let drain = createTransferBodyDataDrain()
guard let t = task else {
fatalError("Cannot create transfer state")
}
switch t.body {
case .none:
return _TransferState(url: url, bodyDataDrain: drain)
case .data(let data):
let source = _BodyDataSource(data: data)
return _TransferState(url: url, bodyDataDrain: drain,bodySource: source)
case .file(let fileURL):
let source = _BodyFileSource(fileURL: fileURL, workQueue: workQueue, dataAvailableHandler: { [weak self] in
// Unpause the easy handle
self?.easyHandle.unpauseSend()
})
return _TransferState(url: url, bodyDataDrain: drain,bodySource: source)
case .stream:
NSUnimplemented()
}
}
/// Start a new transfer
func startNewTransfer(with request: URLRequest) {
guard let t = task else {
fatalError()
}
t.currentRequest = request
guard let url = request.url else {
fatalError("No URL in request.")
}
self.internalState = .transferReady(createTransferState(url: url, workQueue: t.workQueue))
if let authRequest = task?.authRequest {
configureEasyHandle(for: authRequest)
} else {
configureEasyHandle(for: request)
}
if (t.suspendCount) < 1 {
resume()
}
}
func resume() {
if case .initial = self.internalState {
guard let r = task?.originalRequest else {
fatalError("Task has no original request.")
}
startNewTransfer(with: r)
}
if case .transferReady(let transferState) = self.internalState {
self.internalState = .transferInProgress(transferState)
}
}
func suspend() {
if case .transferInProgress(let transferState) = self.internalState {
self.internalState = .transferReady(transferState)
}
}
func configureEasyHandle(for: URLRequest) {
NSRequiresConcreteImplementation()
}
}
extension _NativeProtocol {
/// Action to be taken after a transfer completes
enum _CompletionAction {
case completeTask
case failWithError(Int)
case redirectWithRequest(URLRequest)
}
func completeTask(withError error: Error) {
task?.error = error
guard case .transferFailed = self.internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete / failed.")
}
//We don't want a timeout to be triggered after this. The timeout timer needs to be cancelled.
easyHandle.timeoutTimer = nil
self.internalState = .taskCompleted
}
func failWith(error: NSError, request: URLRequest) {
//TODO: Error handling
let userInfo: [String : Any]? = request.url.map {
[
NSUnderlyingErrorKey: error,
NSURLErrorFailingURLErrorKey: $0,
NSURLErrorFailingURLStringErrorKey: $0.absoluteString,
NSLocalizedDescriptionKey: NSLocalizedString(error.localizedDescription, comment: "N/A")
]
}
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: error.code, userInfo: userInfo))
completeTask(withError: urlError)
self.client?.urlProtocol(self, didFailWithError: urlError)
}
/// Give the delegate a chance to tell us how to proceed once we have a
/// response / complete header.
///
/// This will pause the transfer.
func askDelegateHowToProceedAfterCompleteResponse(_ response: URLResponse, delegate: URLSessionDataDelegate) {
// Ask the delegate how to proceed.
// This will pause the easy handle. We need to wait for the
// delegate before processing any more data.
guard case .transferInProgress(let ts) = self.internalState else {
fatalError("Transfer not in progress.")
}
self.internalState = .waitingForResponseCompletionHandler(ts)
let dt = task as! URLSessionDataTask
// We need this ugly cast in order to be able to support `URLSessionTask.init()`
guard let s = task?.session as? URLSession else {
fatalError()
}
s.delegateQueue.addOperation {
delegate.urlSession(s, dataTask: dt, didReceive: response, completionHandler: { [weak self] disposition in
guard let task = self else { return }
self?.task?.workQueue.async {
task.didCompleteResponseCallback(disposition: disposition)
}
})
}
}
/// This gets called (indirectly) when the data task delegates lets us know
/// how we should proceed after receiving a response (i.e. complete header).
func didCompleteResponseCallback(disposition: URLSession.ResponseDisposition) {
guard case .waitingForResponseCompletionHandler(let ts) = self.internalState else {
fatalError("Received response disposition, but we're not waiting for it.")
}
switch disposition {
case .cancel:
let error = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled))
self.completeTask(withError: error)
self.client?.urlProtocol(self, didFailWithError: error)
case .allow:
// Continue the transfer. This will unpause the easy handle.
self.internalState = .transferInProgress(ts)
case .becomeDownload:
/* Turn this request into a download */
NSUnimplemented()
case .becomeStream:
/* Turn this task into a stream task */
NSUnimplemented()
}
}
}
extension _NativeProtocol {
enum _InternalState {
/// Task has been created, but nothing has been done, yet
case initial
/// The easy handle has been fully configured. But it is not added to
/// the multi handle.
case transferReady(_TransferState)
/// The easy handle is currently added to the multi handle
case transferInProgress(_TransferState)
/// The transfer completed.
///
/// The easy handle has been removed from the multi handle. This does
/// not necessarily mean the task completed. A task that gets
/// redirected will do multiple transfers.
case transferCompleted(response: URLResponse, bodyDataDrain: _NativeProtocol._DataDrain)
/// The transfer failed.
///
/// Same as `.transferCompleted`, but without response / body data
case transferFailed
/// Waiting for the completion handler of the HTTP redirect callback.
///
/// When we tell the delegate that we're about to perform an HTTP
/// redirect, we need to wait for the delegate to let us know what
/// action to take.
case waitingForRedirectCompletionHandler(response: URLResponse, bodyDataDrain: _NativeProtocol._DataDrain)
/// Waiting for the completion handler of the 'did receive response' callback.
///
/// When we tell the delegate that we received a response (i.e. when
/// we received a complete header), we need to wait for the delegate to
/// let us know what action to take. In this state the easy handle is
/// paused in order to suspend delegate callbacks.
case waitingForResponseCompletionHandler(_TransferState)
/// The task is completed
///
/// Contrast this with `.transferCompleted`.
case taskCompleted
}
}
extension _NativeProtocol._InternalState {
var isEasyHandleAddedToMultiHandle: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return true
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
var isEasyHandlePaused: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return false
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
}
extension _NativeProtocol {
enum _Error: Error {
case parseSingleLineError
case parseCompleteHeaderError
}
func errorCode(fileSystemError error: Error) -> Int {
func fromCocoaErrorCode(_ code: Int) -> Int {
switch code {
case CocoaError.fileReadNoSuchFile.rawValue:
return NSURLErrorFileDoesNotExist
case CocoaError.fileReadNoPermission.rawValue:
return NSURLErrorNoPermissionsToReadFile
default:
return NSURLErrorUnknown
}
}
switch error {
case let e as NSError where e.domain == NSCocoaErrorDomain:
return fromCocoaErrorCode(e.code)
default:
return NSURLErrorUnknown
}
}
}
extension _NativeProtocol._ResponseHeaderLines {
func createURLResponse(for URL: URL, contentLength: Int64) -> URLResponse? {
return URLResponse(url: URL, mimeType: nil, expectedContentLength: Int(contentLength), textEncodingName: nil)
}
}
internal extension _NativeProtocol {
enum _Body {
case none
case data(DispatchData)
/// Body data is read from the given file URL
case file(URL)
case stream(InputStream)
}
}
fileprivate extension _NativeProtocol._Body {
enum _Error : Error {
case fileForBodyDataNotFound
}
/// - Returns: The body length, or `nil` for no body (e.g. `GET` request).
func getBodyLength() throws -> UInt64? {
switch self {
case .none:
return 0
case .data(let d):
return UInt64(d.count)
/// Body data is read from the given file URL
case .file(let fileURL):
guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else {
throw _Error.fileForBodyDataNotFound
}
return s.uint64Value
case .stream:
return nil
}
}
}
extension _NativeProtocol {
/// Set request body length.
///
/// An unknown length
func set(requestBodyLength length: _HTTPURLProtocol._RequestBodyLength) {
switch length {
case .noBody:
easyHandle.set(upload: false)
easyHandle.set(requestBodyLength: 0)
case .length(let length):
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: Int64(length))
case .unknown:
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: -1)
}
}
enum _RequestBodyLength {
case noBody
///
case length(UInt64)
/// Will result in a chunked upload
case unknown
}
}
extension URLSession {
static func printDebug(_ text: @autoclosure () -> String) {
guard enableDebugOutput else { return }
debugPrint(text())
}
}
| 2a49ea34518afd2ee904099edd1e5616 | 38.462036 | 145 | 0.61825 | false | false | false | false |
Yummypets/YPImagePicker | refs/heads/master | Source/Pages/Gallery/BottomPager/YPPagerMenu.swift | mit | 1 | //
// YPPagerMenu.swift
// YPImagePicker
//
// Created by Sacha DSO on 24/01/2018.
// Copyright © 2016 Yummypets. All rights reserved.
//
import UIKit
import Stevia
final class YPPagerMenu: UIView {
var didSetConstraints = false
var menuItems = [YPMenuItem]()
convenience init() {
self.init(frame: .zero)
backgroundColor = .offWhiteOrBlack
clipsToBounds = true
}
var separators = [UIView]()
func setUpMenuItemsConstraints() {
let screenWidth = YPImagePickerConfiguration.screenWidth
let menuItemWidth: CGFloat = screenWidth / CGFloat(menuItems.count)
var previousMenuItem: YPMenuItem?
for m in menuItems {
subviews(
m
)
m.fillVertically().width(menuItemWidth)
if let pm = previousMenuItem {
pm-0-m
} else {
|m
}
previousMenuItem = m
}
}
override func updateConstraints() {
super.updateConstraints()
if !didSetConstraints {
setUpMenuItemsConstraints()
}
didSetConstraints = true
}
func refreshMenuItems() {
didSetConstraints = false
updateConstraints()
}
}
| e0a4f9032e3a3a0255b1c977db944e61 | 22.122807 | 75 | 0.557663 | false | false | false | false |
studyYF/YueShiJia | refs/heads/master | YueShiJia/YueShiJia/Classes/Main/YFTabBarViewController.swift | apache-2.0 | 1 | //
// YFTabBarViewController.swift
// YueShiJia
//
// Created by YangFan on 2017/5/10.
// Copyright © 2017年 YangFan. All rights reserved.
//
import UIKit
class YFTabBarViewController: UITabBarController {
//MARK: 定义属性
//MARK: 生命周期函数
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
tabBar.isTranslucent = false
addChildVC(vc: YFHomeViewController(), title: "首页", image: "YS_index_nor", selImage: "YS_index_sel", tag: 100)
addChildVC(vc: YFSubjectViewController(), title: "专题", image: "YS_pro_nor", selImage: "YS_pro_sel", tag: 101)
addChildVC(vc: YFShopViewController(), title: "店铺", image: "YS_shop_nor", selImage: "YS_shop_sel", tag: 102)
addChildVC(vc: YFBasketViewController(), title: "购物篮", image: "YS_car_nor", selImage: "YS_car_sel", tag: 103)
let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "YFProfileViewController")
addChildVC(vc: vc, title: "我", image: "YS_mine_nor", selImage: "YS_mine_sel", tag: 104)
}
}
//MARK: 设置UI
extension YFTabBarViewController {
fileprivate func addChildVC(vc: UIViewController, title: String, image: String,selImage: String,tag: Int) {
vc.tabBarItem.title = title
vc.tabBarItem.tag = tag
vc.tabBarItem.image = UIImage(named: image)
vc.tabBarItem.selectedImage = UIImage(named: selImage)
addChildViewController(YFNavigationController(rootViewController: vc))
}
}
// MARK: - UITabBarControllerDelegate
extension YFTabBarViewController: UITabBarControllerDelegate {
//获取选中的UITabBarButton,并添加图片动画
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
var view = tabBar.subviews[item.tag - 99]
if !view.isKind(of: NSClassFromString("UITabBarButton")!) {
view = tabBar.subviews[item.tag - 99 + 1]
}
for imageView in view.subviews {
//添加关键帧动画
if imageView.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) {
let keyAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
keyAnimation.values = [1.0,1.3,0.9,1.15,0.95,1.02,1.0]
keyAnimation.duration = 0.8
keyAnimation.calculationMode = kCAAnimationCubic
imageView.layer.add(keyAnimation, forKey: "transform.scale")
}
}
}
}
| 67d5887652e203b8e09e98e5c5a35a8f | 36.454545 | 130 | 0.652104 | false | false | false | false |
nishiyamaosamu/ColorLogger | refs/heads/master | ColorLoggerExample/ColorLoggerExample/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// ColorLoggerExample
//
// Created by Osamu Nishiyama on 2015/04/09.
// Copyright (c) 2015年 EVER SENSE, INC. All rights reserved.
//
import UIKit
let log = ColorLogger.defaultInstance
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
log.verbose("This is Verbose Log") //verbose not active. Default outputLogLevel is Debug
log.debug("This is Debug Log")
log.info("This is Info Log")
log.warning("This is Warning Log")
log.error("This is Error Log")
log.debug([1,2,3,4]) // AnyObject
let a : NSObject? = nil
log.debug(a) //nil
log.debug("one", 2, [3,4]) //variadic parameter
log.outputLogLevel = .Verbose
log.showFileInfo = false
log.showDate = false
log.showLogLevel = true
log.showFunctionName = false
print("")
log.verbose("This is Verbose Log")
log.debug("This is Debug Log")
log.info("This is Info Log")
log.warning("This is Warning Log")
log.error("This is Error Log")
log.outputLogLevel = .Warning
log.showLogLevel = false
log.showFileInfo = false
log.showFunctionName = true
log.showDate = true
print("")
log.verbose("This is Verbose Log") // not active
log.debug("This is Debug Log") // not active
log.info("This is Info Log") // not active
log.warning("This is Warning Log")
log.error("This is Error Log")
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 3dff3424d0e72133138bb6278102a26b | 38.077778 | 285 | 0.676713 | false | false | false | false |
karwa/swift | refs/heads/master | test/Interpreter/generic_objc_subclass.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
//
// RUN: %target-clang -fobjc-arc %S/../Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o
// RUN: %target-build-swift -I %S/../Inputs/ObjCClasses/ -Xlinker %t/ObjCClasses.o %s -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import ObjCClasses
@objc protocol P {
func calculatePrice() -> Int
}
protocol PP {
func calculateTaxes() -> Int
}
//
// Generic subclass of an @objc class
//
class A<T> : HasHiddenIvars, P {
var first: Int = 16
var second: T?
var third: Int = 61
override var description: String {
return "Grilled artichokes"
}
func calculatePrice() -> Int {
return 400
}
}
let a = A<Int>()
// CHECK: Grilled artichokes
// CHECK: Grilled artichokes
print(a.description)
print((a as NSObject).description)
let f = { (a.x, a.y, a.z, a.t, a.first, a.second, a.third) }
// CHECK: (0, 0, 0, 0, 16, nil, 61)
print(f())
// CHECK: (25, 225, 255, 2255, 16, nil, 61)
a.x = 25
a.y = 225
a.z = 255
a.t = 2255
print(f())
// CHECK: (36, 225, 255, 2255, 16, nil, 61)
a.x = 36
print(f())
// CHECK: (36, 225, 255, 2255, 16, Optional(121), 61)
a.second = 121
print(f())
//
// Instantiate the class with a different set of generic parameters
//
let aa = A<(Int, Int)>()
let ff = { (aa.x, aa.y, aa.z, aa.t, aa.first, aa.second, aa.third) }
// CHECK: (0, 0, 0, 0, 16, nil, 61)
print(ff())
aa.x = 101
aa.second = (19, 84)
aa.third = 17
// CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17)
print(ff())
//
// Concrete subclass of generic subclass of @objc class
//
class B : A<(Int, Int)> {
override var description: String {
return "Salmon"
}
@nonobjc override func calculatePrice() -> Int {
return 1675
}
}
class BB : B {}
class C : A<(Int, Int)>, PP {
@nonobjc override var description: String {
return "Invisible Chicken"
}
override func calculatePrice() -> Int {
return 650
}
func calculateTaxes() -> Int {
return 110
}
}
// CHECK: 400
// CHECK: 400
// CHECK: 650
// CHECK: 110
print((BB() as P).calculatePrice())
print((B() as P).calculatePrice())
print((C() as P).calculatePrice())
print((C() as PP).calculateTaxes())
// CHECK: Salmon
// CHECK: Grilled artichokes
print((B() as NSObject).description)
print((C() as NSObject).description)
let b = B()
let g = { (b.x, b.y, b.z, b.t, b.first, b.second, b.third) }
// CHECK: (0, 0, 0, 0, 16, nil, 61)
print(g())
b.x = 101
b.second = (19, 84)
b.third = 17
// CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17)
print(g())
//
// Generic subclass of @objc class without any generically-sized members
//
class FixedA<T> : HasHiddenIvars, P {
var first: Int = 16
var second: [T] = []
var third: Int = 61
override var description: String {
return "Grilled artichokes"
}
func calculatePrice() -> Int {
return 400
}
}
let fixedA = FixedA<Int>()
// CHECK: Grilled artichokes
// CHECK: Grilled artichokes
print(fixedA.description)
print((fixedA as NSObject).description)
let fixedF = { (fixedA.x, fixedA.y, fixedA.z, fixedA.t, fixedA.first, fixedA.second, fixedA.third) }
// CHECK: (0, 0, 0, 0, 16, [], 61)
print(fixedF())
// CHECK: (25, 225, 255, 2255, 16, [], 61)
fixedA.x = 25
fixedA.y = 225
fixedA.z = 255
fixedA.t = 2255
print(fixedF())
// CHECK: (36, 225, 255, 2255, 16, [], 61)
fixedA.x = 36
print(fixedF())
// CHECK: (36, 225, 255, 2255, 16, [121], 61)
fixedA.second = [121]
print(fixedF())
//
// Instantiate the class with a different set of generic parameters
//
let fixedAA = FixedA<(Int, Int)>()
let fixedFF = { (fixedAA.x, fixedAA.y, fixedAA.z, fixedAA.t, fixedAA.first, fixedAA.second, fixedAA.third) }
// CHECK: (0, 0, 0, 0, 16, [], 61)
print(fixedFF())
fixedAA.x = 101
fixedAA.second = [(19, 84)]
fixedAA.third = 17
// CHECK: (101, 0, 0, 0, 16, [(19, 84)], 17)
print(fixedFF())
//
// Concrete subclass of generic subclass of @objc class
// without any generically-sized members
//
class FixedB : FixedA<Int> {
override var description: String {
return "Salmon"
}
override func calculatePrice() -> Int {
return 1675
}
}
// CHECK: 675
print((FixedB() as P).calculatePrice())
// CHECK: Salmon
print((FixedB() as NSObject).description)
let fixedB = FixedB()
let fixedG = { (fixedB.x, fixedB.y, fixedB.z, fixedB.t, fixedB.first, fixedB.second, fixedB.third) }
// CHECK: (0, 0, 0, 0, 16, [], 61)
print(fixedG())
fixedB.x = 101
fixedB.second = [19, 84]
fixedB.third = 17
// CHECK: (101, 0, 0, 0, 16, [19, 84], 17)
print(fixedG())
// Problem with field alignment in direct generic subclass of NSObject -
// <https://bugs.swift.org/browse/SR-2586>
public class PandorasBox<T>: NSObject {
final public var value: T
public init(_ value: T) {
// Uses ConstantIndirect access pattern
self.value = value
}
}
let c = PandorasBox(30)
// CHECK: 30
// Uses ConstantDirect access pattern
print(c.value)
// Super method calls from a generic subclass of an @objc class
class HasDynamicMethod : NSObject {
@objc dynamic class func funkyTown() {
print("Here we are with \(self)")
}
}
class GenericOverrideOfDynamicMethod<T> : HasDynamicMethod {
override class func funkyTown() {
print("Hello from \(self) with T = \(T.self)")
super.funkyTown()
print("Goodbye from \(self) with T = \(T.self)")
}
}
class ConcreteOverrideOfDynamicMethod : GenericOverrideOfDynamicMethod<Int> {
override class func funkyTown() {
print("Hello from \(self)")
super.funkyTown()
print("Goodbye from \(self)")
}
}
// CHECK: Hello from ConcreteOverrideOfDynamicMethod
// CHECK: Hello from ConcreteOverrideOfDynamicMethod with T = Int
// CHECK: Here we are with ConcreteOverrideOfDynamicMethod
// CHECK: Goodbye from ConcreteOverrideOfDynamicMethod with T = Int
// CHECK: Goodbye from ConcreteOverrideOfDynamicMethod
ConcreteOverrideOfDynamicMethod.funkyTown()
class Foo {}
class Bar {}
class DependOnAlignOf<T> : HasHiddenIvars2 {
var first = Foo()
var second = Bar()
var third: T?
}
let ad = DependOnAlignOf<Double>()
let ai = DependOnAlignOf<Int>()
do {
let fd = { (ad.x, ad.first, ad.second, ad.third) }
let fi = { (ai.x, ai.first, ai.second, ai.third) }
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fd())
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fi())
}
// Same as above, but there's another class in between the
// Objective-C class and us
class HasHiddenIvars3 : HasHiddenIvars2 { }
class AlsoDependOnAlignOf<T> : HasHiddenIvars3 {
var first = Foo()
var second = Bar()
var third: T?
}
do {
let ad = AlsoDependOnAlignOf<Double>()
let ai = AlsoDependOnAlignOf<Int>()
let fd = { (ad.x, ad.first, ad.second, ad.third) }
let fi = { (ai.x, ai.first, ai.second, ai.third) }
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fd())
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fi())
}
| 9785be57329cdaf4edab623abab7a03d | 20.091743 | 108 | 0.642453 | false | false | false | false |
Zhendeshede/weiboBySwift | refs/heads/master | 新浪微博/新浪微博/NetworkTool.swift | mit | 1 | //
// NetworkTool.swift
// 新浪微博
//
// Created by 李旭飞 on 15/10/10.
// Copyright © 2015年 lee. All rights reserved.
//
import UIKit
private let ErrorDomain="network.error"
//网络访问错误枚举
private enum NetworkError:Int{
case emptyDataError = -1
case emptyTokenError = -2
///错误描述
private var errorDescription:String{
switch self {
case .emptyDataError: return "空数据"
case .emptyTokenError: return "没有权限"
}
}
///根据枚举类型返回错误信息
private func error()->NSError{
return NSError(domain: ErrorDomain, code: rawValue, userInfo:[ErrorDomain:errorDescription])
}
}
class NetworkTool: NSObject {
//MARK:- 检查token
private func checkToken(finished:FinishedCallBack)->[String:AnyObject]?{
if UserAccess.loadUserAccount?.access_token == nil{
let error = NetworkError.emptyTokenError.error()
finished(result: nil, error: error)
return nil
}
//返回字典时为啦包成参数,这样直接再添加额外参数就可
return ["access_token":UserAccess.loadUserAccount!.access_token!]
}
//MARK:- 加载微博数据
func loadWeiboData(since_id:Int,max_id:Int,finished:FinishedCallBack){
guard var param=checkToken(finished) else{
return
}
if since_id>0{
param["since_id"]="\(since_id)";
}
if max_id>0{
param["max_id"]="\(max_id-1)";
}
let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
networkRequest(.GET, URLString: urlString, paramater: param, finished: finished)
}
static let shareNetworkTool=NetworkTool()
//MARK: - OAuth授权
private let clientId="2260003661"
private let appSecret="84630ccd2050db7da66f9d1e7c25d105"
let redirectURL="http://www.baidu.com"
func oauthURL()->NSURL{
let path=NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectURL)")
return path!
}
//MARK:- 获取用户信息
func loadUserInfo(uid:String,finished:FinishedCallBack){
//判断token是否存在
guard var param = checkToken(finished) else{
finished(result: nil, error: NetworkError.emptyTokenError.error())
return
}
let url="https://api.weibo.com/2/users/show.json"
param["uid"]=uid
networkRequest(.GET, URLString: url, paramater: param, finished: finished)
}
// MARK:- 获取授权码token
func oauthToken(code:String,finished:FinishedCallBack){
let dict=["client_id":clientId,
"client_secret":appSecret,
"grant_type":"authorization_code",
"code":code,
"redirect_uri":redirectURL]
let url="https://api.weibo.com/oauth2/access_token"
networkRequest(.POST, URLString: url, paramater: dict, finished: finished)
}
// 这里要加问号,有可能为空
typealias FinishedCallBack = (result:AnyObject?,error:NSError?)->()
///网络请求方式枚举
enum HttpMethod:String{
case GET = "GET"
case POST = "POST"
}
//MARK:- 封装网络请求方法
func networkRequest(methed:HttpMethod,URLString:String,paramater:[String:AnyObject],finished:FinishedCallBack){
var body = ""
for (key,value) in paramater{
body += "\(key)=\(value as! String)&"
}
body = (body as NSString).substringToIndex(body.characters.count-1)
let request = NSMutableURLRequest()
switch methed{
case .POST :
request.URL = NSURL(string: URLString)
request.HTTPMethod = "POST"
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
case .GET :
request.URL = NSURL(string: "\(URLString)?\(body)")
request.HTTPMethod = "GET"
}
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil || data == nil{
finished(result: nil, error: error)
return
}
do{
let obj = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
dispatch_async(dispatch_get_main_queue(), { () -> Void in
finished(result: obj, error: nil)
})
}catch{
finished(result: nil, error: NetworkError.emptyDataError.error())
}
}.resume()
}
} | b7920e38d7f5a95ae27b35262794accb | 25.086486 | 119 | 0.550674 | false | false | false | false |
fahidattique55/FAPanels | refs/heads/master | FAPanels/Classes/FAPanel.swift | apache-2.0 | 1 | //
// FAPanel.swift
// FAPanels
//
// Created by Fahid Attique on 10/06/2017.
// Copyright © 2017 Fahid Attique. All rights reserved.
//
import UIKit
// FAPanel Delegate
public protocol FAPanelStateDelegate {
func centerPanelWillBecomeActive()
func leftPanelWillBecomeActive()
func rightPanelWillBecomeActive()
func centerPanelDidBecomeActive()
func leftPanelDidBecomeActive()
func rightPanelDidBecomeActive()
}
public extension FAPanelStateDelegate {
func centerPanelWillBecomeActive() {}
func leftPanelWillBecomeActive() {}
func rightPanelWillBecomeActive() {}
func centerPanelDidBecomeActive() {}
func leftPanelDidBecomeActive() {}
func rightPanelDidBecomeActive() {}
}
// Left Panel Position
public enum FASidePanelPosition: Int {
case front = 0, back
}
// FAPanel Controller
open class FAPanelController: UIViewController {
// MARK:- Open
open var configs = FAPanelConfigurations()
open func center( _ controller: UIViewController, afterThat completion: (() -> Void)?) {
setCenterPanelVC(controller, afterThat: completion)
}
@discardableResult
open func center( _ controller: UIViewController) -> FAPanelController {
centerPanelVC = controller
return self
}
@discardableResult
open func left( _ controller: UIViewController?) -> FAPanelController {
leftPanelVC = controller
return self
}
@discardableResult
open func right( _ controller: UIViewController?) -> FAPanelController {
rightPanelVC = controller
return self
}
open func openLeft(animated:Bool) {
openLeft(animated: animated, shouldBounce: configs.bounceOnLeftPanelOpen)
}
open func openRight(animated:Bool) {
openRight(animated: animated, shouldBounce: configs.bounceOnRightPanelOpen)
}
open func openCenter(animated:Bool) { // Can be used for the same menu option selected
if centerPanelHidden {
centerPanelHidden = false
unhideCenterPanel()
}
openCenter(animated: animated, shouldBounce: configs.bounceOnCenterPanelOpen, afterThat: nil)
}
open func closeLeft() {
if isLeftPanelOnFront { slideLeftPanelOut(animated: true, afterThat: nil) }
else { openCenter(animated: true) }
}
open func closeRight() {
if isRightPanelOnFront { slideRightPanelOut(animated: true, afterThat: nil) }
else { openCenter(animated: true) }
}
// MARK:- Life Cycle
public init() {
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func viewDidLoad() {
super.viewDidLoad()
viewConfigurations()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
layoutSideContainers(withDuration: 0.0, animated: false)
layoutSidePanelVCs()
centerPanelContainer.frame = updateCenterPanelSlidingFrame()
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
_ = updateCenterPanelSlidingFrame()
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let shadowPath = UIBezierPath(rect: leftPanelContainer.bounds)
leftPanelContainer.layer.masksToBounds = false
leftPanelContainer.layer.shadowColor = configs.shadowColor
leftPanelContainer.layer.shadowOffset = configs.shadowOffset
leftPanelContainer.layer.shadowOpacity = configs.shadowOppacity
leftPanelContainer.layer.shadowPath = shadowPath.cgPath
}
deinit {
if centerPanelVC != nil {
centerPanelVC!.removeObserver(self, forKeyPath: keyPathOfView)
}
}
private func viewConfigurations() {
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
centerPanelContainer = UIView(frame: view.bounds)
centeralPanelSlidingFrame = self.centerPanelContainer.frame
centerPanelHidden = false
leftPanelContainer = UIView(frame: view.bounds)
layoutLeftContainer()
leftPanelContainer.isHidden = true
rightPanelContainer = UIView(frame: view.bounds)
layoutRightContainer()
rightPanelContainer.isHidden = true
containersConfigurations()
view.addSubview(centerPanelContainer)
view.addSubview(leftPanelContainer)
view.addSubview(rightPanelContainer)
state = .center
swapCenter(animated: false, FromVC: nil, withVC: centerPanelVC)
view.bringSubviewToFront(centerPanelContainer)
tapView = UIView()
tapView?.alpha = 0.0
}
private func containersConfigurations() {
leftPanelContainer.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
rightPanelContainer.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
centerPanelContainer.autoresizingMask = [.flexibleHeight, .flexibleWidth]
centerPanelContainer.frame = view.bounds
}
// MARK:- internal Properties
internal var leftPanelContainer : UIView!
internal var rightPanelContainer : UIView!
internal var centerPanelContainer: UIView!
internal var visiblePanelVC: UIViewController!
internal var centeralPanelSlidingFrame: CGRect = CGRect.zero
internal var centerPanelOriginBeforePan: CGPoint = CGPoint.zero
internal var leftPanelOriginBeforePan: CGPoint = CGPoint.zero
internal var rightPanelOriginBeforePan: CGPoint = CGPoint.zero
internal let keyPathOfView = "view"
internal static var kvoContext: Character!
internal var _leftPanelPosition : FASidePanelPosition = .back {
didSet {
if _leftPanelPosition == .front {
configs.resizeLeftPanel = false
}
layoutLeftContainer()
}
}
internal var isLeftPanelOnFront : Bool {
return leftPanelPosition == .front
}
open var leftPanelPosition : FASidePanelPosition {
get {
return _leftPanelPosition
}
set {
_leftPanelPosition = newValue
}
}
internal var _rightPanelPosition : FASidePanelPosition = .back {
didSet {
if _rightPanelPosition == .front {
configs.resizeRightPanel = true
}
layoutRightContainer()
layoutSidePanelVCs()
}
}
internal var isRightPanelOnFront : Bool {
return rightPanelPosition == .front
}
open var rightPanelPosition : FASidePanelPosition {
get {
return _rightPanelPosition
}
set {
_rightPanelPosition = newValue
}
}
internal enum GestureStartDirection: UInt { case left = 0, right, none }
internal var paningStartDirection: GestureStartDirection = .none
internal var _leftPanelVC: UIViewController? = nil
internal var leftPanelVC : UIViewController? {
get{
return _leftPanelVC
}
set{
if newValue != _leftPanelVC {
_leftPanelVC?.willMove(toParent: nil)
_leftPanelVC?.view.removeFromSuperview()
_leftPanelVC?.removeFromParent()
_leftPanelVC = newValue
if _leftPanelVC != nil {
addChild(_leftPanelVC!)
_leftPanelVC!.didMove(toParent: self)
}
else {
leftPanelContainer.isHidden = true
}
if state == .left {
visiblePanelVC = _leftPanelVC
}
}
}
}
open var left: UIViewController? {
get {
return leftPanelVC
}
}
internal var _rightPanelVC: UIViewController? = nil
internal var rightPanelVC : UIViewController? {
get{
return _rightPanelVC
}
set{
if newValue != _rightPanelVC {
_rightPanelVC?.willMove(toParent: nil)
_rightPanelVC?.view.removeFromSuperview()
_rightPanelVC?.removeFromParent()
_rightPanelVC = newValue
if _rightPanelVC != nil {
addChild(_rightPanelVC!)
_rightPanelVC?.didMove(toParent: self)
}
else {
rightPanelContainer.isHidden = true
}
if state == .right {
visiblePanelVC = _rightPanelVC
}
}
}
}
open var right: UIViewController? {
get {
return rightPanelVC
}
}
internal var _centerPanelVC: UIViewController? = nil
internal var centerPanelVC : UIViewController? {
get{
return _centerPanelVC
}
set{
setCenterPanelVC(newValue, afterThat: nil)
}
}
open var center: UIViewController? {
get {
return centerPanelVC
}
}
internal func setCenterPanelVC( _ newValue: UIViewController?, afterThat completion: (() -> Void)? = nil) {
let previousVC: UIViewController? = _centerPanelVC
if _centerPanelVC != newValue {
_centerPanelVC?.removeObserver(self, forKeyPath: keyPathOfView)
_centerPanelVC = newValue
_centerPanelVC!.addObserver(self, forKeyPath: keyPathOfView, options: NSKeyValueObservingOptions.initial, context: &FAPanelController.kvoContext)
if state == .center {
visiblePanelVC = _centerPanelVC
}
}
if isViewLoaded && state == .center {
swapCenter(animated: configs.changeCenterPanelAnimated, FromVC: previousVC, withVC: _centerPanelVC!)
}
else if (self.isViewLoaded) {
if state == .left {
if isLeftPanelOnFront {
swapCenter(animated: false,FromVC: previousVC, withVC: self._centerPanelVC)
slideLeftPanelOut(animated: true, afterThat: completion)
return
}
}
else if state == .right {
if isRightPanelOnFront {
swapCenter(animated: false, FromVC: previousVC, withVC: self._centerPanelVC)
slideRightPanelOut(animated: true, afterThat: completion)
return
}
}
UIView.animate(withDuration: 0.2, animations: {
if self.configs.bounceOnCenterPanelChange {
let x: CGFloat = (self.state == .left) ? self.view.bounds.size.width : -self.view.bounds.size.width
self.centeralPanelSlidingFrame.origin.x = x
}
self.centerPanelContainer.frame = self.centeralPanelSlidingFrame
}, completion: { (finised) in
self.swapCenter(animated: false,FromVC: previousVC, withVC: self._centerPanelVC)
self.openCenter(animated: true, shouldBounce: false, afterThat: completion)
})
}
}
// Left panel frame on basis of its position type i.e: front or back
internal func layoutLeftContainer() {
if isLeftPanelOnFront {
if leftPanelContainer != nil {
var frame = leftPanelContainer.frame
frame.size.width = widthForLeftPanelVC
frame.origin.x = -widthForLeftPanelVC
leftPanelContainer.frame = frame
}
}
else {
if leftPanelContainer != nil {
leftPanelContainer.frame = view.bounds
}
}
}
internal func layoutRightContainer() {
if isRightPanelOnFront {
if rightPanelContainer != nil {
var frame = rightPanelContainer.frame
frame.size.width = widthForRightPanelVC
frame.origin.x = view.frame.size.width
rightPanelContainer.frame = frame
}
}
else {
if rightPanelContainer != nil {
rightPanelContainer.frame = view.bounds
}
}
}
// tap view on centeral panel, to dismiss side panels if visible
internal var _tapView: UIView? = nil
internal var tapView: UIView? {
get{
return _tapView
}
set{
if newValue != _tapView {
_tapView?.removeFromSuperview()
_tapView = newValue
if _tapView != nil {
_tapView?.backgroundColor = configs.colorForTapView
_tapView?.frame = centerPanelContainer.bounds
_tapView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addTapGestureToView(view: _tapView!)
if configs.canRecognizePanGesture { addPanGesture(toView: _tapView!) }
centerPanelContainer.addSubview(_tapView!)
}
}
}
}
// visible widths for side panels
internal var widthForLeftPanelVC: CGFloat {
get{
if centerPanelHidden && configs.resizeLeftPanel {
return view.bounds.size.width
}
else {
return configs.leftPanelWidth == 0.0 ? CGFloat(floorf(Float(view.bounds.size.width * configs.leftPanelGapPercentage))) : configs.leftPanelWidth
}
}
}
internal var widthForRightPanelVC: CGFloat {
get{
if centerPanelHidden && configs.resizeRightPanel {
return view.bounds.size.width
}
else {
return configs.rightPanelWidth == 0 ? CGFloat(floorf(Float(view.bounds.size.width * configs.rightPanelGapPercentage))) : configs.rightPanelWidth
}
}
}
// style for panels
internal func applyStyle(onView: UIView) {
onView.layer.cornerRadius = configs.cornerRadius
onView.clipsToBounds = true
}
// Panel States
open var delegate: FAPanelStateDelegate? = nil
internal var _state: FAPanelVisibleState = .center {
willSet {
switch newValue {
case .center:
delegate?.centerPanelWillBecomeActive()
break
case .left:
delegate?.leftPanelWillBecomeActive()
break
case .right:
delegate?.rightPanelWillBecomeActive()
break
}
}
didSet {
switch _state {
case .center:
delegate?.centerPanelDidBecomeActive()
break
case .left:
delegate?.leftPanelDidBecomeActive()
break
case .right:
delegate?.rightPanelDidBecomeActive()
break
}
}
}
internal var state: FAPanelVisibleState {
get{
return _state
}
set{
if _state != newValue {
_state = newValue
switch _state {
case .center:
visiblePanelVC = centerPanelVC
leftPanelContainer.isUserInteractionEnabled = false
rightPanelContainer.isUserInteractionEnabled = false
break
case .left:
visiblePanelVC = leftPanelVC
leftPanelContainer.isUserInteractionEnabled = true
break
case .right:
visiblePanelVC = rightPanelVC
rightPanelContainer.isUserInteractionEnabled = true
break
}
setNeedsStatusBarAppearanceUpdate()
}
}
}
// Center Panel Hiding Functions
internal var _centerPanelHidden: Bool = false
internal var centerPanelHidden: Bool {
get{
return _centerPanelHidden
}
set{
setCenterPanelHidden(newValue, animated: false, duration: 0.0)
}
}
internal func setCenterPanelHidden(_ hidden: Bool, animated: Bool, duration: TimeInterval) {
if hidden != _centerPanelHidden && state != .center {
_centerPanelHidden = hidden
let animationDuration = animated ? duration : 0.0
if hidden {
UIView.animate(withDuration: animationDuration, animations: {
var frame: CGRect = self.centerPanelContainer.frame
frame.origin.x = self.state == .left ? self.centerPanelContainer.frame.size.width : -self.centerPanelContainer.frame.size.width
self.centerPanelContainer.frame = frame
self.layoutSideContainers(withDuration: 0.0, animated: false)
if self.configs.resizeLeftPanel || self.configs.resizeRightPanel {
self.layoutSidePanelVCs()
}
}, completion: { (finished) in
if self._centerPanelHidden {
self.hideCenterPanel()
}
})
}
else {
unhideCenterPanel()
UIView.animate(withDuration: animationDuration, animations: {
if self.state == .left {
self.openLeft(animated: false)
}
else {
self.openRight(animated: false)
}
if self.configs.resizeLeftPanel || self.configs.resizeRightPanel {
self.layoutSidePanelVCs()
}
})
}
}
}
}
| 972ef3b67df854a90498b7dda246af27 | 25.125837 | 160 | 0.532076 | false | false | false | false |
karstengresch/trhs-ios | refs/heads/master | stormy/Stormy/Stormy/DailyWeather.swift | unlicense | 1 | //
// DailyWeather.swift
// Stormy
//
// Created by Karsten Gresch on 07.09.15.
// Copyright (c) 2015 Closure One. All rights reserved.
//
import Foundation
import UIKit
struct DailyWeather {
let maxTemperature: Int?
let minTemperature: Int?
let humidity: Int?
let preciperationChance: Int?
let summary: String?
var icon: UIImage? = UIImage(named: "default.png")
var largeIcon: UIImage? = UIImage(named: "default_large.png")
var sunriseTime: String?
var sunsetTime: String?
var day: String?
let dateFormatter = NSDateFormatter()
init(dailyweatherData: [String: AnyObject]) {
maxTemperature = dailyweatherData["temperatureMax"] as? Int
minTemperature = dailyweatherData["temperatureMin"] as? Int
if let humidityFloat = dailyweatherData["humidity"] as? Double {
humidity = Int(humidityFloat * 100)
} else {
humidity = nil
}
if let preciperationChanceFloat = dailyweatherData["precipProbability"] as? Double {
preciperationChance = Int(preciperationChanceFloat * 100)
} else {
preciperationChance = nil
}
summary = dailyweatherData["summary"] as? String
if let iconString = dailyweatherData["icon"] as? String,
let iconEnum = Icon(rawValue: iconString) {
(icon, largeIcon) = iconEnum.toImage()
}
if let sunriseDate = dailyweatherData["sunriseTime"] as? Double {
sunriseTime = timeStringFromUnixTime(sunriseDate)
} else {
sunriseTime = nil
}
if let sunsetDate = dailyweatherData["sunsetTime"] as? Double {
sunsetTime = timeStringFromUnixTime(sunsetDate)
} else {
sunsetTime = nil
}
if let time = dailyweatherData["time"] as? Double {
day = dayStringFromTime(time)
}
}
func timeStringFromUnixTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
// "hh:mm a"
dateFormatter.dateFormat = "HH:mm"
return dateFormatter.stringFromDate(date)
}
func dayStringFromTime(time: Double) -> String {
let date = NSDate(timeIntervalSince1970: time)
dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(date)
}
}
| b7ead9ef6ba794468a522aeaf6d358a6 | 27.530864 | 96 | 0.678494 | false | false | false | false |
xuzhenguo/LayoutComposer | refs/heads/master | Example/LayoutComposer/TopViewController.swift | mit | 1 | //
// TopViewController.swift
// LayoutComposer
//
// Created by Yusuke Kawakami on 08/22/2015.
// Copyright (c) 2015 Yusuke Kawakami. All rights reserved.
//
import UIKit
import LayoutComposer
class TopViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func loadView() {
doLayout()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func doLayout() {
view = UIView()
view.backgroundColor = UIColor.whiteColor()
let header = UIView()
header.backgroundColor = UIColor.blackColor()
let titleLabel = UILabel()
titleLabel.text = "LayoutComposer Examples"
titleLabel.textColor = UIColor.whiteColor()
let scrollView = UIScrollView()
view.applyLayout(VBox(), items: [
$(header, height: 65, layout: Relative(), item:
$(titleLabel, halign: .Center, marginTop: 20)
),
$(scrollView, flex: 1, layout: VBox(align: .Center, pack: .Fit, defaultMargins: (10, 0, 0, 0)), items: [
$(makeButton(title: "VBox Basic", action: "onVBoxExampleTapped:", tag: VBoxExampleType.Basic.rawValue)),
$(makeButton(title: "VBox Margin", action: "onVBoxExampleTapped:", tag: VBoxExampleType.Margin.rawValue)),
$(makeButton(title: "VBox Default Margin", action: "onVBoxExampleTapped:", tag: VBoxExampleType.DefaultMargin.rawValue)),
$(makeButton(title: "VBox Flex Height", action: "onVBoxExampleTapped:", tag: VBoxExampleType.Flex.rawValue)),
$(makeButton(title: "VBox Align Start(Left)", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignStart.rawValue)),
$(makeButton(title: "VBox Align End(Right)", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignEnd.rawValue)),
$(makeButton(title: "VBox Align Center", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignCenter.rawValue)),
$(makeButton(title: "VBox Align Stretch", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignStretch.rawValue)),
$(makeButton(title: "VBox Align Each Component", action: "onVBoxExampleTapped:", tag: VBoxExampleType.AlignEachComponent.rawValue)),
$(makeButton(title: "VBox Pack Start(Top)", action: "onVBoxExampleTapped:", tag: VBoxExampleType.PackStart.rawValue)),
$(makeButton(title: "VBox Pack End(Bottom)", action: "onVBoxExampleTapped:", tag: VBoxExampleType.PackEnd.rawValue)),
$(makeButton(title: "VBox Pack Center", action: "onVBoxExampleTapped:", tag: VBoxExampleType.PackCenter.rawValue)),
$(makeButton(title: "VBox Pack Fit", action: "onVBoxExampleTapped:", tag: VBoxExampleType.PackFit.rawValue)),
$(makeButton(title: "HBox Basic", action: "onHBoxExampleTapped:", tag: HBoxExampleType.Basic.rawValue)),
$(makeButton(title: "HBox Margin", action: "onHBoxExampleTapped:", tag: HBoxExampleType.Margin.rawValue)),
$(makeButton(title: "HBox Default Margin", action: "onHBoxExampleTapped:", tag: HBoxExampleType.DefaultMargin.rawValue)),
$(makeButton(title: "HBox Flex Width", action: "onHBoxExampleTapped:", tag: HBoxExampleType.Flex.rawValue)),
$(makeButton(title: "HBox Align Start(Top)", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignStart.rawValue)),
$(makeButton(title: "HBox Align End(Bottom)", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignEnd.rawValue)),
$(makeButton(title: "HBox Align Center", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignCenter.rawValue)),
$(makeButton(title: "HBox Align Stretch", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignStretch.rawValue)),
$(makeButton(title: "HBox Align Each Component", action: "onHBoxExampleTapped:", tag: HBoxExampleType.AlignEachComponent.rawValue)),
$(makeButton(title: "HBox Pack Start(Left)", action: "onHBoxExampleTapped:", tag: HBoxExampleType.PackStart.rawValue)),
$(makeButton(title: "HBox Pack End(Right)", action: "onHBoxExampleTapped:", tag: HBoxExampleType.PackEnd.rawValue)),
$(makeButton(title: "HBox Pack Center", action: "onHBoxExampleTapped:", tag: HBoxExampleType.PackCenter.rawValue)),
$(makeButton(title: "HBox Pack Fit", action: "onHBoxExampleTapped:", tag: HBoxExampleType.PackFit.rawValue)),
$(makeButton(title: "Relative 1", action: "onRelativeExampleTapped:", tag: RelativeExampleType.Example1.rawValue)),
$(makeButton(title: "Relative 2", action: "onRelativeExampleTapped:", tag: RelativeExampleType.Example2.rawValue)),
$(makeButton(title: "Relative 3", action: "onRelativeExampleTapped:", tag: RelativeExampleType.Example3.rawValue)),
$(makeButton(title: "Fit", action: "onFitExampleTapped:", tag: FitExampleType.Example1.rawValue)),
$(makeButton(title: "Nesting Layout", action: "onNestExampleTapped:", tag: NestExampleType.Example1.rawValue))
])
])
}
private func makeButton(#title: String, action: Selector, tag: Int) -> UIButton {
let button = UIButton.buttonWithType(.System) as! UIButton
button.setTitle(title, forState: .Normal)
button.addTarget(self, action: action, forControlEvents: .TouchUpInside)
button.tag = tag
return button
}
func onVBoxExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = VBoxExampleType(rawValue: sender.tag)
{
let vc = VBoxExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
func onHBoxExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = HBoxExampleType(rawValue: sender.tag)
{
let vc = HBoxExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
func onRelativeExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = RelativeExampleType(rawValue: sender.tag)
{
let vc = RelativeExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
func onFitExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = FitExampleType(rawValue: sender.tag)
{
let vc = FitExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
func onNestExampleTapped(sender: UIButton) {
if let title = sender.titleForState(.Normal),
exampleType = NestExampleType(rawValue: sender.tag)
{
let vc = NestExampleViewController(exampleType: exampleType, headerTitle: title)
navigationController?.pushViewController(vc, animated: true)
}
}
}
| cc5759bd1875e5dda948f292b1632842 | 54.583942 | 148 | 0.655417 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | refs/heads/master | Classes/Vendor/Kingsfisher/Filter.swift | apache-2.0 | 1 | //
// Filter.swift
// Kingfisher
//
// Created by Wei Wang on 2016/08/31.
//
// Copyright (c) 2018 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import CoreImage
import Accelerate
// Reuse the same CI Context for all CI drawing.
private let ciContext = CIContext(options: nil)
/// Transformer method which will be used in to provide a `Filter`.
internal typealias Transformer = (CIImage) -> CIImage?
/// Supply a filter to create an `ImageProcessor`.
internal protocol CIImageProcessor: ImageProcessor {
var filter: Filter { get }
}
extension CIImageProcessor {
internal func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.apply(filter)
case .data(_):
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Wrapper for a `Transformer` of CIImage filters.
internal struct Filter {
let transform: Transformer
internal init(transform: @escaping Transformer) {
self.transform = transform
}
/// Tint filter which will apply a tint color to images.
internal static var tint: (Color) -> Filter = {
color in
Filter(transform: { input in
let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
let colorImage = colorFilter.outputImage
let filter = CIFilter(name: "CISourceOverCompositing")!
filter.setValue(colorImage, forKey: kCIInputImageKey)
filter.setValue(input, forKey: kCIInputBackgroundImageKey)
return filter.outputImage?.cropped(to: input.extent)
})
}
internal typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)
/// Color control filter which will apply color control change to images.
internal static var colorControl: (ColorElement) -> Filter = { arg -> Filter in
let (brightness, contrast, saturation, inputEV) = arg
return Filter(transform: { input in
let paramsColor = [kCIInputBrightnessKey: brightness,
kCIInputContrastKey: contrast,
kCIInputSaturationKey: saturation]
let paramsExposure = [kCIInputEVKey: inputEV]
let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor)
return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure)
})
}
}
// MARK: - Deprecated
extension Filter {
@available(*, deprecated, message: "Use init(transform:) instead.", renamed: "init(transform:)")
internal init(tranform: @escaping Transformer) {
self.transform = tranform
}
}
extension Kingfisher where Base: Image {
/// Apply a `Filter` containing `CIImage` transformer to `self`.
///
/// - parameter filter: The filter used to transform `self`.
///
/// - returns: A transformed image by input `Filter`.
///
/// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
internal func apply(_ filter: Filter) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
return base
}
let inputImage = CIImage(cgImage: cgImage)
guard let outputImage = filter.transform(inputImage) else {
return base
}
guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
assertionFailure("[Kingfisher] Can not make an tint image within context.")
return base
}
#if os(macOS)
return fixedForRetinaPixel(cgImage: result, to: size)
#else
return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
#endif
}
}
| 7d3873f1f5db81d7777f66bf6a13134a | 37.237037 | 118 | 0.663696 | false | false | false | false |
lgp123456/tiantianTV | refs/heads/master | douyuTV/douyuTV/douyuTV.swift | mit | 1 | //
// douyuTV.swift
// douyuTV
//
// Created by 李贵鹏 on 16/8/24.
// Copyright © 2016年 李贵鹏. All rights reserved.
//
import UIKit
///屏幕宽度
let XTScreenW = UIScreen.mainScreen().bounds.width
///屏幕高度
let XTScreenH = UIScreen.mainScreen().bounds.height
///顶部预留的间距
let XTTopSpace = XTScreenW / 414 * 240
///标题(顶部view)栏高度
let XTTopViewH = XTScreenW / 414 * 35
///间距
let XTMagin = 10
///基本的url
let baseUrl = "http://capi.douyucdn.cn" | fb293896f83fbfec6e096913b264d739 | 15.730769 | 51 | 0.679724 | false | false | false | false |
Caktuspace/iTunesCover | refs/heads/master | iTunesCover/iTunesCover/Classes/Modules/List/User Interface/Presenter/AlbumDisplayData.swift | gpl-2.0 | 1 | //
// AlbumDisplayData.swift
// iTunesCover
//
// Created by Quentin Metzler on 20/12/15.
// Copyright © 2015 LocalFitness. All rights reserved.
//
import Foundation
struct AlbumDisplayData : Equatable {
var items : [AlbumDisplayItem] = []
init(items: [AlbumDisplayItem]) {
self.items = items
}
}
func == (leftSide: AlbumDisplayData, rightSide: AlbumDisplayData) -> Bool {
var hasEqualSections = false
hasEqualSections = rightSide.items == leftSide.items
return hasEqualSections
} | 133f92885ae7bff1f1ca6698be73c3b4 | 21.826087 | 75 | 0.688931 | false | false | false | false |
HamzaGhazouani/HGCircularSlider | refs/heads/master | HGCircularSlider/Classes/CircularSlider.swift | mit | 1 | //
// CircularSlider.swift
// Pods
//
// Created by Hamza Ghazouani on 19/10/2016.
//
//
import UIKit
/**
* A visual control used to select a single value from a continuous range of values.
* Can also be used like a circular progress view
* CircularSlider uses the target-action mechanism to report changes made during the course of editing:
* ValueChanged, EditingDidBegin and EditingDidEnd
*/
@IBDesignable
open class CircularSlider: UIControl {
// MARK: Changing the Slider’s Appearance
/**
* The color shown for the selected portion of the slider disk. (between start and end values)
* The default value is a transparent color.
*/
@IBInspectable
open var diskFillColor: UIColor = .clear
/**
* The color shown for the unselected portion of the slider disk. (outside start and end values)
* The default value of this property is the black color with alpha = 0.3.
*/
@IBInspectable
open var diskColor: UIColor = .gray
/**
* The color shown for the selected track portion. (between start and end values)
* The default value of this property is the tint color.
*/
@IBInspectable
open var trackFillColor: UIColor = .clear
/**
* The color shown for the unselected track portion. (outside start and end values)
* The default value of this property is the white color.
*/
@IBInspectable
open var trackColor: UIColor = .white
/**
* The width of the circular line
*
* The default value of this property is 5.0.
*/
@IBInspectable
open var lineWidth: CGFloat = 5.0
/**
* The width of the unselected track portion of the slider
*
* The default value of this property is 5.0.
*/
@IBInspectable
open var backtrackLineWidth: CGFloat = 5.0
/**
* The shadow offset of the slider
*
* The default value of this property is .zero.
*/
@IBInspectable
open var trackShadowOffset: CGPoint = .zero
/**
* The color of the shadow offset of the slider
*
* The default value of this property is .gray.
*/
@IBInspectable
open var trackShadowColor: UIColor = .gray
/**
* The width of the thumb stroke line
*
* The default value of this property is 4.0.
*/
@IBInspectable
open var thumbLineWidth: CGFloat = 4.0
/**
* The radius of the thumb
*
* The default value of this property is 13.0.
*/
@IBInspectable
open var thumbRadius: CGFloat = 13.0
/**
* The color used to tint the thumb
* Ignored if the endThumbImage != nil
*
* The default value of this property is the groupTableViewBackgroundColor.
*/
@IBInspectable
open var endThumbTintColor: UIColor = .groupTableViewBackground
/**
* The stroke highlighted color of the end thumb
* The default value of this property is blue
*/
@IBInspectable
open var endThumbStrokeHighlightedColor: UIColor = .blue
/**
* The color used to tint the stroke of the end thumb
* Ignored if the endThumbImage != nil
*
* The default value of this property is red.
*/
@IBInspectable
open var endThumbStrokeColor: UIColor = .red
/**
* The image of the end thumb
* Clears any custom color you may have provided for the end thumb.
*
* The default value of this property is nil
*/
open var endThumbImage: UIImage?
// MARK: Accessing the Slider’s Value Limits
/**
* Fixed number of rounds - how many circles has user to do to reach max value (like apple bedtime clock - which have 2)
* the default value if this property is 1
*/
@IBInspectable
open var numberOfRounds: Int = 1 {
didSet {
assert(numberOfRounds > 0, "Number of rounds has to be positive value!")
setNeedsDisplay()
}
}
/**
* The minimum value of the receiver.
*
* If you change the value of this property, and the end value of the receiver is below the new minimum, the end point value is adjusted to match the new minimum value automatically.
* The default value of this property is 0.0.
*/
@IBInspectable
open var minimumValue: CGFloat = 0.0 {
didSet {
if endPointValue < minimumValue {
endPointValue = minimumValue
}
}
}
/**
* The maximum value of the receiver.
*
* If you change the value of this property, and the end value of the receiver is above the new maximum, the end value is adjusted to match the new maximum value automatically.
* The default value of this property is 1.0.
*/
@IBInspectable
open var maximumValue: CGFloat = 1.0 {
didSet {
if endPointValue > maximumValue {
endPointValue = maximumValue
}
}
}
/**
* The offset of the thumb centre from the circle.
*
* You can use this to move the thumb inside or outside the circle of the slider
* If the value is grather than 0 the thumb will be displayed outside the cirlce
* And if the value is negative, the thumb will be displayed inside the circle
*/
@IBInspectable
open var thumbOffset: CGFloat = 0.0 {
didSet {
setNeedsDisplay()
}
}
/**
* Stop the thumb going beyond the min/max.
*
*/
@IBInspectable
open var stopThumbAtMinMax: Bool = false
/**
* The value of the endThumb (changed when the user change the position of the end thumb)
*
* If you try to set a value that is above the maximum value, the property automatically resets to the maximum value.
* And if you try to set a value that is below the minimum value, the property automatically resets to the minimum value.
*
* The default value of this property is 0.5
*/
open var endPointValue: CGFloat = 0.5 {
didSet {
if oldValue == endPointValue {
return
}
if endPointValue > maximumValue {
endPointValue = maximumValue
}
if endPointValue < minimumValue {
endPointValue = minimumValue
}
setNeedsDisplay()
}
}
/**
* The radius of circle
*/
internal var radius: CGFloat {
get {
// the minimum between the height/2 and the width/2
var radius = min(bounds.center.x, bounds.center.y)
// if we use an image for the thumb, the radius of the image will be used
let maxThumbRadius = max(thumbRadius, (self.endThumbImage?.size.height ?? 0) / 2)
// all elements should be inside the view rect, for that we should subtract the highest value between the radius of thumb and the line width
radius -= max(lineWidth, (maxThumbRadius + thumbLineWidth + thumbOffset))
return radius
}
}
/// See superclass documentation
override open var isHighlighted: Bool {
didSet {
setNeedsDisplay()
}
}
// MARK: init methods
/**
See superclass documentation
*/
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
/**
See superclass documentation
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
internal func setup() {
trackFillColor = tintColor
}
// MARK: Drawing methods
/**
See superclass documentation
*/
override open func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
drawCircularSlider(inContext: context)
let valuesInterval = Interval(min: minimumValue, max: maximumValue, rounds: numberOfRounds)
// get end angle from end value
let endAngle = CircularSliderHelper.scaleToAngle(value: endPointValue, inInterval: valuesInterval) + CircularSliderHelper.circleInitialAngle
drawFilledArc(fromAngle: CircularSliderHelper.circleInitialAngle, toAngle: endAngle, inContext: context)
// draw end thumb
endThumbTintColor.setFill()
(isHighlighted == true) ? endThumbStrokeHighlightedColor.setStroke() : endThumbStrokeColor.setStroke()
drawThumbAt(endAngle, with: endThumbImage, inContext: context)
}
// MARK: User interaction methods
/**
See superclass documentation
*/
override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
sendActions(for: .editingDidBegin)
return true
}
/**
See superclass documentation
*/
override open func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
// the position of the pan gesture
let touchPosition = touch.location(in: self)
let startPoint = CGPoint(x: bounds.center.x, y: 0)
let value = newValue(from: endPointValue, touch: touchPosition, start: startPoint)
endPointValue = value
sendActions(for: .valueChanged)
return true
}
/**
See superclass documentation
*/
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
sendActions(for: .editingDidEnd)
}
// MARK: Utilities methods
internal func newValue(from oldValue: CGFloat, touch touchPosition: CGPoint, start startPosition: CGPoint) -> CGFloat {
let angle = CircularSliderHelper.angle(betweenFirstPoint: startPosition, secondPoint: touchPosition, inCircleWithCenter: bounds.center)
let interval = Interval(min: minimumValue, max: maximumValue, rounds: numberOfRounds)
let deltaValue = CircularSliderHelper.delta(in: interval, for: angle, oldValue: oldValue)
var newValue = oldValue + deltaValue - minimumValue
let range = maximumValue - minimumValue
if !stopThumbAtMinMax {
if newValue > maximumValue {
newValue -= range
}
else if newValue < minimumValue {
newValue += range
}
}
return newValue
}
}
| 4b3bd6a862fd934af53985064a200c59 | 29.176301 | 186 | 0.617182 | false | false | false | false |
Abedalkareem/LanguageManger-iOS | refs/heads/master | Example/LanguageManger-iOS/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// LanguageManager
//
// Created by abedalkareem omreyh on 4/9/17.
// Copyright © 2017 abedalkareem. All rights reserved.
//
import UIKit
import LanguageManager_iOS
class SettingsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func changeLanguage(_ sender: UIButton) {
let selectedLanguage: Languages = sender.tag == 1 ? .en : .ar
// change the language
LanguageManager.shared.setLanguage(language: selectedLanguage,
viewControllerFactory: { title -> UIViewController in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// the view controller that you want to show after changing the language
return storyboard.instantiateInitialViewController()!
}) { view in
// do custom animation
view.transform = CGAffineTransform(scaleX: 2, y: 2)
view.alpha = 0
}
}
}
| 4290e381b414a55568d8603a39a9b88a | 25.162162 | 92 | 0.674587 | false | false | false | false |
MastodonKit/MastodonKit | refs/heads/master | Sources/MastodonKit/Requests/Lists.swift | mit | 1 | //
// Lists.swift
// MastodonKit
//
// Created by Ornithologist Coder on 1/2/18.
// Copyright © 2018 MastodonKit. All rights reserved.
//
import Foundation
/// `Lists` requests.
public enum Lists {
/// Retrieves lists.
///
/// - Returns: Request for `[List]`.
public static func all() -> Request<[List]> {
return Request<[List]>(path: "/api/v1/lists")
}
/// Retrieves accounts in a list.
///
/// - Parameter id: The list ID.
/// - Returns: Request for `[Account]`.
public static func accounts(id: String) -> Request<[Account]> {
return Request<[Account]>(path: "/api/v1/lists/\(id)/accounts")
}
/// Retrieves a list.
///
/// - Parameter id: The list ID.
/// - Returns: Request for `List`.
public static func list(id: String) -> Request<List> {
return Request<List>(path: "/api/v1/lists/\(id)")
}
/// Creates a list.
///
/// - Parameter title: The title of the list.
/// - Returns: Request for `List`.
public static func create(title: String) -> Request<List> {
let parameter = [Parameter(name: "title", value: title)]
let method = HTTPMethod.post(.parameters(parameter))
return Request<List>(path: "/api/v1/lists", method: method)
}
/// Updates the list title.
///
/// - Parameters:
/// - id: The list ID.
/// - title: The title of the list.
/// - Returns: Request for `List`.
public static func update(id: String, title: String) -> Request<List> {
let parameter = [Parameter(name: "title", value: title)]
let method = HTTPMethod.put(.parameters(parameter))
return Request<List>(path: "/api/v1/lists/\(id)", method: method)
}
/// Deletes a list.
///
/// - Parameter id: The list ID.
/// - Returns: Request for `Empty`.
public static func delete(id: String) -> Request<Empty> {
return Request<Empty>(path: "/api/v1/lists/\(id)", method: .delete(.empty))
}
/// Adds accounts to a list.
///
/// - Parameters:
/// - accountIDs: The account IDs to be added to the list.
/// - id: The list ID>
/// - Returns: Request for `Empty`.
public static func add(accountIDs: [String], toList id: String) -> Request<Empty> {
let parameter = accountIDs.map(toArrayOfParameters(withName: "account_ids"))
let method = HTTPMethod.post(.parameters(parameter))
return Request<Empty>(path: "/api/v1/lists/\(id)/accounts", method: method)
}
/// Removes accounts from a list.
///
/// - Parameters:
/// - accountIDs: The account IDs to be removed from the list.
/// - id: The list ID>
/// - Returns: Request for `Empty`.
public static func remove(accountIDs: [String], fromList id: String) -> Request<Empty> {
let parameter = accountIDs.map(toArrayOfParameters(withName: "account_ids"))
let method = HTTPMethod.delete(.parameters(parameter))
return Request<Empty>(path: "/api/v1/lists/\(id)/accounts", method: method)
}
}
| 3e2332df2439f98c03e8e85b017fb4b6 | 31.946237 | 92 | 0.594321 | false | false | false | false |
lantun/DGElasticPullToRefresh-add-pull-up- | refs/heads/master | DGElasticPullToRefresh/DGElasticPullToRefreshView.swift | mit | 1 | /*
The MIT License (MIT)
Copyright (c) 2015 Danil Gontovnik
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
// MARK: -
// MARK: DGElasticPullToRefreshState
public
enum DGElasticPullToRefreshState: Int {
case Stopped
case Dragging
case AnimatingBounce
case Loading
case AnimatingToStopped
func isAnyOf(values: [DGElasticPullToRefreshState]) -> Bool {
return values.contains({ $0 == self })
}
}
enum PullDirection: Int {
case Up // 上拉
case Down // 下拉
}
// MARK: -
// MARK: DGElasticPullToRefreshView
public class DGElasticPullToRefreshView: UIView {
var direction: PullDirection!
// MARK: -
// MARK: Vars
private var _state: DGElasticPullToRefreshState = .Stopped
private(set) var state: DGElasticPullToRefreshState {
get { return _state }
set {
let previousValue = state
_state = newValue
if previousValue == .Dragging && newValue == .AnimatingBounce {
loadingView?.startAnimating()
animateBounce()
} else if newValue == .Loading && actionHandler != nil {
actionHandler()
} else if newValue == .AnimatingToStopped {
resetScrollViewContentInset(shouldAddObserverWhenFinished: true, animated: true, completion: { [weak self] () -> () in self?.state = .Stopped })
} else if newValue == .Stopped {
loadingView?.stopLoading()
}
}
}
private var originalContentInsetTop: CGFloat = 0.0 { didSet { layoutSubviews() } }
private var originalContentInsetBottom: CGFloat = 0.0 { didSet { layoutSubviews() } }
private let shapeLayer = CAShapeLayer()
private var displayLink: CADisplayLink!
var actionHandler: (() -> Void)! = nil
var loadingView: DGElasticPullToRefreshLoadingView? {
willSet {
loadingView?.removeFromSuperview()
if let newValue = newValue {
addSubview(newValue)
}
}
}
var observing: Bool = false {
didSet {
guard let scrollView = scrollView() else { return }
if observing {
scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentOffset)
scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset)
scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.Frame)
scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.PanGestureRecognizerState)
} else {
scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentOffset)
scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset)
scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.Frame)
scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.PanGestureRecognizerState)
}
}
}
var fillColor: UIColor = .clearColor() { didSet { shapeLayer.fillColor = fillColor.CGColor } }
// MARK: Views
private let bounceAnimationHelperView = UIView()
private let cControlPointView = UIView()
private let l1ControlPointView = UIView()
private let l2ControlPointView = UIView()
private let l3ControlPointView = UIView()
private let r1ControlPointView = UIView()
private let r2ControlPointView = UIView()
private let r3ControlPointView = UIView()
// MARK: -
// MARK: Constructors
init() {
super.init(frame: CGRect.zero)
displayLink = CADisplayLink(target: self, selector: Selector("displayLinkTick"))
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
displayLink.paused = true
shapeLayer.backgroundColor = UIColor.clearColor().CGColor
shapeLayer.fillColor = UIColor.blackColor().CGColor
shapeLayer.actions = ["path" : NSNull(), "position" : NSNull(), "bounds" : NSNull()]
layer.addSublayer(shapeLayer)
addSubview(bounceAnimationHelperView)
addSubview(cControlPointView)
addSubview(l1ControlPointView)
addSubview(l2ControlPointView)
addSubview(l3ControlPointView)
addSubview(r1ControlPointView)
addSubview(r2ControlPointView)
addSubview(r3ControlPointView)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("applicationWillEnterForeground"), name: UIApplicationWillEnterForegroundNotification, object: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
/**
Has to be called when the receiver is no longer required. Otherwise the main loop holds a reference to the receiver which in turn will prevent the receiver from being deallocated.
*/
func disassociateDisplayLink() {
displayLink?.invalidate()
}
deinit {
observing = false
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: -
// MARK: Observer
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == DGElasticPullToRefreshConstants.KeyPaths.ContentOffset {
guard let scrollView = scrollView() else { return }
scrollViewDidChangeContentOffset(dragging: scrollView.dragging)
layoutSubviews()
} else if keyPath == DGElasticPullToRefreshConstants.KeyPaths.ContentInset {
// 设置内距
if let newContentInsetTop = change?[NSKeyValueChangeNewKey]?.UIEdgeInsetsValue().top {
originalContentInsetTop = newContentInsetTop
}
if let newContentInsetBottom = change?[NSKeyValueChangeNewKey]?.UIEdgeInsetsValue().bottom {
originalContentInsetBottom = newContentInsetBottom
}
} else if keyPath == DGElasticPullToRefreshConstants.KeyPaths.Frame {
layoutSubviews()
} else if keyPath == DGElasticPullToRefreshConstants.KeyPaths.PanGestureRecognizerState {
if let gestureState = scrollView()?.panGestureRecognizer.state where gestureState.dg_isAnyOf([.Ended, .Cancelled, .Failed]) {
scrollViewDidChangeContentOffset(dragging: false)
}
}
}
// MARK: -
// MARK: Notifications
func applicationWillEnterForeground() {
if state == .Loading {
layoutSubviews()
}
}
// MARK: -
// MARK: Methods (Public)
private func scrollView() -> UIScrollView? {
return superview as? UIScrollView
}
func stopLoading() {
// Prevent stop close animation
if state == .AnimatingToStopped {
return
}
state = .AnimatingToStopped
}
// MARK: Methods (Private)
private func isAnimating() -> Bool {
return state.isAnyOf([.AnimatingBounce, .AnimatingToStopped])
}
private func actualContentOffsetY() -> CGFloat {
guard let scrollView = scrollView() else { return 0.0 }
let offsetY = scrollView.contentOffset.y + scrollView.bounds.height - scrollView.contentSize.height
if direction == .Up {
return max(offsetY + originalContentInsetBottom, 0)
}
return max( -originalContentInsetTop-scrollView.contentOffset.y, 0)
}
private func currentHeight() -> CGFloat {
guard let scrollView = scrollView() else { return 0.0 }
let offsetY = scrollView.contentOffset.y + scrollView.bounds.height - scrollView.contentSize.height
if direction == .Up {
return max(offsetY + originalContentInsetBottom, 0)
}
return max( -originalContentInsetTop-scrollView.contentOffset.y, 0)
}
private func currentWaveHeight() -> CGFloat {
return min(bounds.height / 3.0 * 1.6, DGElasticPullToRefreshConstants.WaveMaxHeight)
}
private func checkPullUp() -> Bool {
guard let scrollView = scrollView() else { return false }
let offsetY = scrollView.contentOffset.y + scrollView.bounds.height - scrollView.contentSize.height
if offsetY >= 0 {
return true
}
if scrollView.contentOffset.y < 0 {
return false
}
return false
}
private func currentPath() -> CGPath {
let width: CGFloat = scrollView()?.bounds.width ?? 0.0
let bezierPath = UIBezierPath()
let animating = isAnimating()
let height = max(currentHeight(), DGElasticPullToRefreshConstants.LoadingContentInset)
if direction == .Up {
bezierPath.moveToPoint(CGPoint(x: 0.0, y: height))
}else{
bezierPath.moveToPoint(CGPoint(x: 0.0, y: 0.0))
}
bezierPath.addLineToPoint(CGPoint(x: 0.0, y: l3ControlPointView.dg_center(animating).y))
bezierPath.addCurveToPoint(l1ControlPointView.dg_center(animating), controlPoint1: l3ControlPointView.dg_center(animating), controlPoint2: l2ControlPointView.dg_center(animating))
bezierPath.addCurveToPoint(r1ControlPointView.dg_center(animating), controlPoint1: cControlPointView.dg_center(animating), controlPoint2: r1ControlPointView.dg_center(animating))
bezierPath.addCurveToPoint(r3ControlPointView.dg_center(animating), controlPoint1: r1ControlPointView.dg_center(animating), controlPoint2: r2ControlPointView.dg_center(animating))
if direction == .Up {
bezierPath.addLineToPoint(CGPoint(x: width, y: height))
}else{
bezierPath.addLineToPoint(CGPoint(x: width, y: 0.0))
}
bezierPath.closePath()
return bezierPath.CGPath
}
private func scrollViewDidChangeContentOffset(dragging dragging: Bool) {
if checkPullUp() {
direction = .Up
}else{
direction = .Down
}
let offsetY = actualContentOffsetY()
if state == .Stopped && dragging {
state = .Dragging
} else if state == .Dragging && dragging == false {
if offsetY >= DGElasticPullToRefreshConstants.MinOffsetToPull {
// 转圈圈
state = .AnimatingBounce
} else {
// 直接收起
state = .Stopped
}
} else if state.isAnyOf([.Dragging, .Stopped]) {
// set progress
let pullProgress: CGFloat = offsetY / DGElasticPullToRefreshConstants.MinOffsetToPull
loadingView?.setPullProgress(pullProgress)
}
}
private func resetScrollViewContentInset(shouldAddObserverWhenFinished shouldAddObserverWhenFinished: Bool, animated: Bool, completion: (() -> ())?) {
guard let scrollView = scrollView() else { return }
var contentInset = scrollView.contentInset
contentInset.top = originalContentInsetTop
contentInset.bottom = originalContentInsetBottom
if state == .AnimatingBounce {
// bounce animation
if direction == .Up {
contentInset.bottom += currentHeight()
}else{
contentInset.top += currentHeight()
}
} else if state == .Loading {
if direction == .Up {
contentInset.bottom += DGElasticPullToRefreshConstants.LoadingContentInset
}else{
contentInset.top += DGElasticPullToRefreshConstants.LoadingContentInset
}
}
scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset)
let animationBlock = { scrollView.contentInset = contentInset }
let completionBlock = { () -> Void in
if shouldAddObserverWhenFinished && self.observing {
scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset)
}
completion?()
}
if animated {
startDisplayLink()
UIView.animateWithDuration(0.4, animations: animationBlock, completion: { _ in
self.stopDisplayLink()
completionBlock()
})
} else {
animationBlock()
completionBlock()
}
}
private func animateBounce() {
guard let scrollView = scrollView() else { return }
resetScrollViewContentInset(shouldAddObserverWhenFinished: false, animated: false, completion: nil)
var centerY = DGElasticPullToRefreshConstants.LoadingContentInset
if direction == .Up {
centerY = 0
}
let duration = 0.9
scrollView.scrollEnabled = false
startDisplayLink()
scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentOffset)
scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset)
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.43, initialSpringVelocity: 0.0, options: [], animations: { [weak self] in
self?.cControlPointView.center.y = centerY
self?.l1ControlPointView.center.y = centerY
self?.l2ControlPointView.center.y = centerY
self?.l3ControlPointView.center.y = centerY
self?.r1ControlPointView.center.y = centerY
self?.r2ControlPointView.center.y = centerY
self?.r3ControlPointView.center.y = centerY
}, completion: { [weak self] _ in
self?.stopDisplayLink()
self?.resetScrollViewContentInset(shouldAddObserverWhenFinished: true, animated: false, completion: nil)
if let strongSelf = self, scrollView = strongSelf.scrollView() {
scrollView.dg_addObserver(strongSelf, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentOffset)
scrollView.scrollEnabled = true
}
self?.state = .Loading // begin loading
})
bounceAnimationHelperView.center = CGPoint(x: 0.0, y: 0 + currentHeight())
UIView.animateWithDuration(duration * 0.4, animations: { [weak self] in
self?.bounceAnimationHelperView.center = CGPoint(x: 0.0, y: DGElasticPullToRefreshConstants.LoadingContentInset)
}, completion: nil)
}
// MARK: -
// MARK: CADisplayLink
private func startDisplayLink() {
displayLink.paused = false
}
private func stopDisplayLink() {
displayLink.paused = true
}
func displayLinkTick() {
let width = bounds.width
var height: CGFloat = 0.0
if state == .AnimatingBounce {
guard let scrollView = scrollView() else { return }
if direction == .Up {
// 渐渐向下收起
scrollView.contentInset.bottom = bounceAnimationHelperView.dg_center(isAnimating()).y
scrollView.contentOffset.y = scrollView.contentSize.height-(scrollView.bounds.height - scrollView.contentInset.bottom)
height = scrollView.contentInset.bottom
frame = CGRect(x: 0.0, y: scrollView.contentSize.height + 1.0, width: width, height: height)
}else{
// 渐渐向上收起
scrollView.contentInset.top = bounceAnimationHelperView.dg_center(isAnimating()).y
scrollView.contentOffset.y = -scrollView.contentInset.top
height = scrollView.contentInset.top - originalContentInsetTop
frame = CGRect(x: 0.0, y: -height - 1.0, width: width, height: height)
}
} else if state == .AnimatingToStopped {
height = actualContentOffsetY()
}
shapeLayer.frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
shapeLayer.path = currentPath()
layoutLoadingView()
}
// MARK: -
// MARK: Layout
private func layoutLoadingView() {
let width = bounds.width
let height: CGFloat = bounds.height
let loadingViewSize: CGFloat = DGElasticPullToRefreshConstants.LoadingViewSize
let minOriginY = (DGElasticPullToRefreshConstants.LoadingContentInset - loadingViewSize) / 2.0
var originY: CGFloat = max(min((height - loadingViewSize) / 2.0, minOriginY), 0.0)
if direction == .Up {
originY = max(currentHeight() - loadingViewSize - originY ,0)
}
loadingView?.frame = CGRect(x: (width - loadingViewSize) / 2.0, y: originY, width: loadingViewSize, height: loadingViewSize)
loadingView?.maskLayer.frame = convertRect(shapeLayer.frame, toView: loadingView)
loadingView?.maskLayer.path = shapeLayer.path
}
override public func layoutSubviews() {
super.layoutSubviews()
if let scrollView = scrollView() where state != .AnimatingBounce {
let width = scrollView.bounds.width
let height = currentHeight()
if direction == .Up {
frame = CGRect(x: 0.0, y: scrollView.contentSize.height, width: width, height: height)
}else{
frame = CGRect(x: 0.0, y: -height, width: width, height: height)
}
if state.isAnyOf([.Loading, .AnimatingToStopped]) {
cControlPointView.center = CGPoint(x: width / 2.0, y: height)
l1ControlPointView.center = CGPoint(x: 0.0, y: height)
l2ControlPointView.center = CGPoint(x: 0.0, y: height)
l3ControlPointView.center = CGPoint(x: 0.0, y: height)
r1ControlPointView.center = CGPoint(x: width, y: height)
r2ControlPointView.center = CGPoint(x: width, y: height)
r3ControlPointView.center = CGPoint(x: width, y: height)
if direction == .Up {
cControlPointView.center = CGPoint(x: width / 2.0, y: 0)
l1ControlPointView.center = CGPoint(x: 0.0, y: 0)
l2ControlPointView.center = CGPoint(x: 0.0, y: 0)
l3ControlPointView.center = CGPoint(x: 0.0, y: 0)
r1ControlPointView.center = CGPoint(x: width, y: 0)
r2ControlPointView.center = CGPoint(x: width, y: 0)
r3ControlPointView.center = CGPoint(x: width, y: 0)
}
} else {
let locationX = scrollView.panGestureRecognizer.locationInView(scrollView).x
let waveHeight = currentWaveHeight()
let baseHeight = bounds.height - waveHeight
print("\(baseHeight)")
let minLeftX = min((locationX - width / 2.0) * 0.28, 0.0)
let maxRightX = max(width + (locationX - width / 2.0) * 0.28, width)
let leftPartWidth = locationX - minLeftX
let rightPartWidth = maxRightX - locationX
cControlPointView.center = CGPoint(x: locationX , y: baseHeight + waveHeight * 1.36)
l1ControlPointView.center = CGPoint(x: minLeftX + leftPartWidth * 0.71, y: baseHeight + waveHeight * 0.64)
l2ControlPointView.center = CGPoint(x: minLeftX + leftPartWidth * 0.44, y: baseHeight)
l3ControlPointView.center = CGPoint(x: minLeftX, y: baseHeight)
r1ControlPointView.center = CGPoint(x: maxRightX - rightPartWidth * 0.71, y: baseHeight + waveHeight * 0.64)
r2ControlPointView.center = CGPoint(x: maxRightX - (rightPartWidth * 0.44), y: baseHeight)
r3ControlPointView.center = CGPoint(x: maxRightX, y: baseHeight)
if direction == .Up {
cControlPointView.center.y -= height
l1ControlPointView.center.y -= height
l2ControlPointView.center.y -= height
l3ControlPointView.center.y -= height
r1ControlPointView.center.y -= height
r2ControlPointView.center.y -= height
r3ControlPointView.center.y -= height
cControlPointView.center.y = -cControlPointView.center.y
l1ControlPointView.center.y = -l1ControlPointView.center.y
l2ControlPointView.center.y = -l2ControlPointView.center.y
l3ControlPointView.center.y = -l3ControlPointView.center.y
r1ControlPointView.center.y = -r1ControlPointView.center.y
r2ControlPointView.center.y = -r2ControlPointView.center.y
r3ControlPointView.center.y = -r3ControlPointView.center.y
}
print("cControlPointView.center.y\(cControlPointView.center.y)")
}
shapeLayer.frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
shapeLayer.path = currentPath()
layoutLoadingView()
}
}
}
| 504f4505771682bfbcdbb16e4c651ff2 | 40.845872 | 187 | 0.618916 | false | false | false | false |
ThumbWorks/i-meditated | refs/heads/master | Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/Do.swift | mit | 6 | //
// Do.swift
// Rx
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DoSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias Parent = Do<Element>
private let _parent: Parent
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func on(_ event: Event<Element>) {
do {
try _parent._eventHandler(event)
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
catch let error {
forwardOn(.error(error))
dispose()
}
}
}
class Do<Element> : Producer<Element> {
typealias EventHandler = (Event<Element>) throws -> Void
fileprivate let _source: Observable<Element>
fileprivate let _eventHandler: EventHandler
fileprivate let _onSubscribe: (() -> ())?
fileprivate let _onDispose: (() -> ())?
init(source: Observable<Element>, eventHandler: @escaping EventHandler, onSubscribe: (() -> ())?, onDispose: (() -> ())?) {
_source = source
_eventHandler = eventHandler
_onSubscribe = onSubscribe
_onDispose = onDispose
}
override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_onSubscribe?()
let sink = DoSink(parent: self, observer: observer)
let subscription = _source.subscribe(sink)
let onDispose = _onDispose
sink.disposable = Disposables.create {
subscription.dispose()
onDispose?()
}
return sink
}
}
| acd15bed391ce74f094188dad9e8f9be | 26.190476 | 127 | 0.572096 | false | false | false | false |
keygx/GradientCircularProgress | refs/heads/master | GCProgressSample/GradientCircularProgress/Progress/Elements/ArcView.swift | mit | 2 | //
// Arc.swift
// GradientCircularProgress
//
// Created by keygx on 2015/06/24.
// Copyright (c) 2015年 keygx. All rights reserved.
//
import UIKit
class ArcView: UIView {
var prop: Property?
var ratio: CGFloat = 1.0
var color: UIColor = UIColor.black
var lineWidth: CGFloat = 0.0
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(frame: CGRect, lineWidth: CGFloat) {
super.init(frame: frame)
backgroundColor = UIColor.clear
layer.masksToBounds = true
self.lineWidth = lineWidth
}
override func draw(_ rect: CGRect) {
drawArc(rect: rect)
}
private func drawArc(rect: CGRect) {
guard let prop = prop else {
return
}
let circularRect: CGRect = prop.progressRect
let arcPoint: CGPoint = CGPoint(x: rect.width/2, y: rect.height/2)
let arcRadius: CGFloat = circularRect.width/2 + prop.arcLineWidth/2
let arcStartAngle: CGFloat = -CGFloat.pi/2
let arcEndAngle: CGFloat = ratio * 2.0 * CGFloat.pi - CGFloat.pi/2
let arc: UIBezierPath = UIBezierPath(arcCenter: arcPoint,
radius: arcRadius,
startAngle: arcStartAngle,
endAngle: arcEndAngle,
clockwise: true)
color.setStroke()
arc.lineWidth = lineWidth
arc.lineCapStyle = prop.arcLineCapStyle
arc.stroke()
}
}
| 351d94ffda7c59f93031b674c89754eb | 27.016393 | 79 | 0.528964 | false | false | false | false |
phatblat/3DTouchDemo | refs/heads/master | 3DTouchDemo/MasterViewController+UIViewControllerPreviewing.swift | mit | 1 | //
// MasterViewController.swift
// 3DTouchDemo
//
// Created by Ben Chatelain on 9/28/15.
// Copyright © 2015 Ben Chatelain. All rights reserved.
//
import UIKit
extension MasterViewController: UIViewControllerPreviewingDelegate {
// MARK: - UIViewControllerPreviewingDelegate
/// Create a previewing view controller to be shown as a "Peek".
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
// Obtain the index path and the cell that was pressed.
guard let indexPath = tableView.indexPathForRowAtPoint(location),
cell = tableView.cellForRowAtIndexPath(indexPath) else { return nil }
if #available(iOS 9, *) {
// Set the source rect to the cell frame, so surrounding elements are blurred.
previewingContext.sourceRect = cell.frame
}
return viewControllerForIndexPath(indexPath)
}
/// Present the view controller for the "Pop" action.
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
// Reuse the "Peek" view controller for presentation.
showViewController(viewControllerToCommit, sender: self)
}
}
extension MasterViewController {
private func viewControllerForIndexPath(indexPath: NSIndexPath) -> UIViewController? {
switch indexPath.row {
case 0..<touchCanvasRow:
// Create a detail view controller and set its properties.
guard let detailViewController = storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController else { return nil }
let previewDetail = sampleData[indexPath.row]
detailViewController.detailItemTitle = previewDetail.title
if let color = previewDetail.color {
detailViewController.view.backgroundColor = color
}
// Set the height of the preview by setting the preferred content size of the detail view controller.
// Width should be zero, because it's not used in portrait.
detailViewController.preferredContentSize = CGSize(width: 0.0, height: previewDetail.preferredHeight)
return detailViewController
case touchCanvasRow:
return storyboard?.instantiateViewControllerWithIdentifier("TouchCanvasViewController")
case touchCanvasRow + 1:
return storyboard?.instantiateViewControllerWithIdentifier("ForceProgressViewController")
default:
return nil
}
}
}
| 4a3b75272d9df536b84b2d47b739ee6b | 37.695652 | 165 | 0.702996 | false | false | false | false |
Syject/MyLessPass-iOS | refs/heads/master | LessPass/Libraries/BigInteger/MG Benchmark Tools.swift | gpl-3.0 | 1 | /*
————————————————————————————————————————————————————————————————————————————
MG Benchmark Tools.swift
————————————————————————————————————————————————————————————————————————————
Created by Marcel Kröker on 03.04.15.
Copyright (c) 2016 Blubyte. All rights reserved.
*/
import Foundation
#if os(Linux)
import Glibc
import CBSD
private func mach_absolute_time() -> UInt64 {
var tv = timeval();
guard gettimeofday(&tv, nil) != -1 else { return 0 }
let t = UInt64(tv.tv_usec) + UInt64(tv.tv_sec) * 1000000
return t;
}
private struct mach_timebase_info_data_t {
var numer: Int = 1000
var denom: Int = 1
}
private func mach_timebase_info(_: inout mach_timebase_info_data_t) {}
#endif
private func durationNS(_ call: () -> ()) -> Int
{
var start = UInt64()
var end = UInt64()
start = mach_absolute_time()
call()
end = mach_absolute_time()
let elapsed = end - start
var timeBaseInfo = mach_timebase_info_data_t()
mach_timebase_info(&timeBaseInfo)
let elapsedNano = Int(elapsed) * Int(timeBaseInfo.numer) / Int(timeBaseInfo.denom)
return elapsedNano
}
private func adjustPrecision(_ ns: Int, toPrecision: String) -> Int
{
switch toPrecision
{
case "ns": // nanoseconds
return ns
case "us": // microseconds
return ns / 1_000
case "ms": // milliseconds
return ns / 1_000_000
default: // seconds
return ns / 1_000_000_000
}
}
/**
Measure execution time of trailing closure.
- Parameter precision: Precision of measurement. Possible
values:
- "ns": nanoseconds
- "us": microseconds
- "ms" or omitted parameter: milliseconds
- "s" or invalid input: seconds
*/
public func benchmark(_ precision: String = "ms", _ call: () -> ()) -> Int
{
// empty call duration to subtract
let emptyCallNano = durationNS({})
let elapsedNano = durationNS(call)
let elapsedCorrected = elapsedNano >= emptyCallNano
? elapsedNano - emptyCallNano
: 0
return adjustPrecision(elapsedCorrected, toPrecision: precision)
}
/**
Measure execution time of trailing closure, and print result
with description into the console.
- Parameter precision: Precision of measurement. Possible
values:
- "ns": nanoseconds
- "us": microseconds
- "ms" or omitted parameter: milliseconds
- "s" or invalid input: seconds
- Parameter title: Description of benchmark.
*/
public func benchmarkPrint(_ precision: String = "ms", title: String, _ call: () -> ())
{
print(title + ": \(benchmark(precision, call))" + precision)
}
/**
Measure the average execution time of trailing closure.
- Parameter precision: Precision of measurement. Possible
values:
- "ns": nanoseconds
- "us": microseconds
- "ms" or omitted parameter: milliseconds
- "s" or invalid input: seconds
- Parameter title: Description of benchmark.
- Parameter times: Amount of executions.
Default when parameter is omitted: 100.
- Returns: Minimum, Average and Maximum execution time of
benchmarks as 3-tuple.
*/
public func benchmarkAvg(
_ precision: String = "ms",
title: String = "",
times: Int = 10,
_ call: () -> ())
-> (min: Int, avg: Int, max: Int)
{
let emptyCallsNano = durationNS(
{
for _ in 0..<times {}
})
var min = Int.max
var max = 0
var elapsedNanoCombined = 0
for _ in 0..<times
{
let duration = durationNS(call)
if duration < min { min = duration }
if duration > max { max = duration }
elapsedNanoCombined += duration
}
let elapsedCorrected = elapsedNanoCombined >= emptyCallsNano
? elapsedNanoCombined - emptyCallsNano
: 0
return (adjustPrecision(min, toPrecision: precision),
adjustPrecision(elapsedCorrected / times, toPrecision: precision),
adjustPrecision(max, toPrecision: precision)
)
}
| 9c146cd38e53805dc25fcbdb3bb08142 | 22.531646 | 87 | 0.655729 | false | false | false | false |
JeffESchmitz/OnTheMap | refs/heads/master | OnTheMap/OnTheMap/StudentInformation.swift | mit | 1 | //
// StudentInformation.swift
// OnTheMap
//
// Created by Jeff Schmitz on 4/30/16.
// Copyright © 2016 Jeff Schmitz. All rights reserved.
//
import Foundation
// Represents a post of student information returned from the data table via the parse server.
struct StudentInformation {
var objectId: String?
var uniqueKey: String?
var firstName: String?
var lastName: String?
var mapString: String?
var mediaURL: String?
var latitude: Double?
var longitude: Double?
var createdAt: String?
var updatedAt: String?
init(dictionary: [String:AnyObject]) {
objectId = dictionary[Constants.ParseAPI.ObjectId] as? String
uniqueKey = dictionary[Constants.ParseAPI.UniqueKey] as? String
firstName = dictionary[Constants.ParseAPI.FirstName] as? String
lastName = dictionary[Constants.ParseAPI.LastName] as? String
mapString = dictionary[Constants.ParseAPI.MapString] as? String
mediaURL = dictionary[Constants.ParseAPI.MediaURL] as? String
latitude = dictionary[Constants.ParseAPI.Latitude] as? Double
longitude = dictionary[Constants.ParseAPI.Longitude] as? Double
createdAt = dictionary[Constants.ParseAPI.CreatedAt] as? String
updatedAt = dictionary[Constants.ParseAPI.UpdatedAt] as? String
}
} | ea047320e538920391787425cb8c3171 | 34.921053 | 94 | 0.690616 | false | false | false | false |
priya273/stockAnalyzer | refs/heads/master | Stock Analyzer/Stock Analyzer/QuoteService.swift | apache-2.0 | 1 | //
// QuoteService.swift
// Stock Analyzer
//
// Created by Naga sarath Thodime on 3/16/16.
// Copyright © 2016 Priyadarshini Ragupathy. All rights reserved.
//
import Foundation
import Alamofire
protocol QuoteServiceCallBacksProtocol
{
func ServiceFailed(message: String)
func ServicePassed(stock: StockContract)
}
class QuoteService
{
var delegate : QuoteServiceCallBacksProtocol!
func Run(symbol : String, id : String?)
{
let url = NSURL(string: "http://stockanalyzer.azurewebsites.net/api/stock/quote/\(symbol)");
let headers = ["id" : "\(id)"]
Alamofire.request(.GET, url!, parameters: headers).responseJSON
{
JSON in
do
{
let values = try NSJSONSerialization.JSONObjectWithData(JSON.data! as NSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
let object = StockContract();
object.name = values.valueForKey("Name") as? String
object.symbol = values.valueForKey("Symbol") as? String
object.open = values.valueForKey("Open") as? NSNumber
object.high = values.valueForKey("High") as? NSNumber
object.low = values.valueForKey("Low") as? NSNumber
object.marketCap = values.valueForKey("MarketCap") as? NSNumber
object.lastPrice = values.valueForKey("LastPrice") as? NSNumber
object.volumn = values.valueForKey("Volume") as? NSNumber
object.change = values.valueForKey("Change") as? NSNumber
object.changePercent = values.valueForKey("ChangePercent") as? NSNumber
self.delegate?.ServicePassed(object)
}
catch
{
self.delegate?.ServiceFailed("Failed to Load Quote from service for Symbol: \(symbol)")
}
}
}
} | 15daf4c475229332aac50105fc98a8bc | 35.140625 | 168 | 0.509083 | false | false | false | false |
DDSSwiftTech/SwiftMine | refs/heads/master | Sources/SwiftMineCore/src/Config/ServerConfig.swift | apache-2.0 | 1 | //
// BaseClass.swift
// SwiftMine
//
// Created by David Schwartz on 8/24/16.
// Copyright © 2016 David Schwartz. All rights reserved.
//
import Foundation
internal final class ServerConfig {
/// Currently supported server config version
static let VERSION: Int8 = 2
//all default configuration goes here
static let DEFAULT_CONFIG_DICT: Dictionary<String, Any> = [
"_config_version": Int(VERSION),
"port": 19132,
"server_name": "§cSwiftMine Server",
"max_players": 999,
"log_level": LogLevel.info.rawValue
]
internal var configurationArray: Dictionary<String, Any> = [:]
private let configurationFilename = "swiftmine.sws"
internal let configPath: URL
internal init(withPath path: URL) {
self.configPath = path.appendingPathComponent("config/\(configurationFilename)")
if FileManager.default.fileExists(atPath: self.configPath.path) {
let inStream = InputStream(url: self.configPath)!
inStream.open()
let tempConfig = (try! JSONSerialization.jsonObject(with: inStream, options: JSONSerialization.ReadingOptions(
rawValue: JSONSerialization.ReadingOptions.mutableContainers.rawValue | JSONSerialization.ReadingOptions.mutableLeaves.rawValue)) as! Dictionary<String, Any>)
if (tempConfig["_config_version"] as! Int) == ServerConfig.VERSION {
configurationArray = tempConfig
return
}
}
doConfig(forItems: nil)
}
//separate function, to keep the init less cluttered
internal func doConfig(forItems items: [String]?) {
var items = items
/// Used to determine whether or not we should care about private configuration items
var configuringAllItems = false
// This means that we should configure or reconfigure everything
if items == nil {
print("Welcome to the SwiftMine version \(GLOBAL_VARS["VERSION"]!) setup!")
configuringAllItems = true
items = Array(ServerConfig.DEFAULT_CONFIG_DICT.keys)
}
guard (try? FileManager.default.createDirectory(at: configPath.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)) != nil else {
print("could not create config directory")
Server.main.stop(code: .CONFIG_DIR_CREATE_FAILED)
}
var configChanged = false
for (item) in items! {
if ServerConfig.DEFAULT_CONFIG_DICT.keys.contains(item) {
guard !item.hasPrefix("_") else {
if !configuringAllItems {
print("Cannot configure private item \(item).")
}
self.configurationArray[item] = ServerConfig.DEFAULT_CONFIG_DICT[item]!
continue
}
print("Enter a value for \(item) (default value - \(ServerConfig.DEFAULT_CONFIG_DICT[item]!)): ")
let ENTRY_STRING = readLine(strippingNewline: true)!
switch type(of: ServerConfig.DEFAULT_CONFIG_DICT[item]!) {
case is String.Type:
// need custom behavior for log_level, to verify that the log level exists
if item == "log_level" {
configurationArray[item] = (LogLevel(rawValue: ENTRY_STRING) != nil ? ENTRY_STRING : ServerConfig.DEFAULT_CONFIG_DICT[item]!)
} else {
configurationArray[item] = (ENTRY_STRING != "" ? ENTRY_STRING : ServerConfig.DEFAULT_CONFIG_DICT[item]!)
}
case is Int.Type:
configurationArray[item] = NumberFormatter().number(from: ENTRY_STRING) ?? ServerConfig.DEFAULT_CONFIG_DICT[item]!
default:
continue
}
configChanged = true
} else {
print("Config item \(item) not found.")
}
}
if configChanged {
if FileManager.default.fileExists(atPath: configPath.path) {
try! FileManager.default.removeItem(atPath: configPath.path)
}
let outStream = OutputStream(url: configPath, append: false)!
outStream.open()
#if os(Linux)
do {
_ = try JSONSerialization.writeJSONObject(configurationArray, toStream: outStream, options: JSONSerialization.WritingOptions.prettyPrinted)
} catch (let error) {
print(error)
Server.main.stop()
}
#else
if JSONSerialization.writeJSONObject(configurationArray, to: outStream, options: JSONSerialization.WritingOptions.prettyPrinted, error: nil) == 0 {
print("Could not save config")
Server.main.stop()
}
#endif
print("saving config...")
}
}
}
| 58ca33357c358d7dd706118492485486 | 38.30597 | 174 | 0.558572 | false | true | false | false |
vanshg/MacAssistant | refs/heads/master | MacAssistant/Auth/Authenticator.swift | mit | 1 | //
// Created by Vansh Gandhi on 7/26/18.
// Copyright (c) 2018 Vansh Gandhi. All rights reserved.
//
import Foundation
import Cocoa
import Alamofire
import SwiftyJSON
import Log
import SwiftyUserDefaults
public class Authenticator {
static let instance = Authenticator(scope: "https://www.googleapis.com/auth/assistant-sdk-prototype")
let Log = Logger()
var scope: String
var authUrl: String
var tokenUrl: String
var redirectUrl: String
var clientId: String
var clientSecret: String
var loginUrl: String
init(scope: String) {
self.scope = scope
let url = Bundle.main.url(forResource: "google_oauth", withExtension: "json")!
let json = try! JSON(data: Data(contentsOf: url))["installed"]
authUrl = json["auth_uri"].stringValue
tokenUrl = json["token_uri"].stringValue
redirectUrl = json["redirect_uris"][1].stringValue // Get the "http://localhost" url
clientId = json["client_id"].stringValue
clientSecret = json["client_secret"].stringValue
loginUrl = "\(authUrl)?client_id=\(clientId)&scope=\(scope)&response_type=code&redirect_uri=\(redirectUrl)"
Timer.scheduledTimer(withTimeInterval: 600, repeats: true) { _ in
// First run is at time 0 (aka, when the app first starts up)
if Defaults[.isLoggedIn] {
self.refreshTokenIfNecessary()
}
}.fire()
}
func authenticate(code: String, onLoginResult: @escaping (Error?) -> Void) {
let parameters = [
"code": code,
"client_id": clientId,
"client_secret": clientSecret,
"redirect_uri": redirectUrl,
"grant_type": "authorization_code",
]
Alamofire.request(tokenUrl, method: .post, parameters: parameters).responseJSON() { response in
switch response.result {
case .success(let value):
let json = JSON(value)
if let err = json["error"].string {
self.Log.debug("\(err): \(json["error_description"].string ?? "no error msg")")
onLoginResult(NSError())
return
}
let tokenExpiration = Date(timeInterval: TimeInterval(json["expires_in"].intValue), since: Date())
Defaults[.tokenExpirationDate] = tokenExpiration
Defaults[.accessToken] = json["access_token"].stringValue
Defaults[.refreshToken] = json["refresh_token"].stringValue
Defaults[.isLoggedIn] = true
self.Log.debug("Login success")
onLoginResult(nil)
case .failure(let error):
self.Log.error("Error fetching access token \(error)")
onLoginResult(error)
}
}
}
func refresh() {
let parameters = [
"refresh_token": Defaults[.refreshToken],
"client_id": clientId,
"client_secret": clientSecret,
"grant_type": "refresh_token",
]
Alamofire.request(tokenUrl, method: .post, parameters: parameters).responseJSON() { response in
switch response.result {
case .success(let value):
let json = JSON(value)
if let err = json["error"].string {
self.Log.debug("\(err): \(json["error_description"].string ?? "No error msg provided")")
return
}
let tokenExpiration = Date(timeInterval: TimeInterval(json["expires_in"].int!), since: Date())
Defaults[.tokenExpirationDate] = tokenExpiration
Defaults[.accessToken] = json["access_token"].stringValue
self.Log.debug("Refresh token success")
case .failure(let error):
self.Log.error("Error refreshing token: \(error)")
}
}
}
func refreshTokenIfNecessary() {
Log.info("Checking if token needs to be refreshed")
if var date = Defaults[.tokenExpirationDate] {
date.addTimeInterval(60 * 5) //refresh token with 5 mins left
if date < Date() && Defaults[.isLoggedIn] {
refresh()
}
}
}
func logout() {
Defaults[.isLoggedIn] = false
Defaults[.accessToken] = ""
Defaults[.refreshToken] = ""
}
}
| 6e3c7c874592559319dd18deb6284bfd | 35.735537 | 115 | 0.568954 | false | false | false | false |
deyton/swift | refs/heads/master | test/Generics/associated_type_typo.swift | apache-2.0 | 7 | // RUN: %target-typecheck-verify-swift
// RUN: not %target-swift-frontend -typecheck -debug-generic-signatures %s > %t.dump 2>&1
// RUN: %FileCheck -check-prefix CHECK-GENERIC %s < %t.dump
protocol P1 {
associatedtype Assoc
}
protocol P2 {
associatedtype AssocP2 : P1
}
protocol P3 { }
protocol P4 { }
// expected-error@+1{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}
func typoAssoc1<T : P1>(x: T.assoc, _: T) { }
// expected-error@+2{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{53-58=Assoc}}
// expected-error@+1{{'U' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{64-69=Assoc}}
func typoAssoc2<T : P1, U : P1>(_: T, _: U) where T.assoc == U.assoc {}
// CHECK-GENERIC-LABEL: .typoAssoc2
// CHECK-GENERIC: Generic signature: <T, U where T : P1, U : P1>
// expected-error@+3{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{42-47=Assoc}}
// expected-error@+2{{'U.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{19-24=Assoc}}
func typoAssoc3<T : P2, U : P2>(t: T, u: U)
where U.AssocP2.assoc : P3, T.AssocP2.assoc : P4,
T.AssocP2 == U.AssocP2 {}
// expected-error@+2{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}
// expected-error@+1{{'T' does not have a member type named 'Assocp2'; did you mean 'AssocP2'?}}{{39-46=AssocP2}}
func typoAssoc4<T : P2>(_: T) where T.Assocp2.assoc : P3 {}
// CHECK-GENERIC-LABEL: .typoAssoc4@
// CHECK-GENERIC-NEXT: Requirements:
// CHECK-GENERIC-NEXT: τ_0_0 : P2 [τ_0_0: Explicit @ {{.*}}:21]
// CHECK-GENERIC-NEXT: τ_0_0[.P2].AssocP2 : P1 [τ_0_0: Explicit @ {{.*}}:21 -> Protocol requirement (via Self.AssocP2 in P2)
// CHECK-GENERIC-NEXT: Potential archetypes
// <rdar://problem/19620340>
func typoFunc1<T : P1>(x: TypoType) { // expected-error{{use of undeclared type 'TypoType'}}
let _: (T.Assoc) -> () = { let _ = $0 }
}
func typoFunc2<T : P1>(x: TypoType, y: T) { // expected-error{{use of undeclared type 'TypoType'}}
let _: (T.Assoc) -> () = { let _ = $0 }
}
func typoFunc3<T : P1>(x: TypoType, y: (T.Assoc) -> ()) { // expected-error{{use of undeclared type 'TypoType'}}
}
// rdar://problem/29261689
typealias Element_<S: Sequence> = S.Iterator.Element
public protocol _Indexable1 {
associatedtype Slice // expected-note{{declared here}}
}
public protocol Indexable : _Indexable1 {
associatedtype Slice : _Indexable1 // expected-warning{{redeclaration of associated type 'Slice'}}
}
protocol Pattern {
associatedtype Element : Equatable
// FIXME: This works for all of the wrong reasons, but it is correct that
// it works.
func matched<C: Indexable>(atStartOf c: C)
where Element_<C> == Element
, Element_<C.Slice> == Element
}
class C {
typealias SomeElement = Int
}
func typoSuperclass1<T : C>(_: T) where T.someElement: P3 { }
// expected-error@-1{{'T' does not have a member type named 'someElement'; did you mean 'SomeElement'?}}{{43-54=SomeElement}}
class D {
typealias AElement = Int // expected-note{{did you mean 'AElement'?}}
typealias BElement = Int // expected-note{{did you mean 'BElement'?}}
}
func typoSuperclass2<T : D>(_: T, _: T.Element) { } // expected-error{{'Element' is not a member type of 'T'}}
| f25c3f0af6b21a06e89bf7adcae611ae | 36.089888 | 126 | 0.657679 | false | false | false | false |
Allen17/InternationalSpaceStation | refs/heads/Doharmony | Alamofire/Source/Manager.swift | agpl-3.0 | 70 | // Manager.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
*/
public class Manager {
// MARK: - Properties
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
for any ad hoc requests.
*/
public static let sharedInstance: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return Manager(configuration: configuration)
}()
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
*/
public static let defaultHTTPHeaders: [String: String] = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joinWithSeparator(", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) {
return mutableUserAgent as String
}
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// The session delegate handling all the task and session delegate callbacks.
public let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
The background completion handler closure provided by the UIApplicationDelegate
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
will automatically call the handler.
If you need to handle your own events before the handler is called, then you need to override the
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
`nil` by default.
*/
public var backgroundCompletionHandler: (() -> Void)?
// MARK: - Lifecycle
/**
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
- parameter configuration: The configuration used to construct the managed session.
`NSURLSessionConfiguration.defaultSessionConfiguration()` by default.
- parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
default.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance.
*/
public init(
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/**
Initializes the `Manager` instance with the specified session, delegate and server trust policy.
- parameter session: The URL session.
- parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter.
*/
public init?(
session: NSURLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = session
guard delegate === session.delegate else { return nil }
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Request
/**
Creates a request for the specified method, URL string, parameters, parameter encoding and headers.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter parameters: The parameters. `nil` by default.
- parameter encoding: The parameter encoding. `.URL` by default.
- parameter headers: The HTTP headers. `nil` by default.
- returns: The created request.
*/
public func request(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
return request(encodedURLRequest)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask!
dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) }
let request = Request(session: session, task: dataTask)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: - SessionDelegate
/**
Responsible for handling all delegate callbacks for the underlying session.
*/
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
}
}
/**
Initializes the `SessionDelegate` instance.
- returns: The new `SessionDelegate` instance.
*/
public override init() {
super.init()
}
// MARK: - NSURLSessionDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the session has been invalidated.
- parameter session: The session object that was invalidated.
- parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
*/
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
sessionDidBecomeInvalidWithError?(session, error)
}
/**
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
- parameter session: The session containing the task that requested authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
/**
Tells the delegate that all messages enqueued for a session have been delivered.
- parameter session: The session that no longer has any outstanding requests.
*/
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the remote server requested an HTTP redirect.
- parameter session: The session containing the task whose request resulted in a redirect.
- parameter task: The task whose request resulted in a redirect.
- parameter response: An object containing the server’s response to the original request.
- parameter request: A URL request object filled out with the new location.
- parameter completionHandler: A closure that your handler should call with either the value of the request
parameter, a modified URL request object, or NULL to refuse the redirect and
return the body of the redirect response.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: ((NSURLRequest?) -> Void))
{
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/**
Requests credentials from the delegate in response to an authentication request from the remote server.
- parameter session: The session containing the task whose request requires authentication.
- parameter task: The task whose request requires authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
completionHandler(taskDidReceiveChallenge(session, task, challenge))
} else if let delegate = self[task] {
delegate.URLSession(
session,
task: task,
didReceiveChallenge: challenge,
completionHandler: completionHandler
)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
/**
Tells the delegate when a task requires a new request body stream to send to the remote server.
- parameter session: The session containing the task that needs a new body stream.
- parameter task: The task that needs a new body stream.
- parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
{
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/**
Periodically informs the delegate of the progress of sending body content to the server.
- parameter session: The session containing the data task.
- parameter task: The data task.
- parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
- parameter totalBytesSent: The total number of bytes sent so far.
- parameter totalBytesExpectedToSend: The expected length of the body data.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
/**
Tells the delegate that the task finished transferring data.
- parameter session: The session containing the task whose request finished transferring data.
- parameter task: The task whose request finished transferring data.
- parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
*/
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidComplete = taskDidComplete {
taskDidComplete(session, task, error)
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
self[task] = nil
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
// MARK: Delegate Methods
/**
Tells the delegate that the data task received the initial reply (headers) from the server.
- parameter session: The session containing the data task that received an initial reply.
- parameter dataTask: The data task that received an initial reply.
- parameter response: A URL response object populated with headers.
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
constant to indicate whether the transfer should continue as a data task or
should become a download task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: ((NSURLSessionResponseDisposition) -> Void))
{
var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/**
Tells the delegate that the data task was changed to a download task.
- parameter session: The session containing the task that was replaced by a download task.
- parameter dataTask: The data task that was replaced by a download task.
- parameter downloadTask: The new download task that replaced the data task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
}
/**
Tells the delegate that the data task has received some of the expected data.
- parameter session: The session containing the data task that provided data.
- parameter dataTask: The data task that provided data.
- parameter data: A data object containing the transferred data.
*/
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
}
/**
Asks the delegate whether the data (or upload) task should store the response in the cache.
- parameter session: The session containing the data (or upload) task.
- parameter dataTask: The data (or upload) task.
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
caching policy and the values of certain received headers, such as the Pragma
and Cache-Control headers.
- parameter completionHandler: A block that your handler must call, providing either the original proposed
response, a modified version of that response, or NULL to prevent caching the
response. If your delegate implements this method, it must call this completion
handler; otherwise, your app leaks memory.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: ((NSCachedURLResponse?) -> Void))
{
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that a download task has finished downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that finished.
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
open the file for reading or move it to a permanent location in your app’s sandbox
container directory before returning from this delegate method.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
}
/**
Periodically informs the delegate about the download’s progress.
- parameter session: The session containing the download task.
- parameter downloadTask: The download task.
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
method was called.
- parameter totalBytesWritten: The total number of bytes transferred so far.
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
header. If this header was not provided, the value is
`NSURLSessionTransferSizeUnknown`.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/**
Tells the delegate that the download task has resumed downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
existing content, then this value is zero. Otherwise, this value is an
integer representing the number of bytes on disk that do not need to be
retrieved again.
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
// MARK: - NSURLSessionStreamDelegate
var _streamTaskReadClosed: Any?
var _streamTaskWriteClosed: Any?
var _streamTaskBetterRouteDiscovered: Any?
var _streamTaskDidBecomeInputStream: Any?
// MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return sessionDidBecomeInvalidWithError != nil
case "URLSession:didReceiveChallenge:completionHandler:":
return sessionDidReceiveChallenge != nil
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return sessionDidFinishEventsForBackgroundURLSession != nil
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return taskWillPerformHTTPRedirection != nil
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return dataTaskDidReceiveResponse != nil
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
| 9cdfa5d277df4659cf18597c56ebcfc0 | 48.233094 | 169 | 0.644943 | false | false | false | false |
Alecrim/AlecrimAsyncKit | refs/heads/master | Sources/Cancellation.swift | mit | 1 | //
// Cancellation.swift
// AlecrimAsyncKit
//
// Created by Vanderlei Martinelli on 10/03/18.
// Copyright © 2018 Alecrim. All rights reserved.
//
import Foundation
// MARK: -
private let _cancellationDispatchQueue = DispatchQueue(label: "com.alecrim.AlecrimAsyncKit.Cancellation", qos: .utility, attributes: .concurrent, target: DispatchQueue.global(qos: .utility))
// MARK: -
public typealias CancellationHandler = () -> Void
// MARK: -
public final class Cancellation {
private var _cancellationHandlersLock = os_unfair_lock_s()
private var _cancellationHandlers: [CancellationHandler]?
internal init() {
}
fileprivate func addCancellationHandler(_ newValue: @escaping CancellationHandler) {
os_unfair_lock_lock(&self._cancellationHandlersLock); defer { os_unfair_lock_unlock(&self._cancellationHandlersLock) }
if self._cancellationHandlers == nil {
self._cancellationHandlers = [newValue]
}
else {
self._cancellationHandlers!.append(newValue)
}
}
internal func run() {
var cancellationHandlers: [CancellationHandler]?
do {
os_unfair_lock_lock(&self._cancellationHandlersLock); defer { os_unfair_lock_unlock(&self._cancellationHandlersLock) }
cancellationHandlers = self._cancellationHandlers
self._cancellationHandlers = nil
}
//
cancellationHandlers?.forEach {
$0()
}
}
internal func run(after workItem: DispatchWorkItem) {
workItem.notify(queue: _cancellationDispatchQueue, execute: self.run)
}
}
// MARK: -
public func +=(left: Cancellation, right: @escaping CancellationHandler) {
left.addCancellationHandler(right)
}
| 72f163c95d721b3999c665be627511ab | 25.432836 | 190 | 0.66629 | false | false | false | false |
newtonstudio/cordova-plugin-device | refs/heads/master | imgly-sdk-ios-master/imglyKit/Frontend/Camera/IMGLYCameraController.swift | apache-2.0 | 1 | //
// IMGLYCameraController.swift
// imglyKit
//
// Created by Sascha Schwabbauer on 15/05/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import Foundation
import AVFoundation
import OpenGLES
import GLKit
import CoreMotion
struct IMGLYSDKVersion: Comparable, Printable {
let majorVersion: Int
let minorVersion: Int
let patchVersion: Int
var description: String {
return "\(majorVersion).\(minorVersion).\(patchVersion)"
}
}
func ==(lhs: IMGLYSDKVersion, rhs: IMGLYSDKVersion) -> Bool {
return (lhs.majorVersion == rhs.majorVersion) && (lhs.minorVersion == rhs.minorVersion) && (lhs.patchVersion == rhs.patchVersion)
}
func <(lhs: IMGLYSDKVersion, rhs: IMGLYSDKVersion) -> Bool {
if lhs.majorVersion < rhs.majorVersion {
return true
} else if lhs.majorVersion > rhs.majorVersion {
return false
}
if lhs.minorVersion < rhs.minorVersion {
return true
} else if lhs.minorVersion > rhs.minorVersion {
return false
}
if lhs.patchVersion < rhs.patchVersion {
return true
} else if lhs.patchVersion > rhs.patchVersion {
return false
}
return false
}
let CurrentSDKVersion = IMGLYSDKVersion(majorVersion: 2, minorVersion: 2, patchVersion: 1)
private let kIMGLYIndicatorSize = CGFloat(75)
private var CapturingStillImageContext = 0
private var SessionRunningAndDeviceAuthorizedContext = 0
private var FocusAndExposureContext = 0
@objc public protocol IMGLYCameraControllerDelegate: class {
optional func cameraControllerDidStartCamera(cameraController: IMGLYCameraController)
optional func cameraControllerDidStopCamera(cameraController: IMGLYCameraController)
optional func cameraControllerDidStartStillImageCapture(cameraController: IMGLYCameraController)
optional func cameraControllerDidFailAuthorization(cameraController: IMGLYCameraController)
optional func cameraController(cameraController: IMGLYCameraController, didChangeToFlashMode flashMode: AVCaptureFlashMode)
optional func cameraControllerDidCompleteSetup(cameraController: IMGLYCameraController)
optional func cameraController(cameraController: IMGLYCameraController, willSwitchToCameraPosition cameraPosition: AVCaptureDevicePosition)
optional func cameraController(cameraController: IMGLYCameraController, didSwitchToCameraPosition cameraPosition: AVCaptureDevicePosition)
}
public typealias IMGLYTakePhotoBlock = (UIImage?, NSError?) -> Void
public class IMGLYCameraController: NSObject {
// MARK: - Properties
/// The response filter that is applied to the live-feed.
public var effectFilter: IMGLYResponseFilter = IMGLYNoneFilter()
public let previewView: UIView
public weak var delegate: IMGLYCameraControllerDelegate?
public let tapGestureRecognizer = UITapGestureRecognizer()
dynamic private let session = AVCaptureSession()
private let sessionQueue = dispatch_queue_create("capture_session_queue", nil)
private let sampleBufferQueue = dispatch_queue_create("sample_buffer_queue", nil)
private var videoDeviceInput: AVCaptureDeviceInput?
private var videoDataOutput: AVCaptureVideoDataOutput?
dynamic private var stillImageOutput: AVCaptureStillImageOutput?
private var runtimeErrorHandlingObserver: NSObjectProtocol?
dynamic private var deviceAuthorized = false
private var glContext: EAGLContext?
private var ciContext: CIContext?
private var videoPreviewView: GLKView?
private var setupComplete = false
private var videoPreviewFrame = CGRectZero
private let focusIndicatorLayer = CALayer()
private var focusIndicatorFadeOutTimer: NSTimer?
private var focusIndicatorAnimating = false
private let motionManager: CMMotionManager = {
let motionManager = CMMotionManager()
motionManager.accelerometerUpdateInterval = 0.2
return motionManager
}()
private let motionManagerQueue = NSOperationQueue()
private var captureVideoOrientation: AVCaptureVideoOrientation?
dynamic private var sessionRunningAndDeviceAuthorized: Bool {
return session.running && deviceAuthorized
}
// MARK: - Initializers
init(previewView: UIView) {
self.previewView = previewView
super.init()
}
// MARK: - NSKeyValueObserving
class func keyPathsForValuesAffectingSessionRunningAndDeviceAuthorized() -> Set<String> {
return Set(["session.running", "deviceAuthorized"])
}
public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == &CapturingStillImageContext {
let capturingStillImage = change[NSKeyValueChangeNewKey]?.boolValue
if let isCapturingStillImage = capturingStillImage where isCapturingStillImage {
self.delegate?.cameraControllerDidStartStillImageCapture?(self)
}
} else if context == &SessionRunningAndDeviceAuthorizedContext {
let running = change[NSKeyValueChangeNewKey]?.boolValue
if let isRunning = running {
if isRunning {
self.delegate?.cameraControllerDidStartCamera?(self)
} else {
self.delegate?.cameraControllerDidStopCamera?(self)
}
}
} else if context == &FocusAndExposureContext {
dispatch_async(dispatch_get_main_queue()) {
self.updateFocusIndicatorLayer()
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
// MARK: - SDK
private func versionComponentsFromString(version: String) -> (majorVersion: Int, minorVersion: Int, patchVersion: Int)? {
let versionComponents = version.componentsSeparatedByString(".")
if count(versionComponents) == 3 {
if let major = versionComponents[0].toInt(), minor = versionComponents[1].toInt(), patch = versionComponents[2].toInt() {
return (major, minor, patch)
}
}
return nil
}
private func checkSDKVersion() {
let appIdentifier = NSBundle.mainBundle().infoDictionary?["CFBundleIdentifier"] as? String
if let appIdentifier = appIdentifier, url = NSURL(string: "http://photoeditorsdk.com/version.json?type=ios&app=\(appIdentifier)") {
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { data, response, error in
if let data = data {
let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [String: AnyObject]
if let json = json, version = json["version"] as? String, versionComponents = self.versionComponentsFromString(version) {
let remoteVersion = IMGLYSDKVersion(majorVersion: versionComponents.majorVersion, minorVersion: versionComponents.minorVersion, patchVersion: versionComponents.patchVersion)
if CurrentSDKVersion < remoteVersion {
println("Your version of the img.ly SDK is outdated. You are using version \(CurrentSDKVersion), the latest available version is \(remoteVersion). Please consider updating.")
}
}
}
}
task.resume()
}
}
// MARK: - Authorization
public func checkDeviceAuthorizationStatus() {
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { granted in
if granted {
self.deviceAuthorized = true
} else {
self.delegate?.cameraControllerDidFailAuthorization?(self)
self.deviceAuthorized = false
}
})
}
// MARK: - Camera
/// Use this property to determine if more than one camera is available. Within the SDK this property is used to determine if the toggle button is visible.
public var moreThanOneCameraPresent: Bool {
let videoDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
return videoDevices.count > 1
}
public func toggleCameraPosition() {
if let device = videoDeviceInput?.device {
let nextPosition: AVCaptureDevicePosition
switch (device.position) {
case .Front:
nextPosition = .Back
case .Back:
nextPosition = .Front
default:
nextPosition = .Back
}
delegate?.cameraController?(self, willSwitchToCameraPosition: nextPosition)
focusIndicatorLayer.hidden = true
let sessionGroup = dispatch_group_create()
if let videoPreviewView = videoPreviewView {
// Hiding live preview
videoPreviewView.hidden = true
// Adding a simple snapshot and immediately showing it
let snapshot = videoPreviewView.snapshotViewAfterScreenUpdates(false)
snapshot.transform = videoPreviewView.transform
snapshot.frame = videoPreviewView.frame
previewView.addSubview(snapshot)
// Creating a snapshot with a UIBlurEffect added
let snapshotWithBlur = videoPreviewView.snapshotViewAfterScreenUpdates(false)
snapshotWithBlur.transform = videoPreviewView.transform
snapshotWithBlur.frame = videoPreviewView.frame
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
visualEffectView.frame = snapshotWithBlur.bounds
visualEffectView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
snapshotWithBlur.addSubview(visualEffectView)
// Transitioning between the regular snapshot and the blurred snapshot, this automatically removes `snapshot` and adds `snapshotWithBlur` to the view hierachy
UIView.transitionFromView(snapshot, toView: snapshotWithBlur, duration: 0.4, options: .TransitionFlipFromLeft | .CurveEaseOut, completion: { _ in
// Wait for camera to toggle
dispatch_group_notify(sessionGroup, dispatch_get_main_queue()) {
// Cross fading between blur and live preview, this sets `snapshotWithBlur.hidden` to `true` and `videoPreviewView.hidden` to false
UIView.transitionFromView(snapshotWithBlur, toView: videoPreviewView, duration: 0.2, options: .TransitionCrossDissolve | .ShowHideTransitionViews, completion: { _ in
// Deleting the blurred snapshot
snapshotWithBlur.removeFromSuperview()
})
}
})
}
dispatch_async(sessionQueue) {
dispatch_group_enter(sessionGroup)
self.session.beginConfiguration()
self.session.removeInput(self.videoDeviceInput)
self.removeObserversFromInputDevice()
self.setupInputsForPreferredCameraPosition(nextPosition)
self.addObserversToInputDevice()
self.session.commitConfiguration()
dispatch_group_leave(sessionGroup)
self.delegate?.cameraController?(self, didSwitchToCameraPosition: nextPosition)
}
}
}
// MARK: - Flash
/**
Selects the next flash-mode. The order is Auto->On->Off.
If the current device does not support auto-flash, this method
just toggles between on and off.
*/
public func selectNextFlashMode() {
var nextFlashMode: AVCaptureFlashMode = .Off
switch flashMode {
case .Auto:
if let device = videoDeviceInput?.device where device.isFlashModeSupported(.On) {
nextFlashMode = .On
}
case .On:
nextFlashMode = .Off
case .Off:
if let device = videoDeviceInput?.device {
if device.isFlashModeSupported(.Auto) {
nextFlashMode = .Auto
} else if device.isFlashModeSupported(.On) {
nextFlashMode = .On
}
}
}
flashMode = nextFlashMode
}
public private(set) var flashMode: AVCaptureFlashMode {
get {
if let device = self.videoDeviceInput?.device {
return device.flashMode
} else {
return .Off
}
}
set {
dispatch_async(sessionQueue) {
var error: NSError?
self.session.beginConfiguration()
if let device = self.videoDeviceInput?.device {
device.lockForConfiguration(&error)
//device.flashMode = newValue
device.unlockForConfiguration()
}
self.session.commitConfiguration()
if let error = error {
println("Error changing flash mode: \(error.description)")
return
}
self.delegate?.cameraController?(self, didChangeToFlashMode: newValue)
}
}
}
// MARK: - Focus
private func setupFocusIndicator() {
focusIndicatorLayer.borderColor = UIColor.whiteColor().CGColor
focusIndicatorLayer.borderWidth = 1
focusIndicatorLayer.frame.size = CGSize(width: kIMGLYIndicatorSize, height: kIMGLYIndicatorSize)
focusIndicatorLayer.hidden = true
focusIndicatorLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
previewView.layer.addSublayer(focusIndicatorLayer)
tapGestureRecognizer.addTarget(self, action: "tapped:")
if let videoPreviewView = videoPreviewView {
videoPreviewView.addGestureRecognizer(tapGestureRecognizer)
}
}
private func showFocusIndicatorLayerAtLocation(location: CGPoint) {
focusIndicatorFadeOutTimer?.invalidate()
focusIndicatorFadeOutTimer = nil
focusIndicatorAnimating = false
CATransaction.begin()
focusIndicatorLayer.opacity = 1
focusIndicatorLayer.hidden = false
focusIndicatorLayer.borderColor = UIColor.whiteColor().CGColor
focusIndicatorLayer.frame.size = CGSize(width: kIMGLYIndicatorSize, height: kIMGLYIndicatorSize)
focusIndicatorLayer.position = location
focusIndicatorLayer.transform = CATransform3DIdentity
focusIndicatorLayer.removeAllAnimations()
CATransaction.commit()
let resizeAnimation = CABasicAnimation(keyPath: "transform")
resizeAnimation.fromValue = NSValue(CATransform3D: CATransform3DMakeScale(1.5, 1.5, 1))
resizeAnimation.duration = 0.25
focusIndicatorLayer.addAnimation(resizeAnimation, forKey: nil)
}
@objc private func tapped(recognizer: UITapGestureRecognizer) {
if focusPointSupported || exposurePointSupported {
if let videoPreviewView = videoPreviewView {
let focusPointLocation = recognizer.locationInView(videoPreviewView)
let scaleFactor = videoPreviewView.contentScaleFactor
let videoFrame = CGRectMake(CGRectGetMinX(videoPreviewFrame) / scaleFactor, CGRectGetMinY(videoPreviewFrame) / scaleFactor, CGRectGetWidth(videoPreviewFrame) / scaleFactor, CGRectGetHeight(videoPreviewFrame) / scaleFactor)
if CGRectContainsPoint(videoFrame, focusPointLocation) {
let focusIndicatorLocation = recognizer.locationInView(previewView)
showFocusIndicatorLayerAtLocation(focusIndicatorLocation)
var pointOfInterest = CGPoint(x: focusPointLocation.x / CGRectGetWidth(videoFrame), y: focusPointLocation.y / CGRectGetHeight(videoFrame))
pointOfInterest.x = 1 - pointOfInterest.x
if let device = videoDeviceInput?.device where device.position == .Front {
pointOfInterest.y = 1 - pointOfInterest.y
}
focusWithMode(.AutoFocus, exposeWithMode: .AutoExpose, atDevicePoint: pointOfInterest, monitorSubjectAreaChange: true)
}
}
}
}
private var focusPointSupported: Bool {
if let device = videoDeviceInput?.device {
return device.focusPointOfInterestSupported && device.isFocusModeSupported(.AutoFocus) && device.isFocusModeSupported(.ContinuousAutoFocus)
}
return false
}
private var exposurePointSupported: Bool {
if let device = videoDeviceInput?.device {
return device.exposurePointOfInterestSupported && device.isExposureModeSupported(.AutoExpose) && device.isExposureModeSupported(.ContinuousAutoExposure)
}
return false
}
private func focusWithMode(focusMode: AVCaptureFocusMode, exposeWithMode exposureMode: AVCaptureExposureMode, atDevicePoint point: CGPoint, monitorSubjectAreaChange: Bool) {
dispatch_async(sessionQueue) {
if let device = self.videoDeviceInput?.device {
var error: NSError?
if device.lockForConfiguration(&error) {
if self.focusPointSupported {
device.focusMode = focusMode
device.focusPointOfInterest = point
}
if self.exposurePointSupported {
device.exposureMode = exposureMode
device.exposurePointOfInterest = point
}
device.subjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange
device.unlockForConfiguration()
} else {
println("Error in focusWithMode:exposeWithMode:atDevicePoint:monitorSubjectAreaChange: \(error?.description)")
}
}
}
}
private func updateFocusIndicatorLayer() {
if let device = videoDeviceInput?.device {
if focusIndicatorLayer.hidden == false {
if device.focusMode == .Locked && device.exposureMode == .Locked {
focusIndicatorLayer.borderColor = UIColor(white: 1, alpha: 0.5).CGColor
}
}
}
}
@objc private func subjectAreaDidChange(notification: NSNotification) {
dispatch_async(dispatch_get_main_queue()) {
self.disableFocusLockAnimated(true)
}
}
public func disableFocusLockAnimated(animated: Bool) {
if focusIndicatorAnimating {
return
}
focusIndicatorAnimating = true
focusIndicatorFadeOutTimer?.invalidate()
if focusPointSupported || exposurePointSupported {
focusWithMode(.ContinuousAutoFocus, exposeWithMode: .ContinuousAutoExposure, atDevicePoint: CGPoint(x: 0.5, y: 0.5), monitorSubjectAreaChange: false)
if animated {
CATransaction.begin()
CATransaction.setDisableActions(true)
focusIndicatorLayer.borderColor = UIColor.whiteColor().CGColor
focusIndicatorLayer.frame.size = CGSize(width: kIMGLYIndicatorSize * 2, height: kIMGLYIndicatorSize * 2)
focusIndicatorLayer.transform = CATransform3DIdentity
focusIndicatorLayer.position = previewView.center
CATransaction.commit()
let resizeAnimation = CABasicAnimation(keyPath: "transform")
resizeAnimation.duration = 0.25
resizeAnimation.fromValue = NSValue(CATransform3D: CATransform3DMakeScale(1.5, 1.5, 1))
resizeAnimation.delegate = IMGLYAnimationDelegate(block: { finished in
if finished {
self.focusIndicatorFadeOutTimer = NSTimer.after(0.85) { [unowned self] in
self.focusIndicatorLayer.opacity = 0
let fadeAnimation = CABasicAnimation(keyPath: "opacity")
fadeAnimation.duration = 0.25
fadeAnimation.fromValue = 1
fadeAnimation.delegate = IMGLYAnimationDelegate(block: { finished in
if finished {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.focusIndicatorLayer.hidden = true
self.focusIndicatorLayer.opacity = 1
self.focusIndicatorLayer.frame.size = CGSize(width: kIMGLYIndicatorSize, height: kIMGLYIndicatorSize)
CATransaction.commit()
self.focusIndicatorAnimating = false
}
})
self.focusIndicatorLayer.addAnimation(fadeAnimation, forKey: nil)
}
}
})
focusIndicatorLayer.addAnimation(resizeAnimation, forKey: nil)
} else {
focusIndicatorLayer.hidden = true
focusIndicatorAnimating = false
}
} else {
focusIndicatorLayer.hidden = true
focusIndicatorAnimating = false
}
}
// MARK: - Capture Session
/**
Initializes the camera and has to be called before calling `startCamera()` / `stopCamera()`
*/
public func setup() {
if setupComplete {
return
}
checkSDKVersion()
checkDeviceAuthorizationStatus()
glContext = EAGLContext(API: .OpenGLES2)
videoPreviewView = GLKView(frame: CGRectZero, context: glContext)
videoPreviewView!.autoresizingMask = .FlexibleWidth | .FlexibleHeight
videoPreviewView!.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
videoPreviewView!.frame = previewView.bounds
previewView.addSubview(videoPreviewView!)
previewView.sendSubviewToBack(videoPreviewView!)
ciContext = CIContext(EAGLContext: glContext)
videoPreviewView!.bindDrawable()
setupWithPreferredCameraPosition(.Back) {
if let device = self.videoDeviceInput?.device {
if device.isFlashModeSupported(.Auto) {
self.flashMode = .Auto
}
}
self.delegate?.cameraControllerDidCompleteSetup?(self)
}
setupFocusIndicator()
setupComplete = true
}
private func setupWithPreferredCameraPosition(cameraPosition: AVCaptureDevicePosition, completion: (() -> (Void))?) {
dispatch_async(sessionQueue) {
if self.session.canSetSessionPreset(AVCaptureSessionPresetPhoto) {
self.session.sessionPreset = AVCaptureSessionPresetPhoto
}
self.setupInputsForPreferredCameraPosition(cameraPosition)
self.setupOutputs()
completion?()
}
}
private func setupInputsForPreferredCameraPosition(cameraPosition: AVCaptureDevicePosition) {
var error: NSError?
let videoDevice = IMGLYCameraController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: cameraPosition)
let videoDeviceInput = AVCaptureDeviceInput(device: videoDevice, error: &error)
if let error = error {
println("Error in setupInputsForPreferredCameraPosition: \(error.description)")
}
if self.session.canAddInput(videoDeviceInput) {
self.session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
dispatch_async(dispatch_get_main_queue()) {
if let videoPreviewView = self.videoPreviewView, device = videoDevice {
if device.position == .Front {
// front camera is mirrored so we need to transform the preview view
videoPreviewView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
videoPreviewView.transform = CGAffineTransformScale(videoPreviewView.transform, 1, -1)
} else {
videoPreviewView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
}
}
}
}
}
private func setupOutputs() {
let videoDataOutput = AVCaptureVideoDataOutput()
videoDataOutput.setSampleBufferDelegate(self, queue: self.sampleBufferQueue)
if self.session.canAddOutput(videoDataOutput) {
self.session.addOutput(videoDataOutput)
self.videoDataOutput = videoDataOutput
}
let stillImageOutput = AVCaptureStillImageOutput()
if self.session.canAddOutput(stillImageOutput) {
self.session.addOutput(stillImageOutput)
self.stillImageOutput = stillImageOutput
}
}
/**
Starts the camera preview.
*/
public func startCamera() {
assert(setupComplete, "setup() needs to be called before calling startCamera()")
if session.running {
return
}
startCameraWithCompletion(nil)
// Used to determine device orientation even if orientation lock is active
motionManager.startAccelerometerUpdatesToQueue(motionManagerQueue, withHandler: { accelerometerData, _ in
if abs(accelerometerData.acceleration.y) < abs(accelerometerData.acceleration.x) {
if accelerometerData.acceleration.x > 0 {
self.captureVideoOrientation = .LandscapeLeft
} else {
self.captureVideoOrientation = .LandscapeRight
}
} else {
if accelerometerData.acceleration.y > 0 {
self.captureVideoOrientation = .PortraitUpsideDown
} else {
self.captureVideoOrientation = .Portrait
}
}
})
}
private func startCameraWithCompletion(completion: (() -> (Void))?) {
dispatch_async(sessionQueue) {
self.addObserver(self, forKeyPath: "sessionRunningAndDeviceAuthorized", options: .Old | .New, context: &SessionRunningAndDeviceAuthorizedContext)
self.addObserver(self, forKeyPath: "stillImageOutput.capturingStillImage", options: .Old | .New, context: &CapturingStillImageContext)
self.addObserversToInputDevice()
self.runtimeErrorHandlingObserver = NSNotificationCenter.defaultCenter().addObserverForName(AVCaptureSessionRuntimeErrorNotification, object: self.session, queue: nil, usingBlock: { [unowned self] _ in
dispatch_async(self.sessionQueue) {
self.session.startRunning()
}
})
self.session.startRunning()
completion?()
}
}
private func addObserversToInputDevice() {
if let device = self.videoDeviceInput?.device {
device.addObserver(self, forKeyPath: "focusMode", options: .Old | .New, context: &FocusAndExposureContext)
device.addObserver(self, forKeyPath: "exposureMode", options: .Old | .New, context: &FocusAndExposureContext)
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "subjectAreaDidChange:", name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: self.videoDeviceInput?.device)
}
private func removeObserversFromInputDevice() {
if let device = self.videoDeviceInput?.device {
device.removeObserver(self, forKeyPath: "focusMode", context: &FocusAndExposureContext)
device.removeObserver(self, forKeyPath: "exposureMode", context: &FocusAndExposureContext)
}
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: self.videoDeviceInput?.device)
}
/**
Stops the camera preview.
*/
public func stopCamera() {
assert(setupComplete, "setup() needs to be called before calling stopCamera()")
if !session.running {
return
}
stopCameraWithCompletion(nil)
motionManager.stopAccelerometerUpdates()
}
private func stopCameraWithCompletion(completion: (() -> (Void))?) {
dispatch_async(sessionQueue) {
self.session.stopRunning()
self.removeObserversFromInputDevice()
if let runtimeErrorHandlingObserver = self.runtimeErrorHandlingObserver {
NSNotificationCenter.defaultCenter().removeObserver(runtimeErrorHandlingObserver)
}
self.removeObserver(self, forKeyPath: "sessionRunningAndDeviceAuthorized", context: &SessionRunningAndDeviceAuthorizedContext)
self.removeObserver(self, forKeyPath: "stillImageOutput.capturingStillImage", context: &CapturingStillImageContext)
completion?()
}
}
/// Check if the current device has a flash.
public var flashAvailable: Bool {
if let device = self.videoDeviceInput?.device {
return device.flashAvailable
}
return false
}
// MARK: - Still Image Capture
/**
Takes a photo and hands it over to the completion block.
:param: completion A completion block that has an image and an error as parameters.
If the image was taken sucessfully the error is nil.
*/
public func takePhoto(completion: IMGLYTakePhotoBlock) {
if let stillImageOutput = self.stillImageOutput {
dispatch_async(sessionQueue) {
let connection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
// Update the orientation on the still image output video connection before capturing.
if let captureVideoOrientation = self.captureVideoOrientation {
connection.videoOrientation = captureVideoOrientation
}
stillImageOutput.captureStillImageAsynchronouslyFromConnection(connection) {
(imageDataSampleBuffer: CMSampleBuffer?, error: NSError?) -> Void in
if let imageDataSampleBuffer = imageDataSampleBuffer {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
let image = UIImage(data: imageData)
completion(image, nil)
} else {
completion(nil, error)
}
}
}
}
}
// MARK: - Helpers
class func deviceWithMediaType(mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice? {
let devices = AVCaptureDevice.devicesWithMediaType(mediaType) as! [AVCaptureDevice]
var captureDevice = devices.first
for device in devices {
if device.position == position {
captureDevice = device
break
}
}
return captureDevice
}
}
extension IMGLYCameraController: AVCaptureVideoDataOutputSampleBufferDelegate {
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer)
let mediaType = CMFormatDescriptionGetMediaType(formatDescription)
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
let sourceImage = CIImage(CVPixelBuffer: imageBuffer as CVPixelBufferRef, options: nil)
let filteredImage: CIImage?
if effectFilter is IMGLYNoneFilter {
filteredImage = sourceImage
} else {
filteredImage = IMGLYPhotoProcessor.processWithCIImage(sourceImage, filters: [effectFilter])
}
let sourceExtent = sourceImage.extent()
if let videoPreviewView = videoPreviewView {
let targetRect = CGRect(x: 0, y: 0, width: videoPreviewView.drawableWidth, height: videoPreviewView.drawableHeight)
videoPreviewFrame = sourceExtent
videoPreviewFrame.fittedIntoTargetRect(targetRect, withContentMode: .ScaleAspectFit)
if glContext != EAGLContext.currentContext() {
EAGLContext.setCurrentContext(glContext)
}
videoPreviewView.bindDrawable()
glClearColor(0, 0, 0, 1.0)
glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
if let filteredImage = filteredImage {
ciContext?.drawImage(filteredImage, inRect: videoPreviewFrame, fromRect: sourceExtent)
}
videoPreviewView.display()
}
}
}
extension CGRect {
mutating func fittedIntoTargetRect(targetRect: CGRect, withContentMode contentMode: UIViewContentMode) {
if !(contentMode == .ScaleAspectFit || contentMode == .ScaleAspectFill) {
// Not implemented
return
}
var scale = targetRect.width / self.width
if contentMode == .ScaleAspectFit {
if self.height * scale > targetRect.height {
scale = targetRect.height / self.height
}
} else if contentMode == .ScaleAspectFill {
if self.height * scale < targetRect.height {
scale = targetRect.height / self.height
}
}
let scaledWidth = self.width * scale
let scaledHeight = self.height * scale
let scaledX = targetRect.width / 2 - scaledWidth / 2
let scaledY = targetRect.height / 2 - scaledHeight / 2
self.origin.x = scaledX
self.origin.y = scaledY
self.size.width = scaledWidth
self.size.height = scaledHeight
}
}
| a45f10dc03a290fb6da0364b2dc5c45c | 41.450418 | 238 | 0.615012 | false | false | false | false |
RoRoche/iOSSwiftStarter | refs/heads/master | iOS/Pods/CoreStore/CoreStore/NSError+CoreStore.swift | apache-2.0 | 2 | //
// NSError+CoreStore.swift
// CoreStore
//
// Copyright © 2014 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - CoreStoreError
/**
The `NSError` error domain for `CoreStore`.
*/
public let CoreStoreErrorDomain = "com.corestore.error"
/**
The `NSError` error codes for `CoreStoreErrorDomain`.
*/
public enum CoreStoreErrorCode: Int {
/**
A failure occured because of an unknown error.
*/
case UnknownError
/**
The `NSPersistentStore` could note be initialized because another store existed at the specified `NSURL`.
*/
case DifferentPersistentStoreExistsAtURL
/**
The `NSPersistentStore` specified could not be found.
*/
case PersistentStoreNotFound
/**
An `NSMappingModel` could not be found for a specific source and destination model versions.
*/
case MappingModelNotFound
}
// MARK: - NSError
public extension NSError {
/**
If the error's domain is equal to `CoreStoreErrorDomain`, returns the associated `CoreStoreErrorCode`. For other domains, returns `nil`.
*/
public var coreStoreErrorCode: CoreStoreErrorCode? {
return (self.domain == CoreStoreErrorDomain
? CoreStoreErrorCode(rawValue: self.code)
: nil)
}
// MARK: Internal
internal convenience init(coreStoreErrorCode: CoreStoreErrorCode) {
self.init(coreStoreErrorCode: coreStoreErrorCode, userInfo: nil)
}
internal convenience init(coreStoreErrorCode: CoreStoreErrorCode, userInfo: [NSObject: AnyObject]?) {
self.init(
domain: CoreStoreErrorDomain,
code: coreStoreErrorCode.rawValue,
userInfo: userInfo)
}
internal var isCoreDataMigrationError: Bool {
let code = self.code
return (code == NSPersistentStoreIncompatibleVersionHashError
|| code == NSMigrationMissingSourceModelError
|| code == NSMigrationError)
&& self.domain == NSCocoaErrorDomain
}
}
| 1136059ce1315230d00e66579b224047 | 30.22549 | 141 | 0.685714 | false | false | false | false |
jmgc/swift | refs/heads/master | benchmark/single-source/Differentiation.swift | apache-2.0 | 1 | //===--- Differentiation.swift -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
#if canImport(_Differentiation)
import TestsUtils
import _Differentiation
public let Differentiation = [
BenchmarkInfo(
name: "DifferentiationIdentity",
runFunction: run_DifferentiationIdentity,
tags: [.regression, .differentiation]
),
BenchmarkInfo(
name: "DifferentiationSquare",
runFunction: run_DifferentiationSquare,
tags: [.regression, .differentiation]
),
BenchmarkInfo(
name: "DifferentiationArraySum",
runFunction: run_DifferentiationArraySum,
tags: [.regression, .differentiation],
setUpFunction: { blackHole(onesArray) }
),
]
@inline(never)
public func run_DifferentiationIdentity(N: Int) {
func f(_ x: Float) -> Float {
x
}
for _ in 0..<1000*N {
blackHole(valueWithGradient(at: 1, in: f))
}
}
@inline(never)
public func run_DifferentiationSquare(N: Int) {
func f(_ x: Float) -> Float {
x * x
}
for _ in 0..<1000*N {
blackHole(valueWithGradient(at: 1, in: f))
}
}
let onesArray: [Float] = Array(repeating: 1, count: 50)
@inline(never)
public func run_DifferentiationArraySum(N: Int) {
func sum(_ array: [Float]) -> Float {
var result: Float = 0
for i in withoutDerivative(at: 0..<array.count) {
result += array[i]
}
return result
}
for _ in 0..<N {
blackHole(valueWithGradient(at: onesArray, in: sum))
}
}
#endif
| f487efb635ea69d9084bbce8777dc0d8 | 24.589041 | 80 | 0.631692 | false | false | false | false |
PureSwift/Kronos | refs/heads/master | Sources/Kronos/Capability.swift | mit | 2 | //
// Capability.swift
// Kronos
//
// Created by Alsey Coleman Miller on 1/21/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if os(iOS) || os(tvOS)
import OpenGLES
#endif
/// OpenGL server-side Capabilities. Can be enabled or disabled.
///
/// - Note: All cases, with the exception of `Dither`, are false by default.
public enum Capability: GLenum {
case Texture2D = 0x0DE1
/// If enabled, cull polygons based on their winding in window coordinates.
case CullFace = 0x0B44
/// If enabled, blend the computed fragment color values with the values in the color buffers.
case Blend = 0x0BE2
/// If enabled, dither color components or indices before they are written to the color buffer.
case Dither = 0x0BD0
/// If enabled, do stencil testing and update the stencil buffer.
case StencilTest = 0x0B90
/// If enabled, do depth comparisons and update the depth buffer.
///
/// - Note: Even if the depth buffer exists and the depth mask is non-zero,
/// the depth buffer is not updated if the depth test is disabled.
case DepthTest = 0x0B71
/// If enabled, discard fragments that are outside the scissor rectangle.
case ScissorTest = 0x0C11
/// If enabled, an offset is added to depth values of a polygon's fragments produced by rasterization.
case PloygonOffsetFill = 0x8037
/// If enabled, compute a temporary coverage value where each bit is determined by the alpha value at
/// the corresponding sample location. The temporary coverage value is then ANDed with the fragment coverage value.
case SampleAlphaToCoverage = 0x809E
/// If enabled, the fragment's coverage is ANDed with the temporary coverage value.
/// If `GL_SAMPLE_COVERAGE_INVERT` is set to `GL_TRUE`, invert the coverage value.
case SampleCoverage = 0x80A0
public var enabled: Bool {
return glIsEnabled(rawValue).boolValue
}
@inline(__always)
public func enable() {
glEnable(rawValue)
}
@inline(__always)
public func disable() {
glDisable(rawValue)
}
}
| 065bc2f81405b654cdf25193a7208059 | 32.289855 | 119 | 0.634741 | false | true | false | false |
ProjectGinsberg/SDK | refs/heads/master | ExampleApp/iOS/Example1/Src/VCPost.swift | mit | 1 | //
// ViewController.swift
// Example1
//
// Created by CD on 22/07/2014.
// Copyright (c) 2014 Ginsberg. All rights reserved.
//
import UIKit
//
// Main handler of demonstrating getting and posting of users Ginsberg data
//
class VCPost: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate, GAPIProtocol
{
//
// MARK: Outlets
//
@IBOutlet weak var aiBusy: UIView!
@IBOutlet weak var vMain: UIView!
@IBOutlet weak var lbText: UILabel!
@IBOutlet weak var pkType: UIPickerView!
@IBOutlet weak var pkGetPeriod: UIPickerView!
@IBOutlet weak var pkGetFrom: UIPickerView!
@IBOutlet weak var pkGetTo: UIPickerView!
@IBOutlet weak var lbGetID: UITextField!
@IBOutlet weak var lbGetFrom: UITextField!
@IBOutlet weak var lbGetTo: UITextField!
@IBOutlet weak var lbDeleteID: UITextField!
@IBOutlet weak var svSendData: UIScrollView!
@IBOutlet weak var svOutput: UIScrollView!
@IBOutlet weak var btGet: UIButton!
@IBOutlet weak var btPost: UIButton!
@IBOutlet weak var btDelete: UIButton!
@IBOutlet weak var vFromTo: UIView!
@IBOutlet weak var vPost: UIView!
//
// MARK: Onscreen items
//
let Types = [/*"Aggregate",*/ "Correlations", "Daily Summary", "Notifications", "Profile", "Tag", "Activity" , "Alcohol", "Body" , "Caffeine", "Exercise", "Events", "Measures", "Nutrition", "Sleep", "Smoking", "Social", "Stepcount", "Survey", "Wellbeing", "Mood", "Happy", "Uneasy", "Well", "Sad"];
let Range = ["All", "ID", "FromBelow", "ToBelow", "FromToBelow"];
let Time = ["Yesterday", "Lastweek", "Lastyear", "Date"];
var dataRequested:Bool = false;
//
// MARK: View Controller
//
override func viewDidLoad()
{
super.viewDidLoad();
//Set callbacks to this instance
GAPI.Instance().SetCallbacks(self);
//Hide busy indicator
SetBusy(false);
//Set onscreen dates to now
pressedSetTimeNow(nil);
//Set text colour for when buttons are disabled
btPost.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled);
btDelete.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled);
//Set initial picker selection
self.pickerView(pkType, didSelectRow: 0, inComponent: 0);
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated);
//Make pickers a bit smaller
pkType.transform = CGAffineTransformMakeScale(0.6, 0.4);
pkGetPeriod.transform = CGAffineTransformMakeScale(0.6, 0.4);
pkGetFrom.transform = CGAffineTransformMakeScale(0.6, 0.4);
pkGetTo.transform = CGAffineTransformMakeScale(0.6, 0.4);
//Configure send data entries
svSendData.contentSize = CGSizeMake(svSendData.contentSize.width, 620.0);
svOutput.contentSize = CGSizeMake(svOutput.contentSize.width, 2000.0);
//Space out send data
for subView in svSendData.subviews
{
var obj:UIView = subView as UIView;
var i = obj.tag;
if(i != 0)
{
obj.frame = CGRectMake(obj.frame.origin.x, CGFloat(30*((i-1)/2)), obj.frame.size.width, obj.frame.size.height);
}
}
}
//
// MARK: TextField
//
func textFieldShouldReturn(textField: UITextField) -> Bool
{
//Hide keyboard on return press
textField.resignFirstResponder();
return false;
}
//
// MARK: Pickerview
//
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
return 1;
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
if(pickerView == pkType)
{
return Types.count;
}
else
if(pickerView == pkGetPeriod)
{
return Range.count;
}
else
if(pickerView == pkGetFrom)
{
return Time.count;
}
else
if(pickerView == pkGetTo)
{
return Time.count;
}
return 0;
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String!
{
if(pickerView == pkType)
{
return Types[row];
}
else
if(pickerView == pkGetPeriod)
{
return Range[row];
}
else
if(pickerView == pkGetFrom)
{
return Time[row];
}
else
if(pickerView == pkGetTo)
{
return Time[row];
}
return "";
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
//Format view per selection
var selection:String = Types[pkType.selectedRowInComponent(0)];
switch(selection)
{
//case "Aggregate":Int(ID)); break;
case "Correlations": EnableViews(false, postData:false, deleteData:false, valueType:nil); break;
case "Daily Summary":EnableViews(true, postData:false, deleteData:false, valueType:nil); break;
case "Tag": EnableViews(true, postData:false, deleteData:false, valueType:nil); break;
case "Profile": EnableViews(false, postData:false, deleteData:false, valueType:nil); break;
case "Activity": EnableViews(true, postData:true, deleteData:true, valueType:nil, variables:"timeStart","timeEnd","distance","calories","steps","timeStamp"); break;
case "Alcohol": EnableViews(true, postData:true, deleteData:true, valueType:"Units", variables:"timeStamp"); break;
case "Body": EnableViews(true, postData:true, deleteData:true, valueType:nil,
variables:"weight", "fat", "timeStamp"); break;
case "Caffeine": EnableViews(true, postData:true, deleteData:true, valueType:"Caffeine", variables:"timeStamp"); break;
case "Events": EnableViews(true, postData:true, deleteData:true, valueType:nil, variables:"timeStamp"); break;
case "Exercise": EnableViews(true, postData:true, deleteData:true, valueType:"Distance", variables:"timeStamp"); break;
case "Measures": EnableViews(false, postData:false, deleteData:false, valueType:nil); break;
case "Notifications": EnableViews(true, postData:false, deleteData:false, valueType:nil); break;
case "Nutrition": EnableViews(true, postData:true, deleteData:true, valueType:nil, variables:"calories","carbohydrates","fat","fiber","protein","sugar","timeStamp"); break;
case "Sleep": EnableViews(true, postData:true, deleteData:true, valueType:nil,
variables:"timesAwoken","awake","lightSleep","remSleep","deepSleep","totalSleep","sleepQuality","timeStamp"); break;
case "Smoking": EnableViews(true, postData:true, deleteData:true, valueType:"Quantity", variables:"timeStamp"); break;
case "Social": EnableViews(true, postData:true, deleteData:true, valueType:nil, variables:"timeStamp"); break;
case "Stepcount": EnableViews(true, postData:true, deleteData:true, valueType:nil,
variables:"timeStart","timeEnd","distance","calories","steps","timeStamp"); break;
case "Survey": EnableViews(false, postData:false, deleteData:false, valueType:nil); break;
case "Wellbeing": EnableViews(true, postData:true, deleteData:true, valueType:nil); break;
case "Mood": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
case "Happy": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
case "Uneasy": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
case "Well": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
case "Sad": EnableViews(true, postData:true, deleteData:true, valueType:"Value"); break;
default: break;
}
}
// Customise view
func EnableViews(getPeriod:Bool, postData:Bool, deleteData:Bool, valueType:String?, variables:String...)
{
//Show/hide used/unused views
UIView.animateWithDuration(0.5)
{
self.vFromTo.userInteractionEnabled = !getPeriod;
self.vPost.userInteractionEnabled = !postData;
if(getPeriod)
{
self.vFromTo.alpha = 0.0;
}
else
{
self.vFromTo.alpha = 1.0;
}
if(postData)
{
self.vPost.alpha = 0.0;
}
else
{
self.vPost.alpha = 1.0;
}
}
//Enable buttons
btPost.enabled = postData;
btDelete.enabled = deleteData;
lbDeleteID.enabled = deleteData;
if(deleteData)
{
lbDeleteID.textColor = UIColor.blackColor();
}
else
{
lbDeleteID.textColor = UIColor.grayColor();
}
//Hide all posting items
for subView in svSendData.subviews
{
var obj:UIView = subView as UIView;
obj.hidden = true;
}
svSendData.setContentOffset(CGPoint(x:0.0,y:0.0),animated:true);
var i = 0;
//If using the value entry posting box then enable it and put at top of posting panel
if(valueType != nil)
{
RepositionView(7, index:i++);
(svSendData.viewWithTag(7) as UILabel).text = valueType;
}
//Enable data entry items listed in the passed variables list
for variable in variables
{
switch(variable)
{
case "timeStamp": RepositionView(1, index:i); break;
case "weight": RepositionView(13, index:i); break;
case "fat": RepositionView(15, index:i); break;
case "timeStart": RepositionView(3, index:i); break;
case "timeEnd": RepositionView(5, index:i); break;
case "distance": RepositionView(9, index:i); break;
case "calories": RepositionView(11, index:i); break;
case "steps": RepositionView(37, index:i); break;
case "carbohydrates": RepositionView(17, index:i); break;
case "fiber": RepositionView(19, index:i); break;
case "protein": RepositionView(21, index:i); break;
case "sugar": RepositionView(23, index:i); break;
case "timesAwoken": RepositionView(35, index:i); break;
case "awake": RepositionView(33, index:i); break;
case "lightSleep": RepositionView(31, index:i); break;
case "remSleep": RepositionView(29, index:i); break;
case "deepSleep": RepositionView(27, index:i); break;
case "totalSleep": RepositionView(25, index:i); break;
case "sleepQuality": RepositionView(125, index:i); break;
default: break;
}
++i;
}
}
//Reposition and enable passed item
func RepositionView(tag:Int, index:Int)
{
var viewTitle:UIView! = svSendData.viewWithTag(tag);
var viewValue:UIView! = svSendData.viewWithTag(tag+1);
viewTitle.hidden = false;
viewValue.hidden = false;
viewTitle.frame = CGRectMake(viewTitle.frame.origin.x, CGFloat(10+35*index), viewTitle.frame.size.width, viewTitle.frame.size.height);
viewValue.frame = CGRectMake(viewValue.frame.origin.x, CGFloat(10+35*index), viewValue.frame.size.width, viewValue.frame.size.height);
}
//
// MARK: Actions
//
@IBAction func pressedPostData(sender: UIButton)
{
SetBusy(true);
// Get all potential data from view
var ev:String = "1";
var selection:String=Types[pkType.selectedRowInComponent(0)];
var timeStamp:String = (svSendData.viewWithTag(2) as UITextField).text; //"2014-07-23T14:38:58";
var ed:Double = ((svSendData.viewWithTag(8) as UITextField).text as NSString).doubleValue;
var ei:Int = Int(ed);
var timeStart:String = (svSendData.viewWithTag(4) as UITextField).text;
var timeEnd:String = (svSendData.viewWithTag(6) as UITextField).text;
var distance:Double = ((svSendData.viewWithTag(10) as UITextField).text as NSString).doubleValue;
var calories:Double = ((svSendData.viewWithTag(12) as UITextField).text as NSString).doubleValue;
var weight:Double = ((svSendData.viewWithTag(14) as UITextField).text as NSString).doubleValue;
var fat:Double = ((svSendData.viewWithTag(16) as UITextField).text as NSString).doubleValue;
var carbohydrates:Double = ((svSendData.viewWithTag(18) as UITextField).text as NSString).doubleValue;
var fiber:Double = ((svSendData.viewWithTag(20) as UITextField).text as NSString).doubleValue;
var protein:Double = ((svSendData.viewWithTag(22) as UITextField).text as NSString).doubleValue;
var sugar:Double = ((svSendData.viewWithTag(24) as UITextField).text as NSString).doubleValue;
var totalSleep:Double = ((svSendData.viewWithTag(26) as UITextField).text as NSString).doubleValue;
var deepSleep:Double = ((svSendData.viewWithTag(28) as UITextField).text as NSString).doubleValue;
var remSleep:Double = ((svSendData.viewWithTag(30) as UITextField).text as NSString).doubleValue;
var lightSleep:Double = ((svSendData.viewWithTag(32) as UITextField).text as NSString).doubleValue;
var awake:Double = ((svSendData.viewWithTag(34) as UITextField).text as NSString).doubleValue;
var timesAwoken:Int = ((svSendData.viewWithTag(36) as UITextField).text as NSString).integerValue;
var stepCount:Int = ((svSendData.viewWithTag(38) as UITextField).text as NSString).integerValue;
var wellbeingType:Int = ((svSendData.viewWithTag(40) as UITextField).text as NSString).integerValue;
var wellbeingQues:String = "I've been interested in new things";
//Post data with the respective SDK call
switch(selection)
{
case "Body": GAPI.Instance().PostBody(timeStamp, weight:weight, fat:fat); break;
case "Caffeine": GAPI.Instance().PostCaffeine(timeStamp, amount:ed); break;
case "Smoking": GAPI.Instance().PostSmoking(timeStamp, amount:Int32(ei)); break;
case "Stepcount": GAPI.Instance().PostStepcount(timeStamp, timeStart:timeStart, timeEnd:timeEnd, distance:distance, calories:calories, steps:Int32(stepCount)); break;
case "Social": GAPI.Instance().PostSocial(timeStamp); break;
case "Nutrition": GAPI.Instance().PostNutrition(timeStamp, calories:calories, carbohydrates:carbohydrates, fat:fat, fiber:fiber, protein:protein, sugar:sugar); break;
case "Activity": GAPI.Instance().PostActivity(timeStamp, start:timeStart, end:timeEnd, dist:distance, cal:calories, steps:Int32(stepCount)); break;
case "Alcohol": GAPI.Instance().PostAlcohol(timeStamp, units:ed); break;
case "Events": GAPI.Instance().PostEvent(timeStamp, event:"Todays event string", ID:GAPI.Instance().todaysEventID); break;
case "Sleep": GAPI.Instance().PostSleep(timeStamp, timesAwoken:Int32(timesAwoken), awake:Double(awake), lightSleep:Double(lightSleep), remSleep:Double(remSleep), deepSleep:Double(deepSleep), totalSleep:Double(totalSleep), quality:Int32(10)); break;
//case "Survey": GAPI.Instance().PostSurvey(1234); break;
//To finish
case "Exercise": GAPI.Instance().PostExercise(timeStamp, activity:"Jogging", distance:ed); break;
case "Wellbeing": GAPI.Instance().PostWellbeing(timeStamp, value:Int32(5), wbques:"I've been interested in new things", wbtype:Int32(10)); break;
case "Profile": GAPI.Instance().PostProfile("Chris", lastName:"Brown", phoneNumber:"12345", country:Int32(0+1)); break;
case "Mood": GAPI.Instance().PostMood(timeStamp, value:Int32(ei)); break;
case "Happy": GAPI.Instance().PostHappy(timeStamp, value:Int32(ei)); break;
case "Uneasy": GAPI.Instance().PostUneasy(timeStamp, value:Int32(ei)); break;
case "Well": GAPI.Instance().PostWell(timeStamp, value:Int32(ei)); break;
case "Sad": GAPI.Instance().PostSad(timeStamp, value:Int32(ei)); break;
//Done other than input values
//case "Notifications": GAPI.Instance().PostNotifications(timeStamp, value:Int32(ei));
default: break;
}
}
@IBAction func pressedGetData(sender: UIButton)
{
SetBusy(true);
dataRequested = true;
var selection:String = Types[pkType.selectedRowInComponent(0)];
var range:String = Range[pkGetPeriod.selectedRowInComponent(0)];
var typeFrom:String = Time[pkGetFrom.selectedRowInComponent(0)];
var typeTo:String = Time[pkGetTo.selectedRowInComponent(0)];
var dateFrom:String = lbGetFrom.text;
var dateTo:String = lbGetTo.text;
var ID:Int! = lbGetID.text.toInt();
//Get data with the respective SDK call
switch(selection)
{
//case "Aggregate": GAPI.Instance().GetAggregate(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Correlations": GAPI.Instance().GetCorrelations(); break;
case "Daily Summary": GAPI.Instance().GetDailySummary(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo); break;
case "Profile": GAPI.Instance().GetProfile(); break;
case "Tag": GAPI.Instance().GetTag(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo); break;
case "Activity": GAPI.Instance().GetActivity(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Alcohol": GAPI.Instance().GetAlcohol(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Body": GAPI.Instance().GetBody(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Caffeine": GAPI.Instance().GetCaffeine(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Events": GAPI.Instance().GetEvent(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Exercise": GAPI.Instance().GetExercise(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
//case "Measures": GAPI.Instance().GetMeasures(Int(ID)); break;
case "Notifications": GAPI.Instance().GetNotifications(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Nutrition": GAPI.Instance().GetNutrition(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Sleep": GAPI.Instance().GetSleep(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Smoking": GAPI.Instance().GetSmoking(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Social": GAPI.Instance().GetSocial(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Stepcount": GAPI.Instance().GetStepcount(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
//case "Survey": GAPI.Instance().GetSurvey(); break;
case "Wellbeing": GAPI.Instance().GetWellbeing(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Mood": GAPI.Instance().GetMood(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Happy": GAPI.Instance().GetHappy(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Uneasy": GAPI.Instance().GetUneasy(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Well": GAPI.Instance().GetWell(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
case "Sad": GAPI.Instance().GetSad(range,typeFrom:typeFrom,dateFrom:dateFrom,typeTo:typeTo,dateTo:dateTo,ID:Int(ID)); break;
default: break;
}
}
@IBAction func pressedDelete(sender: UIButton)
{
SetBusy(true);
var selection:String = Types[pkType.selectedRowInComponent(0)];
var ev:String = lbDeleteID.text;
var ei:Int! = ev.toInt();
//Delete data record with the respective SDK call
switch(selection)
{
case "Activity": GAPI.Instance().DeleteActivity(Int32(ei)); break;
case "Alcohol": GAPI.Instance().DeleteAlcohol(Int32(ei)); break;
case "Body": GAPI.Instance().DeleteBody(Int32(ei)); break;
case "Caffeine": GAPI.Instance().DeleteCaffeine(Int32(ei)); break;
case "Events": GAPI.Instance().DeleteEvent(Int32(ei)); break;
case "Exercise": GAPI.Instance().DeleteExercise(Int32(ei)); break;
//case "Measures": GAPI.Instance().DeleteMeasures(Int32(ei)); break;
//case "Notifications": GAPI.Instance().DeleteNotifications(Int32(ei)); break;
case "Nutrition": GAPI.Instance().DeleteNutrition(Int32(ei)); break;
case "Sleep": GAPI.Instance().DeleteSleep(Int32(ei)); break;
case "Smoking": GAPI.Instance().DeleteSmoking(Int32(ei)); break;
case "Social": GAPI.Instance().DeleteSocial(Int32(ei)); break;
case "Stepcount": GAPI.Instance().DeleteStepcount(Int32(ei)); break;
//case "Survey": GAPI.Instance().DeleteSurvey(Int32(ei)); break;
case "Wellbeing": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Mood": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Happy": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Uneasy": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Well": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
case "Sad": GAPI.Instance().DeleteWellbeing(Int32(ei)); break;
default: break;
}
}
// Clear output view at top of screen
@IBAction func pressedClear(sender: UIButton)
{
lbText.text = "";
lbText.sizeToFit();
lbText.frame = CGRectMake(lbText.frame.origin.x, lbText.frame.origin.y, 300, lbText.frame.size.height);
svOutput.setContentOffset(CGPoint(x:0.0,y:0.0),animated:true);
}
// Clear user login token, resulting in current/different user having to log in again
@IBAction func pressedClearToken(sender: UIButton)
{
GAPI.Instance().ClearToken();
self.dismissViewControllerAnimated(true, completion: nil);
}
//Update views time entries to current date
@IBAction func pressedSetTimeNow(sender: UIButton?)
{
var date = GAPI.GetDateShort(0);
var now = GAPI.GetDateTime(0);
lbGetFrom.text = date;
lbGetTo.text = date;
//Time now
(svSendData.viewWithTag(2) as UITextField).text = now;
//Start time
(svSendData.viewWithTag(4) as UITextField).text = now;
//End time
(svSendData.viewWithTag(6) as UITextField).text = now;
}
//
// MARK: Callbacks
//
func SetBusy(truth: Bool)
{
aiBusy.hidden = !truth;
}
func Comment(text: String)
{
//Add comment to top of view
lbText.text = text + "\n" + lbText.text!;
lbText.sizeToFit();
lbText.frame = CGRectMake(lbText.frame.origin.x, lbText.frame.origin.y, 300, lbText.frame.size.height);
}
func CommentError(text: String)
{
Comment(text);
}
func CommentResult(text: String)
{
}
func CommentSystem(text: String)
{
}
func DataReceived(endPoint:String, withData:NSDictionary?, andString:String)
{
//Is data recieved not from default login process, display at top of view, as data apps user requested directly
if( dataRequested ||
( endPoint != "/defaults.json" && endPoint != "/account/signupmetadata"
&& endPoint != "/v1/me" && endPoint != "/v1/wellbeing"
&& endPoint != "/v1/o/events" && endPoint != "/v1/tags") )
{
Comment("Got data from '\(endPoint)' of '\(andString)'");
SetBusy(false);
dataRequested = false;
}
}
}
| 982f3279c49666867a77dceeb3751b5d | 43.765009 | 302 | 0.613955 | false | false | false | false |
Ahrodite/LigaFix | refs/heads/master | LigaFix/SwiftForms/cells/FormSegmentedControlCell.swift | mit | 4 | //
// FormSegmentedControlCell.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 21/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormSegmentedControlCell: FormBaseCell {
/// MARK: Cell views
public let titleLabel = UILabel()
public let segmentedControl = UISegmentedControl()
/// MARK: Properties
private var customConstraints: [AnyObject]!
/// MARK: FormBaseCell
public override func configure() {
super.configure()
selectionStyle = .None
titleLabel.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
titleLabel.setContentCompressionResistancePriority(500, forAxis: .Horizontal)
segmentedControl.setContentCompressionResistancePriority(500, forAxis: .Horizontal)
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
contentView.addSubview(titleLabel)
contentView.addSubview(segmentedControl)
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
segmentedControl.addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)
}
public override func update() {
super.update()
titleLabel.text = rowDescriptor.title
updateSegmentedControl()
var idx = 0
if rowDescriptor.value != nil {
if let options = rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray {
for optionValue in options {
if optionValue as! NSObject == rowDescriptor.value {
segmentedControl.selectedSegmentIndex = idx
break
}
++idx
}
}
}
}
public override func constraintsViews() -> [String : UIView] {
return ["titleLabel" : titleLabel, "segmentedControl" : segmentedControl]
}
public override func defaultVisualConstraints() -> [String] {
if titleLabel.text != nil && (titleLabel.text!).characters.count > 0 {
return ["H:|-16-[titleLabel]-16-[segmentedControl]-16-|"]
}
else {
return ["H:|-16-[segmentedControl]-16-|"]
}
}
/// MARK: Actions
internal func valueChanged(sender: UISegmentedControl) {
let options = rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray
let optionValue = options?[sender.selectedSegmentIndex] as? NSObject
rowDescriptor.value = optionValue
}
/// MARK: Private
private func updateSegmentedControl() {
segmentedControl.removeAllSegments()
var idx = 0
if let options = rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray {
for optionValue in options {
segmentedControl.insertSegmentWithTitle(rowDescriptor.titleForOptionValue(optionValue as! NSObject), atIndex: idx, animated: false)
++idx
}
}
}
}
| 756d2ad0c343a8a3073caba0fc3ea436 | 34.67 | 191 | 0.634427 | false | true | false | false |
coffee-cup/solis | refs/heads/master | SunriseSunset/Spring/Misc.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public extension String {
func toURL() -> NSURL? {
return NSURL(string: self)
}
}
public func htmlToAttributedString(text: String) -> NSAttributedString! {
let htmlData = text.data(using: String.Encoding.utf8, allowLossyConversion: false)
let htmlString: NSAttributedString?
do {
htmlString = try NSAttributedString(data: htmlData!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch _ {
htmlString = nil
}
return htmlString
}
public func degreesToRadians(degrees: CGFloat) -> CGFloat {
return degrees * CGFloat(CGFloat.pi / 180)
}
public func delay(delay:Double, closure: @escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
public func imageFromURL(_ Url: String) -> UIImage {
let url = Foundation.URL(string: Url)
let data = try? Data(contentsOf: url!)
return UIImage(data: data!)!
}
public func rgbaToUIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
public func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
public func stringFromDate(date: NSDate, format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: date as Date)
}
public func dateFromString(date: String, format: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
if let date = dateFormatter.date(from: date) {
return date
} else {
return Date(timeIntervalSince1970: 0)
}
}
public func randomStringWithLength (len : Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: len)
for _ in 0 ..< len {
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.character(at: Int(rand)))
}
return randomString
}
public func timeAgoSinceDate(date: Date, numericDates: Bool) -> String {
let calendar = Calendar.current
let unitFlags = Set<Calendar.Component>(arrayLiteral: Calendar.Component.minute, Calendar.Component.hour, Calendar.Component.day, Calendar.Component.weekOfYear, Calendar.Component.month, Calendar.Component.year, Calendar.Component.second)
let now = Date()
let dateComparison = now.compare(date)
var earliest: Date
var latest: Date
switch dateComparison {
case .orderedAscending:
earliest = now
latest = date
default:
earliest = date
latest = now
}
let components: DateComponents = calendar.dateComponents(unitFlags, from: earliest, to: latest)
guard
let year = components.year,
let month = components.month,
let weekOfYear = components.weekOfYear,
let day = components.day,
let hour = components.hour,
let minute = components.minute,
let second = components.second
else {
fatalError()
}
if (year >= 2) {
return "\(year)y"
} else if (year >= 1) {
if (numericDates){
return "1y"
} else {
return "1y"
}
} else if (month >= 2) {
return "\(month * 4)w"
} else if (month >= 1) {
if (numericDates){
return "4w"
} else {
return "4w"
}
} else if (weekOfYear >= 2) {
return "\(weekOfYear)w"
} else if (weekOfYear >= 1){
if (numericDates){
return "1w"
} else {
return "1w"
}
} else if (day >= 2) {
return "\(String(describing: components.day))d"
} else if (day >= 1){
if (numericDates){
return "1d"
} else {
return "1d"
}
} else if (hour >= 2) {
return "\(hour)h"
} else if (hour >= 1){
if (numericDates){
return "1h"
} else {
return "1h"
}
} else if (minute >= 2) {
return "\(minute)m"
} else if (minute >= 1){
if (numericDates){
return "1m"
} else {
return "1m"
}
} else if (second >= 3) {
return "\(second)s"
} else {
return "now"
}
}
| 618a1a24e586332f9be802cb92ee7d4a | 30.796791 | 242 | 0.62849 | false | false | false | false |
Chaosspeeder/YourGoals | refs/heads/master | YourGoals/UI/Controller/SelectableCommitDatesCreator.swift | lgpl-3.0 | 1 | //
// CommitDatesCreator.swift
// YourGoals
//
// Created by André Claaßen on 17.12.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
enum CommitDateType {
case noCommitDate
case explicitCommitDate
case userDefinedCommitDate
}
/// a tuple representing a commit date in the future and a string representation
struct CommitDateTuple:Equatable {
static func ==(lhs: CommitDateTuple, rhs: CommitDateTuple) -> Bool {
return lhs.date == rhs.date && lhs.type == rhs.type
}
let text:String
let date:Date?
let type:CommitDateType
}
/// utility class for creating a list of commit dates
class SelectableCommitDatesCreator {
/// convert a commit date to a tuple with a readable text explanatin
///
/// - Parameter date: the date
/// - Returns: the tuple
func dateAsTuple(date:Date?, type: CommitDateType) -> CommitDateTuple {
switch type {
case .noCommitDate:
return CommitDateTuple(text: "No commit date", date: nil, type: type)
case .userDefinedCommitDate:
return CommitDateTuple(text: "Select date", date: nil, type: type)
default:
return CommitDateTuple(text: date!.formattedWithTodayTommorrowYesterday(), date: date, type: type)
}
}
/// create a list of commit dates for the next 7 days with a string
/// representation of the date
///
/// None (date = nil)
/// Today
/// Tommorrow
/// Tuesday (12/19/2017) (for 19.12.2017
/// Wednesday
///
/// - Parameters:
/// - date: start date of the list
/// - numberOfDays: a number of dates
/// - includingDate: a date which should be included in the list
///
/// - Returns: a list of formatted dates
func selectableCommitDates(startingWith date:Date, numberOfDays:Int, includingDate:Date? ) -> [CommitDateTuple] {
guard let range = Calendar.current.dateRange(startDate: date.day(), steps: numberOfDays-1) else {
NSLog("couldn't create a date range for startDate \(date) with days")
return []
}
var tuples = [CommitDateTuple]()
tuples.append(dateAsTuple(date: nil, type: .noCommitDate))
tuples.append(contentsOf: range.map { dateAsTuple(date: $0, type: .explicitCommitDate) })
tuples.append(dateAsTuple(date: nil, type: .userDefinedCommitDate))
if let includingDate = includingDate {
let tuple = tuples.first { $0.date?.compare(includingDate.day()) == .orderedSame }
if tuple == nil {
tuples.insert(dateAsTuple(date: includingDate.day(), type: .explicitCommitDate), at: 1)
}
}
return tuples
}
}
| 5b1f5281063cc2973330e11f7e843e96 | 32.590361 | 117 | 0.626255 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | refs/heads/master | Source/Internal/Utility/NSRange.swift | mit | 1 | import Foundation
internal extension NSRange {
init(forString string: String) {
self.init(range: string.startIndex ..< string.endIndex, inString: string)
}
init(range: Range<String.Index>?, inString string: String) {
if let range = range {
let location = NSRange.locationForIndex(range.lowerBound, inString: string)
let endLocation = NSRange.locationForIndex(range.upperBound, inString: string)
self.init(location: location, length: location.distance(to: endLocation))
} else {
self.init(location: NSNotFound, length: 0)
}
}
func endIndexInString(_ string: String) -> String.Index? {
return NSRange.indexForLocation(NSMaxRange(self), inString: string)
}
fileprivate static func indexForLocation(_ location: Int, inString string: String) -> String.Index? {
if location == NSNotFound {
return nil
}
return string.utf16.index(string.utf16.startIndex, offsetBy: location, limitedBy: string.utf16.endIndex)?.samePosition(in: string)
}
private static func locationForIndex(_ index: String.Index, inString string: String) -> Int {
guard let toPosition = index.samePosition(in: string.utf16) else {return -1}
return string.utf16.distance(from: string.utf16.startIndex, to: toPosition)
}
func rangeInString(_ string: String) -> Range<String.Index>? {
if let startIndex = startIndexInString(string),
let endIndex = endIndexInString(string) {
return startIndex ..< endIndex
}
return nil
}
func startIndexInString(_ string: String) -> String.Index? {
return NSRange.indexForLocation(location, inString: string)
}
}
| 75e3be51d8b9fbb4e2fe3181514d9e86 | 32.22449 | 138 | 0.713145 | false | false | false | false |
BenziAhamed/Nevergrid | refs/heads/master | NeverGrid/Source/TargetAction.swift | isc | 1 | //
// TargetAction.swift
// OnGettingThere
//
// Created by Benzi on 06/08/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
// http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/
import Foundation
protocol TargetAction {
func performAction()
}
class Callback<T: AnyObject> : TargetAction {
weak var target: T?
let action: (T) -> () -> ()
init(_ target:T, _ action:(T) -> () -> ()) {
self.target = target
self.action = action
}
func performAction() -> () {
if let t = target {
action(t)()
}
}
}
//struct EventArgs { }
//
//protocol EventHandler {
// func handleEvent(sender:AnyObject, args:EventArgs)
//}
//
//struct EventHandlerCallback<T:AnyObject> : EventHandler {
// weak var target: T?
// let action: (T) -> (AnyObject,EventArgs) -> ()
//
// init(_ target:T, _ action:(T) -> (AnyObject,EventArgs) -> ()) {
// self.target = target
// self.action = action
// }
//
// func handleEvent(sender:AnyObject, args:EventArgs) -> () {
// if let t = target {
// action(t)(sender, args)
// }
// }
//}
| fa393cbdd3f87c68a62b7ceb732b0559 | 20.962963 | 73 | 0.554806 | false | false | false | false |
JGiola/swift | refs/heads/main | test/decl/protocol/special/coding/enum_codable_simple_conditional.swift | apache-2.0 | 13 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown -swift-version 4
enum Conditional<T> {
case a(x: T, y: T?)
case b(z: [T])
func foo() {
// They should receive a synthesized CodingKeys enum.
let _ = Conditional.CodingKeys.self
let _ = Conditional.ACodingKeys.self
// The enum should have a case for each of the cases.
let _ = Conditional.CodingKeys.a
let _ = Conditional.CodingKeys.b
// The enum should have a case for each of the parameters.
let _ = Conditional.ACodingKeys.x
let _ = Conditional.ACodingKeys.y
let _ = Conditional.BCodingKeys.z
}
}
extension Conditional: Codable where T: Codable { // expected-note 4{{where 'T' = 'Nonconforming'}}
}
// They should receive synthesized init(from:) and an encode(to:).
let _ = Conditional<Int>.init(from:)
let _ = Conditional<Int>.encode(to:)
// but only for Codable parameters.
struct Nonconforming {}
let _ = Conditional<Nonconforming>.init(from:) // expected-error {{referencing initializer 'init(from:)' on 'Conditional' requires that 'Nonconforming' conform to 'Encodable'}}
// expected-error@-1 {{referencing initializer 'init(from:)' on 'Conditional' requires that 'Nonconforming' conform to 'Decodable'}}
let _ = Conditional<Nonconforming>.encode(to:) // expected-error {{referencing instance method 'encode(to:)' on 'Conditional' requires that 'Nonconforming' conform to 'Encodable'}}
// expected-error@-1 {{referencing instance method 'encode(to:)' on 'Conditional' requires that 'Nonconforming' conform to 'Decodable'}}
// The synthesized CodingKeys type should not be accessible from outside the
// enum.
let _ = Conditional<Int>.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
let _ = Conditional<Int>.ACodingKeys.self // expected-error {{'ACodingKeys' is inaccessible due to 'private' protection level}}
let _ = Conditional<Int>.BCodingKeys.self // expected-error {{'BCodingKeys' is inaccessible due to 'private' protection level}}
| cce495f8e1c4d3ef3281f9e96f6ea821 | 47.02381 | 180 | 0.722856 | false | false | false | false |
qinting513/SwiftNote | refs/heads/master | youtube/YouTube/Model/VideoItem.swift | apache-2.0 | 1 | //
// Video.swift
// YouTube
//
// Created by Haik Aslanyan on 6/27/16.
// Copyright © 2016 Haik Aslanyan. All rights reserved.
//
import Foundation
import UIKit
class VideoItem {
//MARK: Properties
let tumbnail: UIImage
let title: String
let views: Int
let channel: Channel
let duration: Int
//MARK: Download the list of items
class func getVideosList(fromURL: URL, completition: @escaping ([[String : AnyObject]]) -> (Void)) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
var items = [[String : AnyObject]]()
URLSession.shared.dataTask(with: fromURL) { (data, response, error) in
if error != nil {
showNotification()
} else{
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
items = json as! [[String : AnyObject]]
} catch _ {
showNotification()
}
completition(items)
}
}.resume()
}
//MARK: single item download
class func object(at: Int, fromList: Array<[String : AnyObject]>, completiotion: @escaping ((VideoItem, Int) -> Void)) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
DispatchQueue.global(qos: .userInteractive).async(execute: {
let item = fromList[at]
let title = item["title"] as! String
let tumbnail = UIImage.contentOfURL(link: item["thumbnail_image_name"] as! String)
let views = item["number_of_views"] as! Int
let duration = item["duration"] as! Int
let channelDic = item["channel"] as! [String : String]
let channelPic = UIImage.contentOfURL(link: channelDic["profile_image_name"]!)
let channelName = channelDic["name"]!
let channel = Channel.init(name: channelName, image: channelPic)
let video = VideoItem.init(title: title, tumbnail: tumbnail, views: views, duration: duration, channel: channel)
completiotion(video, at)
})
}
//MARK: Inits
init(title: String, tumbnail: UIImage, views: Int, duration: Int, channel: Channel) {
self.title = title
self.views = views
self.tumbnail = tumbnail
self.channel = channel
self.duration = duration
}
}
| 9ab33ecd7952625fde249ccbccd5b523 | 35.58209 | 125 | 0.586291 | false | false | false | false |
Zewo/Zewo | refs/heads/master | Sources/Core/String/String.swift | mit | 1 | import Foundation
extension Character {
public var isASCII: Bool {
return unicodeScalars.reduce(true, { $0 && $1.isASCII })
}
public var isAlphabetic: Bool {
return isLowercase || isUppercase
}
public var isDigit: Bool {
return ("0" ... "9").contains(self)
}
}
extension String {
public func uppercasedFirstCharacter() -> String {
let first = prefix(1).capitalized
let other = dropFirst()
return first + other
}
}
extension CharacterSet {
public static var urlAllowed: CharacterSet {
let uppercaseAlpha = CharacterSet(charactersIn: "A" ... "Z")
let lowercaseAlpha = CharacterSet(charactersIn: "a" ... "z")
let numeric = CharacterSet(charactersIn: "0" ... "9")
let symbols: CharacterSet = ["_", "-", "~", "."]
return uppercaseAlpha
.union(lowercaseAlpha)
.union(numeric)
.union(symbols)
}
}
extension String {
public func trimmed() -> String {
let regex = try! NSRegularExpression(pattern: " +", options: .caseInsensitive)
return regex.stringByReplacingMatches(
in: self,
options: [],
range: NSRange(location: 0, length: utf8.count),
withTemplate: " "
).trimmingCharacters(in: .whitespaces)
}
public func camelCaseSplit() -> [String] {
var entries: [String] = []
var runes: [[Character]] = []
var lastClass = 0
var currentClass = 0
for character in self {
switch true {
case character.isLowercase:
currentClass = 1
case character.isUppercase:
currentClass = 2
case character.isDigit:
currentClass = 3
default:
currentClass = 4
}
if currentClass == lastClass {
var rune = runes[runes.count - 1]
rune.append(character)
runes[runes.count - 1] = rune
} else {
runes.append([character])
}
lastClass = currentClass
}
// handle upper case -> lower case sequences, e.g.
// "PDFL", "oader" -> "PDF", "Loader"
if runes.count >= 2 {
for i in 0 ..< runes.count - 1 {
if runes[i][0].isUppercase && runes[i + 1][0].isLowercase {
runes[i + 1] = [runes[i][runes[i].count - 1]] + runes[i + 1]
runes[i] = Array(runes[i][..<(runes[i].count - 1)])
}
}
}
for rune in runes where rune.count > 0 {
entries.append(String(rune))
}
return entries
}
}
extension UUID : LosslessStringConvertible {
public init?(_ string: String) {
guard let uuid = UUID(uuidString: string) else {
return nil
}
self = uuid
}
}
| 90422112e9213dbe30b0395d46a3085f | 27.212963 | 87 | 0.501477 | false | false | false | false |
MYLILUYANG/DouYuZB | refs/heads/master | DouYuZB/DouYuZB/Class/Home/View/PageTitleView.swift | mit | 1 | //
// PageTitleView.swift
// DouYuZB
//
// Created by liluyang on 17/2/13.
// Copyright © 2017年 liluyang. All rights reserved.
//
import UIKit
private let kScrollLineH : CGFloat = 2
class PageTitleView: UIView {
//定义属性
fileprivate var titles : [String]
//懒加载属性
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
fileprivate lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
//MARK - 自定义构造函数
init(frame: CGRect, titles:[String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView
{
fileprivate func setupUI(){
addSubview(scrollView)
//添加title对应的label
scrollView.frame = bounds;
setupTitleLabe()//添加titlelabel
setupBottonLineAndScrollLine()//添加底部线条
}
fileprivate func setupTitleLabe(){
let labelY : CGFloat = 0;
let labelW : CGFloat = frame.width / CGFloat(titles.count);
let labelH : CGFloat = frame.height - kScrollLineH;
for(index, title) in titles.enumerated(){
//创建label
let label = UILabel()
//设置label
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 14.0)
label.textColor = UIColor.darkGray
label.textAlignment = .center
//设置label 的frame
let labelX : CGFloat = labelW * CGFloat(index);
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titleLabels .append(label)
}
}
fileprivate func setupBottonLineAndScrollLine(){
//添加底部线条
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: kScreenW, height: lineH)
addSubview(bottomLine)
//添加scrollline 获取第一个label
scrollView.addSubview(scrollLine)
guard let firstLabel = titleLabels.first else {return}
firstLabel.textColor = UIColor.orange
scrollLine.frame = CGRect(x: 0, y: frame.height - kScrollLineH, width: firstLabel.frame.size.width, height: kScrollLineH)
}
}
| ae06d26f6ea64a7befe6ac99bbc82d75 | 22.520661 | 129 | 0.599789 | false | false | false | false |
SeaHub/ImgTagging | refs/heads/master | ImgTagger/ImgTagger/NameChangingViewController.swift | gpl-3.0 | 1 | //
// NameChangingViewController.swift
// ImgTagger
//
// Created by SeaHub on 2017/6/30.
// Copyright © 2017年 SeaCluster. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
import PopupDialog
class NameChangingViewController: UIViewController {
@IBOutlet weak var maskView: UIView!
@IBOutlet weak var nameTextField: UITextField!
private var indicator: NVActivityIndicatorView! = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), type: .ballScaleRippleMultiple, color: .white, padding: nil)
override func viewDidLoad() {
super.viewDidLoad()
self.configureIndicator()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func indicatorStartAnimating() {
UIView.animate(withDuration: 0.5) {
self.maskView.alpha = 0.5
}
}
private func indicatorStopAnimating() {
UIView.animate(withDuration: 0.5) {
self.maskView.alpha = 0
self.indicator.stopAnimating()
}
}
private func configureIndicator() {
self.indicator.center = CGPoint(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2)
self.maskView.addSubview(self.indicator)
self.indicator.startAnimating()
}
private func showErrorAlert() {
let alert = PopupDialog(title: "Tips", message: "An error occured, please retry later!", image: nil)
let cancelButton = CancelButton(title: "OK") { }
alert.addButtons([cancelButton])
self.present(alert, animated: true, completion: nil)
}
@IBAction func commitButtonClicked(_ sender: Any) {
if let name = self.nameTextField.text {
self.indicatorStopAnimating()
APIManager.modifyInfo(token: ImgTaggerUtil.userToken!, name: name, avatarImage: nil, success: {
self.indicatorStopAnimating()
let alert = PopupDialog(title: "Tips", message: "Change successfully", image: nil)
let cancelButton = DefaultButton(title: "OK") {
self.navigationController?.popToRootViewController(animated: true)
}
alert.addButtons([cancelButton])
self.present(alert, animated: true, completion: nil)
}, failure: { (error) in
self.indicatorStopAnimating()
debugPrint(error.localizedDescription)
self.showErrorAlert()
})
}
}
@IBAction func backButtonClicked(_ sender: Any) {
self.navigationController?.popToRootViewController(animated: true)
}
// MARK: - Keyboard Related
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
| 63bfeebfe7db068b8bc88e2c67aa86af | 33.771084 | 190 | 0.623008 | false | false | false | false |
zhangbozhb/WebViewBridge.Swift | refs/heads/master | Example/WebViewBridge.Swift/ZHViewController2.swift | mit | 1 | //
// ZHViewController2.swift
// WebViewBridge.Swift
//
// Created by travel on 16/6/20.
// Copyright © 2016年 travel. All rights reserved.
//
import UIKit
import WebKit
import WebViewBridge_Swift
class ZHViewController2: UIViewController {
@IBOutlet weak var container: UIView!
var webView: WKWebView!
var bridge: ZHWebViewBridge<WKWebView>!
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView()
webView.frame = view.bounds
container.addSubview(webView)
bridge = ZHWebViewBridge.bridge(webView)
bridge.registerHandler("Image.updatePlaceHolder") { (_: [Any]) -> (Bool, [Any]?) in
return (true, ["place_holder.png"])
}
bridge.registerHandler("Image.ViewImage") { [weak self](args: [Any]) -> (Bool, [Any]?) in
if let index = args.first as? Int, args.count == 1 {
self?.viewImageAtIndex(index)
return (true, nil)
}
return (false, nil)
}
bridge.registerHandler("Image.DownloadImage") { [weak self](args: [Any]) -> (Bool, [Any]?) in
if let index = args.first as? Int, args.count == 1 {
self?.downloadImageAtIndex(index)
return (true, nil)
}
return (false, nil)
}
bridge.registerHandler("Time.GetCurrentTime") { [weak self](args: [Any]) -> (Bool, [Any]?) in
self?.bridge.callJsHandler("Time.updateTime", args: [Date.init().description])
return (true, nil)
}
bridge.registerHandler("Device.GetAppVersion") { [weak self](args: [Any]) -> (Bool, [Any]?) in
self?.bridge.callJsHandler("Device.updateAppVersion", args: [Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String], callback: { (data: Any?) in
if let data = data as? String {
let alert = UIAlertController.init(title: "Device.updateAppVersion", message: data, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "OK", style: .default, handler: { [weak self](_:UIAlertAction) in
self?.dismiss(animated: false, completion: nil)
}))
self?.present(alert, animated: true, completion: nil)
}
})
return (true, nil)
}
prepareResources()
webView.loadHTMLString(ZHData.instance.htmlData, baseURL: URL.init(fileURLWithPath: ZHData.instance.imageFolder))
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
webView.frame = container.bounds
}
func prepareResources() {
let basePath = ZHData.instance.imageFolder
let resources = ["place_holder.png", "bridge_core.js"]
for resource in resources {
if let path = Bundle.main.path(forResource: resource, ofType: nil) {
let targetPath = (basePath as NSString).appendingPathComponent(resource)
if !FileManager.default.fileExists(atPath: targetPath) {
_ = try? FileManager.default.copyItem(atPath: path, toPath: targetPath)
}
}
}
}
func viewImageAtIndex(_ index: Int) {
let alert = UIAlertController.init(title: "ViewImage atIndex \(index)", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "OK", style: .default, handler: { [weak self](_:UIAlertAction) in
self?.dismiss(animated: false, completion: nil)
}))
present(alert, animated: true, completion: nil)
}
func downloadImageAtIndex(_ index: Int) {
let images = ZHData.instance.imageUrls
if index < images.count {
let image = images[index]
ZHData.instance.downloadImage(image, handler: { [weak self](file: String) in
self?.bridge.callJsHandler("Image.updateImageAtIndex", args: [file, index], callback: nil)
})
}
}
func downloadImages() {
for (index, _) in ZHData.instance.imageUrls.enumerated() {
downloadImageAtIndex(index)
}
}
}
| 23da82d0178e3ed16d41f8c3d6d950b7 | 38.514019 | 184 | 0.592242 | false | false | false | false |
huonw/swift | refs/heads/master | test/IRGen/globals.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
var g0 : Int = 1
var g1 : (Void, Int, Void)
var g2 : (Void, Int, Int)
var g3 : Bool
// FIXME: enum IRgen
// enum TY4 { case some(Int, Int); case none }
// var g4 : TY4
// FIXME: enum IRgen
// enum TY5 { case a(Int8, Int8, Int8, Int8)
// case b(Int16) }
// var g5 : TY5
var g6 : Double
var g7 : Float
// FIXME: enum IRgen
// enum TY8 { case a }
// var g8 : TY8
struct TY9 { }
var g9 : TY9
// rdar://16520242
struct A {}
extension A {
static var foo : Int = 5
}
// CHECK: [[INT:%.*]] = type <{ i64 }>
// CHECK: [[BOOL:%.*]] = type <{ i1 }>
// CHECK: [[DOUBLE:%.*]] = type <{ double }>
// CHECK: [[FLOAT:%.*]] = type <{ float }>
// CHECK-NOT: TY8
// CHECK: @"$S7globals2g0Sivp" = hidden global [[INT]] zeroinitializer, align 8
// CHECK: @"$S7globals2g1yt_Siyttvp" = hidden global <{ [[INT]] }> zeroinitializer, align 8
// CHECK: @"$S7globals2g2yt_S2itvp" = hidden global <{ [[INT]], [[INT]] }> zeroinitializer, align 8
// CHECK: @"$S7globals2g3Sbvp" = hidden global [[BOOL]] zeroinitializer, align 1
// CHECK: @"$S7globals2g6Sdvp" = hidden global [[DOUBLE]] zeroinitializer, align 8
// CHECK: @"$S7globals2g7Sfvp" = hidden global [[FLOAT]] zeroinitializer, align 4
// CHECK: @"$S7globals1AV3fooSivpZ" = hidden global [[INT]] zeroinitializer, align 8
// CHECK-NOT: g8
// CHECK-NOT: g9
// CHECK: define{{( dllexport)?}}{{( protected)?}} i32 @main(i32, i8**) {{.*}} {
// CHECK: store i64 {{.*}}, i64* getelementptr inbounds ([[INT]], [[INT]]* @"$S7globals2g0Sivp", i32 0, i32 0), align 8
// FIXME: give these initializers a real mangled name
// CHECK: define internal void @globalinit_{{.*}}func0() {{.*}} {
// CHECK: store i64 5, i64* getelementptr inbounds (%TSi, %TSi* @"$S7globals1AV3fooSivpZ", i32 0, i32 0), align 8
| 286a00891248dc45a4327260a0cb84cb | 31.655172 | 125 | 0.62038 | false | false | false | false |
JonyFang/AnimatedDropdownMenu | refs/heads/master | Examples/Examples/MenuTypes/LeftTypeSixViewController.swift | mit | 1 | //
// LeftTypeSixViewController.swift
// AnimatedDropdownMenu
//
// Created by JonyFang on 17/3/3.
// Copyright © 2017年 JonyFang. All rights reserved.
//
import UIKit
import AnimatedDropdownMenu
class LeftTypeSixViewController: UIViewController {
// MARK: - Properties
fileprivate let dropdownItems: [AnimatedDropdownMenu.Item] = [
AnimatedDropdownMenu.Item.init("From | Photography", nil, nil),
AnimatedDropdownMenu.Item.init("From | Artwork", nil, nil),
AnimatedDropdownMenu.Item.init("Others", nil, nil)
]
fileprivate var selectedStageIndex: Int = 0
fileprivate var lastStageIndex: Int = 0
fileprivate var dropdownMenu: AnimatedDropdownMenu!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupAnimatedDropdownMenu()
view.backgroundColor = .white
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
resetNavigationBarColor()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
dropdownMenu.show()
}
// MARK: - Private Methods
fileprivate func setupAnimatedDropdownMenu() {
let dropdownMenu = AnimatedDropdownMenu(navigationController: navigationController, containerView: view, selectedIndex: selectedStageIndex, items: dropdownItems)
dropdownMenu.cellBackgroundColor = UIColor.menuPurpleColor()
dropdownMenu.menuTitleColor = UIColor.menuLightTextColor()
dropdownMenu.menuArrowTintColor = UIColor.menuLightTextColor()
dropdownMenu.cellTextColor = UIColor.init(white: 1.0, alpha: 0.3)
dropdownMenu.cellTextSelectedColor = UIColor.menuLightTextColor()
dropdownMenu.cellSeparatorColor = UIColor.init(white: 1.0, alpha: 0.1)
dropdownMenu.cellTextAlignment = .left
dropdownMenu.didSelectItemAtIndexHandler = {
[weak self] selectedIndex in
guard let strongSelf = self else {
return
}
strongSelf.lastStageIndex = strongSelf.selectedStageIndex
strongSelf.selectedStageIndex = selectedIndex
guard strongSelf.selectedStageIndex != strongSelf.lastStageIndex else {
return
}
//Configure Selected Action
strongSelf.selectedAction()
}
self.dropdownMenu = dropdownMenu
navigationItem.titleView = dropdownMenu
}
private func selectedAction() {
print("\(dropdownItems[selectedStageIndex].title)")
}
fileprivate func resetNavigationBarColor() {
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.barTintColor = UIColor.menuPurpleColor()
let textAttributes: [String: Any] = [
NSForegroundColorAttributeName: UIColor.menuLightTextColor(),
NSFontAttributeName: UIFont.navigationBarTitleFont()
]
navigationController?.navigationBar.titleTextAttributes = textAttributes
}
}
| d6fd710c5df3b91bf27443ff1b697b06 | 31.52 | 169 | 0.647294 | false | false | false | false |
queueit/QueueIT.iOS.Sdk | refs/heads/master | QueueItSDK/StatusDTO.swift | lgpl-3.0 | 1 | import Foundation
class StatusDTO {
var eventDetails: EventDTO?
var redirectDto: RedirectDTO?
var widgets: [WidgetDTO]?
var nextCallMSec: Int
var rejectDto: RejectDTO?
init(_ eventDetails: EventDTO?, _ redirectDto: RedirectDTO?, _ widgets: [WidgetDTO]?, _ nextCallMSec: Int, _ rejectDto: RejectDTO?) {
self.eventDetails = eventDetails
self.redirectDto = redirectDto
self.widgets = widgets
self.nextCallMSec = nextCallMSec
self.rejectDto = rejectDto
}
}
| 6385ddd13083ea6a4bcb5cfb63da2f6a | 30 | 137 | 0.669829 | false | false | false | false |
BigxMac/firefox-ios | refs/heads/master | ThirdParty/SwiftKeychainWrapper/KeychainWrapper.swift | mpl-2.0 | 19 | //
// KeychainWrapper.swift
// KeychainWrapper
//
// Created by Jason Rendel on 9/23/14.
// Copyright (c) 2014 jasonrendel. All rights reserved.
//
import Foundation
let SecMatchLimit: String! = kSecMatchLimit as String
let SecReturnData: String! = kSecReturnData as String
let SecValueData: String! = kSecValueData as String
let SecAttrAccessible: String! = kSecAttrAccessible as String
let SecClass: String! = kSecClass as String
let SecAttrService: String! = kSecAttrService as String
let SecAttrGeneric: String! = kSecAttrGeneric as String
let SecAttrAccount: String! = kSecAttrAccount as String
let SecAttrAccessGroup: String! = kSecAttrAccessGroup as String
let SecAttrAccessibleWhenUnlocked: String! = kSecAttrAccessibleWhenUnlocked as String
let SecReturnAttributes: String! = kSecReturnAttributes as String
/// KeychainWrapper is a class to help make Keychain access in Swift more straightforward. It is designed to make accessing the Keychain services more like using NSUserDefaults, which is much more familiar to people.
public class KeychainWrapper {
// MARK: Private static Properties
private struct internalVars {
static var serviceName: String = ""
static var accessGroup: String = ""
}
// MARK: Public Properties
/// ServiceName is used for the kSecAttrService property to uniquely identify this keychain accessor. If no service name is specified, KeychainWrapper will default to using the bundleIdentifier.
///
///This is a static property and only needs to be set once
public class var serviceName: String {
get {
if internalVars.serviceName.isEmpty {
internalVars.serviceName = NSBundle.mainBundle().bundleIdentifier ?? "SwiftKeychainWrapper"
}
return internalVars.serviceName
}
set(newServiceName) {
internalVars.serviceName = newServiceName
}
}
/// AccessGroup is used for the kSecAttrAccessGroup property to identify which Keychain Access Group this entry belongs to. This allows you to use the KeychainWrapper with shared keychain access between different applications.
///
/// Access Group defaults to an empty string and is not used until a valid value is set.
///
/// This is a static property and only needs to be set once. To remove the access group property after one has been set, set this to an empty string.
public class var accessGroup: String {
get {
return internalVars.accessGroup
}
set(newAccessGroup){
internalVars.accessGroup = newAccessGroup
}
}
// MARK: Public Methods
/// Checks if keychain data exists for a specified key.
///
/// :param: keyName The key to check for.
/// :returns: True if a value exists for the key. False otherwise.
public class func hasValueForKey(keyName: String) -> Bool {
var keychainData: NSData? = self.dataForKey(keyName)
if let data = keychainData {
return true
} else {
return false
}
}
/// Returns a string value for a specified key.
///
/// :param: keyName The key to lookup data for.
/// :returns: The String associated with the key if it exists. If no data exists, or the data found cannot be encoded as a string, returns nil.
public class func stringForKey(keyName: String) -> String? {
var keychainData: NSData? = self.dataForKey(keyName)
var stringValue: String?
if let data = keychainData {
stringValue = NSString(data: data, encoding: NSUTF8StringEncoding) as String?
}
return stringValue
}
/// Returns an object that conforms to NSCoding for a specified key.
///
/// :param: keyName The key to lookup data for.
/// :returns: The decoded object associated with the key if it exists. If no data exists, or the data found cannot be decoded, returns nil.
public class func objectForKey(keyName: String) -> NSCoding? {
let dataValue: NSData? = self.dataForKey(keyName)
var objectValue: NSCoding?
if let data = dataValue {
objectValue = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSCoding
}
return objectValue;
}
/// Returns a NSData object for a specified key.
///
/// :param: keyName The key to lookup data for.
/// :returns: The NSData object associated with the key if it exists. If no data exists, returns nil.
public class func dataForKey(keyName: String) -> NSData? {
var keychainQueryDictionary = self.setupKeychainQueryDictionaryForKey(keyName)
var result: AnyObject?
// Limit search results to one
keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne
// Specify we want NSData/CFData returned
keychainQueryDictionary[SecReturnData] = kCFBooleanTrue
// Search
let status = withUnsafeMutablePointer(&result) {
SecItemCopyMatching(keychainQueryDictionary, UnsafeMutablePointer($0))
}
return status == noErr ? result as? NSData : nil
}
/// Returns a NSData object for a specified key.
///
/// :param: keyName The key to lookup data for.
/// :returns: The NSData object associated with the key if it exists. If no data exists, returns nil.
public class func accessibilityOfKey(keyName: String) -> String? {
var keychainQueryDictionary = self.setupKeychainQueryDictionaryForKey(keyName)
var result: AnyObject?
// Limit search results to one
keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne
// Specify we want SecAttrAccessible returned
keychainQueryDictionary[SecReturnAttributes] = kCFBooleanTrue
// Search
let status = withUnsafeMutablePointer(&result) {
SecItemCopyMatching(keychainQueryDictionary, UnsafeMutablePointer($0))
}
if status == noErr {
if let resultsDictionary = result as? [String:AnyObject] {
return resultsDictionary[SecAttrAccessible] as? String
}
}
return nil
}
/// Save a String value to the keychain associated with a specified key. If a String value already exists for the given keyname, the string will be overwritten with the new value.
///
/// :param: value The String value to save.
/// :param: forKey The key to save the String under.
/// :returns: True if the save was successful, false otherwise.
public class func setString(value: String, forKey keyName: String, withAccessibility accessibility: String = SecAttrAccessibleWhenUnlocked) -> Bool {
if let data = value.dataUsingEncoding(NSUTF8StringEncoding) {
return self.setData(data, forKey: keyName, withAccessibility: accessibility)
} else {
return false
}
}
/// Save an NSCoding compliant object to the keychain associated with a specified key. If an object already exists for the given keyname, the object will be overwritten with the new value.
///
/// :param: value The NSCoding compliant object to save.
/// :param: forKey The key to save the object under.
/// :returns: True if the save was successful, false otherwise.
public class func setObject(value: NSCoding, forKey keyName: String, withAccessibility accessibility: String = SecAttrAccessibleWhenUnlocked) -> Bool {
let data = NSKeyedArchiver.archivedDataWithRootObject(value)
return self.setData(data, forKey: keyName, withAccessibility: accessibility)
}
/// Save a NSData object to the keychain associated with a specified key. If data already exists for the given keyname, the data will be overwritten with the new value.
///
/// :param: value The NSData object to save.
/// :param: forKey The key to save the object under.
/// :returns: True if the save was successful, false otherwise.
public class func setData(value: NSData, forKey keyName: String, withAccessibility accessibility: String = SecAttrAccessibleWhenUnlocked) -> Bool {
var keychainQueryDictionary: [String:AnyObject] = self.setupKeychainQueryDictionaryForKey(keyName)
keychainQueryDictionary[SecValueData] = value
// Protect the keychain entry so it's only valid when the device is unlocked
keychainQueryDictionary[SecAttrAccessible] = accessibility
let status: OSStatus = SecItemAdd(keychainQueryDictionary, nil)
if status == errSecSuccess {
return true
} else if status == errSecDuplicateItem {
return self.updateData(value, forKey: keyName, withAccessibility: accessibility)
} else {
return false
}
}
/// Remove an object associated with a specified key.
///
/// :param: keyName The key value to remove data for.
/// :returns: True if successful, false otherwise.
public class func removeObjectForKey(keyName: String) -> Bool {
let keychainQueryDictionary: [String:AnyObject] = self.setupKeychainQueryDictionaryForKey(keyName)
// Delete
let status: OSStatus = SecItemDelete(keychainQueryDictionary);
if status == errSecSuccess {
return true
} else {
return false
}
}
// MARK: Private Methods
/// Update existing data associated with a specified key name. The existing data will be overwritten by the new data
private class func updateData(value: NSData, forKey keyName: String, withAccessibility accessibility: String? = nil) -> Bool {
let keychainQueryDictionary: [String:AnyObject] = self.setupKeychainQueryDictionaryForKey(keyName)
var updateDictionary: [String:AnyObject] = [SecValueData: value]
if let accessibility = accessibility {
updateDictionary[SecAttrAccessible] = accessibility
}
// Update
let status: OSStatus = SecItemUpdate(keychainQueryDictionary, updateDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
/// Setup the keychain query dictionary used to access the keychain on iOS for a specified key name. Takes into account the Service Name and Access Group if one is set.
///
/// :param: keyName The key this query is for
/// :returns: A dictionary with all the needed properties setup to access the keychain on iOS
private class func setupKeychainQueryDictionaryForKey(keyName: String) -> [String:AnyObject] {
// Setup dictionary to access keychain and specify we are using a generic password (rather than a certificate, internet password, etc)
var keychainQueryDictionary: [String:AnyObject] = [SecClass:kSecClassGenericPassword]
// Uniquely identify this keychain accessor
keychainQueryDictionary[SecAttrService] = KeychainWrapper.serviceName
// Set the keychain access group if defined
if !KeychainWrapper.accessGroup.isEmpty {
keychainQueryDictionary[SecAttrAccessGroup] = KeychainWrapper.accessGroup
}
// Uniquely identify the account who will be accessing the keychain
var encodedIdentifier: NSData? = keyName.dataUsingEncoding(NSUTF8StringEncoding)
keychainQueryDictionary[SecAttrGeneric] = encodedIdentifier
keychainQueryDictionary[SecAttrAccount] = encodedIdentifier
return keychainQueryDictionary
}
}
| 3b022eec6fd6d00090d0e2b86cf22735 | 42.067416 | 230 | 0.691364 | false | false | false | false |
gnachman/iTerm2 | refs/heads/master | iTermFileProvider/ItemCreator.swift | gpl-2.0 | 2 | //
// ItemCreator.swift
// FileProvider
//
// Created by George Nachman on 6/10/22.
//
import Foundation
import FileProvider
import FileProviderService
actor ItemCreator {
struct Request: CustomDebugStringConvertible {
let itemTemplate: NSFileProviderItem
let fields: NSFileProviderItemFields
let contents: URL?
let options: NSFileProviderCreateItemOptions
let request: NSFileProviderRequest
let progress = Progress()
var debugDescription: String {
return "<ItemCreator.Request template=\(itemTemplate.terseDescription) fields=\(fields.description) contents=\(contents.descriptionOrNil) options=\(options.description) request=\(request.description)>"
}
}
struct Item {
let item: NSFileProviderItem
let fields: NSFileProviderItemFields
let shouldFetchContent: Bool
}
private let domain: NSFileProviderDomain
private let manager: NSFileProviderManager
private let remoteService: RemoteService
init(domain: NSFileProviderDomain, remoteService: RemoteService) {
self.domain = domain
self.remoteService = remoteService
manager = NSFileProviderManager(for: domain)!
}
func create(_ request: Request) async throws -> Item {
try await logging("create(\(request))") {
guard let file = RemoteFile(template: request.itemTemplate,
fields: request.fields) else {
// There isn't an appropriate exception for when we don't support a file
// type (e.g., aliases).
throw NSFileProviderError(.noSuchItem)
}
let data: Data
if request.fields.contains(.contents), let url = request.contents {
data = try Data(contentsOf: url, options: .alwaysMapped)
log("content=\(data.stringOrHex)")
} else {
log("No content - using empty data just in case")
data = Data()
}
switch file.kind {
case .symlink(let target):
log("Create symlink")
_ = try await remoteService.ln(
source: await rebaseLocalFile(manager, path: target),
file: file)
case .folder:
log("Create folder")
try await remoteService.mkdir(file)
case .file(_):
log("Create file")
request.progress.totalUnitCount = Int64(data.count)
try await remoteService.create(file, content: data)
request.progress.completedUnitCount = Int64(data.count)
case .host:
log("Create host")
throw NSFileProviderError(.noSuchItem) // no appropriate error exists
}
return Item(item: await FileProviderItem(file, manager: manager),
fields: [],
shouldFetchContent: false)
}
}
}
extension RemoteFile {
init?(template: NSFileProviderItem,
fields: NSFileProviderItemFields) {
guard let kind = Self.kind(template, fields) else {
return nil
}
self.init(kind: kind,
absolutePath: Self.path(template),
permissions: Self.permissions(template, fields),
ctime: Self.ctime(template, fields),
mtime: Self.mtime(template, fields))
}
private static func ctime(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Date {
if fields.contains(.creationDate),
case let creationDate?? = template.creationDate {
return creationDate
}
return Date()
}
private static func mtime(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Date {
if fields.contains(.contentModificationDate),
case let modifiationDate?? = template.contentModificationDate {
return modifiationDate
}
return Date()
}
private static func permissions(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Permissions {
if fields.contains(.fileSystemFlags), let flags = template.fileSystemFlags {
return Permissions(fileSystemFlags: flags)
}
return Permissions(r: true, w: true, x: true)
}
private static func path(_ template: NSFileProviderItem) -> String {
var url = URL(fileURLWithPath: template.parentItemIdentifier.rawValue)
url.appendPathComponent(template.filename)
return url.path
}
private static func kind(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Kind? {
switch template.contentType {
case .folder?:
return .folder
case .symbolicLink?:
if fields.contains(.contents),
case let target?? = template.symlinkTargetPath {
return .symlink(target)
}
log("symlink without target not allowed")
return nil
case .aliasFile?:
log("aliases not supported")
return nil
default:
return .file(FileInfo(size: nil))
}
}
}
extension RemoteFile.Permissions {
init(fileSystemFlags flags: NSFileProviderFileSystemFlags) {
self.init(r: flags.contains(.userReadable),
w: flags.contains(.userWritable),
x: flags.contains(.userExecutable))
}
}
| b9cba7a66acd6e4d96f9ba852599ea0d | 34.465839 | 213 | 0.585289 | false | false | false | false |
gregomni/swift | refs/heads/main | stdlib/private/OSLog/OSLogStringAlignment.swift | apache-2.0 | 7 | //===----------------- OSLogStringAlignment.swift -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
// This file defines types and functions for specifying alignment of the
// interpolations passed to the os log APIs.
@usableFromInline
internal enum OSLogCollectionBound {
case start
case end
}
@frozen
public struct OSLogStringAlignment {
/// Minimum number of characters to be displayed. If the value to be printed
/// is shorter than this number, the result is padded with spaces. The value
/// is not truncated even if the result is larger. This value need not be a
/// compile-time constant, and is therefore an autoclosure.
@usableFromInline
internal var minimumColumnWidth: (() -> Int)?
/// This captures right/left alignment.
@usableFromInline
internal var anchor: OSLogCollectionBound
/// Initiailzes stored properties.
///
/// - Parameters:
/// - minimumColumnWidth: Minimum number of characters to be displayed. If the value to be
/// printed is shorter than this number, the result is padded with spaces. The value is not truncated
/// even if the result is larger.
/// - anchor: Use `.end` for right alignment and `.start` for left.
@_transparent
@usableFromInline
internal init(
minimumColumnWidth: (() -> Int)? = nil,
anchor: OSLogCollectionBound = .end
) {
self.minimumColumnWidth = minimumColumnWidth
self.anchor = anchor
}
/// Indicates no alignment.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
public static var none: OSLogStringAlignment { OSLogStringAlignment(anchor: .end) }
/// Right align and display at least `columns` characters.
///
/// The interpolated value would be padded with spaces, if necessary, to
/// meet the specified `columns` characters.
///
/// - Parameter columns: minimum number of characters to display.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
public static func right(
columns: @escaping @autoclosure () -> Int
) -> OSLogStringAlignment {
OSLogStringAlignment(minimumColumnWidth: columns, anchor: .end)
}
/// Left align and display at least `columns` characters.
///
/// The interpolated value would be padded with spaces, if necessary, to
/// meet the specified `columns` characters.
///
/// - Parameter columns: minimum number of characters to display.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
public static func left(
columns: @escaping @autoclosure () -> Int
) -> OSLogStringAlignment {
OSLogStringAlignment(minimumColumnWidth: columns, anchor: .start)
}
}
| 077f2dfff77e469d58b608a7a058e6df | 33.965517 | 106 | 0.683761 | false | false | false | false |
sendyhalim/iYomu | refs/heads/master | Yomu/Screens/MangaList/MangaRealm.swift | mit | 1 | //
// MangaRealm.swift
// Yomu
//
// Created by Sendy Halim on 5/30/17.
// Copyright © 2017 Sendy Halim. All rights reserved.
//
import Foundation
import RealmSwift
/// Represents Manga object for `Realm` database
class MangaRealm: Object {
@objc dynamic var id: String = ""
@objc dynamic var slug: String = ""
@objc dynamic var title: String = ""
@objc dynamic var author: String = ""
@objc dynamic var imageEndpoint: String = ""
@objc dynamic var releasedYear: Int = 0
@objc dynamic var commaSeparatedCategories: String = ""
@objc dynamic var plot: String = ""
@objc dynamic var position: Int = MangaPosition.undefined.rawValue
override static func primaryKey() -> String? {
return "id"
}
/// Convert the given `Manga` struct to `MangaRealm` object
///
/// - parameter manga: `Manga`
///
/// - returns: `MangaRealm`
static func from(manga: Manga) -> MangaRealm {
let mangaRealm = MangaRealm()
mangaRealm.id = manga.id!
mangaRealm.slug = manga.slug
mangaRealm.title = manga.title
mangaRealm.author = manga.author
mangaRealm.imageEndpoint = manga.image.endpoint
mangaRealm.releasedYear = manga.releasedYear ?? 0
mangaRealm.commaSeparatedCategories = manga.categories.joined(separator: ",")
mangaRealm.position = manga.position
mangaRealm.plot = manga.plot
return mangaRealm
}
/// Convert the given `MangaRealm` object to `Manga` struct
///
/// - parameter mangaRealm: `MangaRealm`
///
/// - returns: `Manga`
static func mangaFrom(mangaRealm: MangaRealm) -> Manga {
let categories = mangaRealm
.commaSeparatedCategories
.split {
$0 == ","
}
.map(String.init)
return Manga(
position: mangaRealm.position,
id: mangaRealm.id,
slug: mangaRealm.slug,
title: mangaRealm.title,
author: mangaRealm.author,
image: ImageUrl(endpoint: mangaRealm.imageEndpoint),
releasedYear: mangaRealm.releasedYear,
plot: mangaRealm.plot,
categories: categories
)
}
}
| 19a70f9683c04bb442deb8a2abbe5094 | 26.77027 | 81 | 0.665693 | false | false | false | false |
maranathApp/GojiiFramework | refs/heads/master | GojiiFrameWork/UILabelExtensions.swift | mit | 1 | //
// CGFloatExtensions.swift
// GojiiFrameWork
//
// Created by Stency Mboumba on 01/06/2017.
// Copyright © 2017 Stency Mboumba. All rights reserved.
//
import UIKit
// MARK: - extension UILabel Initilizers
public extension UILabel {
/* --------------------------------------------------------------------------- */
// MARK: - Initilizers ( init )
/* --------------------------------------------------------------------------- */
/**
Initializes and returns a newly allocated view object with the specified frame rectangle.
- parameter frame: CGRect
- parameter text: String
- parameter textColor: UIColor
- parameter textAlignment: NSTextAlignment
- parameter font: UIFont
- returns: UILabel
*/
public convenience init (
frame: CGRect,
text: String,
textColor: UIColor,
textAlignment: NSTextAlignment,
font: UIFont) {
self.init(frame: frame)
self.text = text
self.textColor = textColor
self.textAlignment = textAlignment
self.font = font
self.numberOfLines = 0
}
/**
Initializes and returns a newly allocated view object with the specified frame rectangle.
- parameter x: CGFloat
- parameter y: CGFloat
- parameter width: CGFloat
- parameter height: CGFloat
- parameter text: String
- parameter textColor: UIColor
- parameter textAlignment: NSTextAlignment
- parameter font: UIFont
- returns: UILabel
*/
public convenience init (
x: CGFloat,
y: CGFloat,
width: CGFloat,
height: CGFloat,
text: String,
textColor: UIColor,
textAlignment: NSTextAlignment,
font: UIFont) {
self.init(frame: CGRect (x: x, y: y, width: width, height: height))
self.text = text
self.textColor = textColor
self.textAlignment = textAlignment
self.font = font
self.numberOfLines = 0
}
/**
Initializes and returns a newly allocated view object with the specified frame rectangle.
- parameter frame: CGRect
- parameter attributedText: NSAttributedString
- parameter textAlignment: NSTextAlignment
- returns: UILabel
*/
public convenience init (
frame: CGRect,
attributedText: NSAttributedString,
textAlignment: NSTextAlignment) {
self.init(frame: frame)
self.attributedText = attributedText
self.textAlignment = textAlignment
self.numberOfLines = 0
}
/**
Initializes and returns a newly allocated view object with the specified frame rectangle.
- parameter x: CGFloat
- parameter y: CGFloat
- parameter width: CGFloat
- parameter height: CGFloat
- parameter attributedText: NSAttributedString
- parameter textAlignment: NSTextAlignment
- returns: UILabel
*/
public convenience init (
x: CGFloat,
y: CGFloat,
width: CGFloat,
height: CGFloat,
attributedText: NSAttributedString,
textAlignment: NSTextAlignment) {
self.init(frame: CGRect (x: x, y: y, width: width, height: height))
self.attributedText = attributedText
self.textAlignment = textAlignment
self.numberOfLines = 0
}
/* --------------------------------------------------------------------------- */
// MARK: - Size
/* --------------------------------------------------------------------------- */
/**
Resize height of contraint of UILabel by new size text set, and number of line wanted
- parameter numberOfLine: Int / Number of numberOfLines
- parameter heightConstraint: NSLayoutConstraint
*/
public func resizeHeightToFit(numberOfLine:Int,heightConstraint: NSLayoutConstraint) {
let attributes = [NSFontAttributeName : font!]
self.numberOfLines = numberOfLine
self.lineBreakMode = NSLineBreakMode.byWordWrapping
let rect = text!.boundingRect(with: CGSize(width: frame.size.width,height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes , context: nil)
heightConstraint.constant = rect.height
setNeedsLayout()
}
/**
Get new Size for text
- returns: CGSize
@available(*, deprecated=9.0)
public func getHeightByTextForView() -> CGRect {
let label:UILabel = UILabel(frame: CGRectMake(0, 0, self.width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame
}*/
/**
Get Estimated Size
- parameter width: CGFloat
- parameter height: CGFloat
- returns: CGSize
*/
public func getEstimatedSize(width: CGFloat = CGFloat.greatestFiniteMagnitude, height: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize {
return sizeThatFits(CGSize(width: width, height: height))
}
/**
Get Estimated Height
- returns: CGFloat
*/
public func getEstimatedHeight() -> CGFloat {
return sizeThatFits(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)).height
}
/**
Get Estimated Width
- returns: CGFloat
*/
public func getEstimatedWidth() -> CGFloat {
return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)).width
}
/**
Size to fit Height
*/
public func sizeToFitHeight() {
self.height = getEstimatedHeight()
}
/**
Size to fit Width
*/
public func sizeToFitWidth() {
self.width = getEstimatedWidth()
}
/**
Size to fit Size
*/
public func sizeToFitSize() {
self.sizeToFitWidth()
self.sizeToFitHeight()
sizeToFit()
}
/* --------------------------------------------------------------------------- */
// MARK: - UILabel → Font
/* --------------------------------------------------------------------------- */
/// Font Size
public var fontSize:CGFloat {
get {
return self.font.pointSize
}
set {
self.font = UIFont(name: self.font.fontName, size: newValue)
}
}
/// Font Name
public var fontName:String {
get {
return self.font.fontName
}
set {
self.font = UIFont(name: newValue, size: self.font.pointSize)
}
}
/* --------------------------------------------------------------------------- */
// MARK: - UILabel → Animation
/* --------------------------------------------------------------------------- */
/**
Set Text With animation
- parameter text: String?
- parameter duration: NSTimeInterval?
*/
public func setTextAnimation(text: String?, duration: TimeInterval?) {
UIView.transition(with: self, duration: duration ?? 0.3, options: .transitionCrossDissolve, animations: { () -> Void in
self.text = text
}, completion: nil)
}
}
| a27338f2267e42cb547a38944d2f7480 | 29.696 | 211 | 0.530623 | false | false | false | false |
el-hoshino/NotAutoLayout | refs/heads/master | Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/TopLeftHeight.Individual.swift | apache-2.0 | 1 | //
// TopLeftHeight.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct TopLeftHeight {
let topLeft: LayoutElement.Point
let height: LayoutElement.Length
}
}
// MARK: - Make Frame
extension IndividualProperty.TopLeftHeight {
private func makeFrame(topLeft: Point, height: Float, width: Float) -> Rect {
let x = topLeft.x
let y = topLeft.y
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Width
extension IndividualProperty.TopLeftHeight: LayoutPropertyCanStoreWidthToEvaluateFrameType {
public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let topLeft = self.topLeft.evaluated(from: parameters)
let height = self.height.evaluated(from: parameters, withTheOtherAxis: .width(0))
let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height))
return self.makeFrame(topLeft: topLeft, height: height, width: width)
}
}
| 6aaea5ef8047d8b0303e44535ecc44f6 | 21.307692 | 115 | 0.721552 | false | false | false | false |
arjunkchr/TrackStock | refs/heads/master | Pods/CSwiftV/CSwiftV/CSwiftV.swift | mit | 1 | //
// CSwiftV.swift
// CSwiftV
//
// Created by Daniel Haight on 30/08/2014.
// Copyright (c) 2014 ManyThings. All rights reserved.
//
import Foundation
//TODO: make these prettier and probably not extensions
public extension String {
func splitOnNewLine () -> ([String]) {
return self.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
}
}
//MARK: Parser
public class CSwiftV {
public let columnCount: Int
public let headers : [String]
public let keyedRows: [[String : String]]?
public let rows: [[String]]
public init(String string: String, headers:[String]?, separator:String) {
let lines : [String] = includeQuotedStringInFields(Fields:string.splitOnNewLine().filter{(includeElement: String) -> Bool in
return !includeElement.isEmpty;
} , quotedString: "\r\n")
var parsedLines = lines.map{
(transform: String) -> [String] in
let commaSanitized = includeQuotedStringInFields(Fields: transform.componentsSeparatedByString(separator) , quotedString: separator)
.map
{
(input: String) -> String in
return sanitizedStringMap(String: input)
}
.map
{
(input: String) -> String in
return input.stringByReplacingOccurrencesOfString("\"\"", withString: "\"", options: NSStringCompareOptions.LiteralSearch)
}
return commaSanitized;
}
let tempHeaders : [String]
if let unwrappedHeaders = headers {
tempHeaders = unwrappedHeaders
}
else {
tempHeaders = parsedLines[0]
parsedLines.removeAtIndex(0)
}
self.rows = parsedLines
self.columnCount = tempHeaders.count
let keysAndRows = self.rows.map { (field :[String]) -> [String:String] in
var row = [String:String]()
for (index, value) in field.enumerate() {
row[tempHeaders[index]] = value
}
return row
}
self.keyedRows = keysAndRows
self.headers = tempHeaders
}
//TODO: Document that this assumes header string
public convenience init(String string: String) {
self.init(String: string, headers:nil, separator:",")
}
public convenience init(String string: String, separator:String) {
self.init(String: string, headers:nil, separator:separator)
}
public convenience init(String string: String, headers:[String]?) {
self.init(String: string, headers:headers, separator:",")
}
}
//MARK: Helpers
func includeQuotedStringInFields(Fields fields: [String], quotedString :String) -> [String] {
var mergedField = ""
var newArray = [String]()
for field in fields {
mergedField += field
if (mergedField.componentsSeparatedByString("\"").count%2 != 1) {
mergedField += quotedString
continue
}
newArray.append(mergedField);
mergedField = ""
}
return newArray;
}
func sanitizedStringMap(String string :String) -> String {
let _ : String = "\""
let startsWithQuote: Bool = string.hasPrefix("\"");
let endsWithQuote: Bool = string.hasSuffix("\"");
if (startsWithQuote && endsWithQuote) {
let startIndex = string.startIndex.advancedBy(1)
let endIndex = string.endIndex.advancedBy(-1)
let range = startIndex ..< endIndex
let sanitizedField: String = string.substringWithRange(range)
return sanitizedField
}
else {
return string;
}
}
| f85f304b5f03265518f48333932e6ab9 | 27.703704 | 144 | 0.578581 | false | false | false | false |
bigL055/Routable | refs/heads/master | Example/Pods/SPKit/Sources/Foundation/String+UIKit.swift | mit | 1 | //
// SPKit
//
// Copyright (c) 2017 linhay - https://github.com/linhay
//
// 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
import UIKit
// MARK: - 文本区域
public extension String{
/// 获取字符串的Bounds
///
/// - Parameters:
/// - font: 字体大小
/// - size: 字符串长宽限制
/// - Returns: 字符串的Bounds
public func bounds(font: UIFont,size: CGSize) -> CGRect {
if self.isEmpty { return CGRect.zero }
let attributes = [NSAttributedStringKey.font: font]
let option = NSStringDrawingOptions.usesLineFragmentOrigin
let rect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil)
return rect
}
/// 获取字符串的Bounds
///
/// - parameter font: 字体大小
/// - parameter size: 字符串长宽限制
/// - parameter margins: 头尾间距
/// - parameter space: 内部间距
///
/// - returns: 字符串的Bounds
public func size(with font: UIFont,
size: CGSize,
margins: CGFloat = 0,
space: CGFloat = 0) -> CGSize {
if self.isEmpty { return CGSize.zero }
var bound = self.bounds(font: font, size: size)
let rows = self.rows(font: font, width: size.width)
bound.size.height += margins * 2
bound.size.height += space * (rows - 1)
return bound.size
}
/// 文本行数
///
/// - Parameters:
/// - font: 字体
/// - width: 最大宽度
/// - Returns: 行数
public func rows(font: UIFont,width: CGFloat) -> CGFloat {
if self.isEmpty { return 0 }
// 获取单行时候的内容的size
let singleSize = (self as NSString).size(withAttributes: [NSAttributedStringKey.font:font])
// 获取多行时候,文字的size
let textSize = self.bounds(font: font, size: CGSize(width: width, height: CGFloat(MAXFLOAT))).size
// 返回计算的行数
return ceil(textSize.height / singleSize.height);
}
}
| 5a6d363c9d505214dd613283d41e521d | 34.443038 | 102 | 0.668929 | false | false | false | false |
TheBrewery/Hikes | refs/heads/master | WorldHeritage/Extensions/UIFont+Ionic.swift | mit | 1 | import Foundation
import UIKit
extension UIFont {
class func ionicFontOfSize(fontSize: CGFloat) -> UIFont {
return UIFont(name: "ionicons", size: fontSize)!
}
}
public let IonicDictionary: [String: String] = [
"ion-android-color-palette": "\u{f37b}",
"ion-android-bus": "\u{f36d}",
"ion-heart-broken": "\u{f31d}",
"ion-android-home": "\u{f38f}",
"ion-social-youtube": "\u{f24d}",
"ion-ios-lightbulb-outline": "\u{f451}",
"ion-ios-recording": "\u{f497}",
"ion-arrow-right-c": "\u{f10b}",
"ion-ios-color-wand": "\u{f416}",
"ion-log-in": "\u{f29e}",
"ion-android-compass": "\u{f37c}",
"ion-ios-close-empty": "\u{f404}",
"ion-ios-help": "\u{f446}",
"ion-social-python": "\u{f4e9}",
"ion-social-vimeo-outline": "\u{f244}",
"ion-social-whatsapp-outline": "\u{f4ef}",
"ion-social-yahoo": "\u{f24b}",
"ion-spoon": "\u{f2b4}",
"ion-waterdrop": "\u{f25b}",
"ion-trophy": "\u{f356}",
"ion-alert-circled": "\u{f100}",
"ion-ios-rewind": "\u{f4a1}",
"ion-social-designernews-outline": "\u{f22a}",
"ion-ios-calculator": "\u{f3f2}",
"ion-chevron-up": "\u{f126}",
"ion-android-laptop": "\u{f390}",
"ion-play": "\u{f215}",
"ion-funnel": "\u{f31b}",
"ion-ios-skipforward-outline": "\u{f4ac}",
"ion-ios-unlocked": "\u{f4c9}",
"ion-home": "\u{f144}",
"ion-ios-undo-outline": "\u{f4c6}",
"ion-ios-arrow-thin-right": "\u{f3d6}",
"ion-ios-glasses-outline": "\u{f43e}",
"ion-help-circled": "\u{f142}",
"ion-ios-barcode": "\u{f3dc}",
"ion-ios-keypad": "\u{f450}",
"ion-outlet": "\u{f342}",
"ion-earth": "\u{f276}",
"ion-checkmark-round": "\u{f121}",
"ion-ios-photos-outline": "\u{f481}",
"ion-ios-stopwatch": "\u{f4b5}",
"ion-android-happy": "\u{f38e}",
"ion-icecream": "\u{f27d}",
"ion-ios-plus": "\u{f48b}",
"ion-social-codepen": "\u{f4dd}",
"ion-volume-high": "\u{f257}",
"ion-android-done": "\u{f383}",
"ion-android-drafts": "\u{f384}",
"ion-ios-monitor-outline": "\u{f465}",
"ion-ios-paper-outline": "\u{f471}",
"ion-ios-arrow-thin-up": "\u{f3d7}",
"ion-thermometer": "\u{f2b6}",
"ion-ios-flame": "\u{f42f}",
"ion-ios-person-outline": "\u{f47d}",
"ion-android-contacts": "\u{f2d9}",
"ion-android-checkbox-blank": "\u{f371}",
"ion-ios-sunny-outline": "\u{f4b6}",
"ion-cloud": "\u{f12b}",
"ion-ios-thunderstorm-outline": "\u{f4bc}",
"ion-ios-wineglass-outline": "\u{f4d0}",
"ion-social-nodejs": "\u{f4e7}",
"ion-eject": "\u{f131}",
"ion-ios-list-outline": "\u{f453}",
"ion-social-wordpress-outline": "\u{f248}",
"ion-android-cloud-circle": "\u{f377}",
"ion-ios-flower": "\u{f433}",
"ion-social-google-outline": "\u{f34e}",
"ion-ios-partlysunny": "\u{f476}",
"ion-arrow-move": "\u{f263}",
"ion-ios-analytics-outline": "\u{f3cd}",
"ion-android-arrow-dropup": "\u{f365}",
"ion-image": "\u{f147}",
"ion-load-d": "\u{f29d}",
"ion-arrow-up-b": "\u{f10d}",
"ion-plus-circled": "\u{f216}",
"ion-ios-shuffle-strong": "\u{f4a8}",
"ion-ios-trash-outline": "\u{f4c4}",
"ion-ios-volume-low": "\u{f4cf}",
"ion-ios-arrow-right": "\u{f3d3}",
"ion-podium": "\u{f344}",
"ion-ios-undo": "\u{f4c7}",
"ion-pound": "\u{f219}",
"ion-chatbubble-working": "\u{f11d}",
"ion-ios-football-outline": "\u{f436}",
"ion-android-remove-circle": "\u{f3a9}",
"ion-ios-crop-strong": "\u{f41d}",
"ion-ios-lightbulb": "\u{f452}",
"ion-ios-medical": "\u{f45c}",
"ion-ios-albums-outline": "\u{f3c9}",
"ion-android-checkbox-outline-blank": "\u{f372}",
"ion-ios-locked-outline": "\u{f457}",
"ion-ios-minus-outline": "\u{f463}",
"ion-ios-plus-empty": "\u{f489}",
"ion-plus-round": "\u{f217}",
"ion-email-unread": "\u{f3c3}",
"ion-pricetag": "\u{f2aa}",
"ion-social-skype": "\u{f23f}",
"ion-social-tux": "\u{f2c5}",
"ion-ios-home-outline": "\u{f447}",
"ion-speedometer": "\u{f2b3}",
"ion-umbrella": "\u{f2b7}",
"ion-ios-upload": "\u{f4cb}",
"ion-backspace": "\u{f3bf}",
"ion-checkmark-circled": "\u{f120}",
"ion-ios-mic": "\u{f461}",
"ion-ios-pulse": "\u{f493}",
"ion-music-note": "\u{f20c}",
"ion-android-bicycle": "\u{f369}",
"ion-document": "\u{f12f}",
"ion-woman": "\u{f25d}",
"ion-female": "\u{f278}",
"ion-card": "\u{f119}",
"ion-android-lock": "\u{f392}",
"ion-ios-time-outline": "\u{f4be}",
"ion-social-dribbble": "\u{f22d}",
"ion-ionic": "\u{f14b}",
"ion-ios-alarm": "\u{f3c8}",
"ion-android-plane": "\u{f3a4}",
"ion-ios-grid-view": "\u{f441}",
"ion-ios-photos": "\u{f482}",
"ion-android-person": "\u{f3a0}",
"ion-social-javascript": "\u{f4e5}",
"ion-ios-infinite-outline": "\u{f449}",
"ion-ios-pint": "\u{f486}",
"ion-social-github-outline": "\u{f232}",
"ion-medkit": "\u{f2a2}",
"ion-pinpoint": "\u{f2a7}",
"ion-social-euro-outline": "\u{f4e0}",
"ion-android-phone-landscape": "\u{f3a1}",
"ion-person": "\u{f213}",
"ion-ios-partlysunny-outline": "\u{f475}",
"ion-leaf": "\u{f1fd}",
"ion-ios-flower-outline": "\u{f432}",
"ion-android-playstore": "\u{f2f0}",
"ion-ios-book-outline": "\u{f3e7}",
"ion-social-buffer": "\u{f229}",
"ion-bluetooth": "\u{f116}",
"ion-ios-more": "\u{f46a}",
"ion-beaker": "\u{f269}",
"ion-heart": "\u{f141}",
"ion-ios-checkmark-outline": "\u{f3fe}",
"ion-android-stopwatch": "\u{f2fd}",
"ion-android-options": "\u{f39d}",
"ion-bookmark": "\u{f26b}",
"ion-quote": "\u{f347}",
"ion-paper-airplane": "\u{f2c3}",
"ion-asterisk": "\u{f314}",
"ion-ios-clock-outline": "\u{f402}",
"ion-ios-flag-outline": "\u{f42c}",
"ion-calendar": "\u{f117}",
"ion-ios-minus": "\u{f464}",
"ion-social-dropbox-outline": "\u{f22e}",
"ion-social-foursquare-outline": "\u{f34c}",
"ion-arrow-swap": "\u{f268}",
"ion-android-arrow-dropdown-circle": "\u{f35e}",
"ion-android-add-circle": "\u{f359}",
"ion-arrow-graph-up-left": "\u{f261}",
"ion-ios-cog-outline": "\u{f411}",
"ion-paperclip": "\u{f20f}",
"ion-android-bar": "\u{f368}",
"ion-erlenmeyer-flask-bubbles": "\u{f3c4}",
"ion-flash": "\u{f137}",
"ion-clock": "\u{f26e}",
"ion-ios-calendar-outline": "\u{f3f3}",
"ion-ios-nutrition-outline": "\u{f46f}",
"ion-ios-play-outline": "\u{f487}",
"ion-ios-skipforward": "\u{f4ad}",
"ion-pricetags": "\u{f2ab}",
"ion-android-unlock": "\u{f3b5}",
"ion-android-arrow-back": "\u{f2ca}",
"ion-camera": "\u{f118}",
"ion-social-angular": "\u{f4d9}",
"ion-social-twitter-outline": "\u{f242}",
"ion-unlocked": "\u{f254}",
"ion-ios-eye": "\u{f425}",
"ion-navicon-round": "\u{f20d}",
"ion-easel": "\u{f3c2}",
"ion-ios-paper": "\u{f472}",
"ion-ios-reload": "\u{f49d}",
"ion-android-apps": "\u{f35c}",
"ion-social-apple-outline": "\u{f226}",
"ion-ios-cloud-download-outline": "\u{f407}",
"ion-social-dribbble-outline": "\u{f22c}",
"ion-ios-americanfootball-outline": "\u{f3cb}",
"ion-arrow-left-a": "\u{f106}",
"ion-code-working": "\u{f270}",
"ion-ios-cloud-upload": "\u{f40b}",
"ion-ios-bookmarks-outline": "\u{f3e9}",
"ion-wineglass": "\u{f2b9}",
"ion-ios-location-outline": "\u{f455}",
"ion-bowtie": "\u{f3c0}",
"ion-social-css3-outline": "\u{f4de}",
"ion-compass": "\u{f273}",
"ion-wand": "\u{f358}",
"ion-disc": "\u{f12d}",
"ion-ios-filing-outline": "\u{f428}",
"ion-toggle-filled": "\u{f354}",
"ion-social-whatsapp": "\u{f4f0}",
"ion-android-send": "\u{f2f6}",
"ion-reply": "\u{f21e}",
"ion-folder": "\u{f139}",
"ion-android-settings": "\u{f2f7}",
"ion-ios-baseball-outline": "\u{f3dd}",
"ion-ios-medical-outline": "\u{f45b}",
"ion-skip-forward": "\u{f223}",
"ion-android-arrow-dropright-circle": "\u{f362}",
"ion-ios-calculator-outline": "\u{f3f1}",
"ion-close": "\u{f12a}",
"ion-ios-nutrition": "\u{f470}",
"ion-ios-information-empty": "\u{f44b}",
"ion-arrow-up-a": "\u{f10c}",
"ion-android-add": "\u{f2c7}",
"ion-ios-personadd-outline": "\u{f47f}",
"ion-ios-search-strong": "\u{f4a4}",
"ion-map": "\u{f203}",
"ion-model-s": "\u{f2c1}",
"ion-person-stalker": "\u{f212}",
"ion-ios-color-filter-outline": "\u{f413}",
"ion-android-sunny": "\u{f3b0}",
"ion-android-archive": "\u{f2c9}",
"ion-chevron-left": "\u{f124}",
"ion-android-cancel": "\u{f36e}",
"ion-ios-film-outline": "\u{f42a}",
"ion-ios-redo-outline": "\u{f498}",
"ion-ios-paperplane-outline": "\u{f473}",
"ion-refresh": "\u{f21c}",
"ion-ios-pie": "\u{f484}",
"ion-eye": "\u{f133}",
"ion-android-navigate": "\u{f398}",
"ion-android-delete": "\u{f37f}",
"ion-ios-trash": "\u{f4c5}",
"ion-arrow-right-a": "\u{f109}",
"ion-ios-checkmark": "\u{f3ff}",
"ion-ios-cloud-outline": "\u{f409}",
"ion-checkmark": "\u{f122}",
"ion-android-checkmark-circle": "\u{f375}",
"ion-android-upload": "\u{f3b6}",
"ion-chatbubble": "\u{f11e}",
"ion-briefcase": "\u{f26c}",
"ion-erlenmeyer-flask": "\u{f3c5}",
"ion-android-arrow-forward": "\u{f30f}",
"ion-hammer": "\u{f27b}",
"ion-at": "\u{f10f}",
"ion-ios-bolt": "\u{f3e6}",
"ion-android-arrow-dropdown": "\u{f35f}",
"ion-ios-browsers-outline": "\u{f3ef}",
"ion-ios-calendar": "\u{f3f4}",
"ion-battery-empty": "\u{f112}",
"ion-ios-play": "\u{f488}",
"ion-ios-skipbackward-outline": "\u{f4aa}",
"ion-ios-tennisball": "\u{f4bb}",
"ion-minus": "\u{f209}",
"ion-mouse": "\u{f340}",
"ion-network": "\u{f341}",
"ion-person-add": "\u{f211}",
"ion-social-designernews": "\u{f22b}",
"ion-social-foursquare": "\u{f34d}",
"ion-social-linkedin-outline": "\u{f238}",
"ion-load-a": "\u{f29a}",
"ion-social-yahoo-outline": "\u{f24a}",
"ion-usb": "\u{f2b8}",
"ion-ios-medkit": "\u{f45e}",
"ion-log-out": "\u{f29f}",
"ion-ios-grid-view-outline": "\u{f440}",
"ion-android-desktop": "\u{f380}",
"ion-scissors": "\u{f34b}",
"ion-social-rss-outline": "\u{f23c}",
"ion-android-document": "\u{f381}",
"ion-social-rss": "\u{f23d}",
"ion-android-star-half": "\u{f3ad}",
"ion-soup-can-outline": "\u{f4f3}",
"ion-arrow-shrink": "\u{f267}",
"ion-ios-information-outline": "\u{f44c}",
"ion-key": "\u{f296}",
"ion-android-hangout": "\u{f38d}",
"ion-ios-contact-outline": "\u{f419}",
"ion-coffee": "\u{f272}",
"ion-closed-captioning": "\u{f317}",
"ion-social-reddit-outline": "\u{f23a}",
"ion-university": "\u{f357}",
"ion-ios-barcode-outline": "\u{f3db}",
"ion-backspace-outline": "\u{f3be}",
"ion-ios-pricetags": "\u{f48f}",
"ion-ios-shuffle": "\u{f4a9}",
"ion-lock-combination": "\u{f4d4}",
"ion-android-call": "\u{f2d2}",
"ion-android-contract": "\u{f37d}",
"ion-ios-arrow-forward": "\u{f3d1}",
"ion-ios-arrow-left": "\u{f3d2}",
"ion-social-chrome-outline": "\u{f4da}",
"ion-social-twitch": "\u{f4ee}",
"ion-volume-medium": "\u{f259}",
"ion-ios-pint-outline": "\u{f485}",
"ion-social-bitcoin-outline": "\u{f2ae}",
"ion-happy-outline": "\u{f3c6}",
"ion-ios-moon-outline": "\u{f467}",
"ion-arrow-right-b": "\u{f10a}",
"ion-ios-color-wand-outline": "\u{f415}",
"ion-android-warning": "\u{f3bc}",
"ion-minus-circled": "\u{f207}",
"ion-merge": "\u{f33f}",
"ion-stats-bars": "\u{f2b5}",
"ion-wrench": "\u{f2ba}",
"ion-android-cloud": "\u{f37a}",
"ion-ios-chatbubble-outline": "\u{f3fb}",
"ion-power": "\u{f2a9}",
"ion-android-car": "\u{f36f}",
"ion-ios-pie-outline": "\u{f483}",
"ion-ios-camera": "\u{f3f6}",
"ion-ios-loop-strong": "\u{f459}",
"ion-images": "\u{f148}",
"ion-android-arrow-dropleft-circle": "\u{f360}",
"ion-ios-star": "\u{f4b3}",
"ion-ios-pricetags-outline": "\u{f48e}",
"ion-ios-alarm-outline": "\u{f3c7}",
"ion-toggle": "\u{f355}",
"ion-social-freebsd-devil": "\u{f2c4}",
"ion-ios-loop": "\u{f45a}",
"ion-ios-moon": "\u{f468}",
"ion-android-remove": "\u{f2f4}",
"ion-code": "\u{f271}",
"ion-ios-cart-outline": "\u{f3f7}",
"ion-ios-reverse-camera": "\u{f49f}",
"ion-locked": "\u{f200}",
"ion-paintbrush": "\u{f4d5}",
"ion-thumbsup": "\u{f251}",
"ion-trash-b": "\u{f253}",
"ion-navicon": "\u{f20e}",
"ion-android-microphone": "\u{f2ec}",
"ion-android-people": "\u{f39e}",
"ion-social-hackernews": "\u{f237}",
"ion-ios-cloudy-night-outline": "\u{f40d}",
"ion-ios-game-controller-a-outline": "\u{f438}",
"ion-ios-chatboxes": "\u{f3fa}",
"ion-ios-circle-filled": "\u{f400}",
"ion-ios-infinite": "\u{f44a}",
"ion-android-restaurant": "\u{f3aa}",
"ion-ios-paw": "\u{f47a}",
"ion-ios-chatboxes-outline": "\u{f3f9}",
"ion-ios-email-outline": "\u{f422}",
"ion-ribbon-a": "\u{f348}",
"ion-ios-cloud-download": "\u{f408}",
"ion-ios-help-outline": "\u{f445}",
"ion-android-expand": "\u{f386}",
"ion-ios-chatbubble": "\u{f3fc}",
"ion-ios-location": "\u{f456}",
"ion-ios-thunderstorm": "\u{f4bd}",
"ion-man": "\u{f202}",
"ion-ios-game-controller-a": "\u{f439}",
"ion-android-done-all": "\u{f382}",
"ion-ios-search": "\u{f4a5}",
"ion-android-boat": "\u{f36a}",
"ion-android-bulb": "\u{f36c}",
"ion-android-textsms": "\u{f3b2}",
"ion-ios-americanfootball": "\u{f3cc}",
"ion-reply-all": "\u{f21d}",
"ion-social-angular-outline": "\u{f4d8}",
"ion-ios-sunny": "\u{f4b7}",
"ion-android-clipboard": "\u{f376}",
"ion-android-create": "\u{f37e}",
"ion-ios-more-outline": "\u{f469}",
"ion-minus-round": "\u{f208}",
"ion-ios-keypad-outline": "\u{f44f}",
"ion-social-instagram": "\u{f351}",
"ion-ios-fastforward": "\u{f427}",
"ion-android-microphone-off": "\u{f395}",
"ion-stop": "\u{f24f}",
"ion-android-sync": "\u{f3b1}",
"ion-ios-paperplane": "\u{f474}",
"ion-android-star": "\u{f2fc}",
"ion-android-globe": "\u{f38c}",
"ion-ios-plus-outline": "\u{f48a}",
"ion-monitor": "\u{f20a}",
"ion-ios-wineglass": "\u{f4d1}",
"ion-nuclear": "\u{f2a4}",
"ion-radio-waves": "\u{f2ac}",
"ion-settings": "\u{f2ad}",
"ion-share": "\u{f220}",
"ion-ios-analytics": "\u{f3ce}",
"ion-mic-c": "\u{f206}",
"ion-paintbucket": "\u{f4d6}",
"ion-android-cloud-done": "\u{f378}",
"ion-ios-bolt-outline": "\u{f3e5}",
"ion-shuffle": "\u{f221}",
"ion-ios-minus-empty": "\u{f462}",
"ion-social-euro": "\u{f4e1}",
"ion-social-instagram-outline": "\u{f350}",
"ion-ios-filing": "\u{f429}",
"ion-search": "\u{f21f}",
"ion-social-markdown": "\u{f4e6}",
"ion-social-octocat": "\u{f4e8}",
"ion-star": "\u{f24e}",
"ion-ios-recording-outline": "\u{f496}",
"ion-cash": "\u{f316}",
"ion-social-reddit": "\u{f23b}",
"ion-contrast": "\u{f275}",
"ion-android-list": "\u{f391}",
"ion-volume-low": "\u{f258}",
"ion-android-radio-button-off": "\u{f3a6}",
"ion-social-android-outline": "\u{f224}",
"ion-knife": "\u{f297}",
"ion-ios-game-controller-b": "\u{f43b}",
"ion-ios-pulse-strong": "\u{f492}",
"ion-android-locate": "\u{f2e9}",
"ion-upload": "\u{f255}",
"ion-ios-musical-notes": "\u{f46c}",
"ion-ios-redo": "\u{f499}",
"ion-location": "\u{f1ff}",
"ion-information": "\u{f14a}",
"ion-android-volume-off": "\u{f3b9}",
"ion-ios-cog": "\u{f412}",
"ion-ios-musical-note": "\u{f46b}",
"ion-arrow-return-right": "\u{f266}",
"ion-link": "\u{f1fe}",
"ion-social-css3": "\u{f4df}",
"ion-fork": "\u{f27a}",
"ion-ios-folder": "\u{f435}",
"ion-ios-list": "\u{f454}",
"ion-ios-circle-outline": "\u{f401}",
"ion-ios-camera-outline": "\u{f3f5}",
"ion-android-volume-down": "\u{f3b7}",
"ion-ios-gear-outline": "\u{f43c}",
"ion-close-round": "\u{f129}",
"ion-ios-unlocked-outline": "\u{f4c8}",
"ion-android-download": "\u{f2dd}",
"ion-help-buoy": "\u{f27c}",
"ion-ios-drag": "\u{f421}",
"ion-ios-box-outline": "\u{f3eb}",
"ion-social-googleplus": "\u{f235}",
"ion-social-snapchat-outline": "\u{f4eb}",
"ion-android-exit": "\u{f385}",
"ion-android-image": "\u{f2e4}",
"ion-code-download": "\u{f26f}",
"ion-ios-download-outline": "\u{f41f}",
"ion-android-search": "\u{f2f5}",
"ion-mic-a": "\u{f204}",
"ion-social-buffer-outline": "\u{f228}",
"ion-ios-book": "\u{f3e8}",
"ion-aperture": "\u{f313}",
"ion-flag": "\u{f279}",
"ion-ios-telephone": "\u{f4b9}",
"ion-navigate": "\u{f2a3}",
"ion-ios-compose-outline": "\u{f417}",
"ion-ios-flask-outline": "\u{f430}",
"ion-android-film": "\u{f389}",
"ion-arrow-left-c": "\u{f108}",
"ion-ios-contact": "\u{f41a}",
"ion-connection-bars": "\u{f274}",
"ion-ios-heart-outline": "\u{f442}",
"ion-ios-ionic-outline": "\u{f44e}",
"ion-ios-refresh-outline": "\u{f49b}",
"ion-xbox": "\u{f30c}",
"ion-steam": "\u{f30b}",
"ion-ios-pricetag-outline": "\u{f48c}",
"ion-ios-rose-outline": "\u{f4a2}",
"ion-android-favorite": "\u{f388}",
"ion-social-usd-outline": "\u{f352}",
"ion-email": "\u{f132}",
"ion-ios-printer": "\u{f491}",
"ion-chevron-down": "\u{f123}",
"ion-ios-world": "\u{f4d3}",
"ion-record": "\u{f21b}",
"ion-android-phone-portrait": "\u{f3a2}",
"ion-android-arrow-dropup-circle": "\u{f364}",
"ion-information-circled": "\u{f149}",
"ion-ios-heart": "\u{f443}",
"ion-flash-off": "\u{f136}",
"ion-ios-locked": "\u{f458}",
"ion-calculator": "\u{f26d}",
"ion-ios-rainy": "\u{f495}",
"ion-ios-toggle": "\u{f4c3}",
"ion-magnet": "\u{f2a0}",
"ion-ios-arrow-up": "\u{f3d8}",
"ion-android-hand": "\u{f2e3}",
"ion-android-camera": "\u{f2d3}",
"ion-android-notifications-none": "\u{f399}",
"ion-bonfire": "\u{f315}",
"ion-ios-basketball-outline": "\u{f3df}",
"ion-ios-mic-outline": "\u{f460}",
"ion-android-volume-up": "\u{f3ba}",
"ion-ios-navigate": "\u{f46e}",
"ion-ios-cloudy-night": "\u{f40e}",
"ion-cube": "\u{f318}",
"ion-forward": "\u{f13a}",
"ion-ios-pricetag": "\u{f48d}",
"ion-ios-timer-outline": "\u{f4c0}",
"ion-social-chrome": "\u{f4db}",
"ion-social-snapchat": "\u{f4ec}",
"ion-social-tumblr": "\u{f241}",
"ion-android-arrow-dropright": "\u{f363}",
"ion-ios-time": "\u{f4bf}",
"ion-social-tumblr-outline": "\u{f240}",
"ion-videocamera": "\u{f256}",
"ion-android-chat": "\u{f2d4}",
"ion-social-hackernews-outline": "\u{f236}",
"ion-ios-arrow-thin-left": "\u{f3d5}",
"ion-social-sass": "\u{f4ea}",
"ion-skip-backward": "\u{f222}",
"ion-ios-refresh": "\u{f49c}",
"ion-film-marker": "\u{f135}",
"ion-ios-settings": "\u{f4a7}",
"ion-trash-a": "\u{f252}",
"ion-ios-cloud-upload-outline": "\u{f40a}",
"ion-ios-information": "\u{f44d}",
"ion-ios-people-outline": "\u{f47b}",
"ion-load-b": "\u{f29b}",
"ion-ios-person": "\u{f47e}",
"ion-social-linkedin": "\u{f239}",
"ion-ios-compose": "\u{f418}",
"ion-speakerphone": "\u{f2b2}",
"ion-pie-graph": "\u{f2a5}",
"ion-ios-speedometer": "\u{f4b0}",
"ion-drag": "\u{f130}",
"ion-ios-mic-off": "\u{f45f}",
"ion-social-usd": "\u{f353}",
"ion-android-refresh": "\u{f3a8}",
"ion-ios-briefcase": "\u{f3ee}",
"ion-ios-help-empty": "\u{f444}",
"ion-crop": "\u{f3c1}",
"ion-ios-albums": "\u{f3ca}",
"ion-battery-charging": "\u{f111}",
"ion-android-arrow-dropleft": "\u{f361}",
"ion-android-favorite-outline": "\u{f387}",
"ion-social-bitcoin": "\u{f2af}",
"ion-ios-arrow-down": "\u{f3d0}",
"ion-chatbox": "\u{f11b}",
"ion-ios-cloudy-outline": "\u{f40f}",
"ion-planet": "\u{f343}",
"ion-android-notifications-off": "\u{f39a}",
"ion-social-facebook": "\u{f231}",
"ion-social-google": "\u{f34f}",
"ion-ios-clock": "\u{f403}",
"ion-battery-low": "\u{f115}",
"ion-sad-outline": "\u{f4d7}",
"ion-ios-fastforward-outline": "\u{f426}",
"ion-ipad": "\u{f1f9}",
"ion-lightbulb": "\u{f299}",
"ion-transgender": "\u{f4f5}",
"ion-social-windows-outline": "\u{f246}",
"ion-document-text": "\u{f12e}",
"ion-soup-can": "\u{f4f4}",
"ion-battery-full": "\u{f113}",
"ion-android-train": "\u{f3b4}",
"ion-android-mail": "\u{f2eb}",
"ion-arrow-graph-up-right": "\u{f262}",
"ion-laptop": "\u{f1fc}",
"ion-pull-request": "\u{f345}",
"ion-fireball": "\u{f319}",
"ion-ios-folder-outline": "\u{f434}",
"ion-ipod": "\u{f1fb}",
"ion-ios-videocam-outline": "\u{f4cc}",
"ion-ios-at-outline": "\u{f3d9}",
"ion-gear-a": "\u{f13d}",
"ion-headphone": "\u{f140}",
"ion-social-html5-outline": "\u{f4e2}",
"ion-arrow-left-b": "\u{f107}",
"ion-pin": "\u{f2a6}",
"ion-ios-briefcase-outline": "\u{f3ed}",
"ion-android-folder-open": "\u{f38a}",
"ion-social-yen": "\u{f4f2}",
"ion-social-pinterest": "\u{f2b1}",
"ion-arrow-expand": "\u{f25e}",
"ion-arrow-graph-down-right": "\u{f260}",
"ion-ios-people": "\u{f47c}",
"ion-ios-box": "\u{f3ec}",
"ion-ios-printer-outline": "\u{f490}",
"ion-social-facebook-outline": "\u{f230}",
"ion-more": "\u{f20b}",
"ion-social-windows": "\u{f247}",
"ion-ios-rose": "\u{f4a3}",
"ion-ios-bell": "\u{f3e2}",
"ion-android-print": "\u{f3a5}",
"ion-ios-bookmarks": "\u{f3ea}",
"ion-android-bookmark": "\u{f36b}",
"ion-ios-football": "\u{f437}",
"ion-ios-speedometer-outline": "\u{f4af}",
"ion-load-c": "\u{f29c}",
"ion-ios-color-filter": "\u{f414}",
"ion-sad": "\u{f34a}",
"ion-ios-game-controller-b-outline": "\u{f43a}",
"ion-filing": "\u{f134}",
"ion-ios-arrow-back": "\u{f3cf}",
"ion-ios-star-outline": "\u{f4b2}",
"ion-ios-volume-high": "\u{f4ce}",
"ion-ios-browsers": "\u{f3f0}",
"ion-egg": "\u{f277}",
"ion-chatbubbles": "\u{f11f}",
"ion-ios-flag": "\u{f42d}",
"ion-ios-snowy": "\u{f4ae}",
"ion-chevron-right": "\u{f125}",
"ion-android-pin": "\u{f3a3}",
"ion-compose": "\u{f12c}",
"ion-arrow-return-left": "\u{f265}",
"ion-ios-at": "\u{f3da}",
"ion-social-github": "\u{f233}",
"ion-social-yen-outline": "\u{f4f1}",
"ion-ios-baseball": "\u{f3de}",
"ion-android-walk": "\u{f3bb}",
"ion-ios-rainy-outline": "\u{f494}",
"ion-volume-mute": "\u{f25a}",
"ion-ios-arrow-thin-down": "\u{f3d4}",
"ion-android-person-add": "\u{f39f}",
"ion-android-alarm-clock": "\u{f35a}",
"ion-android-share": "\u{f2f8}",
"ion-android-notifications": "\u{f39b}",
"ion-battery-half": "\u{f114}",
"ion-ios-flask": "\u{f431}",
"ion-android-calendar": "\u{f2d1}",
"ion-ios-cloudy": "\u{f410}",
"ion-ios-download": "\u{f420}",
"ion-no-smoking": "\u{f2c2}",
"ion-ios-close": "\u{f406}",
"ion-android-contact": "\u{f2d8}",
"ion-ios-medkit-outline": "\u{f45d}",
"ion-ios-gear": "\u{f43d}",
"ion-android-open": "\u{f39c}",
"ion-arrow-down-b": "\u{f104}",
"ion-ios-checkmark-empty": "\u{f3fd}",
"ion-ios-reverse-camera-outline": "\u{f49e}",
"ion-ios-telephone-outline": "\u{f4b8}",
"ion-plus": "\u{f218}",
"ion-android-close": "\u{f2d7}",
"ion-social-pinterest-outline": "\u{f2b0}",
"ion-ios-pause-outline": "\u{f477}",
"ion-social-javascript-outline": "\u{f4e4}",
"ion-tshirt": "\u{f4f7}",
"ion-ios-star-half": "\u{f4b1}",
"ion-mic-b": "\u{f205}",
"ion-happy": "\u{f31c}",
"ion-ios-cart": "\u{f3f8}",
"ion-social-android": "\u{f225}",
"ion-social-wordpress": "\u{f249}",
"ion-android-star-outline": "\u{f3ae}",
"ion-ios-timer": "\u{f4c1}",
"ion-thumbsdown": "\u{f250}",
"ion-android-alert": "\u{f35b}",
"ion-archive": "\u{f102}",
"ion-android-attach": "\u{f367}",
"ion-bug": "\u{f2be}",
"ion-grid": "\u{f13f}",
"ion-fork-repo": "\u{f2c0}",
"ion-ios-basketball": "\u{f3e0}",
"ion-ios-film": "\u{f42b}",
"ion-android-funnel": "\u{f38b}",
"ion-ios-home": "\u{f448}",
"ion-android-arrow-down": "\u{f35d}",
"ion-arrow-down-a": "\u{f103}",
"ion-ios-body-outline": "\u{f3e3}",
"ion-loop": "\u{f201}",
"ion-ios-body": "\u{f3e4}",
"ion-qr-scanner": "\u{f346}",
"ion-android-checkbox-outline": "\u{f373}",
"ion-ios-bell-outline": "\u{f3e1}",
"ion-android-cart": "\u{f370}",
"ion-social-apple": "\u{f227}",
"ion-ios-settings-strong": "\u{f4a6}",
"ion-beer": "\u{f26a}",
"ion-plane": "\u{f214}",
"ion-android-radio-button-on": "\u{f3a7}",
"ion-android-wifi": "\u{f305}",
"ion-ios-rewind-outline": "\u{f4a0}",
"ion-levels": "\u{f298}",
"ion-ribbon-b": "\u{f349}",
"ion-ios-glasses": "\u{f43f}",
"ion-social-codepen-outline": "\u{f4dc}",
"ion-android-more-horizontal": "\u{f396}",
"ion-ios-cloud": "\u{f40c}",
"ion-social-skype-outline": "\u{f23e}",
"ion-ios-copy-outline": "\u{f41b}",
"ion-ios-videocam": "\u{f4cd}",
"ion-android-folder": "\u{f2e0}",
"ion-eye-disabled": "\u{f306}",
"ion-ios-navigate-outline": "\u{f46d}",
"ion-chatboxes": "\u{f11c}",
"ion-ios-flame-outline": "\u{f42e}",
"ion-chatbox-working": "\u{f11a}",
"ion-android-menu": "\u{f394}",
"ion-ios-stopwatch-outline": "\u{f4b4}",
"ion-ios-tennisball-outline": "\u{f4ba}",
"ion-social-dropbox": "\u{f22f}",
"ion-bag": "\u{f110}",
"ion-ios-toggle-outline": "\u{f4c2}",
"ion-gear-b": "\u{f13e}",
"ion-arrow-resize": "\u{f264}",
"ion-help": "\u{f143}",
"ion-playstation": "\u{f30a}",
"ion-android-volume-mute": "\u{f3b8}",
"ion-arrow-graph-down-left": "\u{f25f}",
"ion-clipboard": "\u{f127}",
"ion-ios-copy": "\u{f41c}",
"ion-printer": "\u{f21a}",
"ion-ios-refresh-empty": "\u{f49a}",
"ion-ios-world-outline": "\u{f4d2}",
"ion-android-cloud-outline": "\u{f379}",
"ion-alert": "\u{f101}",
"ion-arrow-up-c": "\u{f10e}",
"ion-iphone": "\u{f1fa}",
"ion-ios-eye-outline": "\u{f424}",
"ion-ios-paw-outline": "\u{f479}",
"ion-pause": "\u{f210}",
"ion-wifi": "\u{f25c}",
"ion-social-twitter": "\u{f243}",
"ion-social-youtube-outline": "\u{f24c}",
"ion-android-sad": "\u{f3ab}",
"ion-male": "\u{f2a1}",
"ion-pizza": "\u{f2a8}",
"ion-ios-monitor": "\u{f466}",
"ion-ios-crop": "\u{f41e}",
"ion-ios-skipbackward": "\u{f4ab}",
"ion-social-vimeo": "\u{f245}",
"ion-android-arrow-up": "\u{f366}",
"ion-android-checkbox": "\u{f374}",
"ion-flame": "\u{f31a}",
"ion-arrow-down-c": "\u{f105}",
"ion-edit": "\u{f2bf}",
"ion-close-circled": "\u{f128}",
"ion-ios-pause": "\u{f478}",
"ion-ios-close-outline": "\u{f405}",
"ion-ios-email": "\u{f423}",
"ion-android-map": "\u{f393}",
"ion-social-html5": "\u{f4e3}",
"ion-android-watch": "\u{f3bd}",
"ion-social-googleplus-outline": "\u{f234}",
"ion-android-share-alt": "\u{f3ac}",
"ion-android-subway": "\u{f3af}",
"ion-tshirt-outline": "\u{f4f6}",
"ion-ios-personadd": "\u{f480}",
"ion-android-time": "\u{f3b3}",
"ion-jet": "\u{f295}",
"ion-android-more-vertical": "\u{f397}",
"ion-ios-upload-outline": "\u{f4ca}",
"ion-social-twitch-outline": "\u{f4ed}",
]
public enum Ionic: String {
func attributedStringWithFontSize(fontSize: CGFloat) -> NSAttributedString {
return NSAttributedString(string: self.rawValue, attributes: [NSFontAttributeName : UIFont.ionicFontOfSize(fontSize)])
}
case AndroidFolder = "\u{f2e0}"
case IosToggle = "\u{f4c3}"
case IosInfinite = "\u{f44a}"
case IosCart = "\u{f3f8}"
case AndroidPerson = "\u{f3a0}"
case AndroidMail = "\u{f2eb}"
case ChevronLeft = "\u{f124}"
case SocialEuro = "\u{f4e1}"
case AndroidLaptop = "\u{f390}"
case IosEmail = "\u{f423}"
case IosFlameOutline = "\u{f42e}"
case IosMinus = "\u{f464}"
case AndroidDoneAll = "\u{f382}"
case IosSettings = "\u{f4a7}"
case NoSmoking = "\u{f2c2}"
case Pricetags = "\u{f2ab}"
case Share = "\u{f220}"
case IosCheckmarkOutline = "\u{f3fe}"
case Briefcase = "\u{f26c}"
case SocialAndroidOutline = "\u{f224}"
case SocialDropboxOutline = "\u{f22e}"
case AndroidAdd = "\u{f2c7}"
case Calendar = "\u{f117}"
case SkipBackward = "\u{f222}"
case IosMicOutline = "\u{f460}"
case IosArrowLeft = "\u{f3d2}"
case IosArrowThinRight = "\u{f3d6}"
case IosFlame = "\u{f42f}"
case SocialTwitter = "\u{f243}"
case Pricetag = "\u{f2aa}"
case IosCompose = "\u{f418}"
case IosSkipbackwardOutline = "\u{f4aa}"
case IosTelephone = "\u{f4b9}"
case IosArrowForward = "\u{f3d1}"
case SocialPinterest = "\u{f2b1}"
case SocialAngularOutline = "\u{f4d8}"
case QrScanner = "\u{f346}"
case IosVideocamOutline = "\u{f4cc}"
case VolumeHigh = "\u{f257}"
case SoupCanOutline = "\u{f4f3}"
case AndroidColorPalette = "\u{f37b}"
case IosMedical = "\u{f45c}"
case IosLockedOutline = "\u{f457}"
case IosToggleOutline = "\u{f4c2}"
case IosVolumeLow = "\u{f4cf}"
case SocialTumblr = "\u{f241}"
case IosUndoOutline = "\u{f4c6}"
case SocialTwitchOutline = "\u{f4ed}"
case DocumentText = "\u{f12e}"
case IosUnlockedOutline = "\u{f4c8}"
case IosSearchStrong = "\u{f4a4}"
case CheckmarkRound = "\u{f121}"
case AndroidDelete = "\u{f37f}"
case SocialWhatsapp = "\u{f4f0}"
case Speedometer = "\u{f2b3}"
case Mouse = "\u{f340}"
case ArrowReturnLeft = "\u{f265}"
case IosCogOutline = "\u{f411}"
case IosCloudUploadOutline = "\u{f40a}"
case IosBox = "\u{f3ec}"
case ArrowMove = "\u{f263}"
case AndroidMap = "\u{f393}"
case IosNutrition = "\u{f470}"
case AndroidClose = "\u{f2d7}"
case AndroidMoreVertical = "\u{f397}"
case ArrowRightA = "\u{f109}"
case IosStarOutline = "\u{f4b2}"
case At = "\u{f10f}"
case IosTimerOutline = "\u{f4c0}"
case IosGameControllerBOutline = "\u{f43a}"
case Waterdrop = "\u{f25b}"
case IosBrowsersOutline = "\u{f3ef}"
case AndroidTime = "\u{f3b3}"
case IosHeartOutline = "\u{f442}"
case IosPaperplane = "\u{f474}"
case AndroidArrowBack = "\u{f2ca}"
case IosAlarm = "\u{f3c8}"
case IosPartlysunnyOutline = "\u{f475}"
case IosRainy = "\u{f495}"
case IosBody = "\u{f3e4}"
case IosShuffle = "\u{f4a9}"
case AndroidArrowDropup = "\u{f365}"
case MinusRound = "\u{f208}"
case Bug = "\u{f2be}"
case SocialWordpress = "\u{f249}"
case IosSnowy = "\u{f4ae}"
case IosFlagOutline = "\u{f42c}"
case AndroidContacts = "\u{f2d9}"
case AndroidCloud = "\u{f37a}"
case AndroidPin = "\u{f3a3}"
case AndroidWatch = "\u{f3bd}"
case AndroidShareAlt = "\u{f3ac}"
case SocialWindowsOutline = "\u{f246}"
case IosColorFilterOutline = "\u{f413}"
case IosGridView = "\u{f441}"
case Unlocked = "\u{f254}"
case AndroidList = "\u{f391}"
case AndroidMenu = "\u{f394}"
case ErlenmeyerFlask = "\u{f3c5}"
case IosGameControllerAOutline = "\u{f438}"
case IosCartOutline = "\u{f3f7}"
case IosFlower = "\u{f433}"
case IosHome = "\u{f448}"
case IosRefresh = "\u{f49c}"
case IosEmailOutline = "\u{f422}"
case Cash = "\u{f316}"
case AndroidCheckbox = "\u{f374}"
case Information = "\u{f14a}"
case Help = "\u{f143}"
case SocialAndroid = "\u{f225}"
case AndroidGlobe = "\u{f38c}"
case IosRewindOutline = "\u{f4a0}"
case Shuffle = "\u{f221}"
case Heart = "\u{f141}"
case IosAt = "\u{f3da}"
case IosGridViewOutline = "\u{f440}"
case IosLightbulb = "\u{f452}"
case AndroidBus = "\u{f36d}"
case Images = "\u{f148}"
case Bonfire = "\u{f315}"
case AndroidMicrophone = "\u{f2ec}"
case ArrowResize = "\u{f264}"
case ArrowGraphDownRight = "\u{f260}"
case AndroidCart = "\u{f370}"
case AndroidArrowDropright = "\u{f363}"
case IosPeople = "\u{f47c}"
case Card = "\u{f119}"
case Link = "\u{f1fe}"
case SocialDribbbleOutline = "\u{f22c}"
case IosAmericanfootball = "\u{f3cc}"
case AndroidOpen = "\u{f39c}"
case ForkRepo = "\u{f2c0}"
case SocialUsdOutline = "\u{f352}"
case IosChatbubble = "\u{f3fc}"
case AndroidVolumeMute = "\u{f3b8}"
case NaviconRound = "\u{f20d}"
case IosAmericanfootballOutline = "\u{f3cb}"
case PersonAdd = "\u{f211}"
case IosHomeOutline = "\u{f447}"
case ArrowShrink = "\u{f267}"
case IosFiling = "\u{f429}"
case HappyOutline = "\u{f3c6}"
case IosCameraOutline = "\u{f3f5}"
case AndroidCancel = "\u{f36e}"
case Thumbsdown = "\u{f250}"
case Tshirt = "\u{f4f7}"
case IosBaseball = "\u{f3de}"
case IosCloseOutline = "\u{f405}"
case BatteryFull = "\u{f113}"
case Edit = "\u{f2bf}"
case Plane = "\u{f214}"
case AndroidCheckmarkCircle = "\u{f375}"
case Document = "\u{f12f}"
case CheckmarkCircled = "\u{f120}"
case IosBook = "\u{f3e8}"
case IosCog = "\u{f412}"
case IosKeypadOutline = "\u{f44f}"
case IosThunderstormOutline = "\u{f4bc}"
case Record = "\u{f21b}"
case AndroidExpand = "\u{f386}"
case IosThunderstorm = "\u{f4bd}"
case Person = "\u{f213}"
case IosFastforwardOutline = "\u{f426}"
case ModelS = "\u{f2c1}"
case Headphone = "\u{f140}"
case SocialPinterestOutline = "\u{f2b0}"
case IosIonicOutline = "\u{f44e}"
case IosBellOutline = "\u{f3e1}"
case IosBasketball = "\u{f3e0}"
case IosLocked = "\u{f458}"
case IosSpeedometerOutline = "\u{f4af}"
case SocialTux = "\u{f2c5}"
case IosMusicalNotes = "\u{f46c}"
case SocialChrome = "\u{f4db}"
case IosFootball = "\u{f437}"
case IosFlowerOutline = "\u{f432}"
case IosFilingOutline = "\u{f428}"
case AndroidCall = "\u{f2d2}"
case AndroidCreate = "\u{f37e}"
case IosBookmarks = "\u{f3ea}"
case AndroidDownload = "\u{f2dd}"
case EmailUnread = "\u{f3c3}"
case IosPersonadd = "\u{f480}"
case IosContactOutline = "\u{f419}"
case AndroidPlaystore = "\u{f2f0}"
case AndroidWifi = "\u{f305}"
case Flag = "\u{f279}"
case SocialGoogleplusOutline = "\u{f234}"
case Folder = "\u{f139}"
case Plus = "\u{f218}"
case Funnel = "\u{f31b}"
case Easel = "\u{f3c2}"
case IosPlusEmpty = "\u{f489}"
case Image = "\u{f147}"
case IosBriefcase = "\u{f3ee}"
case IosUploadOutline = "\u{f4ca}"
case Map = "\u{f203}"
case IosCloudyNightOutline = "\u{f40d}"
case PlusCircled = "\u{f216}"
case SocialSkype = "\u{f23f}"
case SocialYoutube = "\u{f24d}"
case VolumeLow = "\u{f258}"
case SocialDesignernews = "\u{f22b}"
case Forward = "\u{f13a}"
case IosFlag = "\u{f42d}"
case AndroidArrowDropleft = "\u{f361}"
case IosReverseCameraOutline = "\u{f49e}"
case ArrowDownC = "\u{f105}"
case AndroidRadioButtonOff = "\u{f3a6}"
case Leaf = "\u{f1fd}"
case Power = "\u{f2a9}"
case AndroidCloudOutline = "\u{f379}"
case AndroidRemoveCircle = "\u{f3a9}"
case Magnet = "\u{f2a0}"
case IosAlbumsOutline = "\u{f3c9}"
case AndroidAlarmClock = "\u{f35a}"
case IosNavigateOutline = "\u{f46d}"
case IosStar = "\u{f4b3}"
case IosLocationOutline = "\u{f455}"
case AndroidRestaurant = "\u{f3aa}"
case MicB = "\u{f205}"
case Monitor = "\u{f20a}"
case IosUpload = "\u{f4cb}"
case Filing = "\u{f134}"
case Fork = "\u{f27a}"
case IosPaperplaneOutline = "\u{f473}"
case AndroidArchive = "\u{f2c9}"
case IosPulseStrong = "\u{f492}"
case IosTime = "\u{f4bf}"
case SocialCss3 = "\u{f4df}"
case AndroidVolumeOff = "\u{f3b9}"
case IosUndo = "\u{f4c7}"
case StatsBars = "\u{f2b5}"
case AlertCircled = "\u{f100}"
case IosKeypad = "\u{f450}"
case IosPricetags = "\u{f48f}"
case Contrast = "\u{f275}"
case AndroidPhonePortrait = "\u{f3a2}"
case Camera = "\u{f118}"
case IosFlaskOutline = "\u{f430}"
case IosRedo = "\u{f499}"
case AndroidFavoriteOutline = "\u{f387}"
case ArrowDownB = "\u{f104}"
case IosArrowThinDown = "\u{f3d4}"
case IosFolderOutline = "\u{f434}"
case IosCrop = "\u{f41e}"
case Chatbubble = "\u{f11e}"
case Beer = "\u{f26a}"
case IosMinusOutline = "\u{f463}"
case Sad = "\u{f34a}"
case IosPersonaddOutline = "\u{f47f}"
case SocialCodepen = "\u{f4dd}"
case IosPlus = "\u{f48b}"
case AndroidBar = "\u{f368}"
case Eject = "\u{f131}"
case IosFootballOutline = "\u{f436}"
case Spoon = "\u{f2b4}"
case IosPersonOutline = "\u{f47d}"
case IosMedkit = "\u{f45e}"
case Grid = "\u{f13f}"
case SocialJavascript = "\u{f4e5}"
case IosTrashOutline = "\u{f4c4}"
case IosCloudy = "\u{f410}"
case IosCloudDownloadOutline = "\u{f407}"
case IosMinusEmpty = "\u{f462}"
case IosPieOutline = "\u{f483}"
case AndroidCloudCircle = "\u{f377}"
case IosPulse = "\u{f493}"
case IosRedoOutline = "\u{f498}"
case IosArrowBack = "\u{f3cf}"
case MicA = "\u{f204}"
case IosPintOutline = "\u{f485}"
case SocialCss3Outline = "\u{f4de}"
case AndroidExit = "\u{f385}"
case IosGameControllerB = "\u{f43b}"
case Archive = "\u{f102}"
case BatteryHalf = "\u{f114}"
case IosClose = "\u{f406}"
case IosArrowThinLeft = "\u{f3d5}"
case AndroidStarOutline = "\u{f3ae}"
case CloseCircled = "\u{f128}"
case AndroidBoat = "\u{f36a}"
case Calculator = "\u{f26d}"
case IosComposeOutline = "\u{f417}"
case IosPerson = "\u{f47e}"
case Jet = "\u{f295}"
case ArrowDownA = "\u{f103}"
case Coffee = "\u{f272}"
case IosMic = "\u{f461}"
case SocialGoogleOutline = "\u{f34e}"
case SocialYoutubeOutline = "\u{f24c}"
case Location = "\u{f1ff}"
case BatteryLow = "\u{f115}"
case AndroidLocate = "\u{f2e9}"
case IosColorFilter = "\u{f414}"
case Code = "\u{f271}"
case IosBriefcaseOutline = "\u{f3ed}"
case Loop = "\u{f201}"
case AndroidNotificationsNone = "\u{f399}"
case AndroidAlert = "\u{f35b}"
case IosNutritionOutline = "\u{f46f}"
case AndroidBookmark = "\u{f36b}"
case IosRefreshOutline = "\u{f49b}"
case IosStarHalf = "\u{f4b1}"
case IosFilm = "\u{f42b}"
case Nuclear = "\u{f2a4}"
case IosCloudyNight = "\u{f40e}"
case SadOutline = "\u{f4d7}"
case ChatbubbleWorking = "\u{f11d}"
case IosBodyOutline = "\u{f3e3}"
case ArrowGraphUpLeft = "\u{f261}"
case SocialYen = "\u{f4f2}"
case IosLightbulbOutline = "\u{f451}"
case Thumbsup = "\u{f251}"
case AndroidContract = "\u{f37d}"
case IosEyeOutline = "\u{f424}"
case Playstation = "\u{f30a}"
case IosCalculatorOutline = "\u{f3f1}"
case SocialUsd = "\u{f353}"
case SocialWindows = "\u{f247}"
case AndroidImage = "\u{f2e4}"
case Chatboxes = "\u{f11c}"
case Steam = "\u{f30b}"
case AndroidRadioButtonOn = "\u{f3a7}"
case IosStopwatchOutline = "\u{f4b4}"
case BackspaceOutline = "\u{f3be}"
case IosMedkitOutline = "\u{f45d}"
case IosAnalyticsOutline = "\u{f3cd}"
case ArrowUpC = "\u{f10e}"
case IosShuffleStrong = "\u{f4a8}"
case IosMoonOutline = "\u{f467}"
case IosTrash = "\u{f4c5}"
case IosMicOff = "\u{f45f}"
case IosPricetagsOutline = "\u{f48e}"
case SocialBitcoin = "\u{f2af}"
case IosRainyOutline = "\u{f494}"
case SocialTwitch = "\u{f4ee}"
case IosCopy = "\u{f41c}"
case IosGameControllerA = "\u{f439}"
case IosDownload = "\u{f420}"
case IosInfiniteOutline = "\u{f449}"
case RadioWaves = "\u{f2ac}"
case AndroidArrowDroprightCircle = "\u{f362}"
case SocialWordpressOutline = "\u{f248}"
case Lightbulb = "\u{f299}"
case AndroidLock = "\u{f392}"
case AndroidArrowUp = "\u{f366}"
case AndroidArrowDropdown = "\u{f35f}"
case IosColorWand = "\u{f416}"
case IosHeart = "\u{f443}"
case IosInformationOutline = "\u{f44c}"
case IosPaw = "\u{f47a}"
case AndroidCloudDone = "\u{f378}"
case Female = "\u{f278}"
case IosPawOutline = "\u{f479}"
case AndroidStarHalf = "\u{f3ad}"
case IosTelephoneOutline = "\u{f4b8}"
case Chatbubbles = "\u{f11f}"
case IosVolumeHigh = "\u{f4ce}"
case IosBookmarksOutline = "\u{f3e9}"
case RibbonB = "\u{f349}"
case SocialReddit = "\u{f23b}"
case IosChatbubbleOutline = "\u{f3fb}"
case IosAnalytics = "\u{f3ce}"
case AndroidFolderOpen = "\u{f38a}"
case AndroidUpload = "\u{f3b6}"
case LogOut = "\u{f29f}"
case Eye = "\u{f133}"
case PersonStalker = "\u{f212}"
case IosWineglassOutline = "\u{f4d0}"
case SocialChromeOutline = "\u{f4da}"
case AndroidMoreHorizontal = "\u{f396}"
case IosListOutline = "\u{f453}"
case IosCamera = "\u{f3f6}"
case Aperture = "\u{f313}"
case IosLocation = "\u{f456}"
case AndroidCamera = "\u{f2d3}"
case AndroidWalk = "\u{f3bb}"
case Search = "\u{f21f}"
case SocialFoursquare = "\u{f34d}"
case Beaker = "\u{f269}"
case SocialGithub = "\u{f233}"
case AndroidDone = "\u{f383}"
case SocialAppleOutline = "\u{f226}"
case SocialGithubOutline = "\u{f232}"
case SocialMarkdown = "\u{f4e6}"
case SocialYenOutline = "\u{f4f1}"
case Wrench = "\u{f2ba}"
case Home = "\u{f144}"
case IosReload = "\u{f49d}"
case SocialHtml5Outline = "\u{f4e2}"
case IosArrowRight = "\u{f3d3}"
case AndroidCompass = "\u{f37c}"
case IosCalendar = "\u{f3f4}"
case IosContact = "\u{f41a}"
case AndroidVolumeDown = "\u{f3b7}"
case IosPartlysunny = "\u{f476}"
case Speakerphone = "\u{f2b2}"
case University = "\u{f357}"
case IosArrowUp = "\u{f3d8}"
case Settings = "\u{f2ad}"
case Disc = "\u{f12d}"
case IosLoop = "\u{f45a}"
case IosFilmOutline = "\u{f42a}"
case AndroidChat = "\u{f2d4}"
case AndroidHand = "\u{f2e3}"
case AndroidFilm = "\u{f389}"
case IosHelp = "\u{f446}"
case Clipboard = "\u{f127}"
case ClosedCaptioning = "\u{f317}"
case Drag = "\u{f130}"
case ErlenmeyerFlaskBubbles = "\u{f3c4}"
case ArrowLeftC = "\u{f108}"
case IosMoreOutline = "\u{f469}"
case ChatboxWorking = "\u{f11a}"
case IosAtOutline = "\u{f3d9}"
case IosPricetag = "\u{f48d}"
case IosPricetagOutline = "\u{f48c}"
case IosWineglass = "\u{f4d1}"
case Podium = "\u{f344}"
case Scissors = "\u{f34b}"
case PieGraph = "\u{f2a5}"
case SocialOctocat = "\u{f4e8}"
case IosRewind = "\u{f4a1}"
case TshirtOutline = "\u{f4f6}"
case ArrowGraphDownLeft = "\u{f25f}"
case ArrowRightC = "\u{f10b}"
case Paintbucket = "\u{f4d6}"
case IosRose = "\u{f4a3}"
case SocialLinkedinOutline = "\u{f238}"
case AndroidTextsms = "\u{f3b2}"
case IosArrowDown = "\u{f3d0}"
case Close = "\u{f12a}"
case HelpBuoy = "\u{f27c}"
case IosBarcodeOutline = "\u{f3db}"
case AndroidCheckboxBlank = "\u{f371}"
case Earth = "\u{f276}"
case Quote = "\u{f347}"
case Trophy = "\u{f356}"
case Minus = "\u{f209}"
case Reply = "\u{f21e}"
case Upload = "\u{f255}"
case AndroidOptions = "\u{f39d}"
case IosDrag = "\u{f421}"
case IosCloudyOutline = "\u{f40f}"
case SocialDesignernewsOutline = "\u{f22a}"
case IosSunny = "\u{f4b7}"
case Bowtie = "\u{f3c0}"
case IosClock = "\u{f403}"
case Medkit = "\u{f2a2}"
case Outlet = "\u{f342}"
case More = "\u{f20b}"
case AndroidArrowDropleftCircle = "\u{f360}"
case AndroidSubway = "\u{f3af}"
case IosCalculator = "\u{f3f2}"
case IosPrinter = "\u{f491}"
case IosGearOutline = "\u{f43c}"
case ArrowUpA = "\u{f10c}"
case AndroidUnlock = "\u{f3b5}"
case BatteryEmpty = "\u{f112}"
case IosCloud = "\u{f40c}"
case IosFastforward = "\u{f427}"
case IosTimeOutline = "\u{f4be}"
case AndroidNavigate = "\u{f398}"
case Compass = "\u{f273}"
case Hammer = "\u{f27b}"
case SocialHackernews = "\u{f237}"
case SocialBitcoinOutline = "\u{f2ae}"
case TrashB = "\u{f253}"
case SocialWhatsappOutline = "\u{f4ef}"
case AndroidCheckboxOutline = "\u{f373}"
case AndroidPrint = "\u{f3a5}"
case ChevronUp = "\u{f126}"
case AndroidDrafts = "\u{f384}"
case FilmMarker = "\u{f135}"
case IosLoopStrong = "\u{f459}"
case IosSkipforwardOutline = "\u{f4ac}"
case Levels = "\u{f298}"
case AndroidCheckboxOutlineBlank = "\u{f372}"
case ArrowSwap = "\u{f268}"
case SocialDribbble = "\u{f22d}"
case SocialGoogleplus = "\u{f235}"
case SocialSass = "\u{f4ea}"
case Clock = "\u{f26e}"
case IosPeopleOutline = "\u{f47b}"
case AndroidArrowDropdownCircle = "\u{f35e}"
case IosHelpOutline = "\u{f445}"
case SocialRssOutline = "\u{f23c}"
case AndroidShare = "\u{f2f8}"
case AndroidHome = "\u{f38f}"
case IosBoltOutline = "\u{f3e5}"
case IosPauseOutline = "\u{f477}"
case SocialJavascriptOutline = "\u{f4e4}"
case AndroidRefresh = "\u{f3a8}"
case AndroidVolumeUp = "\u{f3ba}"
case ArrowUpB = "\u{f10d}"
case IosRecordingOutline = "\u{f496}"
case MicC = "\u{f206}"
case AndroidSettings = "\u{f2f7}"
case Printer = "\u{f21a}"
case Cloud = "\u{f12b}"
case IosBaseballOutline = "\u{f3dd}"
case IosInformation = "\u{f44d}"
case LockCombination = "\u{f4d4}"
case IosMonitorOutline = "\u{f465}"
case LoadA = "\u{f29a}"
case SocialBuffer = "\u{f229}"
case AndroidStopwatch = "\u{f2fd}"
case Email = "\u{f132}"
case IosColorWandOutline = "\u{f415}"
case IosFolder = "\u{f435}"
case Alert = "\u{f101}"
case Ipod = "\u{f1fb}"
case Asterisk = "\u{f314}"
case HeartBroken = "\u{f31d}"
case IosChatboxes = "\u{f3fa}"
case IosPrinterOutline = "\u{f490}"
case AndroidClipboard = "\u{f376}"
case IosBell = "\u{f3e2}"
case AndroidRemove = "\u{f2f4}"
case AndroidApps = "\u{f35c}"
case Backspace = "\u{f3bf}"
case PullRequest = "\u{f345}"
case Navigate = "\u{f2a3}"
case SocialApple = "\u{f227}"
case IosBolt = "\u{f3e6}"
case Knife = "\u{f297}"
case AndroidBulb = "\u{f36c}"
case ReplyAll = "\u{f21d}"
case SocialCodepenOutline = "\u{f4dc}"
case SocialRss = "\u{f23d}"
case Thermometer = "\u{f2b6}"
case TrashA = "\u{f252}"
case IosSearch = "\u{f4a5}"
case Wifi = "\u{f25c}"
case SocialFacebookOutline = "\u{f230}"
case Navicon = "\u{f20e}"
case IosBrowsers = "\u{f3f0}"
case IosSpeedometer = "\u{f4b0}"
case AndroidCar = "\u{f36f}"
case IosCopyOutline = "\u{f41b}"
case IosHelpEmpty = "\u{f444}"
case AndroidBicycle = "\u{f369}"
case AndroidPersonAdd = "\u{f39f}"
case IosCircleOutline = "\u{f401}"
case IosVideocam = "\u{f4cd}"
case LoadC = "\u{f29c}"
case IosEye = "\u{f425}"
case ConnectionBars = "\u{f274}"
case LogIn = "\u{f29e}"
case Paperclip = "\u{f20f}"
case Pinpoint = "\u{f2a7}"
case AndroidStar = "\u{f2fc}"
case SocialDropbox = "\u{f22f}"
case SocialLinkedin = "\u{f239}"
case SoupCan = "\u{f4f4}"
case Transgender = "\u{f4f5}"
case SocialRedditOutline = "\u{f23a}"
case Planet = "\u{f343}"
case AndroidArrowDropupCircle = "\u{f364}"
case AndroidContact = "\u{f2d8}"
case IosRecording = "\u{f497}"
case IosUnlocked = "\u{f4c9}"
case Pizza = "\u{f2a8}"
case SocialBufferOutline = "\u{f228}"
case AndroidDocument = "\u{f381}"
case IosDownloadOutline = "\u{f41f}"
case CloseRound = "\u{f129}"
case IosPause = "\u{f478}"
case IosCloudUpload = "\u{f40b}"
case Iphone = "\u{f1fa}"
case Paintbrush = "\u{f4d5}"
case IosReverseCamera = "\u{f49f}"
case IosAlbums = "\u{f3ca}"
case IosCheckmarkEmpty = "\u{f3fd}"
case ArrowLeftA = "\u{f106}"
case IosMoon = "\u{f468}"
case Fireball = "\u{f319}"
case IosChatboxesOutline = "\u{f3f9}"
case SocialTumblrOutline = "\u{f240}"
case VolumeMedium = "\u{f259}"
case IosGear = "\u{f43d}"
case IosCheckmark = "\u{f3ff}"
case SocialVimeo = "\u{f245}"
case IosPlay = "\u{f488}"
case IosSettingsStrong = "\u{f4a6}"
case Cube = "\u{f318}"
case Flash = "\u{f137}"
case AndroidSunny = "\u{f3b0}"
case IosArrowThinUp = "\u{f3d7}"
case Key = "\u{f296}"
case AndroidPlane = "\u{f3a4}"
case SocialNodejs = "\u{f4e7}"
case SocialYahoo = "\u{f24b}"
case AndroidSearch = "\u{f2f5}"
case IosSkipforward = "\u{f4ad}"
case IosPhotos = "\u{f482}"
case IosClockOutline = "\u{f402}"
case IosRefreshEmpty = "\u{f49a}"
case SocialFoursquareOutline = "\u{f34c}"
case Egg = "\u{f277}"
case InformationCircled = "\u{f149}"
case SocialTwitterOutline = "\u{f242}"
case Male = "\u{f2a1}"
case IosAlarmOutline = "\u{f3c7}"
case SocialPython = "\u{f4e9}"
case AndroidAddCircle = "\u{f359}"
case Icecream = "\u{f27d}"
case IosCalendarOutline = "\u{f3f3}"
case IosPhotosOutline = "\u{f481}"
case AndroidNotifications = "\u{f39b}"
case GearB = "\u{f13e}"
case IosGlasses = "\u{f43f}"
case Man = "\u{f202}"
case ChevronRight = "\u{f125}"
case SocialSnapchatOutline = "\u{f4eb}"
case AndroidArrowForward = "\u{f30f}"
case ArrowExpand = "\u{f25e}"
case IosBarcode = "\u{f3dc}"
case IosCloseEmpty = "\u{f404}"
case IosInformationEmpty = "\u{f44b}"
case IosPaper = "\u{f472}"
case AndroidPeople = "\u{f39e}"
case AndroidFavorite = "\u{f388}"
case ArrowRightB = "\u{f10a}"
case IosCloudDownload = "\u{f408}"
case IosPie = "\u{f484}"
case Bluetooth = "\u{f116}"
case IosList = "\u{f454}"
case IosPint = "\u{f486}"
case MinusCircled = "\u{f207}"
case MusicNote = "\u{f20c}"
case IosWorld = "\u{f4d3}"
case AndroidDesktop = "\u{f380}"
case AndroidArrowDown = "\u{f35d}"
case AndroidWarning = "\u{f3bc}"
case Locked = "\u{f200}"
case PaperAirplane = "\u{f2c3}"
case Merge = "\u{f33f}"
case IosWorldOutline = "\u{f4d2}"
case AndroidSync = "\u{f3b1}"
case Checkmark = "\u{f122}"
case CodeWorking = "\u{f270}"
case AndroidHappy = "\u{f38e}"
case IosBasketballOutline = "\u{f3df}"
case CodeDownload = "\u{f26f}"
case IosMusicalNote = "\u{f46b}"
case Bookmark = "\u{f26b}"
case Happy = "\u{f31c}"
case IosCropStrong = "\u{f41d}"
case IosNavigate = "\u{f46e}"
case IosPlusOutline = "\u{f48a}"
case AndroidMicrophoneOff = "\u{f395}"
case ArrowGraphUpRight = "\u{f262}"
case AndroidCalendar = "\u{f2d1}"
case ArrowLeftB = "\u{f107}"
case GearA = "\u{f13d}"
case Ipad = "\u{f1f9}"
case Pause = "\u{f210}"
case IosSunnyOutline = "\u{f4b6}"
case Play = "\u{f215}"
case Refresh = "\u{f21c}"
case SocialEuroOutline = "\u{f4e0}"
case AndroidSend = "\u{f2f6}"
case SocialFacebook = "\u{f231}"
case SocialFreebsdDevil = "\u{f2c4}"
case IosPaperOutline = "\u{f471}"
case SocialGoogle = "\u{f34f}"
case SocialHackernewsOutline = "\u{f236}"
case AndroidHangout = "\u{f38d}"
case EyeDisabled = "\u{f306}"
case IosBookOutline = "\u{f3e7}"
case SocialHtml5 = "\u{f4e3}"
case SocialInstagramOutline = "\u{f350}"
case Ionic = "\u{f14b}"
case SocialSkypeOutline = "\u{f23e}"
case Crop = "\u{f3c1}"
case IosPlayOutline = "\u{f487}"
case SocialYahooOutline = "\u{f24a}"
case Stop = "\u{f24f}"
case BatteryCharging = "\u{f111}"
case HelpCircled = "\u{f142}"
case Toggle = "\u{f355}"
case Umbrella = "\u{f2b7}"
case Usb = "\u{f2b8}"
case SocialSnapchat = "\u{f4ec}"
case Videocamera = "\u{f256}"
case VolumeMute = "\u{f25a}"
case IosCloudOutline = "\u{f409}"
case Wand = "\u{f358}"
case IosBoxOutline = "\u{f3eb}"
case Xbox = "\u{f30c}"
case LoadB = "\u{f29b}"
case IosMedicalOutline = "\u{f45b}"
case SocialInstagram = "\u{f351}"
case ArrowReturnRight = "\u{f266}"
case AndroidFunnel = "\u{f38b}"
case SkipForward = "\u{f223}"
case AndroidNotificationsOff = "\u{f39a}"
case Compose = "\u{f12c}"
case IosGlassesOutline = "\u{f43e}"
case ChevronDown = "\u{f123}"
case IosTennisballOutline = "\u{f4ba}"
case PlusRound = "\u{f217}"
case Pound = "\u{f219}"
case Star = "\u{f24e}"
case Flame = "\u{f31a}"
case Woman = "\u{f25d}"
case AndroidTrain = "\u{f3b4}"
case Chatbox = "\u{f11b}"
case IosStopwatch = "\u{f4b5}"
case IosTennisball = "\u{f4bb}"
case ToggleFilled = "\u{f354}"
case Laptop = "\u{f1fc}"
case IosCircleFilled = "\u{f400}"
case IosTimer = "\u{f4c1}"
case LoadD = "\u{f29d}"
case IosRoseOutline = "\u{f4a2}"
case Wineglass = "\u{f2b9}"
case IosMonitor = "\u{f466}"
case Bag = "\u{f110}"
case IosSkipbackward = "\u{f4ab}"
case Pin = "\u{f2a6}"
case AndroidAttach = "\u{f367}"
case FlashOff = "\u{f136}"
case IosFlask = "\u{f431}"
case Network = "\u{f341}"
case AndroidPhoneLandscape = "\u{f3a1}"
case RibbonA = "\u{f348}"
case AndroidSad = "\u{f3ab}"
case SocialAngular = "\u{f4d9}"
case SocialVimeoOutline = "\u{f244}"
case IosMore = "\u{f46a}"
}
| 8dc045f952c1bee27599d50ae8a2d208 | 35.035714 | 126 | 0.570077 | false | false | false | false |
barankaraoguzzz/FastOnBoarding | refs/heads/master | FOView/Classes/FOView.swift | mit | 1 | //
// FOView.swift
// FastOnBoarding_Example
//
// Created by Baran on 4.04.2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
public class FOView: UIView {
//Mark: -Private Veriable
private var _imageView : UIImageView?
private var _pageControl : UIPageControl?
private var foAnimate = FOAnimation()
//Mark: -Public Veriable
public var foImages : [UIImage]?
public var foDiriction = animateDirection.horizantal
public var isPageControlEnable = true
public var animateType = AnimationStyle.alignedFlip
open var isPageControl : Bool = true {
didSet {
if self.isPageControl {
_pageControl?.isHidden = false
} else {
_pageControl?.isHidden = true
}
}
}
//Mark: -Delegate
public weak var delegate: FODelegate?
override init(frame: CGRect) {
super.init(frame: frame)
commonInıt()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInıt()
}
override public func layoutSubviews() {
setViewFrame()
}
private func commonInıt(){
_imageView = UIImageView()
_pageControl = UIPageControl()
}
public func startOnboarding(){
addSwipe()
}
private func setViewFrame(){
_imageView?.frame = self.frame
_imageView?.contentMode = .scaleAspectFill
_imageView?.clipsToBounds = true
print(isPageControl)
self.addSubview(_imageView!)
//Mark: - ***************************************
if isPageControlEnable {
_pageControl?.frame = CGRect(x: 0, y: self.frame.height - 30, width: self.frame.width, height: 30)
_pageControl?.backgroundColor = UIColor.black.withAlphaComponent(0.4)
_pageControl?.tintColor = UIColor.gray
_pageControl?.currentPageIndicatorTintColor = UIColor.white
self.addSubview(_pageControl!)
}
}
fileprivate func addSwipe(){
self.isUserInteractionEnabled = true
_imageView?.image = foImages![0]
_pageControl?.numberOfPages = (foImages?.count)!
switch foDiriction {
case .horizantal:
//Mark: -Right swipe add
let gestureRight = UISwipeGestureRecognizer(target: self, action: #selector(directionHorizantal(gesture:)))
gestureRight.direction = .right
self.addGestureRecognizer(gestureRight)
//Mark: -Left swipe add
let gestureLeft = UISwipeGestureRecognizer(target: self, action: #selector(directionHorizantal(gesture:)))
gestureRight.direction = .left
self.addGestureRecognizer(gestureLeft)
case .vertical:
//Mark: -Down swipe add
let gestureDown = UISwipeGestureRecognizer(target: self, action: #selector(directionVertical(gesture:)))
gestureDown.direction = .down
self.addGestureRecognizer(gestureDown)
//Mark: -Up swipe add
let gestureUp = UISwipeGestureRecognizer(target: self, action: #selector(directionVertical(gesture:)))
gestureUp.direction = .up
self.addGestureRecognizer(gestureUp)
}
}
@objc fileprivate func directionHorizantal(gesture :UIGestureRecognizer){
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
if (_pageControl?.currentPage)! > 0{
foAnimate.addAnimation(animateType, view: self, subTypeStyle: .right)
_pageControl?.currentPage -= 1
_imageView?.image = foImages?[(_pageControl?.currentPage)!]
}
case UISwipeGestureRecognizerDirection.left:
if (_pageControl?.currentPage)! < (foImages?.count)! - 1{
foAnimate.addAnimation(animateType, view: self, subTypeStyle: .left)
_pageControl?.currentPage += 1
_imageView?.image = foImages?[(_pageControl?.currentPage)!]
}
default:break
}
if delegate != nil {
delegate?.FOnboarding(self, getCountPageControl: (_pageControl?.currentPage)!)
}
}
}
@objc fileprivate func directionVertical(gesture :UIGestureRecognizer){
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.down:
print("down")
if (_pageControl?.currentPage)! > 0{
foAnimate.addAnimation(animateType, view: self, subTypeStyle: .down)
_pageControl?.currentPage -= 1
_imageView?.image = foImages?[(_pageControl?.currentPage)!]
}
case UISwipeGestureRecognizerDirection.up:
print("Up")
if (_pageControl?.currentPage)! < (foImages?.count)! - 1{
foAnimate.addAnimation(animateType, view: self, subTypeStyle: .up)
_pageControl?.currentPage += 1
_imageView?.image = foImages?[(_pageControl?.currentPage)!]
}
default:break
}
if delegate != nil {
delegate?.FOnboarding(self, getCountPageControl: (_pageControl?.currentPage)!)
}
}
}
}
| bcebb447a033ef7ed115da575d092c97 | 34.288344 | 119 | 0.57041 | false | false | false | false |
Brightify/Reactant | refs/heads/master | Tests/Core/Styling/UIColor+ModificatorsTest.swift | mit | 2 | //
// UIColor+ModificatorsTest.swift
// Reactant
//
// Created by Filip Dolnik on 18.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Quick
import Nimble
import Reactant
class UIColorModificatorsTest: QuickSpec {
override func spec() {
describe("UIColor") {
let color = UIColor(red: 0.5, green: 0.1, blue: 0.1, alpha: 0.5)
let grey = UIColor(white: 0.5, alpha: 0.5)
describe("darker") {
it("works with rgb") {
self.assert(UIColor(red: 0.25, green: 0.05, blue: 0.05, alpha: 0.5), color.darker(by: 50%))
}
it("works with greyscale") {
self.assert(UIColor(red: 0.25, green: 0.25, blue: 0.25, alpha: 0.5), grey.darker(by: 50%))
}
}
describe("lighter") {
it("works with rgb") {
self.assert(UIColor(red: 0.75, green: 0.15, blue: 0.15, alpha: 0.5), color.lighter(by: 50%))
}
it("works with greyscale") {
self.assert(UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 0.5), grey.lighter(by: 50%))
}
}
describe("saturated") {
it("works with rgb") {
self.assert(UIColor(red: 0.5, green: 0, blue: 0, alpha: 0.5), color.saturated(by: 50%))
}
it("works with greyscale") {
self.assert(UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5), grey.saturated(by: 50%))
}
}
describe("desaturated") {
it("works with rgb") {
self.assert(UIColor(red: 0.5, green: 0.3, blue: 0.3, alpha: 0.5), color.desaturated(by: 50%))
}
it("works with greyscale") {
self.assert(UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5), grey.desaturated(by: 50%))
}
}
describe("fadedIn") {
it("works with rgb") {
self.assert(UIColor(red: 0.5, green: 0.1, blue: 0.1, alpha: 0.75), color.fadedIn(by: 50%))
}
it("works with greyscale") {
self.assert(UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.75), grey.fadedIn(by: 50%))
}
}
describe("fadedOut") {
it("works with rgb") {
self.assert(UIColor(red: 0.5, green: 0.1, blue: 0.1, alpha: 0.25), color.fadedOut(by: 50%))
}
it("works with greyscale") {
self.assert(UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.25), grey.fadedOut(by: 50%))
}
}
}
}
private func assert(_ expected: UIColor, _ actual: UIColor, file: StaticString = #file, line: UInt = #line) {
var r1: CGFloat = 0
var g1: CGFloat = 0
var b1: CGFloat = 0
var a1: CGFloat = 0
var r2: CGFloat = 0
var g2: CGFloat = 0
var b2: CGFloat = 0
var a2: CGFloat = 0
expected.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
actual.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
let accuracy = CGFloat.ulpOfOne
let message = "\(expected) is not equal to \(actual)"
XCTAssertEqual(r1, r2, accuracy: accuracy, message, file: file, line: line)
XCTAssertEqual(g1, g2, accuracy: accuracy, message, file: file, line: line)
XCTAssertEqual(b1, b2, accuracy: accuracy, message, file: file, line: line)
XCTAssertEqual(a1, a2, accuracy: accuracy, message, file: file, line: line)
}
}
| 45c56f158f9ddedf1e71fc3ece6ad60f | 40.488889 | 113 | 0.490894 | false | false | false | false |
colemancda/json-swift | refs/heads/master | src/JSValue.ErrorHandling.swift | mit | 4 | //
// JSValue.ErrorHandling.swift
// JSON
//
// Created by David Owens II on 8/11/14.
// Copyright (c) 2014 David Owens II. All rights reserved.
//
extension JSValue {
/// A type that holds the error code and standard error message for the various types of failures
/// a `JSValue` can have.
public struct ErrorMessage {
/// The numeric value of the error number.
public let code: Int
/// The default message describing the error.
public let message: String
}
/// All of the error codes and standard error messages when parsing JSON.
public struct ErrorCode {
private init() {}
/// A integer that is outside of the safe range was attempted to be set.
public static let InvalidIntegerValue = ErrorMessage(
code:1,
message: "The specified number is not valid. Valid numbers are within the range: [\(JSValue.MinimumSafeInt), \(JSValue.MaximumSafeInt)]")
/// Error when attempting to access an element from a `JSValue` backed by a dictionary and there is no
/// value stored at the specified key.
public static let KeyNotFound = ErrorMessage(
code: 2,
message: "The specified key cannot be found.")
/// Error when attempting to index into a `JSValue` that is not backed by a dictionary or array.
public static let IndexingIntoUnsupportedType = ErrorMessage(
code: 3,
message: "Indexing is only supported on arrays and dictionaries."
)
/// Error when attempting to access an element from a `JSValue` backed by an array and the index is
/// out of range.
public static let IndexOutOfRange = ErrorMessage(
code: 4,
message: "The specified index is out of range of the bounds for the array.")
/// Error when a parsing error occurs.
public static let ParsingError = ErrorMessage(
code: 5,
message: "The JSON string being parsed was invalid.")
}
}
| 18343006c1270d6b999d2282ff3e333c | 38.45283 | 149 | 0.626495 | false | false | false | false |
meetkei/KxUI | refs/heads/master | KxUI/Color/UIColor+Hex.swift | mit | 1 | //
// Copyright (c) 2016 Keun young Kim <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension UIColor {
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: - Initializing a UIColor Object
/**
Initializes and returns a color object using the hexadecimal color string.
- Parameter hexString: the hexadecimal color string.
- Returns: An initialized color object. If *hexString* is not a valid hexadecimal color string, returns a color object whose grayscale value is 1.0 and whose alpha value is 1.0.
*/
convenience init(hexString: String) {
var red: CGFloat = 1.0
var green: CGFloat = 1.0
var blue: CGFloat = 1.0
var alpha: CGFloat = 1.0
if let color = hexString.parseHexColorString() {
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
var rgbHexString: String {
return toHexString(includeAlpha: false)
}
var rgbaHexString: String {
return toHexString(includeAlpha: true)
}
private func toHexString(includeAlpha: Bool) -> String {
var normalizedR: CGFloat = 0
var normalizedG: CGFloat = 0
var normalizedB: CGFloat = 0
var normalizedA: CGFloat = 0
getRed(&normalizedR, green: &normalizedG, blue: &normalizedB, alpha: &normalizedA)
let r = Int(normalizedR * 255)
let g = Int(normalizedG * 255)
let b = Int(normalizedB * 255)
let a = Int(normalizedA * 255)
if includeAlpha {
return String(format: "#%02X%02X%02X%02X", r, g, b, a)
}
return String(format: "#%02X%02X%02X", r, g, b)
}
}
| eee786b77e0019512141e55e27dbef9e | 37.324675 | 182 | 0.631311 | false | false | false | false |
ssh88/ImageCacheable | refs/heads/master | ImageCacheable/Classes/ImageCacheable.swift | mit | 1 | //
// ImageCacheable.swift
// ImageCacheable
//
// Created by Shabeer Hussain on 23/11/2016.
// Copyright © 2016 Desert Monkey. All rights reserved.
//
import Foundation
import UIKit
protocol ImageCacheable {
/**
Retrieves an image from the local file system. If the image does not exist it will save it
*/
func localImage(forKey key: String, from remoteUrl: URL, completion:@escaping ((UIImage?, String) -> Void))
/**
Retrieves an image from the in memory cache. These images are not persisted across sessions
*/
func inMemoryImage(forKey key: String, from url: URL, completion:@escaping ((UIImage?, String) -> Void))
/**
Folder name. Defaults to "ImageCacheable" unless dedicated cache object declares new name
*/
var imageFolderName: String? {get}
/**
Cache object, only initialized by the conforming object if calling
inMemoryImage(forKey:from:completion:)
*/
var inMemoryImageCache: NSCache<AnyObject, UIImage>? {get}
}
extension ImageCacheable {
//both properties have default values initialized on get
var imageFolderName: String? { return "ImageCacheable" }
var inMemoryImageCache: NSCache<AnyObject, UIImage>? { return NSCache<AnyObject, UIImage>() }
//MARK:- Image Fetching
func localImage(forKey key: String, from remoteUrl: URL, completion:@escaping ((UIImage?, String) -> Void)) {
//create the file path
let documentsDir = imageDirectoryURL().path
var filePathString = "\(documentsDir)/\(key)"
//get the file extension
if let fileExtension = fileExtension(for: remoteUrl) {
filePathString.append(fileExtension)
}
//next create the localURL
let localURL = URL(fileURLWithPath: filePathString)
//checks if the image should be saved locally
let imageExistsLocally = self.fileExists(at: filePathString)
//creates the data url from where to fetch, can be local or remote
let dataURL = imageExistsLocally ? localURL : remoteUrl
//finally fetch the image, pass in the localURL if we need to save it locally
self.fetchImage(from: dataURL, saveTo: (imageExistsLocally ? nil : localURL)) { image in
//grab main thread, as its more than likley this will serve UI layers
DispatchQueue.main.sync {
completion(image, key)
}
}
}
func inMemoryImage(forKey key: String, from url: URL, completion:@escaping ((UIImage?, String) -> Void)) {
guard let inMemoryImageCache = inMemoryImageCache else {
fatalError("ERROR: in Memory Image Cache must be set in order to use in-memory image cache")
}
if let cachedImage = inMemoryImageCache.object(forKey: key as AnyObject) {
completion(cachedImage, key)
} else {
fetchImage(from: url, saveTo: nil, completion: { (image) in
if let image = image {
inMemoryImageCache.setObject(image, forKey: key as AnyObject)
}
completion(image, key)
})
}
}
/**
Creates the UIImage from either local or remote url. If remote, will save to disk
*/
private func fetchImage(from url: URL,
saveTo localURL: URL?,
session: URLSession = URLSession.shared,
completion:@escaping ((UIImage?) -> Void)) {
session.dataTask(with: url) { (imageData, response, error) in
do {
guard
let imageData = imageData,
let image = UIImage(data: imageData)
else {
completion(nil)
return
}
//save if the localURL exists
if let localURL = localURL {
try imageData.write(to: localURL, options: .atomic)
}
completion(image)
} catch {
debugPrint(error.localizedDescription)
completion(nil)
}
}.resume()
}
//MARK:- Cache Management
/**
Deletes the image files on disk
*/
internal func clearLocalCache(success: (Bool) -> Void) {
let fileManager = FileManager.default
let imageDirectory = imageDirectoryURL()
if fileManager.isDeletableFile(atPath: imageDirectory.path) {
do {
try fileManager.removeItem(atPath: imageDirectory.path)
success(true)
} catch {
debugPrint(error.localizedDescription)
success(false)
}
}
success(true)
}
/**
Clears the in memory image cache
*/
internal func clearInMemoryCache(success: (Bool) -> Void) {
guard let inMemoryImageCache = inMemoryImageCache else {
success (false)
return
}
inMemoryImageCache.removeAllObjects()
success (true)
}
/*
TODO: need to handle the success/failure options better before implementing
a clear function that handles both caches
/**
Clears both the in-memory and disk image cache
*/
internal func clearCache(success: (Bool) -> Void) {
clearInMemoryCache { (_) in
clearLocalCache { (_) in
success(true)
}
}
}
*/
//MARK:- File Management
internal func fileExtension(for url: URL) -> String? {
let components = URLComponents(url: url, resolvingAgainstBaseURL: true)
guard let fileExtension = components?.url?.pathComponents.last?.components(separatedBy: ".").last else {
return nil
}
return ".\(fileExtension)"
}
internal func fileExists(at path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
/**
Returns the image folder directory
*/
internal func imageDirectoryURL() -> URL {
guard let imageFolderName = imageFolderName else {
fatalError("ERROR: Image Folder Name must be set in order to use local file storage image cache")
}
//get a ref to the sandbox documents folder
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
//next create a file path to the new documents folder (uses the protcols imagefolderName)
let imageFolderPath = documentsPath.appendingPathComponent(imageFolderName)
//next we check if the folder needs to be creaded
let fileManager = FileManager.default
var directoryExists : ObjCBool = false
if fileManager.fileExists(atPath: imageFolderPath.path, isDirectory:&directoryExists) {
if directoryExists.boolValue {
//if it already exists, return it
return imageFolderPath
}
} else {
// otherwise if it doesnt exist, we create and return it
do {
try FileManager.default.createDirectory(atPath: imageFolderPath.path, withIntermediateDirectories: true, attributes: nil)
} catch {
debugPrint(error.localizedDescription)
}
}
return imageFolderPath
}
}
| 7529dc9931305b86a16b56e5df41e669 | 33.242152 | 137 | 0.581456 | false | false | false | false |
mikelikespie/swiftled | refs/heads/master | src/main/swift/OPC/ClientConnection.swift | mit | 1 | //
// ClientConnection.swift
// SwiftledMobile
//
// Created by Michael Lewis on 12/29/15.
// Copyright © 2015 Lolrus Industries. All rights reserved.
//
import Foundation
import Dispatch
import RxSwift
private let headerSize = 4
private let broadcastChannel: UInt8 = 0
enum OpcCommand : UInt8 {
case setPixels = 0
case customCommand = 255
}
/// A way to reuse by applying an element type over ourselves. This is how a "ClientConnection" is represented
public protocol ValueSink : class {
/// Usually a pixel format or something
associatedtype Element
/// The function we pass in is called inine which should return an element at each index
}
public enum ConnectionMode {
case rgb8 // use for standard OPC protocol
case rgbaRaw // APA protocol for used in go-led-spi. Color conversion will probably be slower
}
extension ConnectionMode {
var bytesPerPixel: Int {
switch self {
case .rgb8: return 3
case .rgbaRaw: return 4
}
}
var headerCommand: OpcCommand {
switch self {
case .rgb8: return .setPixels
case .rgbaRaw: return .customCommand
}
}
}
public final class ClientConnection : Collection {
public typealias Element = RGBFloat
public typealias Index = Int
private var pixelBuffer: [UInt8]
private let workQueue = DispatchQueue(label: "connection work queue", attributes: [])
private var channel: DispatchIO
private var ledCount: Int
private var start: TimeInterval
private let mode: ConnectionMode
private let bytesPerPixel: Int
public init(fd: Int32, ledCount: Int, mode: ConnectionMode) {
self.mode = mode
bytesPerPixel = mode.bytesPerPixel
self.pixelBuffer = [UInt8](repeating: 0, count: headerSize + ledCount * bytesPerPixel)
// Only support 1 channel for now
let channel = broadcastChannel
pixelBuffer[0] = channel
pixelBuffer[1] = mode.headerCommand.rawValue
pixelBuffer[2] = UInt8(truncatingBitPattern: UInt(self.pixelBuffer.count - headerSize) >> 8)
pixelBuffer[3] = UInt8(truncatingBitPattern: UInt(self.pixelBuffer.count - headerSize) >> 0)
self.start = Date.timeIntervalSinceReferenceDate
self.ledCount = ledCount
self.channel = DispatchIO(type: DispatchIO.StreamType.stream, fileDescriptor: fd, queue: workQueue, cleanupHandler: { _ in })
// self.channel.setLimit(lowWater: 0)
// self.channel.setLimit(highWater: Int.max)
self.channel.setInterval(interval: .seconds(0), flags: DispatchIO.IntervalFlags.strictInterval)
}
public func apply<C: ColorConvertible>( _ fn: (_ index: Int, _ now: TimeInterval) -> C) {
let timeOffset = Date.timeIntervalSinceReferenceDate - start
applyOverRange(0..<ledCount, iterations: 4) { rng in
for idx in rng {
self[idx] = fn(idx, timeOffset).rgbFloat
}
}
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return self.ledCount
}
public func index(after i: Index) -> Index {
return i + 1
}
public subscript(index: Int) -> RGBFloat {
get {
let baseOffset = headerSize + index * bytesPerPixel
switch mode {
case .rgb8:
return RGB8(
r: pixelBuffer[baseOffset],
g: pixelBuffer[baseOffset + 1],
b: pixelBuffer[baseOffset + 2]
).rgbFloat
case .rgbaRaw:
return RGBARaw(
r: pixelBuffer[baseOffset],
g: pixelBuffer[baseOffset + 1],
b: pixelBuffer[baseOffset + 2],
a: pixelBuffer[baseOffset + 3]
).rgbFloat
}
}
set {
let baseOffset = headerSize + index * bytesPerPixel
switch mode {
case .rgb8:
let color = newValue.rgb8
pixelBuffer[baseOffset] = color.r
pixelBuffer[baseOffset + 1] = color.g
pixelBuffer[baseOffset + 2] = color.b
case .rgbaRaw:
let color = newValue.rawColor
pixelBuffer[baseOffset] = color.r
pixelBuffer[baseOffset + 1] = color.g
pixelBuffer[baseOffset + 2] = color.b
pixelBuffer[baseOffset + 3] = color.a
}
}
}
public func flush() -> Observable<Void> {
let dispatchData: DispatchData = self.pixelBuffer.withUnsafeBufferPointer {
#if os(Linux)
return DispatchData(bytes: $0)
#else
return DispatchData(bytesNoCopy: $0, deallocator: DispatchData.Deallocator.custom(nil, {}))
#endif
}
let subject = PublishSubject<Void>()
self
.channel
.write(
offset: 0,
data: dispatchData,
queue: self.workQueue
) { done, data, error in
guard error == 0 else {
subject.onError(Error.errorFromStatusCode(error)!)
return
}
if done {
subject.onNext()
subject.onCompleted()
}
}
// self.channel.barrier {
// _ = self.channel.fileDescriptor;
// }
return subject
}
deinit {
NSLog("Deiniting")
}
}
public func applyOverRange(_ fullBounds: CountableRange<Int>, iterations: Int = 16, fn: (CountableRange<Int>) -> ()) {
let chunkSize = ((fullBounds.count - 1) / iterations) + 1
let splitBounds = (0..<iterations).map { idx in
(fullBounds.lowerBound + chunkSize * idx)..<min((fullBounds.lowerBound + chunkSize * (idx + 1)), fullBounds.upperBound)
}
DispatchQueue.concurrentPerform(iterations: iterations) { idx in
let bounds = splitBounds[idx]
fn(bounds)
}
}
| 5c3902d57ba81d2a6354b7b7b9c78aed | 29.765854 | 133 | 0.562391 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS/Sources/UserInterface/StartUI/Common/SectionControllers/Suggestions/DirectorySectionController.swift | gpl-3.0 | 1 | //
// 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 Foundation
import WireDataModel
import UIKit
import WireSyncEngine
final class DirectorySectionController: SearchSectionController {
var suggestions: [ZMSearchUser] = []
weak var delegate: SearchSectionControllerDelegate?
var token: AnyObject?
weak var collectionView: UICollectionView?
override var isHidden: Bool {
return self.suggestions.isEmpty
}
override var sectionTitle: String {
return "peoplepicker.header.directory".localized
}
override func prepareForUse(in collectionView: UICollectionView?) {
super.prepareForUse(in: collectionView)
collectionView?.register(UserCell.self, forCellWithReuseIdentifier: UserCell.zm_reuseIdentifier)
self.token = UserChangeInfo.add(searchUserObserver: self, in: ZMUserSession.shared()!)
self.collectionView = collectionView
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return suggestions.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let user = suggestions[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserCell.zm_reuseIdentifier, for: indexPath) as! UserCell
cell.configure(with: user, selfUser: ZMUser.selfUser())
cell.showSeparator = (suggestions.count - 1) != indexPath.row
cell.userTypeIconView.isHidden = true
cell.accessoryIconView.isHidden = true
cell.connectButton.isHidden = !user.canBeUnblocked
if user.canBeUnblocked {
cell.accessibilityHint = L10n.Accessibility.ContactsList.PendingConnection.hint
}
cell.connectButton.tag = indexPath.row
cell.connectButton.addTarget(self, action: #selector(connect(_:)), for: .touchUpInside)
return cell
}
@objc func connect(_ sender: AnyObject) {
guard let button = sender as? UIButton else { return }
let indexPath = IndexPath(row: button.tag, section: 0)
let user = suggestions[indexPath.row]
if user.isBlocked {
user.accept { [weak self] error in
guard
let strongSelf = self,
let error = error as? UpdateConnectionError
else {
return
}
self?.delegate?.searchSectionController(strongSelf, wantsToDisplayError: error)
}
} else {
user.connect { [weak self] error in
guard
let strongSelf = self,
let error = error as? ConnectToUserError
else {
return
}
self?.delegate?.searchSectionController(strongSelf, wantsToDisplayError: error)
}
}
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let user = suggestions[indexPath.row]
delegate?.searchSectionController(self, didSelectUser: user, at: indexPath)
}
}
extension DirectorySectionController: ZMUserObserver {
func userDidChange(_ changeInfo: UserChangeInfo) {
guard changeInfo.connectionStateChanged else { return }
collectionView?.reloadData()
}
}
| 09d8b7cd9be6ddee6b6f0f71b616d2b3 | 33.957265 | 132 | 0.671149 | false | false | false | false |
ihomway/RayWenderlichCourses | refs/heads/master | iOS Concurrency with GCD and Operations/Dependencies Challenge/Dependencies Challenge/Dependencies Challenge/GradientGenerator.swift | mit | 2 | /*
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
public func topAndBottomGradient(_ size: CGSize, clearLocations: [CGFloat] = [0.4, 0.6], innerIntensity: CGFloat = 0.5) -> UIImage {
let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue)
let colors = [
UIColor.white,
UIColor(white: innerIntensity, alpha: 1.0),
UIColor.black,
UIColor(white: innerIntensity, alpha: 1.0),
UIColor.white
].map { $0.cgColor }
let colorLocations : [CGFloat] = [0, clearLocations[0], (clearLocations[0] + clearLocations[1]) / 2.0, clearLocations[1], 1]
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceGray(), colors: colors as CFArray, locations: colorLocations)
let startPoint = CGPoint(x: 0, y: 0)
let endPoint = CGPoint(x: 0, y: size.height)
context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions())
let cgImage = context?.makeImage()
return UIImage(cgImage: cgImage!)
}
| 416a25f9bc980a0c46efa23cd345208c | 45.617021 | 206 | 0.744409 | false | false | false | false |
Subsets and Splits