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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JohnCoates/Aerial | refs/heads/master | Aerial/Source/Views/AerialView+Player.swift | mit | 1 | //
// AerialView+Player.swift
// Aerial
//
// Created by Guillaume Louel on 06/12/2019.
// Copyright © 2019 Guillaume Louel. All rights reserved.
//
import Foundation
import AVFoundation
import AVKit
extension AerialView {
func setupPlayerLayer(withPlayer player: AVPlayer) {
let displayDetection = DisplayDetection.sharedInstance
self.layer = CALayer()
guard let layer = self.layer else {
errorLog("\(self.description) Couldn't create CALayer")
return
}
self.wantsLayer = true
layer.backgroundColor = NSColor.black.cgColor
layer.needsDisplayOnBoundsChange = true
layer.frame = self.bounds
debugLog("\(self.description) setting up player layer with bounds/frame: \(layer.bounds) / \(layer.frame)")
playerLayer = AVPlayerLayer(player: player)
// Fill/fit is only available in 10.10+
if #available(OSX 10.10, *) {
if PrefsDisplays.aspectMode == .fill {
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
} else {
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
}
}
playerLayer.autoresizingMask = [CAAutoresizingMask.layerWidthSizable, CAAutoresizingMask.layerHeightSizable]
// In case of span mode we need to compute the size of our layer
if PrefsDisplays.viewingMode == .spanned && !isPreview {
let zRect = displayDetection.getZeroedActiveSpannedRect()
let screen = displayDetection.findScreenWith(frame: self.frame)
if let scr = screen {
let tRect = CGRect(x: zRect.origin.x - scr.zeroedOrigin.x,
y: zRect.origin.y - scr.zeroedOrigin.y,
width: zRect.width,
height: zRect.height)
playerLayer.frame = tRect
} else {
errorLog("This is an unknown screen in span mode, this is not good")
playerLayer.frame = layer.bounds
}
} else {
playerLayer.frame = layer.bounds
// "true" mirrored mode
let index = AerialView.instanciatedViews.firstIndex(of: self) ?? 0
if index % 2 == 1 && PrefsDisplays.viewingMode == .mirrored {
playerLayer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(scaleX: -1, y: 1))
}
}
layer.addSublayer(playerLayer)
// The layers for descriptions, clock, message
layerManager.setupExtraLayers(layer: layer, frame: self.frame)
// An extra layer to try and contravent a macOS graphics driver bug
// This is useful on High Sierra+ on Intel Macs
setupGlitchWorkaroundLayer(layer: layer)
}
// MARK: - AVPlayerItem Notifications
@objc func playerItemFailedtoPlayToEnd(_ aNotification: Notification) {
warnLog("\(self.description) AVPlayerItemFailedToPlayToEndTimeNotification \(aNotification)")
playNextVideo()
}
@objc func playerItemNewErrorLogEntryNotification(_ aNotification: Notification) {
warnLog("\(self.description) AVPlayerItemNewErrorLogEntryNotification \(aNotification)")
}
@objc func playerItemPlaybackStalledNotification(_ aNotification: Notification) {
warnLog("\(self.description) AVPlayerItemPlaybackStalledNotification \(aNotification)")
}
@objc func playerItemDidReachEnd(_ aNotification: Notification) {
debugLog("\(self.description) played did reach end")
debugLog("\(self.description) notification: \(aNotification)")
if shouldLoop {
debugLog("Rewinding video!")
if let playerItem = aNotification.object as? AVPlayerItem {
playerItem.seek(to: CMTime.zero, completionHandler: nil)
}
} else {
playNextVideo()
debugLog("\(self.description) playing next video for player \(String(describing: player))")
}
}
// Video fade-in/out
func addPlayerFades(view: AerialView, player: AVPlayer, video: AerialVideo) {
// We only fade in/out if we have duration
if video.duration > 0 && AerialView.shouldFade && !shouldLoop {
let playbackSpeed = Double(PlaybackSpeed.forVideo(video.id))
view.playerLayer.opacity = 0
let fadeAnimation = CAKeyframeAnimation(keyPath: "opacity")
fadeAnimation.values = [0, 1, 1, 0] as [Int]
fadeAnimation.keyTimes = [0,
AerialView.fadeDuration/(video.duration/playbackSpeed),
1-(AerialView.fadeDuration/(video.duration/playbackSpeed)), 1 ] as [NSNumber]
fadeAnimation.duration = video.duration/playbackSpeed
fadeAnimation.calculationMode = CAAnimationCalculationMode.cubic
view.playerLayer.add(fadeAnimation, forKey: "mainfade")
} else {
view.playerLayer.opacity = 1.0
}
}
func removePlayerFades() {
self.playerLayer.removeAllAnimations()
self.playerLayer.opacity = 1.0
}
// This works pre Catalina as of right now
func setupGlitchWorkaroundLayer(layer: CALayer) {
debugLog("Using dot workaround for video driver corruption")
let workaroundLayer = CATextLayer()
workaroundLayer.frame = self.bounds
workaroundLayer.opacity = 1.0
workaroundLayer.font = NSFont(name: "Helvetica Neue Medium", size: 4)
workaroundLayer.fontSize = 4
workaroundLayer.string = "."
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: workaroundLayer.font as Any]
// Calculate bounding box
let attrString = NSAttributedString(string: workaroundLayer.string as! String, attributes: attributes)
let rect = attrString.boundingRect(with: layer.visibleRect.size, options: NSString.DrawingOptions.usesLineFragmentOrigin)
workaroundLayer.frame = rect
workaroundLayer.position = CGPoint(x: 2, y: 2)
workaroundLayer.anchorPoint = CGPoint(x: 0, y: 0)
layer.addSublayer(workaroundLayer)
}
}
| 6c061832af0c0d18f193a938b785939d | 40.164474 | 129 | 0.637206 | false | false | false | false |
mqshen/SwiftForms | refs/heads/master | SwiftForms/cells/FormSwitchCell.swift | mit | 1 | //
// FormSwitchCell.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 FormSwitchCell: FormTitleCell {
// MARK: Cell views
public let switchView = UISwitch()
// MARK: FormBaseCell
public override func configure() {
super.configure()
selectionStyle = .None
switchView.addTarget(self, action: #selector(FormSwitchCell.valueChanged(_:)), forControlEvents: .ValueChanged)
accessoryView = switchView
}
public override func update() {
super.update()
titleLabel.text = rowDescriptor?.title
if let value = rowDescriptor?.value as? Bool {
switchView.on = value
} else {
switchView.on = false
rowDescriptor?.value = false
}
}
// MARK: Actions
internal func valueChanged(_: UISwitch) {
rowDescriptor?.value = switchView.on
}
}
| 7914f2b97a44c202736d172996234041 | 22.086957 | 119 | 0.587571 | false | false | false | false |
Alan881/AAPlayer | refs/heads/master | AAPlayer/AAPlayerActivityIndicicatorView.swift | mit | 2 | //
// AAPlayerActivityIndicicatorView.swift
// AAPlayer
//
// Created by Alan on 2017/7/24.
// Copyright © 2017年 Alan. All rights reserved.
//
import UIKit
class AAPlayerActivityIndicicatorView: UIView {
fileprivate var indicicatorLayer: CALayer!
override init(frame: CGRect) {
super.init(frame: frame)
initWithIndicicatorLayer()
isHidden = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
indicicatorLayer.frame = CGRect(x: 0,y: 0,width: frame.size.width,height: frame.size.height)
indicicatorLayer.contents = createIndicicatorImage().cgImage
}
fileprivate func initWithIndicicatorLayer() {
indicicatorLayer = CALayer()
indicicatorLayer.masksToBounds = true
layer.addSublayer(indicicatorLayer)
}
fileprivate func createIndicicatorImage() -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: frame.width, height: frame.height))
let context = UIGraphicsGetCurrentContext()
let path:CGMutablePath = CGMutablePath()
context!.addArc(center:CGPoint(x: frame.width / 2, y: frame.height / 2), radius: 40, startAngle: 0, endAngle: 1.5 * CGFloat(Double.pi), clockwise: true)
context!.move(to: CGPoint(x: 50, y: 100))
context!.addLine(to: CGPoint(x: 50, y: 150))
context!.addLine(to: CGPoint(x: 100, y: 150))
context!.addPath(path)
let colors = [UIColor(red: 231/255, green: 107/255, blue: 107/255, alpha: 0.6).cgColor,UIColor(red: 231/255, green: 107/255, blue: 107/255, alpha: 0.3).cgColor]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colorLocations:[CGFloat] = [0.6, 1.0]
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: colorLocations)
context?.drawRadialGradient(gradient!, startCenter:CGPoint(x: frame.width / 2, y: frame.height / 2), startRadius: 0, endCenter: CGPoint(x: frame.width / 2 + 5, y: frame.height / 2 + 5), endRadius: 10, options: .drawsBeforeStartLocation)
UIColor(red: 231/255, green: 107/255, blue: 107/255, alpha: 1).setStroke()
context?.drawPath(using: .stroke)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
fileprivate func setAnimation() -> CABasicAnimation {
let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.duration = 1.0
rotation.isRemovedOnCompletion = false
rotation.repeatCount = Float.infinity
rotation.fillMode = kCAFillModeForwards
rotation.fromValue = 0.0
rotation.toValue = Double.pi * 2;
return rotation
}
fileprivate func pauseAnimation() {
let pausedTime = indicicatorLayer.convertTime(CACurrentMediaTime(), from: nil)
indicicatorLayer.speed = 0.0
indicicatorLayer.timeOffset = pausedTime
}
fileprivate func resumeAnimation() {
let pauseTime = indicicatorLayer.timeOffset
indicicatorLayer.speed = 1.0
indicicatorLayer.timeOffset = 0.0
let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pauseTime
indicicatorLayer.beginTime = timeSincePause
}
func startAnimation() {
if indicicatorLayer.animation(forKey: "rotation") == nil {
indicicatorLayer.add(setAnimation(), forKey: "rotation")
}
isHidden = false
resumeAnimation()
}
func stopAnimation() {
isHidden = true
pauseAnimation()
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 5afdfca5f49800c0431167a90bd3a007 | 33.299145 | 244 | 0.638425 | false | false | false | false |
mono0926/LicensePlist | refs/heads/main | Sources/LicensePlistCore/Entity/Manual.swift | mit | 1 | import Foundation
import APIKit
import LoggerAPI
import Yaml
public class Manual: Library {
public let name: String
public var body: String? // Used as a container between YAML and ManualLicence
public var source: String?
public var nameSpecified: String?
public var version: String?
public let licenseType: LicenseType
public init(name n: String, source: String?, nameSpecified: String?, version: String?, licenseType: LicenseType = .unknown) {
self.name = n
self.source = source
self.nameSpecified = nameSpecified
self.version = version
self.licenseType = licenseType
}
}
extension Manual {
public static func==(lhs: Manual, rhs: Manual) -> Bool {
return lhs.name == rhs.name &&
lhs.nameSpecified == rhs.nameSpecified &&
lhs.version == rhs.version &&
lhs.source == rhs.source
}
}
extension Manual: CustomStringConvertible {
public var description: String {
return "name: \(name), source: \(source ?? ""), nameSpecified: \(nameSpecified ?? ""), version: \(version ?? "")"
}
}
extension Manual {
public static func load(_ raw: [Yaml],
renames: [String: String], configBasePath: URL) -> [Manual] {
return raw.map { (manualEntry) -> Manual in
var name = ""
var body: String?
var source: String?
var version: String?
for valuePair in manualEntry.dictionary ?? [:] {
switch valuePair.key.string ?? "" {
case "source":
source = valuePair.value.string
case "name":
name = valuePair.value.string ?? ""
case "version":
version = valuePair.value.string
case "body":
body = valuePair.value.string
case "file":
let url = configBasePath.appendingPathComponent(valuePair.value.string!)
body = try! String(contentsOf: url)
default:
Log.warning("Tried to parse an unknown YAML key")
}
}
let manual = Manual(name: name, source: source, nameSpecified: renames[name], version: version)
manual.body = body // This is so that we do not have to store a body at all ( for testing purposes mostly )
return manual
}
}
}
| 52f3f1a782ac0c93e816c84ea09e6ee8 | 35.308824 | 129 | 0.564196 | false | false | false | false |
achimk/Swift-UIKit-Extensions | refs/heads/master | Controllers/UISplitViewController+Extensions.swift | mit | 1 | //
// UISplitViewController+Extensions.swift
//
// Created by Joachim Kret on 06/10/15.
// Copyright © 2015 Joachim Kret. All rights reserved.
//
import UIKit
extension UISplitViewController: Autorotatable {
private struct Static {
static var token: dispatch_once_t = 0
static var AutorotationMode = "AutorotationMode"
}
// MARK: Swizzle
public override class func initialize() {
// make sure this isn't a subclass
if self !== UISplitViewController.self {
return
}
dispatch_once(&Static.token) {
swizzleInstanceMethod(self, sel1: "shouldAutorotate", sel2: "swizzled_shouldAutorotate")
swizzleInstanceMethod(self, sel1: "supportedInterfaceOrientations", sel2: "swizzled_supportedInterfaceOrientations")
}
}
// MARK: Accessors
var autorotation: Autorotation {
get {
if let autorotationMode = objc_getAssociatedObject(self, &Static.AutorotationMode) as? Int {
return Autorotation(rawValue: autorotationMode)!
} else {
return Autorotation.Container
}
}
set {
objc_setAssociatedObject(self, &Static.AutorotationMode, newValue.rawValue as Int?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: Swizzled Rotation Methods
func swizzled_shouldAutorotate() -> Bool {
switch autorotation {
case .Container:
return self.swizzled_shouldAutorotate()
case .ContainerAndTopChildren, .ContainerAndAllChildren:
for viewController in viewControllers {
if !viewController.shouldAutorotate() {
return false
}
}
return true
}
}
func swizzled_supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
var mask = UIInterfaceOrientationMask.All.rawValue
switch autorotation {
case .Container:
mask = self.swizzled_supportedInterfaceOrientations().rawValue
case .ContainerAndTopChildren, .ContainerAndAllChildren:
for viewController in viewControllers.reverse() {
mask &= viewController.supportedInterfaceOrientations().rawValue
}
}
return UIInterfaceOrientationMask(rawValue: mask)
}
}
| c31f1e8df5b5c1e52ba0e880a4e87d4d | 30.278481 | 131 | 0.604209 | false | false | false | false |
rgkobashi/PhotoSearcher | refs/heads/master | PhotoViewer/FlickrService.swift | mit | 1 | //
// FlickrService.swift
// PhotoViewer
//
// Created by Rogelio Martinez Kobashi on 2/28/17.
// Copyright © 2017 Rogelio Martinez Kobashi. All rights reserved.
//
import Foundation
class FlickrService: Service
{
var requestType = RequestType.GET
var contentType = ContentType.NONE
var acceptType = AcceptType.JSON
var timeOut: TimeInterval = 30
var requestURL = ""
var requestParams: [String: AnyObject]?
var additionalHeaders: [String: String]?
init(tag: String)
{
requestURL = kURLFlickr + "&api_key=" + kKeyFlickr + "&tags=" + tag
}
}
| 263abd97a42789394e17f3737be94bb5 | 22.076923 | 75 | 0.666667 | false | false | false | false |
JJCoderiOS/CollectionViewPhotoBrowse | refs/heads/master | Swift版本的CollectionView/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// Swift版本的CollectionView
//
// Created by majianjie on 2016/12/7.
// Copyright © 2016年 ddtc. All rights reserved.
//
import UIKit
import MJExtension
let ID : String = "DDCollectionCell"
class ViewController: UIViewController,UICollectionViewDelegate {
open var collectionView:UICollectionView!
fileprivate var shops:[ShopModel] = [ShopModel]()
fileprivate lazy var modalDelegate: ModalAnimationDelegate = ModalAnimationDelegate()
override func viewDidLoad() {
super.viewDidLoad()
let shops = ShopModel.mj_objectArray(withFilename: "1.plist")
for shop in shops!{
self.shops.append(shop as! ShopModel)
}
let layout = DDCollectionFlowLayout()
layout.delegate = self
self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
self.collectionView.backgroundColor = UIColor.white
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.view.addSubview(self.collectionView)
let nib = UINib(nibName: "DDCollectionCell", bundle: nil)
self.collectionView.register(nib, forCellWithReuseIdentifier: ID)
}
}
extension ViewController : UICollectionViewDataSource{
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : DDCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: ID, for: indexPath) as! DDCollectionCell
cell.setShops(self.shops[indexPath.item])
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.shops.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.bottom)
let photoVC = PhotoBrowseCollectionVC()
photoVC.indexPaht = indexPath
photoVC.items = self.shops
photoVC.transitioningDelegate = modalDelegate
photoVC.modalPresentationStyle = .custom
present(photoVC, animated: true, completion: nil)
}
}
extension ViewController:UICollectionViewLayoutDelegate{
func waterFlow(_ layout : DDCollectionFlowLayout,_ width : CGFloat,_ indexPath : NSIndexPath) -> CGFloat
{
let shop = self.shops[indexPath.item] as ShopModel
let h = ((shop.h) as NSString).floatValue
let w = ((shop.w) as NSString).floatValue
return CGFloat( h / w ) * width
}
}
| d28cba1cf3674c9ee40d14f9911edef6 | 28.59596 | 134 | 0.648123 | false | false | false | false |
Chaosspeeder/YourGoals | refs/heads/master | YourGoals/Business/Data Model/Extensions/Goal+Type.swift | lgpl-3.0 | 1 | //
// Goal+Type.swift
// YourGoals
//
// Created by André Claaßen on 22.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
enum GoalType:Int16 {
case userGoal = 0
case strategyGoal = 1
case todayGoal = 2
}
extension Goal {
/// retrieve a valid goal type
///
/// - Returns: .userGoal, .todayGoal or .strategyGoal
func goalType() -> GoalType {
if self.parentGoal == nil {
return .strategyGoal
}
return GoalType(rawValue: self.type)!
}
}
| 4808a88f45e7050e71878016740d2a30 | 18.206897 | 57 | 0.59246 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-duplicates/07736-getselftypeforcontainer.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a
class A<T? {
func a(object1: b()?
{
typealias F = a<T where g: NSObject {
var e: A? {
var e: T: A {
func a
}
if true {
map()?
return "
return "
enum S<T : a : A<T: A : e : e {
func a
protocol a {
typealias e : e {
protocol a {
typealias e : b(_ = compose(s(object1: NSObject {
func a
var e: A : a {
typealias F = 1]]
class A.c {
class A.c {
var e: A {
return "
() -> Any in
let t: b("
return "
class A
protocol A : a {
func a
enum S<T where g: T>(_ = F
if true {
class A {
typealias e : Int = D>) {
{
var d {
map(t: Int = 1]
var e: T : a {
class A
(object1: NSObject {
map("
var a(t: A {
var b = D>) {
map(t: NSObject {
protocol A : Int = A<T {
class B? = 1]
protocol A
| 3d869ded7a89141372a3b0daa083f9dc | 14.962264 | 87 | 0.612293 | false | false | false | false |
CodeMozart/MHzSinaWeibo-Swift- | refs/heads/master | SinaWeibo(stroyboard)/SinaWeibo/Classes/Main/VisitorView.swift | mit | 1 | //
// VisitorView.swift
// SinaWeibo
//
// Created by Minghe on 11/6/15.
// Copyright © 2015 Stanford swift. All rights reserved.
//
import UIKit
class VisitorView: UIView {
// 转盘
@IBOutlet weak var turntableView: UIImageView!
// 大图标
@IBOutlet weak var iconView: UIImageView!
// 文本视图
@IBOutlet weak var titleView: UILabel!
// 注册按钮
@IBOutlet weak var registerBtn: UIButton!
// 登录按钮
@IBOutlet weak var loginBtn: UIButton!
/**
快速创建方法
- returns: xib加载的访客页面
*/
class func visitorView() -> VisitorView {
return NSBundle.mainBundle().loadNibNamed("VisitorView", owner: nil, options: nil).last as! VisitorView
}
// MARK: - 外部控制方法
func setupVisitorInfo(imageName: String?, title: String)
{
// homepage
// (因为xib绘制的就是首页的样子,所以首页在调用这个方法的时候不给imageName赋值,这样就可以直接进到else)
guard let name = imageName else
{
startAnimation()
return
}
// other pages
iconView.image = UIImage(named: name)
titleView.text = title
turntableView.hidden = true
}
// MARK: - 内部控制方法
private func startAnimation()
{
// 1.创建动画对象
let anim = CABasicAnimation(keyPath: "transform.rotation")
// 2.设置动画属性
anim.toValue = 2 * M_PI
anim.duration = 10.0
anim.repeatCount = MAXFLOAT
// 2.1告诉系统不要随便移除动画,只有当控件销毁的时候才需要移除
anim.removedOnCompletion = false
// 3.将动画添加到图层
turntableView.layer.addAnimation(anim, forKey: nil)
}
}
| 5faac1f8924a9c25dd7d3afcfd6735b7 | 22.588235 | 111 | 0.590399 | false | false | false | false |
think-dev/UIRefreshableScrollView | refs/heads/master | UIRefreshableScrollView/UIRefreshableScrollView.swift | mit | 1 |
import UIKit
public protocol UIRefreshableScrollViewDelegate: class {
func didStartRefreshing()
func didEndRefreshing()
}
extension UIRefreshableScrollViewDelegate {
func didPull(with pullDistance: CGFloat, and pullRatio: CGFloat) {
}
}
open class UIRefreshableScrollView: UIScrollView, Refreshable {
open weak var refreshDelegate: UIRefreshableScrollViewDelegate?
open var customRefreshView: UIRefreshControlContentView? {
didSet {
insertRefreshControl(using: customRefreshView)
}
}
open var pullToRefreshControl: UIRefreshControl?
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
delegate = self
pullToRefreshControl = UIRefreshControl()
pullToRefreshControl?.tintColor = .clear
pullToRefreshControl?.backgroundColor = .clear
}
open func endRefreshing() {
guard let refreshControlInstance = pullToRefreshControl else {
fatalError("refreshControl cannot be nil")
}
refreshControlInstance.endRefreshing()
refreshControlInstance.sendActions(for: .valueChanged)
}
override open func manageRefreshing() {
guard let refreshControlInstance = pullToRefreshControl else {
fatalError("refreshControl cannot be nil")
}
if refreshControlInstance.isRefreshing {
refreshDelegate?.didStartRefreshing()
} else {
checkForStickyRefreshControlBounds()
refreshDelegate?.didEndRefreshing()
}
}
}
extension UIRefreshableScrollView: UIScrollViewDelegate {
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
update(using: scrollView.contentOffset.y)
}
private func update(using offset: CGFloat) {
guard let refreshControlInstance = pullToRefreshControl else {
fatalError("refreshControl cannot be nil")
}
let pullDistance = max(0.0, -refreshControlInstance.frame.origin.y)
let pullRatio = min(max(pullDistance, 0.0), 100.0) / 100.0
customRefreshView?.performUpdates(using: pullDistance, and: pullRatio)
refreshDelegate?.didPull(with: pullDistance, and: pullRatio)
}
open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
checkForStickyRefreshControlBounds()
}
internal func checkForStickyRefreshControlBounds() {
guard let refreshControlInstance = pullToRefreshControl else {
fatalError("refreshControl cannot be nil")
}
guard let refreshView = customRefreshView else {
return
}
if refreshControlInstance.isRefreshing {
let currentContentOffset = CGPoint(x: 0, y: -refreshView.theme.maximumHeight)
DispatchQueue.main.async {
self.setContentOffset(currentContentOffset, animated: true)
}
} else {
DispatchQueue.main.async {
let currentContentOffset = CGPoint(x: 0, y: 0)
self.setContentOffset(currentContentOffset, animated: true)
}
}
}
}
| 76bd6f7d6aba0542c3ab1f5deae1fa23 | 30.768519 | 101 | 0.646459 | false | false | false | false |
PiXeL16/RevealingSplashView | refs/heads/master | RevealingSplashView/Animations.swift | mit | 1 | //
// Animations.swift
// RevealingSplashView
//
// Created by Chris Jimenez on 2/26/16.
// Copyright © 2016 Chris Jimenez. All rights reserved.
//
import Foundation
import UIKit
public typealias SplashAnimatableCompletion = () -> Void
public typealias SplashAnimatableExecution = () -> Void
// MARK: - Class extension to define the basic functionality for the RevealingSplashView class
public extension RevealingSplashView {
/**
Starts the animation depending on the type
*/
func startAnimation(_ completion: SplashAnimatableCompletion? = nil)
{
switch animationType{
case .twitter:
playTwitterAnimation(completion)
case .rotateOut:
playRotateOutAnimation(completion)
case .woobleAndZoomOut:
playWoobleAnimation(completion)
case .swingAndZoomOut:
playSwingAnimation(completion)
case .popAndZoomOut:
playPopAnimation(completion)
case .squeezeAndZoomOut:
playSqueezeAnimation(completion)
case .heartBeat:
playHeartBeatAnimation(completion)
}
}
/**
Plays the twitter animation
*/
func playTwitterAnimation(_ completion: SplashAnimatableCompletion? = nil)
{
if let imageView = self.imageView {
//Define the shink and grow duration based on the duration parameter
let shrinkDuration: TimeInterval = duration * 0.3
//Plays the shrink animation
UIView.animate(withDuration: shrinkDuration, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 10, options: UIView.AnimationOptions(), animations: {
//Shrinks the image
let scaleTransform: CGAffineTransform = CGAffineTransform(scaleX: 0.75,y: 0.75)
imageView.transform = scaleTransform
//When animation completes, grow the image
}, completion: { finished in
self.playZoomOutAnimation(completion)
})
}
}
/**
Plays the twitter animation
*/
func playSqueezeAnimation(_ completion: SplashAnimatableCompletion? = nil)
{
if let imageView = self.imageView {
//Define the shink and grow duration based on the duration parameter
let shrinkDuration: TimeInterval = duration * 0.5
//Plays the shrink animation
UIView.animate(withDuration: shrinkDuration, delay: delay/3, usingSpringWithDamping: 10, initialSpringVelocity: 10, options: UIView.AnimationOptions(), animations: {
//Shrinks the image
let scaleTransform: CGAffineTransform = CGAffineTransform(scaleX: 0.30,y: 0.30)
imageView.transform = scaleTransform
//When animation completes, grow the image
}, completion: { finished in
self.playZoomOutAnimation(completion)
})
}
}
/**
Plays the rotate out animation
- parameter completion: when the animation completes
*/
func playRotateOutAnimation(_ completion: SplashAnimatableCompletion? = nil)
{
if let imageView = self.imageView{
/**
Sets the animation with duration delay and completion
- returns:
*/
UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping: 0.5, initialSpringVelocity: 3, options: UIView.AnimationOptions(), animations: {
//Sets a simple rotate
let rotateTranform = CGAffineTransform(rotationAngle: CGFloat(Double.pi * 0.99))
//Mix the rotation with the zoom out animation
imageView.transform = rotateTranform.concatenating(self.getZoomOutTranform())
//Removes the animation
self.alpha = 0
}, completion: { finished in
self.removeFromSuperview()
completion?()
})
}
}
/**
Plays a wobble animtion and then zoom out
- parameter completion: completion
*/
func playWoobleAnimation(_ completion: SplashAnimatableCompletion? = nil) {
if let imageView = self.imageView{
let woobleForce = 0.5
animateLayer({
let rotation = CAKeyframeAnimation(keyPath: "transform.rotation")
rotation.values = [0, 0.3 * woobleForce, -0.3 * woobleForce, 0.3 * woobleForce, 0]
rotation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
rotation.isAdditive = true
let positionX = CAKeyframeAnimation(keyPath: "position.x")
positionX.values = [0, 30 * woobleForce, -30 * woobleForce, 30 * woobleForce, 0]
positionX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
positionX.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
positionX.isAdditive = true
let animationGroup = CAAnimationGroup()
animationGroup.animations = [rotation, positionX]
animationGroup.duration = CFTimeInterval(self.duration/2)
animationGroup.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay/2)
animationGroup.repeatCount = 2
imageView.layer.add(animationGroup, forKey: "wobble")
}, completion: {
self.playZoomOutAnimation(completion)
})
}
}
/**
Plays the swing animation and zoom out
- parameter completion: completion
*/
func playSwingAnimation(_ completion: SplashAnimatableCompletion? = nil)
{
if let imageView = self.imageView{
let swingForce = 0.8
animateLayer({
let animation = CAKeyframeAnimation(keyPath: "transform.rotation")
animation.values = [0, 0.3 * swingForce, -0.3 * swingForce, 0.3 * swingForce, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.duration = CFTimeInterval(self.duration/2)
animation.isAdditive = true
animation.repeatCount = 2
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay/3)
imageView.layer.add(animation, forKey: "swing")
}, completion: {
self.playZoomOutAnimation(completion)
})
}
}
/**
Plays the pop animation with completion
- parameter completion: completion
*/
func playPopAnimation(_ completion: SplashAnimatableCompletion? = nil)
{
if let imageView = self.imageView{
let popForce = 0.5
animateLayer({
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
animation.values = [0, 0.2 * popForce, -0.2 * popForce, 0.2 * popForce, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.duration = CFTimeInterval(self.duration/2)
animation.isAdditive = true
animation.repeatCount = 2
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay/2)
imageView.layer.add(animation, forKey: "pop")
}, completion: {
self.playZoomOutAnimation(completion)
})
}
}
/**
Plays the zoom out animation with completion
- parameter completion: completion
*/
func playZoomOutAnimation(_ completion: SplashAnimatableCompletion? = nil)
{
if let imageView = imageView
{
let growDuration: TimeInterval = duration * 0.3
UIView.animate(withDuration: growDuration, animations:{
imageView.transform = self.getZoomOutTranform()
self.alpha = 0
//When animation completes remote self from super view
}, completion: { finished in
self.removeFromSuperview()
completion?()
})
}
}
/**
Retuns the default zoom out transform to be use mixed with other transform
- returns: ZoomOut fransfork
*/
fileprivate func getZoomOutTranform() -> CGAffineTransform
{
let zoomOutTranform: CGAffineTransform = CGAffineTransform(scaleX: 20, y: 20)
return zoomOutTranform
}
// MARK: - Private
fileprivate func animateLayer(_ animation: SplashAnimatableExecution, completion: SplashAnimatableCompletion? = nil) {
CATransaction.begin()
if let completion = completion {
CATransaction.setCompletionBlock { completion() }
}
animation()
CATransaction.commit()
}
/**
Plays the heatbeat animation with completion
- parameter completion: completion
*/
func playHeartBeatAnimation(_ completion: SplashAnimatableCompletion? = nil)
{
if let imageView = self.imageView {
let popForce = 0.8
animateLayer({
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
animation.values = [0, 0.1 * popForce, 0.015 * popForce, 0.2 * popForce, 0]
animation.keyTimes = [0, 0.25, 0.35, 0.55, 1]
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.duration = CFTimeInterval(self.duration/2)
animation.isAdditive = true
animation.repeatCount = Float(minimumBeats > 0 ? minimumBeats : 1)
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay/2)
imageView.layer.add(animation, forKey: "pop")
}, completion: { [weak self] in
if self?.heartAttack ?? true {
self?.playZoomOutAnimation(completion)
} else {
self?.playHeartBeatAnimation(completion)
}
})
}
}
/**
Stops the heart beat animation after gracefully finishing the last beat
This function will not stop the original completion block from getting called
*/
func finishHeartBeatAnimation()
{
self.heartAttack = true
}
}
| 72a62210c6f85ab64f195e2bf744bad5 | 34.062305 | 175 | 0.556819 | false | false | false | false |
yonadev/yona-app-ios | refs/heads/develop | Yona/Yona/BuddyRequestManager.swift | mpl-2.0 | 1 | //
// BuddyRequestManager.swift
// Yona
//
// Created by Ben Smith on 11/05/16.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
class BuddyRequestManager {
let APIService = APIServiceManager.sharedInstance
let APIUserRequestManager = UserRequestManager.sharedInstance
static let sharedInstance = BuddyRequestManager()
var buddy: Buddies?
var buddies: [Buddies] = []
fileprivate init() {}
fileprivate func genericBuddyRequest(_ httpMethod: httpMethods, buddyBody: BodyDataDictionary?, buddy: Buddies?, onCompletion: @escaping APIBuddiesResponse) {
UserRequestManager.sharedInstance.getUser(GetUserRequest.notAllowed){ (success, serverMessage, serverCode, user) in
switch httpMethod {
case .get:
if let buddieLink = user?.buddiesLink {
ActivitiesRequestManager.sharedInstance.getActivityCategories{ (success, message, serverCode, activities, error) in
if success {
self.APIService.callRequestWithAPIServiceResponse(nil, path: buddieLink, httpMethod: httpMethod) { (success, json, error) in
if success {
self.buddies.removeAll()
if let json = json {
if let embedded = json[postBuddyBodyKeys.embedded.rawValue],
let yonaBuddies = embedded[postBuddyBodyKeys.yonaBuddies.rawValue] as? NSArray{
//iterate messages
for buddy in yonaBuddies {
if let buddy = buddy as? BodyDataDictionary {
if let allActivities = activities {
self.buddy = Buddies.init(buddyData: buddy, allActivity: allActivities)
} else {
self.buddy = Buddies.init(buddyData: buddy, allActivity: [])
}
if let buddy = self.buddy {
if buddy.UserRequestmobileNumber.count > 0 {
self.buddies.append(buddy)
}
}
}
}
onCompletion(success, serverMessage, serverCode, nil, self.buddies)
} else { //we just get a buddy response back
self.buddy = Buddies.init(buddyData: json, allActivity: activities!)
onCompletion(success, serverMessage, serverCode, self.buddy, nil)
}
} else {
onCompletion(success, serverMessage, serverCode, nil, nil) //failed json response
}
} else {
onCompletion(success, serverMessage, serverCode, nil, nil)
}
}
}
}
} else {
onCompletion(false, YonaConstants.YonaErrorTypes.GetBuddyLinkFail.localizedDescription, self.APIService.determineErrorCode(YonaConstants.YonaErrorTypes.GetBuddyLinkFail), nil, nil)
}
break
case .post:
if let buddieLink = user?.buddiesLink {
self.APIService.callRequestWithAPIServiceResponse(buddyBody, path: buddieLink, httpMethod: httpMethod) { (success, json, error) in
if success {
if let json = json {
self.buddy = Buddies.init(buddyData: json, allActivity: [])
onCompletion(success, serverMessage, serverCode, self.buddy, nil) //failed to get user
} else {
onCompletion(success, serverMessage, serverCode, nil, nil) //failed json response
}
} else {
if let json = json {
guard let message = json["message"] else { return }
onCompletion(success, message as? ServerMessage, serverCode, nil, nil)
} else {
onCompletion(success, serverMessage, serverCode, nil, nil)
}
}
}
} else {
onCompletion(false, YonaConstants.YonaErrorTypes.GetBuddyLinkFail.localizedDescription, self.APIService.determineErrorCode(YonaConstants.YonaErrorTypes.GetBuddyLinkFail), nil, nil)
}
break
case .put:
break
case .delete:
if let editBuddyLink = buddy?.editLink {
self.APIService.callRequestWithAPIServiceResponse(nil, path: editBuddyLink, httpMethod: httpMethod) { (success, json, error) in
onCompletion(success, serverMessage, serverCode, nil, nil)
}
} else {
onCompletion(false, YonaConstants.YonaErrorTypes.GetBuddyLinkFail.localizedDescription, self.APIService.determineErrorCode(YonaConstants.YonaErrorTypes.GetBuddyLinkFail), nil, nil)
}
break
}
}
}
func requestNewbuddy(_ buddyBody: BodyDataDictionary, onCompletion: @escaping APIBuddiesResponse) {
self.genericBuddyRequest(httpMethods.post, buddyBody: buddyBody, buddy: nil, onCompletion: onCompletion)
}
func getAllbuddies(_ onCompletion: @escaping APIBuddiesResponse) {
self.genericBuddyRequest(httpMethods.get, buddyBody: nil, buddy: nil, onCompletion: onCompletion)
}
func deleteBuddy(_ buddy: Buddies?, onCompletion: @escaping APIBuddiesResponse) {
self.genericBuddyRequest(httpMethods.delete, buddyBody: nil, buddy: buddy, onCompletion: onCompletion)
}
func getBuddy(_ buddiesLink: String?, onCompletion: @escaping APIBuddiesResponse) {
if let buddieLink = buddiesLink {
ActivitiesRequestManager.sharedInstance.getActivityCategories{ (success, message, serverCode, activities, error) in
if success {
self.APIService.callRequestWithAPIServiceResponse(nil, path: buddieLink, httpMethod: httpMethods.get) { (success, json, error ) in
if success {
self.buddies.removeAll()
if let json = json {
//we just get a buddy response back
self.buddy = Buddies.init(buddyData: json, allActivity: activities!)
onCompletion(success,error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), self.buddy, nil)
} else {
onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil, nil) //failed json response
}
} else {
onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil, nil)
}
}
}
}
} else {
onCompletion(false, YonaConstants.YonaErrorTypes.GetBuddyLinkFail.localizedDescription, self.APIService.determineErrorCode(YonaConstants.YonaErrorTypes.GetBuddyLinkFail), nil, nil)
}
}
}
| 161f2f01fecdb515e57c631a71cb5c46 | 56.589041 | 200 | 0.500714 | false | false | false | false |
matsprea/omim | refs/heads/master | iphone/Maps/Classes/CarPlay/CarPlayService.swift | apache-2.0 | 2 | import CarPlay
import Contacts
@available(iOS 12.0, *)
@objc(MWMCarPlayService)
final class CarPlayService: NSObject {
@objc static let shared = CarPlayService()
@objc var isCarplayActivated: Bool = false
private var searchService: CarPlaySearchService?
private var router: CarPlayRouter?
private var window: CPWindow?
private var interfaceController: CPInterfaceController?
private var sessionConfiguration: CPSessionConfiguration?
var currentPositionMode: MWMMyPositionMode = .pendingPosition
var isSpeedCamActivated: Bool {
set {
router?.updateSpeedCameraMode(newValue ? .always: .never)
}
get {
let mode: SpeedCameraManagerMode = router?.speedCameraMode ?? .never
return mode == .always ? true : false
}
}
var isKeyboardLimited: Bool {
return sessionConfiguration?.limitedUserInterfaces.contains(.keyboard) ?? false
}
private var carplayVC: CarPlayMapViewController? {
return window?.rootViewController as? CarPlayMapViewController
}
private var rootMapTemplate: CPMapTemplate? {
return interfaceController?.rootTemplate as? CPMapTemplate
}
var preparedToPreviewTrips: [CPTrip] = []
var isUserPanMap: Bool = false
@objc func setup(window: CPWindow, interfaceController: CPInterfaceController) {
isCarplayActivated = true
self.window = window
self.interfaceController = interfaceController
self.interfaceController?.delegate = self
sessionConfiguration = CPSessionConfiguration(delegate: self)
searchService = CarPlaySearchService()
let router = CarPlayRouter()
router.addListener(self)
router.subscribeToEvents()
router.setupCarPlaySpeedCameraMode()
self.router = router
MWMRouter.unsubscribeFromEvents()
applyRootViewController()
if let sessionData = router.restoredNavigationSession() {
applyNavigationRootTemplate(trip: sessionData.0, routeInfo: sessionData.1)
} else {
applyBaseRootTemplate()
router.restoreTripPreviewOnCarplay(beforeRootTemplateDidAppear: true)
}
ThemeManager.invalidate()
FrameworkHelper.updatePositionArrowOffset(false, offset: 5)
}
@objc func destroy() {
if let carplayVC = carplayVC {
carplayVC.removeMapView()
}
MapViewController.shared()?.disableCarPlayRepresentation()
MapViewController.shared()?.remove(self)
router?.removeListener(self)
router?.unsubscribeFromEvents()
router?.setupInitialSpeedCameraMode()
MWMRouter.subscribeToEvents()
isCarplayActivated = false
if router?.currentTrip != nil {
MWMRouter.showNavigationMapControls()
} else if router?.previewTrip != nil {
MWMRouter.rebuild(withBestRouter: true)
}
searchService = nil
router = nil
sessionConfiguration = nil
interfaceController = nil
ThemeManager.invalidate()
FrameworkHelper.updatePositionArrowOffset(true, offset: 0)
}
@objc func interfaceStyle() -> UIUserInterfaceStyle {
if let window = window,
window.traitCollection.userInterfaceIdiom == .carPlay {
return window.traitCollection.userInterfaceStyle
}
return .unspecified
}
private func applyRootViewController() {
guard let window = window else { return }
let carplaySotyboard = UIStoryboard.instance(.carPlay)
let carplayVC = carplaySotyboard.instantiateInitialViewController() as! CarPlayMapViewController
window.rootViewController = carplayVC
if let mapVC = MapViewController.shared() {
currentPositionMode = mapVC.currentPositionMode
mapVC.enableCarPlayRepresentation()
carplayVC.addMapView(mapVC.mapView, mapButtonSafeAreaLayoutGuide: window.mapButtonSafeAreaLayoutGuide)
mapVC.add(self)
}
}
private func applyBaseRootTemplate() {
let mapTemplate = MapTemplateBuilder.buildBaseTemplate(positionMode: currentPositionMode)
mapTemplate.mapDelegate = self
interfaceController?.setRootTemplate(mapTemplate, animated: true)
FrameworkHelper.rotateMap(0.0, animated: false)
}
private func applyNavigationRootTemplate(trip: CPTrip, routeInfo: RouteInfo) {
let mapTemplate = MapTemplateBuilder.buildNavigationTemplate()
mapTemplate.mapDelegate = self
interfaceController?.setRootTemplate(mapTemplate, animated: true)
router?.startNavigationSession(forTrip: trip, template: mapTemplate)
if let estimates = createEstimates(routeInfo: routeInfo) {
mapTemplate.updateEstimates(estimates, for: trip)
}
if let carplayVC = carplayVC {
carplayVC.updateCurrentSpeed(routeInfo.speed)
carplayVC.showSpeedControl()
}
}
func pushTemplate(_ templateToPush: CPTemplate, animated: Bool) {
if let interfaceController = interfaceController {
switch templateToPush {
case let list as CPListTemplate:
list.delegate = self
case let search as CPSearchTemplate:
search.delegate = self
case let map as CPMapTemplate:
map.mapDelegate = self
default:
break
}
interfaceController.pushTemplate(templateToPush, animated: animated)
}
}
func popTemplate(animated: Bool) {
interfaceController?.popTemplate(animated: animated)
}
func presentAlert(_ template: CPAlertTemplate, animated: Bool) {
interfaceController?.dismissTemplate(animated: false)
interfaceController?.presentTemplate(template, animated: animated)
}
func cancelCurrentTrip() {
router?.cancelTrip()
if let carplayVC = carplayVC {
carplayVC.hideSpeedControl()
}
updateMapTemplateUIToBase()
}
func updateCameraUI(isCameraOnRoute: Bool, speedLimit limit: String?) {
if let carplayVC = carplayVC {
let speedLimit = limit == nil ? nil : Int(limit!)
carplayVC.updateCameraInfo(isCameraOnRoute: isCameraOnRoute, speedLimit: speedLimit)
}
}
func updateMapTemplateUIToBase() {
guard let mapTemplate = rootMapTemplate else {
return
}
MapTemplateBuilder.configureBaseUI(mapTemplate: mapTemplate)
if currentPositionMode == .pendingPosition {
mapTemplate.leadingNavigationBarButtons = []
} else if currentPositionMode == .follow || currentPositionMode == .followAndRotate {
MapTemplateBuilder.setupDestinationButton(mapTemplate: mapTemplate)
} else {
MapTemplateBuilder.setupRecenterButton(mapTemplate: mapTemplate)
}
updateVisibleViewPortState(.default)
FrameworkHelper.rotateMap(0.0, animated: true)
}
func updateMapTemplateUIToTripFinished(_ trip: CPTrip) {
guard let mapTemplate = rootMapTemplate else {
return
}
mapTemplate.leadingNavigationBarButtons = []
mapTemplate.trailingNavigationBarButtons = []
mapTemplate.mapButtons = []
let doneAction = CPAlertAction(title: L("done"), style: .cancel) { [unowned self] _ in
self.updateMapTemplateUIToBase()
}
var subtitle = ""
if let locationName = trip.destination.name {
subtitle = locationName
}
if let address = trip.destination.placemark.addressDictionary?[CNPostalAddressStreetKey] as? String {
subtitle = subtitle + "\n" + address
}
let alert = CPNavigationAlert(titleVariants: [L("trip_finished")],
subtitleVariants: [subtitle],
imageSet: nil,
primaryAction: doneAction,
secondaryAction: nil,
duration: 0)
mapTemplate.present(navigationAlert: alert, animated: true)
}
func updateVisibleViewPortState(_ state: CPViewPortState) {
guard let carplayVC = carplayVC else {
return
}
carplayVC.updateVisibleViewPortState(state)
}
func updateRouteAfterChangingSettings() {
router?.rebuildRoute()
}
@objc func showNoMapAlert() {
guard let mapTemplate = interfaceController?.topTemplate as? CPMapTemplate,
let info = mapTemplate.userInfo as? MapInfo,
info.type == CPConstants.TemplateType.main else {
return
}
let alert = CPAlertTemplate(titleVariants: [L("download_map_carplay")], actions: [])
alert.userInfo = [CPConstants.TemplateKey.alert: CPConstants.TemplateType.downloadMap]
presentAlert(alert, animated: true)
}
@objc func hideNoMapAlert() {
if let presentedTemplate = interfaceController?.presentedTemplate,
let info = presentedTemplate.userInfo as? [String: String],
let alertType = info[CPConstants.TemplateKey.alert],
alertType == CPConstants.TemplateType.downloadMap {
interfaceController?.dismissTemplate(animated: true)
}
}
}
// MARK: - CPInterfaceControllerDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPInterfaceControllerDelegate {
func templateWillAppear(_ aTemplate: CPTemplate, animated: Bool) {
guard let info = aTemplate.userInfo as? MapInfo else {
return
}
switch info.type {
case CPConstants.TemplateType.main:
updateVisibleViewPortState(.default)
case CPConstants.TemplateType.preview:
updateVisibleViewPortState(.preview)
case CPConstants.TemplateType.navigation:
updateVisibleViewPortState(.navigation)
case CPConstants.TemplateType.previewSettings:
aTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.preview)
default:
break
}
}
func templateDidAppear(_ aTemplate: CPTemplate, animated: Bool) {
guard let mapTemplate = aTemplate as? CPMapTemplate,
let info = aTemplate.userInfo as? MapInfo else {
return
}
if !preparedToPreviewTrips.isEmpty && info.type == CPConstants.TemplateType.main {
preparePreview(trips: preparedToPreviewTrips)
preparedToPreviewTrips = []
return
}
if info.type == CPConstants.TemplateType.preview, let trips = info.trips {
showPreview(mapTemplate: mapTemplate, trips: trips)
}
}
func templateWillDisappear(_ aTemplate: CPTemplate, animated: Bool) {
guard let info = aTemplate.userInfo as? MapInfo else {
return
}
if info.type == CPConstants.TemplateType.preview {
router?.completeRouteAndRemovePoints()
}
}
func templateDidDisappear(_ aTemplate: CPTemplate, animated: Bool) {
guard !preparedToPreviewTrips.isEmpty,
let info = aTemplate.userInfo as? [String: String],
let alertType = info[CPConstants.TemplateKey.alert],
alertType == CPConstants.TemplateType.redirectRoute ||
alertType == CPConstants.TemplateType.restoreRoute else {
return
}
preparePreview(trips: preparedToPreviewTrips)
preparedToPreviewTrips = []
}
}
// MARK: - CPSessionConfigurationDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPSessionConfigurationDelegate {
func sessionConfiguration(_ sessionConfiguration: CPSessionConfiguration,
limitedUserInterfacesChanged limitedUserInterfaces: CPLimitableUserInterface) {
}
}
// MARK: - CPMapTemplateDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPMapTemplateDelegate {
public func mapTemplateDidShowPanningInterface(_ mapTemplate: CPMapTemplate) {
isUserPanMap = false
MapTemplateBuilder.configurePanUI(mapTemplate: mapTemplate)
FrameworkHelper.stopLocationFollow()
}
public func mapTemplateDidDismissPanningInterface(_ mapTemplate: CPMapTemplate) {
if let info = mapTemplate.userInfo as? MapInfo,
info.type == CPConstants.TemplateType.navigation {
MapTemplateBuilder.configureNavigationUI(mapTemplate: mapTemplate)
} else {
MapTemplateBuilder.configureBaseUI(mapTemplate: mapTemplate)
}
FrameworkHelper.switchMyPositionMode()
}
func mapTemplate(_ mapTemplate: CPMapTemplate, panEndedWith direction: CPMapTemplate.PanDirection) {
var offset = UIOffset(horizontal: 0.0, vertical: 0.0)
let offsetStep: CGFloat = 0.25
if direction.contains(.up) { offset.vertical -= offsetStep }
if direction.contains(.down) { offset.vertical += offsetStep }
if direction.contains(.left) { offset.horizontal += offsetStep }
if direction.contains(.right) { offset.horizontal -= offsetStep }
FrameworkHelper.moveMap(offset)
isUserPanMap = true
}
func mapTemplate(_ mapTemplate: CPMapTemplate, panWith direction: CPMapTemplate.PanDirection) {
var offset = UIOffset(horizontal: 0.0, vertical: 0.0)
let offsetStep: CGFloat = 0.1
if direction.contains(.up) { offset.vertical -= offsetStep }
if direction.contains(.down) { offset.vertical += offsetStep }
if direction.contains(.left) { offset.horizontal += offsetStep }
if direction.contains(.right) { offset.horizontal -= offsetStep }
FrameworkHelper.moveMap(offset)
isUserPanMap = true
}
func mapTemplate(_ mapTemplate: CPMapTemplate, startedTrip trip: CPTrip, using routeChoice: CPRouteChoice) {
guard let info = routeChoice.userInfo as? RouteInfo else {
if let info = routeChoice.userInfo as? [String: Any],
let code = info[CPConstants.Trip.errorCode] as? RouterResultCode,
let countries = info[CPConstants.Trip.missedCountries] as? [String] {
showErrorAlert(code: code, countries: countries)
}
return
}
mapTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.previewAccepted)
mapTemplate.hideTripPreviews()
guard let router = router,
let interfaceController = interfaceController,
let rootMapTemplate = rootMapTemplate else {
return
}
MapTemplateBuilder.configureNavigationUI(mapTemplate: rootMapTemplate)
interfaceController.popToRootTemplate(animated: false)
router.startNavigationSession(forTrip: trip, template: rootMapTemplate)
router.startRoute()
if let estimates = createEstimates(routeInfo: info) {
rootMapTemplate.updateEstimates(estimates, for: trip)
}
if let carplayVC = carplayVC {
carplayVC.updateCurrentSpeed(info.speed)
carplayVC.showSpeedControl()
}
updateVisibleViewPortState(.navigation)
}
func mapTemplate(_ mapTemplate: CPMapTemplate, displayStyleFor maneuver: CPManeuver) -> CPManeuverDisplayStyle {
if let type = maneuver.userInfo as? String,
type == CPConstants.Maneuvers.secondary {
return .trailingSymbol
}
return .leadingSymbol
}
func mapTemplate(_ mapTemplate: CPMapTemplate,
selectedPreviewFor trip: CPTrip,
using routeChoice: CPRouteChoice) {
guard let previewTrip = router?.previewTrip, previewTrip == trip else {
applyUndefinedEstimates(template: mapTemplate, trip: trip)
router?.buildRoute(trip: trip)
return
}
guard let info = routeChoice.userInfo as? RouteInfo,
let estimates = createEstimates(routeInfo: info) else {
applyUndefinedEstimates(template: mapTemplate, trip: trip)
router?.rebuildRoute()
return
}
mapTemplate.updateEstimates(estimates, for: trip)
routeChoice.userInfo = nil
router?.rebuildRoute()
}
}
// MARK: - CPListTemplateDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPListTemplateDelegate {
func listTemplate(_ listTemplate: CPListTemplate, didSelect item: CPListItem, completionHandler: @escaping () -> Void) {
if let userInfo = item.userInfo as? ListItemInfo {
let fromStat: String
var categoryName = ""
switch userInfo.type {
case CPConstants.ListItemType.history:
fromStat = kStatRecent
let locale = window?.textInputMode?.primaryLanguage ?? "en"
guard let searchService = searchService else {
completionHandler()
return
}
searchService.searchText(item.text ?? "", forInputLocale: locale, completionHandler: { [weak self] results in
guard let self = self else { return }
let template = ListTemplateBuilder.buildListTemplate(for: .searchResults(results: results))
completionHandler()
self.pushTemplate(template, animated: true)
})
case CPConstants.ListItemType.bookmarkLists where userInfo.metadata is CategoryInfo:
fromStat = kStatCategory
let metadata = userInfo.metadata as! CategoryInfo
categoryName = metadata.category.title
let template = ListTemplateBuilder.buildListTemplate(for: .bookmarks(category: metadata.category))
completionHandler()
pushTemplate(template, animated: true)
case CPConstants.ListItemType.bookmarks where userInfo.metadata is BookmarkInfo:
fromStat = kStatBookmarks
let metadata = userInfo.metadata as! BookmarkInfo
let bookmark = MWMCarPlayBookmarkObject(bookmarkId: metadata.bookmarkId)
preparePreview(forBookmark: bookmark)
completionHandler()
case CPConstants.ListItemType.searchResults where userInfo.metadata is SearchResultInfo:
fromStat = kStatSearch
let metadata = userInfo.metadata as! SearchResultInfo
preparePreviewForSearchResults(selectedRow: metadata.originalRow)
completionHandler()
default:
fromStat = ""
completionHandler()
}
guard fromStat.count > 0 else { return }
Statistics.logEvent(kStatCarplayDestinationsItemSelected,
withParameters: [kStatFrom : fromStat,
kStatCategory : categoryName])
}
}
}
// MARK: - CPSearchTemplateDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPSearchTemplateDelegate {
func searchTemplate(_ searchTemplate: CPSearchTemplate, updatedSearchText searchText: String, completionHandler: @escaping ([CPListItem]) -> Void) {
let locale = window?.textInputMode?.primaryLanguage ?? "en"
guard let searchService = searchService else {
completionHandler([])
return
}
searchService.searchText(searchText, forInputLocale: locale, completionHandler: { results in
var items = [CPListItem]()
for object in results {
let item = CPListItem(text: object.title, detailText: object.address)
item.userInfo = ListItemInfo(type: CPConstants.ListItemType.searchResults,
metadata: SearchResultInfo(originalRow: object.originalRow))
items.append(item)
}
completionHandler(items)
})
Alohalytics.logEvent(kStatCarplayKeyboardSearch)
}
func searchTemplate(_ searchTemplate: CPSearchTemplate, selectedResult item: CPListItem, completionHandler: @escaping () -> Void) {
searchService?.saveLastQuery()
if let info = item.userInfo as? ListItemInfo,
let metadata = info.metadata as? SearchResultInfo {
preparePreviewForSearchResults(selectedRow: metadata.originalRow)
}
completionHandler()
}
}
// MARK: - CarPlayRouterListener implementation
@available(iOS 12.0, *)
extension CarPlayService: CarPlayRouterListener {
func didCreateRoute(routeInfo: RouteInfo, trip: CPTrip) {
guard let currentTemplate = interfaceController?.topTemplate as? CPMapTemplate,
let info = currentTemplate.userInfo as? MapInfo,
info.type == CPConstants.TemplateType.preview else {
return
}
if let estimates = createEstimates(routeInfo: routeInfo) {
currentTemplate.updateEstimates(estimates, for: trip)
}
}
func didUpdateRouteInfo(_ routeInfo: RouteInfo, forTrip trip: CPTrip) {
if let carplayVC = carplayVC {
carplayVC.updateCurrentSpeed(routeInfo.speed)
}
guard let router = router,
let template = rootMapTemplate else {
return
}
router.updateUpcomingManeuvers()
if let estimates = createEstimates(routeInfo: routeInfo) {
template.updateEstimates(estimates, for: trip)
}
trip.routeChoices.first?.userInfo = routeInfo
}
func didFailureBuildRoute(forTrip trip: CPTrip, code: RouterResultCode, countries: [String]) {
guard let template = interfaceController?.topTemplate as? CPMapTemplate else { return }
trip.routeChoices.first?.userInfo = [CPConstants.Trip.errorCode: code, CPConstants.Trip.missedCountries: countries]
applyUndefinedEstimates(template: template, trip: trip)
}
func routeDidFinish(_ trip: CPTrip) {
if router?.currentTrip == nil { return }
router?.finishTrip()
if let carplayVC = carplayVC {
carplayVC.hideSpeedControl()
}
updateMapTemplateUIToTripFinished(trip)
}
}
// MARK: - LocationModeListener implementation
@available(iOS 12.0, *)
extension CarPlayService: LocationModeListener {
func processMyPositionStateModeEvent(_ mode: MWMMyPositionMode) {
currentPositionMode = mode
guard let rootMapTemplate = rootMapTemplate,
let info = rootMapTemplate.userInfo as? MapInfo,
info.type == CPConstants.TemplateType.main else {
return
}
switch mode {
case .follow, .followAndRotate:
if !rootMapTemplate.isPanningInterfaceVisible {
MapTemplateBuilder.setupDestinationButton(mapTemplate: rootMapTemplate)
}
case .notFollow:
if !rootMapTemplate.isPanningInterfaceVisible {
MapTemplateBuilder.setupRecenterButton(mapTemplate: rootMapTemplate)
}
case .pendingPosition, .notFollowNoPosition:
rootMapTemplate.leadingNavigationBarButtons = []
}
}
func processMyPositionPendingTimeout() {
}
}
// MARK: - Alerts and Trip Previews
@available(iOS 12.0, *)
extension CarPlayService {
func preparePreviewForSearchResults(selectedRow row: Int) {
var results = searchService?.lastResults ?? []
if let currentItemIndex = results.firstIndex(where: { $0.originalRow == row }) {
let item = results.remove(at: currentItemIndex)
results.insert(item, at: 0)
} else {
results.insert(MWMCarPlaySearchResultObject(forRow: row), at: 0)
}
if let router = router,
let startPoint = MWMRoutePoint(lastLocationAndType: .start,
intermediateIndex: 0) {
let endPoints = results.compactMap({ MWMRoutePoint(cgPoint: $0.mercatorPoint,
title: $0.title,
subtitle: $0.address,
type: .finish,
intermediateIndex: 0) })
let trips = endPoints.map({ router.createTrip(startPoint: startPoint, endPoint: $0) })
if router.currentTrip == nil {
preparePreview(trips: trips)
} else {
showRerouteAlert(trips: trips)
}
}
}
func preparePreview(forBookmark bookmark: MWMCarPlayBookmarkObject) {
if let router = router,
let startPoint = MWMRoutePoint(lastLocationAndType: .start,
intermediateIndex: 0),
let endPoint = MWMRoutePoint(cgPoint: bookmark.mercatorPoint,
title: bookmark.prefferedName,
subtitle: bookmark.address,
type: .finish,
intermediateIndex: 0) {
let trip = router.createTrip(startPoint: startPoint, endPoint: endPoint)
if router.currentTrip == nil {
preparePreview(trips: [trip])
} else {
showRerouteAlert(trips: [trip])
}
}
}
func preparePreview(trips: [CPTrip]) {
let mapTemplate = MapTemplateBuilder.buildTripPreviewTemplate(forTrips: trips)
if let interfaceController = interfaceController {
mapTemplate.mapDelegate = self
interfaceController.popToRootTemplate(animated: false)
interfaceController.pushTemplate(mapTemplate, animated: false)
}
}
func showPreview(mapTemplate: CPMapTemplate, trips: [CPTrip]) {
let tripTextConfig = CPTripPreviewTextConfiguration(startButtonTitle: L("trip_start"),
additionalRoutesButtonTitle: nil,
overviewButtonTitle: nil)
mapTemplate.showTripPreviews(trips, textConfiguration: tripTextConfig)
}
func createEstimates(routeInfo: RouteInfo) -> CPTravelEstimates? {
if let distance = Double(routeInfo.targetDistance) {
let measurement = Measurement(value: distance,
unit: routeInfo.targetUnits)
let estimates = CPTravelEstimates(distanceRemaining: measurement,
timeRemaining: routeInfo.timeToTarget)
return estimates
}
return nil
}
func applyUndefinedEstimates(template: CPMapTemplate, trip: CPTrip) {
let measurement = Measurement(value: -1,
unit: UnitLength.meters)
let estimates = CPTravelEstimates(distanceRemaining: measurement,
timeRemaining: -1)
template.updateEstimates(estimates, for: trip)
}
func showRerouteAlert(trips: [CPTrip]) {
let yesAction = CPAlertAction(title: L("redirect_route_yes"), style: .default, handler: { [unowned self] _ in
self.router?.cancelTrip()
self.updateMapTemplateUIToBase()
self.preparedToPreviewTrips = trips
self.interfaceController?.dismissTemplate(animated: true)
})
let noAction = CPAlertAction(title: L("redirect_route_no"), style: .cancel, handler: { [unowned self] _ in
self.interfaceController?.dismissTemplate(animated: true)
})
let alert = CPAlertTemplate(titleVariants: [L("redirect_route_alert")], actions: [noAction, yesAction])
alert.userInfo = [CPConstants.TemplateKey.alert: CPConstants.TemplateType.redirectRoute]
presentAlert(alert, animated: true)
}
func showKeyboardAlert() {
let okAction = CPAlertAction(title: L("ok"), style: .default, handler: { [unowned self] _ in
self.interfaceController?.dismissTemplate(animated: true)
})
let alert = CPAlertTemplate(titleVariants: [L("keyboard_availability_alert")], actions: [okAction])
presentAlert(alert, animated: true)
}
func showErrorAlert(code: RouterResultCode, countries: [String]) {
var titleVariants = [String]()
switch code {
case .noCurrentPosition:
titleVariants = ["\(L("dialog_routing_check_gps_carplay"))"]
case .startPointNotFound:
titleVariants = ["\(L("dialog_routing_change_start_carplay"))"]
case .endPointNotFound:
titleVariants = ["\(L("dialog_routing_change_end_carplay"))"]
case .routeNotFoundRedressRouteError,
.routeNotFound,
.inconsistentMWMandRoute:
titleVariants = ["\(L("dialog_routing_unable_locate_route_carplay"))"]
case .routeFileNotExist,
.fileTooOld,
.needMoreMaps,
.pointsInDifferentMWM:
titleVariants = ["\(L("dialog_routing_download_files_carplay"))"]
case .internalError,
.intermediatePointNotFound:
titleVariants = ["\(L("dialog_routing_system_error_carplay"))"]
case .noError,
.cancelled,
.hasWarnings,
.transitRouteNotFoundNoNetwork,
.transitRouteNotFoundTooLongPedestrian:
return
}
let okAction = CPAlertAction(title: L("ok"), style: .cancel, handler: { [unowned self] _ in
self.interfaceController?.dismissTemplate(animated: true)
})
let alert = CPAlertTemplate(titleVariants: titleVariants, actions: [okAction])
presentAlert(alert, animated: true)
}
func showRecoverRouteAlert(trip: CPTrip, isTypeCorrect: Bool) {
let yesAction = CPAlertAction(title: L("ok"), style: .default, handler: { [unowned self] _ in
var info = trip.userInfo as? [String: MWMRoutePoint]
if let startPoint = MWMRoutePoint(lastLocationAndType: .start,
intermediateIndex: 0) {
info?[CPConstants.Trip.start] = startPoint
}
trip.userInfo = info
self.preparedToPreviewTrips = [trip]
self.router?.updateStartPointAndRebuild(trip: trip)
self.interfaceController?.dismissTemplate(animated: true)
})
let noAction = CPAlertAction(title: L("cancel"), style: .cancel, handler: { [unowned self] _ in
FrameworkHelper.rotateMap(0.0, animated: false)
self.router?.completeRouteAndRemovePoints()
self.interfaceController?.dismissTemplate(animated: true)
})
let title = isTypeCorrect ? L("dialog_routing_rebuild_from_current_location_carplay") : L("dialog_routing_rebuild_for_vehicle_carplay")
let alert = CPAlertTemplate(titleVariants: [title], actions: [noAction, yesAction])
alert.userInfo = [CPConstants.TemplateKey.alert: CPConstants.TemplateType.restoreRoute]
presentAlert(alert, animated: true)
}
}
| 3ab3b130ca1f0345147168a3d6055434 | 38.188267 | 150 | 0.691384 | false | false | false | false |
pinterest/plank | refs/heads/master | Sources/Core/ObjectiveCInitExtension.swift | apache-2.0 | 1 | //
// ObjectiveCInitExtension.swift
// plank
//
// Created by Rahul Malik on 2/14/17.
//
//
import Foundation
let dateValueTransformerKey = "kPlankDateValueTransformerKey"
extension ObjCFileRenderer {
func renderPostInitNotification(type: String) -> String {
return "[[NSNotificationCenter defaultCenter] postNotificationName:kPlankDidInitializeNotification object:self userInfo:@{ kPlankInitTypeKey : @(\(type)) }];"
}
}
extension ObjCModelRenderer {
func renderModelObjectWithDictionary() -> ObjCIR.Method {
return ObjCIR.method("+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dictionary") {
["return [[self alloc] initWithModelDictionary:dictionary];"]
}
}
func renderModelObjectWithDictionaryError() -> ObjCIR.Method {
return ObjCIR.method("+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dictionary error:(NSError *__autoreleasing *)error") {
["return [[self alloc] initWithModelDictionary:dictionary error:error];"]
}
}
func renderDesignatedInit() -> ObjCIR.Method {
return ObjCIR.method("- (instancetype)init") {
["return [self initWithModelDictionary:@{} error:NULL];"]
}
}
func renderInitWithModelDictionary() -> ObjCIR.Method {
return ObjCIR.method("- (instancetype)initWithModelDictionary:(NSDictionary *)modelDictionary") {
["return [self initWithModelDictionary:modelDictionary error:NULL];"]
}
}
func renderInitWithBuilder() -> ObjCIR.Method {
return ObjCIR.method("- (instancetype)initWithBuilder:(\(builderClassName) *)builder") {
[
"NSParameterAssert(builder);",
"return [self initWithBuilder:builder initType:PlankModelInitTypeDefault];",
]
}
}
func renderInitWithBuilderWithInitType() -> ObjCIR.Method {
return ObjCIR.method("- (instancetype)initWithBuilder:(\(builderClassName) *)builder initType:(PlankModelInitType)initType") {
[
"NSParameterAssert(builder);",
self.isBaseClass ? ObjCIR.ifStmt("!(self = [super init])") { ["return self;"] } :
ObjCIR.ifStmt("!(self = [super initWithBuilder:builder initType:initType])") { ["return self;"] },
self.properties.filter { (_, schema) -> Bool in
!schema.schema.isBoolean()
}.map { name, _ in
"_\(Languages.objectiveC.snakeCaseToPropertyName(name)) = builder.\(Languages.objectiveC.snakeCaseToPropertyName(name));"
}.joined(separator: "\n"),
] +
self.properties.filter { (_, schema) -> Bool in
schema.schema.isBoolean()
}.map { name, _ in
"_\(self.booleanPropertiesIVarName).\(booleanPropertyOption(propertyName: name, className: self.className)) = builder.\(Languages.objectiveC.snakeCaseToPropertyName(name)) == 1;"
} + [
"_\(self.dirtyPropertiesIVarName) = builder.\(self.dirtyPropertiesIVarName);",
ObjCIR.ifStmt("[self class] == [\(self.className) class]") {
[renderPostInitNotification(type: "initType")]
},
"return self;",
]
}
}
func expectedObjectType(schema: Schema) -> String? {
switch schema {
case .object,
.map(valueType: _):
return "NSDictionary"
case .array(itemType: _),
.set(itemType: _):
return "NSArray"
case .integer,
.float,
.boolean,
.enumT(.integer):
return "NSNumber"
case .string(format: _),
.enumT(.string):
return "NSString"
default:
return nil
}
}
public func renderInitWithModelDictionaryError() -> ObjCIR.Method {
func renderPropertyInit(
_ propertyToAssign: String,
_ rawObjectName: String,
keyPath: [String],
schema: Schema,
firstName: String, // TODO: HACK to get enums to work (not clean)
counter: Int = 0,
dirtyPropertyName: String? = nil,
needsTypeCheck: Bool = true
) -> [String] {
func renderTypeCheck(_ body: () -> [String]) -> [String] {
guard needsTypeCheck else { return body() }
guard let kindOf = expectedObjectType(schema: schema) else { return body() }
let key = keyPath.count == 1 ? keyPath[0] : "[@[\(keyPath.joined(separator: ", "))] componentsJoinedByString:@\".\"]"
return [
ObjCIR.ifStmt("!error || [\(rawObjectName) isKindOfClass:[\(kindOf) class]]", body: body) +
ObjCIR.elseStmt {
((dirtyPropertyName != nil) ? ["self->_\(dirtyPropertiesIVarName).\(dirtyPropertyOption(propertyName: dirtyPropertyName!, className: className)) = 0;"] : []) +
["*error = PlankTypeError(\(key), [\(kindOf) class], [\(rawObjectName) class]);"]
},
]
}
switch schema {
case let .array(itemType: .some(itemType)):
let currentResult = "result\(counter)"
let currentTmp = "tmp\(counter)"
let currentObj = "obj\(counter)"
let currentItems = "items\(counter)"
if itemType.isPrimitiveType {
return renderTypeCheck { [
"\(propertyToAssign) = \(rawObjectName);",
] }
}
let propertyInit = renderPropertyInit(currentTmp, currentObj, keyPath: keyPath + ["?".objcLiteral()], schema: itemType, firstName: firstName, counter: counter + 1).joined(separator: "\n")
return renderTypeCheck { [
"NSArray *\(currentItems) = \(rawObjectName);",
"NSMutableArray *\(currentResult) = [NSMutableArray arrayWithCapacity:\(currentItems).count];",
ObjCIR.forStmt("id \(currentObj) in \(currentItems)") { [
ObjCIR.ifStmt("\(currentObj) != (id)kCFNull") { [
"id \(currentTmp) = nil;",
propertyInit,
ObjCIR.ifStmt("\(currentTmp) != nil") { [
"[\(currentResult) addObject:\(currentTmp)];",
] },
] },
] },
"\(propertyToAssign) = \(currentResult);",
] }
case let .set(itemType: .some(itemType)):
let currentResult = "result\(counter)"
let currentTmp = "tmp\(counter)"
let currentObj = "obj\(counter)"
let currentItems = "items\(counter)"
if itemType.isPrimitiveType {
return renderTypeCheck { [
"NSArray *\(currentItems) = \(rawObjectName);",
"\(propertyToAssign) = [NSSet setWithArray:\(currentItems)];",
] }
}
let propertyInit = renderPropertyInit(currentTmp, currentObj, keyPath: keyPath + ["?".objcLiteral()], schema: itemType, firstName: firstName, counter: counter + 1).joined(separator: "\n")
return renderTypeCheck { [
"NSArray *\(currentItems) = \(rawObjectName);",
"NSMutableSet *\(currentResult) = [NSMutableSet setWithCapacity:\(currentItems).count];",
ObjCIR.forStmt("id \(currentObj) in \(currentItems)") { [
ObjCIR.ifStmt("\(currentObj) != (id)kCFNull") { [
"id \(currentTmp) = nil;",
propertyInit,
ObjCIR.ifStmt("\(currentTmp) != nil") { [
"[\(currentResult) addObject:\(currentTmp)];",
] },
] },
] },
"\(propertyToAssign) = \(currentResult);",
] }
case let .map(valueType: .some(valueType)) where valueType.isPrimitiveType == false:
let currentResult = "result\(counter)"
let currentItems = "items\(counter)"
let (currentKey, currentObj, currentStop) = ("key\(counter)", "obj\(counter)", "stop\(counter)")
return renderTypeCheck { [
"NSDictionary *\(currentItems) = \(rawObjectName);",
"NSMutableDictionary *\(currentResult) = [NSMutableDictionary dictionaryWithCapacity:\(currentItems).count];",
ObjCIR.stmt(
ObjCIR.msg(currentItems,
("enumerateKeysAndObjectsUsingBlock",
ObjCIR.block(["NSString * _Nonnull \(currentKey)",
"id _Nonnull \(currentObj)",
"__unused BOOL * _Nonnull \(currentStop)"]) {
[
ObjCIR.ifStmt("\(currentObj) != nil && \(currentObj) != (id)kCFNull") {
renderPropertyInit("\(currentResult)[\(currentKey)]", currentObj, keyPath: keyPath + [currentKey], schema: valueType, firstName: firstName, counter: counter + 1)
},
]
}))
),
"\(propertyToAssign) = \(currentResult);",
] }
case .float:
return renderTypeCheck { ["\(propertyToAssign) = [\(rawObjectName) doubleValue];"] }
case .integer:
return renderTypeCheck { ["\(propertyToAssign) = [\(rawObjectName) integerValue];"] }
case .boolean:
return renderTypeCheck { ["\(propertyToAssign) = [\(rawObjectName) boolValue] & 0x1;"] }
case .string(format: .some(.uri)):
return renderTypeCheck { ["\(propertyToAssign) = [NSURL URLWithString:\(rawObjectName)];"] }
case .string(format: .some(.dateTime)):
return renderTypeCheck { ["\(propertyToAssign) = [[NSValueTransformer valueTransformerForName:\(dateValueTransformerKey)] transformedValue:\(rawObjectName)];"] }
case let .reference(with: ref):
return ref.force().map {
renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: $0, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName)
} ?? {
assert(false, "TODO: Forward optional across methods")
return []
}()
case .enumT(.integer):
let typeName = enumTypeName(propertyName: firstName, className: className)
return renderTypeCheck { ["\(propertyToAssign) = (\(typeName))[\(rawObjectName) integerValue];"] }
case .enumT(.string):
return renderTypeCheck { ["\(propertyToAssign) = \(enumFromStringMethodName(propertyName: firstName, className: className))(value);"] }
case let .object(objectRoot):
return renderTypeCheck { ["\(propertyToAssign) = [\(objectRoot.className(with: self.params)) modelObjectWithDictionary:\(rawObjectName) error:error];"] }
case let .oneOf(types: schemas):
// TODO: Update to create ADT objects
let adtClassName = typeFromSchema(firstName, schema.nonnullProperty()).trimmingCharacters(in: CharacterSet(charactersIn: "*"))
func loop(schema: Schema) -> String {
func transformToADTInit(_ lines: [String]) -> [String] {
if let assignmentLine = lines.last {
let propAssignmentPrefix = "\(propertyToAssign) = "
if assignmentLine.hasPrefix(propAssignmentPrefix) {
let startIndex = propAssignmentPrefix.endIndex
let propertyInitStatement = String(assignmentLine[startIndex...]).trimmingCharacters(in: CharacterSet(charactersIn: " ;"))
let adtInitStatement = propAssignmentPrefix + "[\(adtClassName) objectWith\(ObjCADTRenderer.objectName(schema)):\(propertyInitStatement)];"
return lines.dropLast() + [adtInitStatement]
}
}
return lines
}
switch schema {
case let .object(objectRoot):
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSDictionary class]] && [\(rawObjectName)[\("type".objcLiteral())] isEqualToString:\(objectRoot.typeIdentifier.objcLiteral())]") {
transformToADTInit(["\(propertyToAssign) = [\(objectRoot.className(with: self.params)) modelObjectWithDictionary:\(rawObjectName) error:error];"])
}
case let .reference(with: ref):
return ref.force().map(loop) ?? {
assert(false, "TODO: Forward optional across methods")
return ""
}()
case .float:
let encodingConditions = [
"strcmp([\(rawObjectName) objCType], @encode(float)) == 0",
"strcmp([\(rawObjectName) objCType], @encode(double)) == 0",
]
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSNumber class]] && (\(encodingConditions.joined(separator: " ||\n")))") {
transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: .float, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName, needsTypeCheck: false))
}
case .integer, .enumT(.integer):
let encodingConditions = [
"strcmp([\(rawObjectName) objCType], @encode(int)) == 0",
"strcmp([\(rawObjectName) objCType], @encode(unsigned int)) == 0",
"strcmp([\(rawObjectName) objCType], @encode(short)) == 0",
"strcmp([\(rawObjectName) objCType], @encode(unsigned short)) == 0",
"strcmp([\(rawObjectName) objCType], @encode(long)) == 0",
"strcmp([\(rawObjectName) objCType], @encode(long long)) == 0",
"strcmp([\(rawObjectName) objCType], @encode(unsigned long)) == 0",
"strcmp([\(rawObjectName) objCType], @encode(unsigned long long)) == 0",
]
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSNumber class]] && (\(encodingConditions.joined(separator: " ||\n")))") {
transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: schema, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName, needsTypeCheck: false))
}
case .boolean:
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSNumber class]] && strcmp([\(rawObjectName) objCType], @encode(BOOL)) == 0") {
transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: schema, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName, needsTypeCheck: false))
}
case .array(itemType: _):
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSArray class]]") {
transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: schema, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName, needsTypeCheck: false))
}
case .set(itemType: _):
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSSet class]]") {
transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: schema, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName, needsTypeCheck: false))
}
case .map(valueType: _):
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSDictionary class]]") {
transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: schema, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName, needsTypeCheck: false))
}
case .string(.some(.uri)):
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSString class]] && [NSURL URLWithString:\(rawObjectName)] != nil") {
transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: schema, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName, needsTypeCheck: false))
}
case .string(.some(.dateTime)):
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSString class]] && [[NSValueTransformer valueTransformerForName:\(dateValueTransformerKey)] transformedValue:\(rawObjectName)] != nil") {
transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: schema, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName, needsTypeCheck: false))
}
case .string(.some), .string(.none), .enumT(.string):
return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSString class]]") {
transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, keyPath: keyPath, schema: schema, firstName: firstName, counter: counter, dirtyPropertyName: dirtyPropertyName, needsTypeCheck: false))
}
case .oneOf(types: _):
fatalError("Nested oneOf types are unsupported at this time. Please file an issue if you require this.")
}
}
return schemas.map(loop)
default:
switch schema.memoryAssignmentType() {
case .copy:
return renderTypeCheck { ["\(propertyToAssign) = [\(rawObjectName) copy];"] }
default:
return renderTypeCheck { ["\(propertyToAssign) = \(rawObjectName);"] }
}
}
}
return ObjCIR.method("- (instancetype)initWithModelDictionary:(NS_VALID_UNTIL_END_OF_SCOPE NSDictionary *)modelDictionary error:(NSError *__autoreleasing *)error") {
[
"NSParameterAssert(modelDictionary);",
"NSParameterAssert([modelDictionary isKindOfClass:[NSDictionary class]]);",
self.isBaseClass ? ObjCIR.ifStmt("!(self = [super init])") { ["return self;"] } :
"if (!(self = [super initWithModelDictionary:modelDictionary error:error])) { return self; }",
ObjCIR.ifStmt("!modelDictionary") { ["return self;"] },
self.properties.map { name, prop in
ObjCIR.scope { [
"__unsafe_unretained id value = modelDictionary[\(name.objcLiteral())];",
ObjCIR.ifStmt("value != nil") { [
"self->_\(dirtyPropertiesIVarName).\(dirtyPropertyOption(propertyName: name, className: className)) = 1;",
ObjCIR.ifStmt("value != (id)kCFNull") {
switch prop.schema {
case .boolean:
return renderPropertyInit("self->_\(booleanPropertiesIVarName).\(booleanPropertyOption(propertyName: name, className: className))", "value", keyPath: [name.objcLiteral()], schema: prop.schema, firstName: name, dirtyPropertyName: name)
default:
return renderPropertyInit("self->_\(Languages.objectiveC.snakeCaseToPropertyName(name))", "value", keyPath: [name.objcLiteral()], schema: prop.schema, firstName: name, dirtyPropertyName: name)
}
},
] },
] }
}.joined(separator: "\n"),
ObjCIR.ifStmt("[self class] == [\(self.className) class]") {
[renderPostInitNotification(type: "PlankModelInitTypeDefault")]
},
"return self;",
]
}
}
}
| d22c7531924b7e281c4106796eb9340b | 60.712644 | 270 | 0.534783 | false | false | false | false |
qxuewei/XWSwiftWB | refs/heads/master | XWSwiftWB/XWSwiftWB/Classes/Main/Visitor/VisitorView.swift | apache-2.0 | 1 | //
// VisitorView.swift
// XWSwiftWB
//
// Created by 邱学伟 on 16/10/26.
// Copyright © 2016年 邱学伟. All rights reserved.
//
import UIKit
class VisitorView: UIView {
//MARK: - 控件的属性
@IBOutlet weak var rotationView: UIImageView!
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var registerBtn: UIButton!
@IBOutlet weak var loginBtn: UIButton!
class func visitorView() -> VisitorView {
return Bundle.main.loadNibNamed("VisitorView", owner: nil, options: nil)?.last as! VisitorView
}
}
extension VisitorView{
func setupVisitorViewInfo(iconName : String, tip : String) {
iconView.image = UIImage(named: iconName)
tipLabel.text = tip
rotationView.isHidden = true
}
//旋转动画
func addRotationAnimation() {
//1.创建动画
let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
//2.设置动画属性
rotation.fromValue = 0
rotation.toValue = M_PI * 2
rotation.repeatCount = MAXFLOAT
rotation.duration = 6
//*防止重回当前界面动画消失
rotation.isRemovedOnCompletion = false
//3.将动画添加到目标控件的layer中
rotationView.layer.add(rotation, forKey: nil)
}
}
| cf37b6e60b2efd42320a443afeab517f | 26.23913 | 102 | 0.643256 | false | false | false | false |
JGiola/swift | refs/heads/main | benchmark/single-source/DropFirst.swift | apache-2.0 | 10 | //===--- DropFirst.swift --------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to DropFirst.swift.gyb and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
import TestsUtils
let sequenceCount = 4096
let dropCount = 1024
let suffixCount = sequenceCount - dropCount
let sumCount = suffixCount * (2 * sequenceCount - suffixCount - 1) / 2
let array: [Int] = Array(0..<sequenceCount)
public let benchmarks = [
BenchmarkInfo(
name: "DropFirstCountableRange",
runFunction: run_DropFirstCountableRange,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstSequence",
runFunction: run_DropFirstSequence,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstAnySequence",
runFunction: run_DropFirstAnySequence,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstAnySeqCntRange",
runFunction: run_DropFirstAnySeqCntRange,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstAnySeqCRangeIter",
runFunction: run_DropFirstAnySeqCRangeIter,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstAnyCollection",
runFunction: run_DropFirstAnyCollection,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstArray",
runFunction: run_DropFirstArray,
tags: [.validation, .api, .Array],
setUpFunction: { blackHole(array) }),
BenchmarkInfo(
name: "DropFirstCountableRangeLazy",
runFunction: run_DropFirstCountableRangeLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstSequenceLazy",
runFunction: run_DropFirstSequenceLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstAnySequenceLazy",
runFunction: run_DropFirstAnySequenceLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstAnySeqCntRangeLazy",
runFunction: run_DropFirstAnySeqCntRangeLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstAnySeqCRangeIterLazy",
runFunction: run_DropFirstAnySeqCRangeIterLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstAnyCollectionLazy",
runFunction: run_DropFirstAnyCollectionLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropFirstArrayLazy",
runFunction: run_DropFirstArrayLazy,
tags: [.validation, .api, .Array],
setUpFunction: { blackHole(array) }),
]
@inline(never)
public func run_DropFirstCountableRange(_ n: Int) {
let s = 0..<sequenceCount
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstSequence(_ n: Int) {
let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstAnySequence(_ n: Int) {
let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstAnySeqCntRange(_ n: Int) {
let s = AnySequence(0..<sequenceCount)
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstAnySeqCRangeIter(_ n: Int) {
let s = AnySequence((0..<sequenceCount).makeIterator())
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstAnyCollection(_ n: Int) {
let s = AnyCollection(0..<sequenceCount)
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstArray(_ n: Int) {
let s = array
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstCountableRangeLazy(_ n: Int) {
let s = (0..<sequenceCount).lazy
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstSequenceLazy(_ n: Int) {
let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstAnySequenceLazy(_ n: Int) {
let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstAnySeqCntRangeLazy(_ n: Int) {
let s = (AnySequence(0..<sequenceCount)).lazy
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstAnySeqCRangeIterLazy(_ n: Int) {
let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstAnyCollectionLazy(_ n: Int) {
let s = (AnyCollection(0..<sequenceCount)).lazy
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
@inline(never)
public func run_DropFirstArrayLazy(_ n: Int) {
let s = (array).lazy
for _ in 1...20*n {
var result = 0
for element in s.dropFirst(dropCount) {
result += element
}
check(result == sumCount)
}
}
// Local Variables:
// eval: (read-only-mode 1)
// End:
| 57f37f64019b319230a47d129e0e3225 | 27.318367 | 91 | 0.629576 | false | false | false | false |
JGiola/swift | refs/heads/main | stdlib/public/core/Unmanaged.swift | apache-2.0 | 13 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type for propagating an unmanaged object reference.
///
/// When you use this type, you become partially responsible for
/// keeping the object alive.
@frozen
public struct Unmanaged<Instance: AnyObject> {
@usableFromInline
internal unowned(unsafe) var _value: Instance
@usableFromInline @_transparent
internal init(_private: Instance) { _value = _private }
/// Unsafely turns an opaque C pointer into an unmanaged class reference.
///
/// This operation does not change reference counts.
///
/// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue()
///
/// - Parameter value: An opaque C pointer.
/// - Returns: An unmanaged class reference to `value`.
@_transparent
public static func fromOpaque(
@_nonEphemeral _ value: UnsafeRawPointer
) -> Unmanaged {
return Unmanaged(_private: unsafeBitCast(value, to: Instance.self))
}
/// Unsafely converts an unmanaged class reference to a pointer.
///
/// This operation does not change reference counts.
///
/// let str0 = "boxcar" as CFString
/// let bits = Unmanaged.passUnretained(str0)
/// let ptr = bits.toOpaque()
///
/// - Returns: An opaque pointer to the value of this unmanaged reference.
@_transparent
public func toOpaque() -> UnsafeMutableRawPointer {
return unsafeBitCast(_value, to: UnsafeMutableRawPointer.self)
}
/// Creates an unmanaged reference with an unbalanced retain.
///
/// The instance passed as `value` will leak if nothing eventually balances
/// the retain.
///
/// This is useful when passing an object to an API which Swift does not know
/// the ownership rules for, but you know that the API expects you to pass
/// the object at +1.
///
/// - Parameter value: A class instance.
/// - Returns: An unmanaged reference to the object passed as `value`.
@_transparent
public static func passRetained(_ value: Instance) -> Unmanaged {
return Unmanaged(_private: value).retain()
}
/// Creates an unmanaged reference without performing an unbalanced
/// retain.
///
/// This is useful when passing a reference to an API which Swift
/// does not know the ownership rules for, but you know that the
/// API expects you to pass the object at +0.
///
/// CFArraySetValueAtIndex(.passUnretained(array), i,
/// .passUnretained(object))
///
/// - Parameter value: A class instance.
/// - Returns: An unmanaged reference to the object passed as `value`.
@_transparent
public static func passUnretained(_ value: Instance) -> Unmanaged {
return Unmanaged(_private: value)
}
/// Gets the value of this unmanaged reference as a managed
/// reference without consuming an unbalanced retain of it.
///
/// This is useful when a function returns an unmanaged reference
/// and you know that you're not responsible for releasing the result.
///
/// - Returns: The object referenced by this `Unmanaged` instance.
@_transparent // unsafe-performance
public func takeUnretainedValue() -> Instance {
return _value
}
/// Gets the value of this unmanaged reference as a managed
/// reference and consumes an unbalanced retain of it.
///
/// This is useful when a function returns an unmanaged reference
/// and you know that you're responsible for releasing the result.
///
/// - Returns: The object referenced by this `Unmanaged` instance.
@_transparent // unsafe-performance
public func takeRetainedValue() -> Instance {
let result = _value
release()
return result
}
/// Gets the value of the unmanaged referenced as a managed reference without
/// consuming an unbalanced retain of it and passes it to the closure. Asserts
/// that there is some other reference ('the owning reference') to the
/// instance referenced by the unmanaged reference that guarantees the
/// lifetime of the instance for the duration of the
/// '_withUnsafeGuaranteedRef' call.
///
/// NOTE: You are responsible for ensuring this by making the owning
/// reference's lifetime fixed for the duration of the
/// '_withUnsafeGuaranteedRef' call.
///
/// Violation of this will incur undefined behavior.
///
/// A lifetime of a reference 'the instance' is fixed over a point in the
/// program if:
///
/// * There exists a global variable that references 'the instance'.
///
/// import Foundation
/// var globalReference = Instance()
/// func aFunction() {
/// point()
/// }
///
/// Or if:
///
/// * There is another managed reference to 'the instance' whose life time is
/// fixed over the point in the program by means of 'withExtendedLifetime'
/// dynamically closing over this point.
///
/// var owningReference = Instance()
/// ...
/// withExtendedLifetime(owningReference) {
/// point($0)
/// }
///
/// Or if:
///
/// * There is a class, or struct instance ('owner') whose lifetime is fixed
/// at the point and which has a stored property that references
/// 'the instance' for the duration of the fixed lifetime of the 'owner'.
///
/// class Owned {
/// }
///
/// class Owner {
/// final var owned: Owned
///
/// func foo() {
/// withExtendedLifetime(self) {
/// doSomething(...)
/// } // Assuming: No stores to owned occur for the dynamic lifetime of
/// // the withExtendedLifetime invocation.
/// }
///
/// func doSomething() {
/// // both 'self' and 'owned''s lifetime is fixed over this point.
/// point(self, owned)
/// }
/// }
///
/// The last rule applies transitively through a chain of stored references
/// and nested structs.
///
/// Examples:
///
/// var owningReference = Instance()
/// ...
/// withExtendedLifetime(owningReference) {
/// let u = Unmanaged.passUnretained(owningReference)
/// for i in 0 ..< 100 {
/// u._withUnsafeGuaranteedRef {
/// $0.doSomething()
/// }
/// }
/// }
///
/// class Owner {
/// final var owned: Owned
///
/// func foo() {
/// withExtendedLifetime(self) {
/// doSomething(Unmanaged.passUnretained(owned))
/// }
/// }
///
/// func doSomething(_ u: Unmanaged<Owned>) {
/// u._withUnsafeGuaranteedRef {
/// $0.doSomething()
/// }
/// }
/// }
@inlinable // unsafe-performance
@_transparent
public func _withUnsafeGuaranteedRef<Result>(
_ body: (Instance) throws -> Result
) rethrows -> Result {
var tmp = self
// Builtin.convertUnownedUnsafeToGuaranteed expects to have a base value
// that the +0 value depends on. In this case, we are assuming that is done
// for us opaquely already. So, the builtin will emit a mark_dependence on a
// trivial object. The optimizer knows to eliminate that so we do not have
// any overhead from this.
let fakeBase: Int? = nil
return try body(Builtin.convertUnownedUnsafeToGuaranteed(fakeBase,
&tmp._value))
}
/// Performs an unbalanced retain of the object.
@_transparent
public func retain() -> Unmanaged {
Builtin.retain(_value)
return self
}
/// Performs an unbalanced release of the object.
@_transparent
public func release() {
Builtin.release(_value)
}
#if _runtime(_ObjC)
/// Performs an unbalanced autorelease of the object.
@_transparent
public func autorelease() -> Unmanaged {
Builtin.autorelease(_value)
return self
}
#endif
}
extension Unmanaged: Sendable where Instance: Sendable { }
| 245fd9a622b5f1cacee72f682b1a575f | 32.657143 | 80 | 0.631579 | false | false | false | false |
Istered/FrameManager | refs/heads/master | iOS Example/Source/UI/ActionsView.swift | mit | 1 | //
// Created by Anton Romanov on 17/03/2017.
// Copyright (c) 2017 Istered. All rights reserved.
//
import Foundation
import UIKit
import FrameManager
class ActionsView: UIView {
fileprivate lazy var likeLabel: UILabel = {
let likeLabel = UILabel()
likeLabel.textAlignment = .left
likeLabel.font = UIFont.systemFont(ofSize: 12)
likeLabel.text = "Like"
return likeLabel
}()
fileprivate lazy var commentLabel: UILabel = {
let commentLabel = UILabel()
commentLabel.textAlignment = .center
commentLabel.font = UIFont.systemFont(ofSize: 12)
commentLabel.text = "Comment"
return commentLabel
}()
fileprivate lazy var shareLabel: UILabel = {
let shareLabel = UILabel()
shareLabel.textAlignment = .right
shareLabel.font = UIFont.systemFont(ofSize: 12)
shareLabel.text = "Share"
return shareLabel
}()
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
private func commonInit() {
addSubview(likeLabel)
addSubview(commentLabel)
addSubview(shareLabel)
}
}
extension ActionsView: FrameMountable {
var mountingViews: [AnyHashable: UIView] {
return [
PostFrameCalculator.FrameKey.like: likeLabel,
PostFrameCalculator.FrameKey.comment: commentLabel,
PostFrameCalculator.FrameKey.share: shareLabel
]
}
} | 8239751f472e14e95a8f577feb0ce2d1 | 23.985075 | 63 | 0.635386 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/IRGen/objc_subclass.swift | apache-2.0 | 6 | // RUN: rm -rf %t && mkdir %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize %s
// REQUIRES: objc_interop
// CHECK: [[SGIZMO:C13objc_subclass10SwiftGizmo]] = type
// CHECK: [[TYPE:%swift.type]] = type
// CHECK: [[INT:%Si]] = type <{ [[LLVM_PTRSIZE_INT:i(32|64)]] }>
// CHECK: [[OBJC_CLASS:%objc_class]] = type
// CHECK: [[OPAQUE:%swift.opaque]] = type
// CHECK: [[GIZMO:%CSo5Gizmo]] = type opaque
// CHECK: [[OBJC:%objc_object]] = type opaque
// CHECK-32: @_TWvdvC13objc_subclass10SwiftGizmo1xSi = hidden global i32 12, align [[WORD_SIZE_IN_BYTES:4]]
// CHECK-64: @_TWvdvC13objc_subclass10SwiftGizmo1xSi = hidden global i64 16, align [[WORD_SIZE_IN_BYTES:8]]
// CHECK: @"OBJC_METACLASS_$__TtC13objc_subclass10SwiftGizmo" = hidden global [[OBJC_CLASS]] { [[OBJC_CLASS]]* @"OBJC_METACLASS_$_NSObject", [[OBJC_CLASS]]* @"OBJC_METACLASS_$_Gizmo", [[OPAQUE]]* @_objc_empty_cache, [[OPAQUE]]* null, [[LLVM_PTRSIZE_INT]] ptrtoint ({{.*}} @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo to [[LLVM_PTRSIZE_INT]]) }
// CHECK: [[STRING_X:@.*]] = private unnamed_addr constant [2 x i8] c"x\00"
// CHECK: [[STRING_EMPTY:@.*]] = private unnamed_addr constant [1 x i8] zeroinitializer
// CHECK-32: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [7 x i8] c"l8@0:4\00"
// CHECK-64: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [8 x i8] c"q16@0:8\00"
// CHECK-32: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4l8\00"
// CHECK-64: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8q16\00"
// CHECK-32: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"@8@0:4\00"
// CHECK-64: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00"
// CHECK-32: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [13 x i8] c"@16@0:4l8@12\00"
// CHECK-64: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [14 x i8] c"@32@0:8q16@24\00"
// CHECK-32: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"v8@0:4\00"
// CHECK-64: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK: [[STRING_SWIFTGIZMO:@.*]] = private unnamed_addr constant [32 x i8] c"_TtC13objc_subclass10SwiftGizmo\00"
// CHECK-32: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } {
// CHECK-32: i32 129,
// CHECK-32: i32 20,
// CHECK-32: i32 20,
// CHECK-32: i8* null,
// CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0),
// CHECK-32: i8* null,
// CHECK-32: i8* null,
// CHECK-32: i8* null,
// CHECK-32: i8* null,
// CHECK-32: i8* null
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } {
// CHECK-64: i32 129,
// CHECK-64: i32 40,
// CHECK-64: i32 40,
// CHECK-64: i32 0,
// CHECK-64: i8* null,
// CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0),
// CHECK-64: i8* null,
// CHECK-64: i8* null,
// CHECK-64: i8* null,
// CHECK-64: i8* null,
// CHECK-64: i8* null
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } {
// CHECK-32: i32 12,
// CHECK-32: i32 11,
// CHECK-32: [11 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0),
// CHECK-32: i8* bitcast (i32 (%0*, i8*)* @_TToFC13objc_subclass10SwiftGizmog1xSi to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[METHOD_TYPE_ENCODING2]], i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%0*, i8*, i32)* @_TToFC13objc_subclass10SwiftGizmos1xSi to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0),
// CHECK-32: i8* bitcast (i32 (%0*, i8*)* @_TToFC13objc_subclass10SwiftGizmo4getXfT_Si to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%1* (%0*, i8*)* @_TToFC13objc_subclass10SwiftGizmo9duplicatefT_CSo5Gizmo to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%0*, i8*)* @_TToFC13objc_subclass10SwiftGizmocfT_S0_ to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([13 x i8], [13 x i8]* [[INIT_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%0*, i8*, i32, %2*)* @_TToFC13objc_subclass10SwiftGizmocfT3intSi6stringSS_S0_ to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[DEALLOC_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%0*, i8*)* @_TToFC13objc_subclass10SwiftGizmoD to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast ({{(i8|i1)}} (%0*, i8*)* @_TToFC13objc_subclass10SwiftGizmog7enabledSb to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%0*, i8*, {{(i8|i1)}})* @_TToFC13objc_subclass10SwiftGizmos7enabledSb to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%0*, i8*, i32)* @_TToFC13objc_subclass10SwiftGizmocfT7bellsOnSi_GSQS0__ to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%0*, i8*)* @_TToFC13objc_subclass10SwiftGizmoe to i8*)
// CHECK-32: }]
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } {
// CHECK-64: i32 24,
// CHECK-64: i32 11,
// CHECK-64: [11 x { i8*, i8*, i8* }] [{
// CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0)
// CHECK-64: i8* bitcast (i64 ([[OPAQUE2:%.*]]*, i8*)* @_TToFC13objc_subclass10SwiftGizmog1xSi to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[METHOD_TYPE_ENCODING2]], i64 0, i64 0)
// CHECK-64: i8* bitcast (void ([[OPAQUE3:%.*]]*, i8*, i64)* @_TToFC13objc_subclass10SwiftGizmos1xSi to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0)
// CHECK-64: i8* bitcast (i64 ([[OPAQUE2]]*, i8*)* @_TToFC13objc_subclass10SwiftGizmo4getXfT_Si to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE1:.*]]* ([[OPAQUE0:%.*]]*, i8*)* @_TToFC13objc_subclass10SwiftGizmo9duplicatefT_CSo5Gizmo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE5:.*]]* ([[OPAQUE6:.*]]*, i8*)* @_TToFC13objc_subclass10SwiftGizmocfT_S0_ to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* [[INIT_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE7:%.*]]* ([[OPAQUE8:%.*]]*, i8*, i64, [[OPAQUEONE:.*]]*)* @_TToFC13objc_subclass10SwiftGizmocfT3intSi6stringSS_S0_ to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast (void ([[OPAQUE10:%.*]]*, i8*)* @_TToFC13objc_subclass10SwiftGizmoD to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ({{(i8|i1)}} ([[OPAQUE11:%.*]]*, i8*)* @_TToFC13objc_subclass10SwiftGizmog7enabledSb to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast (void ([[OPAQUE12:%.*]]*, i8*, {{(i8|i1)}})* @_TToFC13objc_subclass10SwiftGizmos7enabledSb to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE11:%.*]]* ([[OPAQUE12:%.*]]*, i8*, i64)* @_TToFC13objc_subclass10SwiftGizmocfT7bellsOnSi_GSQS0__ to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE5]]* ([[OPAQUE6]]*, i8*)* @_TToFC13objc_subclass10SwiftGizmoe to i8*)
// CHECK-64: }]
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } {
// CHECK-32: i32 20,
// CHECK-32: i32 1,
// CHECK-32: [1 x { i32*, i8*, i8*, i32, i32 }] [{ i32*, i8*, i8*, i32, i32 } {
// CHECK-32: i32* @_TWvdvC13objc_subclass10SwiftGizmo1xSi,
// CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i32 0, i32 0),
// CHECK-32: i32 2,
// CHECK-32: i32 4 }]
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } {
// CHECK-64: i32 32,
// CHECK-64: i32 1,
// CHECK-64: [1 x { i64*, i8*, i8*, i32, i32 }] [{ i64*, i8*, i8*, i32, i32 } {
// CHECK-64: i64* @_TWvdvC13objc_subclass10SwiftGizmo1xSi,
// CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i64 0, i64 0),
// CHECK-64: i32 3,
// CHECK-64: i32 8 }]
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-32: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } {
// CHECK-32: i32 132,
// CHECK-32: i32 12,
// CHECK-32: i32 16,
// CHECK-32: i8* null,
// CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0),
// CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo,
// CHECK-32: i8* null,
// CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo,
// CHECK-32: i8* null,
// CHECK-32: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } {
// CHECK-64: i32 132,
// CHECK-64: i32 16,
// CHECK-64: i32 24,
// CHECK-64: i32 0,
// CHECK-64: i8* null,
// CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0),
// CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo,
// CHECK-64: i8* null,
// CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo,
// CHECK-64: i8* null,
// CHECK-64: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-NOT: @_TMCSo13SwiftGizmo = {{.*NSObject}}
// CHECK: @_INSTANCE_METHODS__TtC13objc_subclass12GenericGizmo
// CHECK-32: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4@8\00"
// CHECK-64: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, i32, [5 x { i8*, i8*, i8* }] } {
// CHECK-32: i32 12,
// CHECK-32: i32 5,
// CHECK-32: [5 x { i8*, i8*, i8* }] [
// CHECK-32: {
// CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%0* (%3*, i8*)* @_TToFC13objc_subclass11SwiftGizmo2g2sgCS_10SwiftGizmo to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[SETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%3*, i8*, %0*)* @_TToFC13objc_subclass11SwiftGizmo2s2sgCS_10SwiftGizmo to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast (%3* (%3*, i8*)* @_TToFC13objc_subclass11SwiftGizmo2cfT_S0_ to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (%3* (%3*, i8*, i32)* @_TToFC13objc_subclass11SwiftGizmo2cfT7bellsOnSi_GSQS0__ to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast (void (%3*, i8*)* @_TToFC13objc_subclass11SwiftGizmo2E to i8*)
// CHECK-32: }
// CHECK-32: ]
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, {{.*}}] } {
// CHECK-64: i32 24,
// CHECK-64: i32 5,
// CHECK-64: [5 x { i8*, i8*, i8* }] [
// CHECK-64: {
// CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE13:%.*]]* ([[OPAQUE14:%.*]]*, i8*)* @_TToFC13objc_subclass11SwiftGizmo2g2sgCS_10SwiftGizmo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast (void ([[OPAQUE15:%.*]]*, i8*, [[OPAQUE16:%.*]]*)* @_TToFC13objc_subclass11SwiftGizmo2s2sgCS_10SwiftGizmo to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE18:%.*]]* ([[OPAQUE19:%.*]]*, i8*)* @_TToFC13objc_subclass11SwiftGizmo2cfT_S0_ to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ([[OPAQUE21:%.*]]* ([[OPAQUE22:%.*]]*, i8*, i64)* @_TToFC13objc_subclass11SwiftGizmo2cfT7bellsOnSi_GSQS0__ to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0)
// CHECK-64: i8* bitcast (void ([[OPAQUE20:%.*]]*, i8*)* @_TToFC13objc_subclass11SwiftGizmo2E to i8*)
// CHECK-64: }
// CHECK-64: ] }
// CHECK: @objc_classes = internal global [2 x i8*] [i8* bitcast (%swift.type* @_TMC13objc_subclass10SwiftGizmo to i8*), i8* bitcast (%swift.type* @_TMC13objc_subclass11SwiftGizmo2 to i8*)], section "__DATA, __objc_classlist, regular, no_dead_strip", align [[WORD_SIZE_IN_BYTES]]
// CHECK: @objc_non_lazy_classes = internal global [1 x i8*] [i8* bitcast (%swift.type* @_TMC13objc_subclass11SwiftGizmo2 to i8*)], section "__DATA, __objc_nlclslist, regular, no_dead_strip", align [[WORD_SIZE_IN_BYTES]]
import Foundation
import gizmo
@requires_stored_property_inits
class SwiftGizmo : Gizmo {
var x = Int()
func getX() -> Int {
return x
}
override func duplicate() -> Gizmo {
return SwiftGizmo()
}
override init() {
super.init(bellsOn:0)
}
init(int i: Int, string str : String) {
super.init(bellsOn:i)
}
deinit { var x = 10 }
var enabled: Bool {
@objc(isEnabled) get {
return true
}
@objc(setIsEnabled:) set {
}
}
}
class GenericGizmo<T> : Gizmo {
func foo() {}
var x : Int {
return 0
}
var array : [T] = []
}
// CHECK: define hidden [[LLVM_PTRSIZE_INT]] @_TFC13objc_subclass12GenericGizmog1xSi(
var sg = SwiftGizmo()
sg.duplicate()
@objc_non_lazy_realization
class SwiftGizmo2 : Gizmo {
var sg : SwiftGizmo
override init() {
sg = SwiftGizmo()
super.init()
}
deinit { }
}
| 8d24356324250b5c21a1533ef0d81be5 | 58.462687 | 347 | 0.598243 | false | false | false | false |
matchmore/alps-ios-sdk | refs/heads/master | Matchmore/Miscellaneous/KeychainHelper.swift | mit | 1 | //
// KeychainHelper.swift
// Matchmore
//
// Created by Maciej Burda on 16/11/2017.
// Copyright © 2018 Matchmore SA. All rights reserved.
//
import Foundation
open class KeychainHelper {
open var loggingEnabled = false
private init() {}
private static var _shared: KeychainHelper?
open static var shared: KeychainHelper {
if _shared == nil {
DispatchQueue.global().sync(flags: .barrier) {
if _shared == nil {
_shared = KeychainHelper()
}
}
}
return _shared!
}
open subscript(key: String) -> String? {
get {
return load(withKey: key)
} set {
DispatchQueue.global().sync(flags: .barrier) {
self.save(newValue, forKey: key)
}
}
}
private func save(_ string: String?, forKey key: String) {
let query = keychainQuery(withKey: key)
let objectData: Data? = string?.data(using: .utf8, allowLossyConversion: false)
if SecItemCopyMatching(query, nil) == noErr {
if let dictData = objectData {
let status = SecItemUpdate(query, NSDictionary(dictionary: [kSecValueData: dictData]))
logPrint("Update status: ", status)
} else {
let status = SecItemDelete(query)
logPrint("Delete status: ", status)
}
} else {
if let dictData = objectData {
query.setValue(dictData, forKey: kSecValueData as String)
let status = SecItemAdd(query, nil)
logPrint("Update status: ", status)
}
}
}
private func load(withKey key: String) -> String? {
let query = keychainQuery(withKey: key)
query.setValue(kCFBooleanTrue, forKey: kSecReturnData as String)
query.setValue(kCFBooleanTrue, forKey: kSecReturnAttributes as String)
var result: CFTypeRef?
let status = SecItemCopyMatching(query, &result)
guard
let resultsDict = result as? NSDictionary,
let resultsData = resultsDict.value(forKey: kSecValueData as String) as? Data,
status == noErr
else {
logPrint("Load status: ", status)
return nil
}
return String(data: resultsData, encoding: .utf8)
}
private func keychainQuery(withKey key: String) -> NSMutableDictionary {
let result = NSMutableDictionary()
result.setValue(kSecClassGenericPassword, forKey: kSecClass as String)
result.setValue(key, forKey: kSecAttrService as String)
result.setValue(kSecAttrAccessibleAlwaysThisDeviceOnly, forKey: kSecAttrAccessible as String)
return result
}
private func logPrint(_ items: Any...) {
if loggingEnabled {
print(items)
}
}
}
| fa56399acf5a4376b06698c7008332d7 | 30.912088 | 102 | 0.582645 | false | false | false | false |
Hendrik44/pi-weather-app | refs/heads/master | Carthage/Checkouts/Charts/ChartsDemo-iOS/Swift/Demos/LineChartTimeViewController.swift | apache-2.0 | 3 | //
// LineChartTimeViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import Charts
class LineChartTimeViewController: DemoBaseViewController {
@IBOutlet var chartView: LineChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderTextX: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Time Line Chart"
self.options = [.toggleValues,
.toggleFilled,
.toggleCircles,
.toggleCubic,
.toggleHorizontalCubic,
.toggleStepped,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData]
chartView.delegate = self
chartView.chartDescription?.enabled = false
chartView.dragEnabled = true
chartView.setScaleEnabled(true)
chartView.pinchZoomEnabled = false
chartView.highlightPerDragEnabled = true
chartView.backgroundColor = .white
chartView.legend.enabled = false
let xAxis = chartView.xAxis
xAxis.labelPosition = .topInside
xAxis.labelFont = .systemFont(ofSize: 10, weight: .light)
xAxis.labelTextColor = UIColor(red: 255/255, green: 192/255, blue: 56/255, alpha: 1)
xAxis.drawAxisLineEnabled = false
xAxis.drawGridLinesEnabled = true
xAxis.centerAxisLabelsEnabled = true
xAxis.granularity = 3600
xAxis.valueFormatter = DateValueFormatter()
let leftAxis = chartView.leftAxis
leftAxis.labelPosition = .insideChart
leftAxis.labelFont = .systemFont(ofSize: 12, weight: .light)
leftAxis.drawGridLinesEnabled = true
leftAxis.granularityEnabled = true
leftAxis.axisMinimum = 0
leftAxis.axisMaximum = 170
leftAxis.yOffset = -9
leftAxis.labelTextColor = UIColor(red: 255/255, green: 192/255, blue: 56/255, alpha: 1)
chartView.rightAxis.enabled = false
chartView.legend.form = .line
sliderX.value = 100
slidersValueChanged(nil)
chartView.animate(xAxisDuration: 2.5)
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setDataCount(Int(sliderX.value), range: 30)
}
func setDataCount(_ count: Int, range: UInt32) {
let now = Date().timeIntervalSince1970
let hourSeconds: TimeInterval = 3600
let from = now - (Double(count) / 2) * hourSeconds
let to = now + (Double(count) / 2) * hourSeconds
let values = stride(from: from, to: to, by: hourSeconds).map { (x) -> ChartDataEntry in
let y = arc4random_uniform(range) + 50
return ChartDataEntry(x: x, y: Double(y))
}
let set1 = LineChartDataSet(entries: values, label: "DataSet 1")
set1.axisDependency = .left
set1.setColor(UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1))
set1.lineWidth = 1.5
set1.drawCirclesEnabled = false
set1.drawValuesEnabled = false
set1.fillAlpha = 0.26
set1.fillColor = UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)
set1.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1)
set1.drawCircleHoleEnabled = false
let data = LineChartData(dataSet: set1)
data.setValueTextColor(.white)
data.setValueFont(.systemFont(ofSize: 9, weight: .light))
chartView.data = data
}
override func optionTapped(_ option: Option) {
switch option {
case .toggleFilled:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.drawFilledEnabled = !set.drawFilledEnabled
}
chartView.setNeedsDisplay()
case .toggleCircles:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.drawCirclesEnabled = !set.drawCirclesEnabled
}
chartView.setNeedsDisplay()
case .toggleCubic:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.mode = (set.mode == .cubicBezier) ? .linear : .cubicBezier
}
chartView.setNeedsDisplay()
case .toggleStepped:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.mode = (set.mode == .stepped) ? .linear : .stepped
}
chartView.setNeedsDisplay()
case .toggleHorizontalCubic:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.mode = (set.mode == .cubicBezier) ? .horizontalBezier : .cubicBezier
}
chartView.setNeedsDisplay()
default:
super.handleOption(option, forChartView: chartView)
}
}
@IBAction func slidersValueChanged(_ sender: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
self.updateChartData()
}
}
| 7f12c37d48f3e86548230bd99dc30e44 | 33.852761 | 95 | 0.569442 | false | false | false | false |
CD1212/Doughnut | refs/heads/master | Pods/FeedKit/Sources/FeedKit/Models/Namespaces/Media/MediaRating.swift | gpl-3.0 | 2 | //
// MediaRating.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// This allows the permissible audience to be declared. If this element is not
/// included, it assumes that no restrictions are necessary. It has one optional
/// attribute.
public class MediaRating {
/// The element's attributes.
public class Attributes {
/// The URI that identifies the rating scheme. It is an optional attribute.
/// If this attribute is not included, the default scheme is urn:simple (adult | nonadult).
public var scheme: String?
}
/// The element's attributes.
public var attributes: Attributes?
/// The element's value.
public var value: String?
}
// MARK: - Initializers
extension MediaRating {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = MediaRating.Attributes(attributes: attributeDict)
}
}
extension MediaRating.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.scheme = attributeDict["scheme"]
}
}
// MARK: - Equatable
extension MediaRating: Equatable {
public static func ==(lhs: MediaRating, rhs: MediaRating) -> Bool {
return
lhs.value == rhs.value &&
lhs.attributes == rhs.attributes
}
}
extension MediaRating.Attributes: Equatable {
public static func ==(lhs: MediaRating.Attributes, rhs: MediaRating.Attributes) -> Bool {
return lhs.scheme == rhs.scheme
}
}
| c4dc319f3944ee45dc8c67cc2f888def | 28.375 | 99 | 0.668794 | false | false | false | false |
lammertw/PagingDatePicker | refs/heads/master | Pod/Classes/PagingDatePickerView.swift | mit | 1 | //
// PagingDateWithMonthViewController.swift
// FareCalendar
//
// Created by Lammert Westerhoff on 22/03/16.
// Copyright © 2016 NS International B.V. All rights reserved.
//
import UIKit
import RSDayFlow
import SwiftDate
@objc public protocol PagingDatePickerViewDelegate: class {
optional func pagingDatePickerView(pagingDatePickerView: PagingDatePickerView, didCreateDatePickerView datePickerView: RSDFDatePickerView, forMonthDate date: NSDate)
optional func pagingDatePickerView(pagingDatePickerView: PagingDatePickerView, didPageToMonthDate date: NSDate)
}
public class PagingDatePickerView: UIView {
public var datePickerViewClass = RSDFDatePickerView.self
public var transitionStyle = UIPageViewControllerTransitionStyle.Scroll
public weak var delegate: PagingDatePickerViewDelegate?
public var startDate: NSDate? {
didSet {
pagingDatePickerPageViewController.startDate = startDate
}
}
public var endDate: NSDate? {
didSet {
pagingDatePickerPageViewController.endDate = endDate
}
}
public weak var datePickerViewDelegate: RSDFDatePickerViewDelegate? {
didSet {
if oldValue != nil {
pagingDatePickerPageViewController.datePickerViewDelegate = datePickerViewDelegate
}
}
}
public weak var datePickerViewDataSource: RSDFDatePickerViewDataSource? {
didSet {
if oldValue != nil {
pagingDatePickerPageViewController.datePickerViewDataSource = datePickerViewDataSource
}
}
}
private lazy var pagingDatePickerPageViewController: PagingDatePickerPageViewController = {
let vc = PagingDatePickerPageViewController(transitionStyle: self.transitionStyle, navigationOrientation: .Horizontal, options: [:], datePickerViewClass: self.datePickerViewClass)
vc.pagingDatePickerViewDelegate = self
vc.startDate = self.startDate
vc.endDate = self.endDate
vc.datePickerViewDelegate = self.datePickerViewDelegate
vc.datePickerViewDataSource = self.datePickerViewDataSource
self.addSubview(vc.view)
return vc
}()
public override func layoutSubviews() {
pagingDatePickerPageViewController.view.frame = bounds
}
public func scrollToDate(date: NSDate, reload: Bool = false, animated: Bool = true) {
pagingDatePickerPageViewController.scrollToDate(date, reload: reload, animated: animated)
}
}
extension PagingDatePickerView: PagingDatePickerPageViewControllerDelegate {
func pagingDatePickerViewControllerDidCreateDatePickerView(datePickerView: RSDFDatePickerView, forMonth date: NSDate) {
delegate?.pagingDatePickerView?(self, didCreateDatePickerView: datePickerView, forMonthDate: date)
}
public func pagingDatePickerViewControllerDidScrollToDate(date: NSDate) {
delegate?.pagingDatePickerView?(self, didPageToMonthDate: date)
}
}
protocol PagingDatePickerViewControllerDelegate: class {
func pagingDatePickerViewController(pagingDatePickerViewController: PagingDatePickerViewController, didCreateDatePickerView datePickerView: RSDFDatePickerView, forMonth date: NSDate)
}
class PagingDatePickerViewController: UIViewController {
let datePickerViewClass: RSDFDatePickerView.Type
private let date: NSDate
weak var datePickerViewDelegate: RSDFDatePickerViewDelegate?
weak var datePickerViewDataSource: RSDFDatePickerViewDataSource?
weak var delegate: PagingDatePickerViewControllerDelegate?
private init(date: NSDate, datePickerViewClass: RSDFDatePickerView.Type) {
self.date = date
self.datePickerViewClass = datePickerViewClass
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
let datePickerView = datePickerViewClass.init(frame: CGRectNull, calendar: nil, startDate: date.startOf(.Month), endDate: date.endOf(.Month))
datePickerView.delegate = datePickerViewDelegate
datePickerView.dataSource = datePickerViewDataSource
delegate?.pagingDatePickerViewController(self, didCreateDatePickerView: datePickerView, forMonth: date)
view = datePickerView
}
}
protocol PagingDatePickerPageViewControllerDelegate: class {
func pagingDatePickerViewControllerDidCreateDatePickerView(datePickerView: RSDFDatePickerView, forMonth date: NSDate)
func pagingDatePickerViewControllerDidScrollToDate(date: NSDate)
}
class PagingDatePickerPageViewController: UIPageViewController {
weak var pagingDatePickerViewDelegate: PagingDatePickerPageViewControllerDelegate?
var datePickerViewClass = RSDFDatePickerView.self
weak var datePickerViewDelegate: RSDFDatePickerViewDelegate?
weak var datePickerViewDataSource: RSDFDatePickerViewDataSource?
init(transitionStyle style: UIPageViewControllerTransitionStyle, navigationOrientation: UIPageViewControllerNavigationOrientation, options: [String : AnyObject]?, datePickerViewClass: RSDFDatePickerView.Type) {
self.datePickerViewClass = datePickerViewClass
super.init(transitionStyle: style, navigationOrientation: navigationOrientation, options: options)
}
var startDate: NSDate? {
didSet {
startDate = startDate?.startOf(.Month)
}
}
var endDate: NSDate? {
didSet {
endDate = endDate?.endOf(.Month)
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private var currentDate: NSDate? {
return (viewControllers?.first as? PagingDatePickerViewController)?.date
}
private func firstPagingDatePickerViewController() -> PagingDatePickerViewController? {
return pagingDatePickerViewController(NSDate()) ?? startDate.flatMap(pagingDatePickerViewController)
}
private func pagingDatePickerViewController(date: NSDate) -> PagingDatePickerViewController? {
if startDate <= date && (endDate == nil || endDate >= date) {
let vc = PagingDatePickerViewController(date: date, datePickerViewClass: datePickerViewClass)
vc.datePickerViewDelegate = datePickerViewDelegate
vc.datePickerViewDataSource = datePickerViewDataSource
vc.delegate = self
return vc
}
return nil
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
if let viewController = firstPagingDatePickerViewController() {
setViewControllers([viewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
_ = currentDate.map { pagingDatePickerViewDelegate?.pagingDatePickerViewControllerDidScrollToDate($0) }
}
}
func scrollToDate(date: NSDate, fallbackToStartDate: Bool = true, reload: Bool = false, animated: Bool = true) {
if let currentDate = currentDate where reload || currentDate.startOf(.Month) != date.startOf(.Month) {
if let vc = pagingDatePickerViewController(date) ?? (fallbackToStartDate ? startDate.flatMap(pagingDatePickerViewController) : nil) {
setViewControllers([vc], direction: date > currentDate ? .Forward : .Reverse, animated: true, completion: nil)
}
}
}
}
extension PagingDatePickerPageViewController: PagingDatePickerViewControllerDelegate {
func pagingDatePickerViewController(pagingDatePickerViewController: PagingDatePickerViewController, didCreateDatePickerView datePickerView: RSDFDatePickerView, forMonth date: NSDate) {
pagingDatePickerViewDelegate?.pagingDatePickerViewControllerDidCreateDatePickerView(datePickerView, forMonth: date)
}
}
extension PagingDatePickerPageViewController: UIPageViewControllerDataSource {
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
return ((viewController as? PagingDatePickerViewController)?.date).flatMap {
pagingDatePickerViewController($0 - 1.months)
}
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
return ((viewController as? PagingDatePickerViewController)?.date).flatMap {
pagingDatePickerViewController($0 + 1.months)
}
}
}
extension PagingDatePickerPageViewController: UIPageViewControllerDelegate {
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let currentDate = currentDate where completed {
pagingDatePickerViewDelegate?.pagingDatePickerViewControllerDidScrollToDate(currentDate)
}
}
}
| beefd56288c5c2ec608b266d0e27bb9a | 39.587444 | 214 | 0.745442 | false | false | false | false |
laurentVeliscek/AudioKit | refs/heads/master | AudioKit/macOS/AudioKit for macOS/User Interface/AKButton.swift | mit | 2 | //
// AKButton.swift
// AudioKit for macOS
//
// Created by Aurelius Prochazka on 7/31/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
//
// AKButton.swift
// AudioKit for iOS
//
// Created by Aurelius Prochazka on 7/30/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
public class AKButton: NSView {
internal var callback: ()->(String)
public var title: String {
didSet {
needsDisplay = true
}
}
public var color: NSColor {
didSet {
needsDisplay = true
}
}
override public func mouseDown(theEvent: NSEvent) {
let newTitle = callback()
if newTitle != "" { title = newTitle }
}
public init(title: String,
color: NSColor = NSColor(red: 0.029, green: 1.000, blue: 0.000, alpha: 1.000),
frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 60),
callback: ()->(String)) {
self.title = title
self.callback = callback
self.color = color
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func drawButton() {
//// General Declarations
let context = unsafeBitCast(NSGraphicsContext.currentContext()!.graphicsPort, CGContext.self)
let outerPath = NSBezierPath(rect: CGRect(x: 0, y: 0, width: 440, height: 60))
color.setFill()
outerPath.fill()
let labelRect = CGRect(x: 0, y: 0, width: 440, height: 60)
let labelStyle = NSMutableParagraphStyle()
labelStyle.alignment = .Center
let labelFontAttributes = [NSFontAttributeName: NSFont.boldSystemFontOfSize(24), NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: labelStyle]
let labelInset: CGRect = CGRectInset(labelRect, 10, 0)
let labelTextHeight: CGFloat = NSString(string: title).boundingRectWithSize(CGSize(width: labelInset.width, height: CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: labelFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, labelInset)
NSString(string: title).drawInRect(CGRect(x: labelInset.minX, y: labelInset.minY + (labelInset.height - labelTextHeight) / 2, width: labelInset.width, height: labelTextHeight), withAttributes: labelFontAttributes)
CGContextRestoreGState(context)
}
override public func drawRect(rect: CGRect) {
drawButton()
}
} | c3cb4116fcfe25f8399ffa0d2ef98481 | 33.410256 | 257 | 0.636601 | false | false | false | false |
samodom/TestableMapKit | refs/heads/master | TestableMapKitTests/Tools/Equatability.swift | mit | 1 | //
// Equatability.swift
// TestableMapKit
//
// Created by Sam Odom on 12/25/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import MapKit
extension CLLocationCoordinate2D: Equatable {
}
public func ==(coordinate1: CLLocationCoordinate2D, coordinate2: CLLocationCoordinate2D) -> Bool {
return coordinate1.latitude == coordinate2.latitude && coordinate1.longitude == coordinate2.longitude
}
extension MKCoordinateSpan: Equatable {
}
public func ==(span1: MKCoordinateSpan, span2: MKCoordinateSpan) -> Bool {
return span1.latitudeDelta == span2.latitudeDelta && span1.longitudeDelta == span2.longitudeDelta
}
extension MKCoordinateRegion: Equatable {
}
public func ==(region1: MKCoordinateRegion, region2: MKCoordinateRegion) -> Bool {
return region1.center == region2.center && region1.span == region2.span
}
extension MKMapPoint: Equatable {
}
public func ==(point1: MKMapPoint, point2: MKMapPoint) -> Bool {
return point1.x == point2.x && point1.y == point2.y
}
extension MKMapSize: Equatable {
}
public func ==(size1: MKMapSize, size2: MKMapSize) -> Bool {
return size1.width == size2.width && size1.height == size2.height
}
extension MKMapRect: Equatable {
}
public func ==(rect1: MKMapRect, rect2: MKMapRect) -> Bool {
return rect1.origin == rect2.origin && rect1.size == rect2.size
}
extension UIEdgeInsets: Equatable {
}
public func ==(insets1: UIEdgeInsets, insets2: UIEdgeInsets) -> Bool {
return insets1.top == insets2.top &&
insets1.left == insets2.left &&
insets1.bottom == insets2.bottom &&
insets1.right == insets2.right
}
| a4a933f92284e01de2d4ab6ac3d29a36 | 21.121622 | 105 | 0.706781 | false | false | false | false |
pennlabs/penn-mobile-ios | refs/heads/main | Shared/General/Colors.swift | mit | 1 | //
// Colors.swift
// PennMobile
//
// Created by Dominic Holmes on 10/23/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import UIKit
/*
These colors correspond with color themes defined in Assets.xcassets. Each color variable has a dark and light variant, which the system automatically switches depending on the UI mode (light or dark). They are defined in the Asset catalog to avoid backward compatibility issues with pre-iOS 13 versions. Defining them here would result in verbose code and lots of #ifavailible statements.
*/
extension UIColor {
// MARK: - UI Palette
static let navigation = UIColor(named: "navigation")!
static let uiCardBackground = UIColor(named: "uiCardBackground")!
static let uiGroupedBackground = UIColor(named: "uiGroupedBackground")!
static let uiGroupedBackgroundSecondary = UIColor(named: "uiGroupedBackgroundSecondary")!
static let uiBackground = UIColor(named: "uiBackground")!
static let uiBackgroundSecondary = UIColor(named: "uiBackgroundSecondary")!
static let labelPrimary = UIColor(named: "labelPrimary")!
static let labelSecondary = UIColor(named: "labelSecondary")!
static let labelTertiary = UIColor(named: "labelTertiary")!
static let labelQuaternary = UIColor(named: "labelQuaternary")!
// MARK: - Primary Palette
static let baseDarkBlue = UIColor(named: "baseDarkBlue")!
static let baseLabsBlue = UIColor(named: "baseLabsBlue")!
// MARK: - Neutral Palette
static let grey1 = UIColor(named: "grey1")!
static let grey2 = UIColor(named: "grey2")!
static let grey3 = UIColor(named: "grey3")!
static let grey4 = UIColor(named: "grey4")!
static let grey5 = UIColor(named: "grey5")!
static let grey6 = UIColor(named: "grey6")!
// MARK: - Secondary Palette
static let baseBlue = UIColor(named: "baseBlue")!
static let baseGreen = UIColor(named: "baseGreen")!
static let baseOrange = UIColor(named: "baseOrange")!
static let basePurple = UIColor(named: "basePurple")!
static let baseRed = UIColor(named: "baseRed")!
static let baseYellow = UIColor(named: "baseYellow")!
// MARK: - Extended Palette
static let blueLight = UIColor(named: "blueLight")!
static let blueLighter = UIColor(named: "blueLighter")!
static let blueDark = UIColor(named: "blueDark")!
static let blueDarker = UIColor(named: "blueDarker")!
static let greenLight = UIColor(named: "greenLight")!
static let greenLighter = UIColor(named: "greenLighter")!
static let greenDark = UIColor(named: "greenDark")!
static let greenDarker = UIColor(named: "greenDarker")!
static let orangeLight = UIColor(named: "orangeLight")!
static let orangeLighter = UIColor(named: "orangeLighter")!
static let orangeDark = UIColor(named: "orangeDark")!
static let orangeDarker = UIColor(named: "orangeDarker")!
static let purpleLight = UIColor(named: "purpleLight")!
static let purpleLighter = UIColor(named: "purpleLighter")!
static let purpleDark = UIColor(named: "purpleDark")!
static let purpleDarker = UIColor(named: "purpleDarker")!
static let redLight = UIColor(named: "redLight")!
static let redLighter = UIColor(named: "redLighter")!
static let redDark = UIColor(named: "redDark")!
static let redDarker = UIColor(named: "redDarker")!
static let yellowLight = UIColor(named: "yellowLight")!
static let yellowLighter = UIColor(named: "yellowLighter")!
static let yellowDark = UIColor(named: "yellowDark")!
static let yellowDarker = UIColor(named: "yellowDarker")!
}
extension UIColor {
// for getting a lighter variant (using a multiplier)
func borderColor(multiplier: CGFloat) -> UIColor {
let rgba = self.rgba
return UIColor(red: rgba.red * multiplier, green: rgba.green * multiplier, blue: rgba.blue * multiplier, alpha: rgba.alpha)
}
var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
// returns rgba colors.
return (red, green, blue, alpha)
}
}
import SwiftUI
extension Color {
// MARK: - UI Palette
static let navigation = Color("navigation")
static let uiCardBackground = Color("uiCardBackground")
static let uiGroupedBackground = Color("uiGroupedBackground")
static let uiGroupedBackgroundSecondary = Color("uiGroupedBackgroundSecondary")
static let uiBackground = Color("uiBackground")
static let uiBackgroundSecondary = Color("uiBackgroundSecondary")
static let labelPrimary = Color("labelPrimary")
static let labelSecondary = Color("labelSecondary")
static let labelTertiary = Color("labelTertiary")
static let labelQuaternary = Color("labelQuaternary")
// MARK: - Primary Palette
static var baseDarkBlue = Color("baseDarkBlue")
static let baseLabsBlue = Color("baseLabsBlue")
// MARK: - Neutral Palette
static var grey1 = Color("grey1")
static var grey2 = Color("grey2")
static var grey3 = Color("grey3")
static var grey4 = Color("grey4")
static var grey5 = Color("grey5")
static var grey6 = Color("grey6")
// MARK: - Secondary Palette
static var baseBlue = Color("baseBlue")
static var baseGreen = Color("baseGreen")
static var baseOrange = Color("baseOrange")
static var basePurple = Color("basePurple")
static var baseRed = Color("baseRed")
static var baseYellow = Color("baseYellow")
// MARK: - Extended Palette
static var blueLight = Color("blueLighter")
static var blueLighter = Color("blueLighter")
static var blueDark = Color("blueDark")
static var blueDarker = Color("blueDarker")
static var greenLight = Color("greenLighter")
static var greenLighter = Color("greenLighter")
static var greenDark = Color("greenDark")
static var greenDarker = Color("greenDarker")
static var orangeLight = Color("orangeLighter")
static var orangeLighter = Color("orangeLighter")
static var orangeDark = Color("orangeDark")
static var orangeDarker = Color("orangeDarker")
static var purpleLight = Color("purpleLighter")
static var purpleLighter = Color("purpleLighter")
static var purpleDark = Color("purpleDark")
static var purpleDarker = Color("purpleDarker")
static var redLight = Color("redLight")
static var redLighter = Color("redLighter")
static var redDark = Color("redDark")
static var redDarker = Color("redDarker")
static var yellowLight = Color("yellowLighter")
static var yellowLighter = Color("yellowLighter")
static var yellowDark = Color("yellowDark")
static var yellowDarker = Color("yellowDarker")
}
| 8bd92f9bb38adec0f5f8685e99a2b15e | 40.192771 | 389 | 0.702398 | false | false | false | false |
IBM-MIL/BluePic | refs/heads/master | BluePic-iOS/BluePic/Extensions/UIImageExtension.swift | apache-2.0 | 1 | /**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import AVFoundation
import UIKit
extension UIImage{
/**
Resizes a UIImage given a height
- parameter image: image to resize
- parameter newHeight: height of new size of image
- returns: newly resized image
*/
class func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/**
Method rotates image by degrees provided in the parameter. As will it will flip it with true or not with false.
- parameter degrees: CGFloat
- parameter flip: Bool
- returns: UIImage
*/
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(M_PI)
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
let t = CGAffineTransformMakeRotation(degreesToRadians(degrees));
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0);
// // Rotate the image context
CGContextRotateCTM(bitmap, degreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
var yFlip: CGFloat
if(flip){
yFlip = CGFloat(-1.0)
} else {
yFlip = CGFloat(1.0)
}
CGContextScaleCTM(bitmap, yFlip, -1.0)
CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
} | 90987d86a1c64dba9635e11b7ecfe811 | 32.55914 | 116 | 0.647436 | false | false | false | false |
akpw/VisualBinaryTrees | refs/heads/master | VisualBinaryTrees.playground/Sources/TreeDrawing/TreeDrawing.swift | gpl-3.0 | 1 | // GNU General Public License. See the LICENSE file for more details.
// Copyright © 2016 Arseniy Kuznetsov. All rights reserved.
import UIKit
import CoreGraphics
/// Customizable Tree Drawing Attributes
public struct TreeDrawingAttributes {
var gridUnitSize: CGFloat, gridLineWidth: CGFloat
var treeLineWidth: CGFloat, treeFontSize: CGFloat
var gridColor: UIColor, treeNodeColor: UIColor, treeLineColor: UIColor
var backGroundColor: UIColor
}
/// Draws Tree Layout model built by specified TreeLayoutBuilder,
/// using DrawingState machine to manage states
public final class TreeDrawing<Node: BinaryTree>: Drawable {
public var width: CGFloat { return treeLayout.layoutWidth }
public var height: CGFloat { return treeLayout.layoutHeight }
public init(rootNode: Node,
drawingAttributes: TreeDrawingAttributes,
layoutBuilder: TreeLayoutBuilder,
visualizeTraversal: Bool) {
self.drawingAttributes = drawingAttributes
var layoutBuilder = layoutBuilder
treeLayout = layoutBuilder.buildLayout(rootNode: rootNode,
gridUnitSize: drawingAttributes.gridUnitSize)
if treeLayout.traversalStrategy == nil {
self.visualizeTraversal = false
treeLayout.traversalStrategy = InOrderTraversalStrategy.self
} else {
self.visualizeTraversal = visualizeTraversal
}
drawingState = .ready
}
public func draw(_ renderer: Renderer) {
drawGrid(renderer)
drawTreeNodes(renderer)
drawTreeLines(renderer)
if visualizeTraversal { visualizeTraversal(renderer) }
}
// MARK: - Private
private var visualizeTraversal: Bool
private func drawGrid(_ renderer: Renderer) {
drawingState = drawingState.toDrawingGrid(renderer, drawingAttributes: drawingAttributes)
let grid = Grid(bounds: CGRect(x: 0, y: 0, width: width, height: height),
gridUnitSize: drawingAttributes.gridUnitSize,
lineWidth: drawingAttributes.gridLineWidth)
grid.draw(renderer)
drawingState = drawingState.toDoneDrawingGrid()
}
private func drawTreeNodes(_ renderer: Renderer) {
drawingState = drawingState.toDrawingTreeNodes(renderer, drawingAttributes: drawingAttributes)
for layout in treeLayout {
drawNode(layout)
}
drawingState = drawingState.toDoneDrawingTreeNodes()
}
private func drawTreeLines(_ renderer: Renderer) {
drawingState = drawingState.toDrawingTreeLines(renderer, drawingAttributes: drawingAttributes)
for layout in treeLayout {
if let left = layout.left {
drawLine(fromNode: layout, toNode: left)
}
if let right = layout.right {
drawLine(fromNode: layout, toNode: right)
}
}
drawingState = drawingState.toDoneDrawingTreeLines()
}
private func visualizeTraversal(_ renderer: Renderer) {
var keyRects = [CGRect]()
for layout in treeLayout {
keyRects.append(layout.boundingRect)
}
renderer.renderTraversal(at: keyRects)
}
private func drawNode(_ node: TreeLayout<Node>) {
guard case let DrawingState.drawingTreeNodes(renderer) = drawingState else { return }
let strValue = String(describing: node.element)
renderer.renderText(strValue, fontSize: drawingAttributes.treeFontSize,
fontColor: drawingAttributes.treeNodeColor,
inBoundingRect: node.boundingRect)
}
private func drawLine(fromNode from: TreeLayout<Node>,
toNode to: TreeLayout<Node>) {
guard case let DrawingState.drawingTreeLines(renderer) = drawingState else { return }
renderer.renderLine(from: from.childLineAnchor, to: to.parentLineAnchor)
}
private var treeLayout: TreeLayout<Node>
private let drawingAttributes: TreeDrawingAttributes
private var drawingState: DrawingState
}
/// Drawing States
///
/// - ready: ready for drawing
/// - drawingGrid: drawing (optional) grid
/// - doneDrawingGrid: done drawing (optional) grid
/// - drawingTreeNodes: drawing tree nodes
/// - doneDrawingTreeNodes: done drawing tree nodes
/// - drawingTreeLines: drawing tree lines
/// - doneDrawingTreeLines: done drawing tree lines
enum DrawingState {
case ready
case drawingGrid(Renderer)
case doneDrawingGrid
case drawingTreeNodes(Renderer)
case doneDrawingTreeNodes
case drawingTreeLines(Renderer)
case doneDrawingTreeLines
// Grid drawing states
func toDrawingGrid(_ renderer: Renderer, drawingAttributes: TreeDrawingAttributes) -> DrawingState {
switch self {
case .ready, .doneDrawingTreeNodes, .doneDrawingTreeLines:
renderer.configureLine(color: drawingAttributes.gridColor,
width: drawingAttributes.gridLineWidth,
dotted: false)
return .drawingGrid(renderer)
case .drawingGrid:
return self
default:
fatalError("Non valid attempt of transition from \(self) to .DrawingGrid")
}
}
func toDoneDrawingGrid() -> DrawingState {
switch self {
case .drawingGrid(let renderer):
renderer.strokePath()
return .doneDrawingGrid
default:
fatalError("Non valid attempt of transition from \(self) to .toDoneDrawingGrid")
}
}
// Nodes drawing states
func toDrawingTreeNodes(_ renderer: Renderer, drawingAttributes: TreeDrawingAttributes) -> DrawingState {
switch self {
case .ready, .doneDrawingGrid, .doneDrawingTreeLines:
return .drawingTreeNodes(renderer)
case .drawingTreeNodes:
return self
default:
fatalError("Non valid attempt of transition from \(self) to .toDrawingTreeNodes")
}
}
func toDoneDrawingTreeNodes() -> DrawingState {
switch self {
case .drawingTreeNodes(let renderer):
renderer.strokePath()
return .doneDrawingTreeNodes
default:
fatalError("Non valid attempt of transition from \(self) to .toDoneDrawingTreeNodes")
}
}
// Tree Lines drawing states
func toDrawingTreeLines(_ renderer: Renderer, drawingAttributes: TreeDrawingAttributes) -> DrawingState {
switch self {
case .ready, .doneDrawingGrid, .doneDrawingTreeNodes:
renderer.configureLine(color: drawingAttributes.treeLineColor,
width: drawingAttributes.treeLineWidth,
dotted: true)
return .drawingTreeLines(renderer)
case .drawingTreeLines:
return self
default:
fatalError("Non valid attempt of transition from \(self) to .toDrawingTreeLines")
}
}
func toDoneDrawingTreeLines() -> DrawingState {
switch self {
case .drawingTreeLines(let renderer):
renderer.strokePath()
return .doneDrawingTreeLines
default:
fatalError("Non valid attempt of transition from \(self) to .toDoneDrawingTreeLines")
}
}
}
| 7b5121314ff11c21aaf1ae744156f3ee | 38.198953 | 109 | 0.643382 | false | false | false | false |
jessesquires/swift-sorts | refs/heads/master | SwiftSorts/sorts.swift | mit | 1 | //
// Jesse Squires
// http://www.jessesquires.com
//
// GitHub
// https://github.com/jessesquires/swift-sorts
//
// Copyright (c) 2014 Jesse Squires
//
func swiftSort(arr: [Int]) -> [Int]
{
return arr.sort();
}
func selectionSort(array: [Int]) -> [Int]
{
var arr = array
var minIndex = 0
for i in 0..<arr.count {
minIndex = i
for j in (i + 1)..<arr.count {
if arr[j] < arr[minIndex] {
minIndex = j
}
}
if (minIndex != i) {
swap(&arr[i], &arr[minIndex])
}
}
return arr;
}
func insertionSort(array: [Int]) -> [Int]
{
var arr = array
for i in 1..<arr.count {
var j = i
let target = arr[i]
while j > 0 && target < arr[j - 1] {
swap(&arr[j], &arr[j - 1])
j -= 1
}
arr[j] = target
}
return arr;
}
func quickSort(array: [Int]) -> [Int]
{
var arr = array
quickSort(&arr, left: 0, right: arr.count - 1)
return arr;
}
func quickSort(inout arr: [Int], left: Int, right: Int)
{
let index = partition(&arr, left: left, right: right)
if left < index - 1 {
quickSort(&arr, left: left, right: index - 1)
}
if index < right {
quickSort(&arr, left: index, right: right)
}
}
func partition(inout arr: [Int], left: Int, right: Int) -> Int
{
var i = left
var j = right
let pivot = arr[(left + right) / 2]
while i <= j {
while arr[i] < pivot {
i += 1
}
while j > 0 && arr[j] > pivot {
j -= 1
}
if i <= j {
if i != j {
swap(&arr[i], &arr[j])
}
i += 1
if j > 0 {
j -= 1
}
}
}
return i
}
func heapSort(array: [Int]) -> [Int]
{
var arr = array
heapify(&arr, count: arr.count)
var end = arr.count - 1
while end > 0 {
swap(&arr[end], &arr[0])
siftDown(&arr, start: 0, end: end - 1)
end -= 1
}
return arr;
}
func heapify(inout arr: [Int], count: Int)
{
var start = (count - 2) / 2
while start >= 0 {
siftDown(&arr, start: start, end: count - 1)
start -= 1
}
}
func siftDown(inout arr: [Int], start: Int, end: Int)
{
var root = start
while root * 2 + 1 <= end {
var child = root * 2 + 1
if child + 1 <= end && arr[child] < arr[child + 1] {
child += 1
}
if arr[root] < arr[child] {
swap(&arr[root], &arr[child])
root = child
}
else {
return
}
}
}
| 0f2d1aad96ee5488a29e1e2c4f4fabb2 | 17.709459 | 62 | 0.433731 | false | false | false | false |
JasonChen2015/Paradise-Lost | refs/heads/master | Paradise Lost/Classes/Views/Game/TwoZeroFourEightView.swift | mit | 3 | //
// TwoZeroFourEightView.swift
// Paradise Lost
//
// Created by Jason Chen on 5/16/16.
// Copyright © 2016 Jason Chen. All rights reserved.
//
import Foundation
import UIKit
protocol TwoZeroFourEightViewDelegate {
func newButtonAction()
func exitButtonAction()
}
class TwoZeroFourEightView: UIView {
/// the length of a tile
fileprivate let length = 86
/// distance between two tile
fileprivate let padding = 6
/// restore the (dimension * dimension) of tile
fileprivate var tilesSet: [UIView] = []
var delegate: TwoZeroFourEightViewDelegate? = nil
// MARK: life cycle
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = Color().CosmicLatte
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
fileprivate func setupView() {
// add tiles
for j in 0..<4 {
for i in 0..<4 {
let tile = TZFETileView(
frame: CGRect(
x: (padding + i * (length + padding)),
y: (padding + j * (length + padding)),
width: length,
height: length
),
value: 0
)
tilesBackground.addSubview(tile)
tilesSet.append(tile)
}
}
addSubview(titleLabel)
addSubview(scoreTextLabel)
addSubview(scoreNumLabel)
addSubview(tilesBackground)
addSubview(highScoreTextLabel)
addSubview(highScoreNumLabel)
addSubview(newButton)
addSubview(exitButton)
newButton.addTarget(self, action: #selector(TwoZeroFourEightView.newGame), for: .touchUpInside)
exitButton.addTarget(self, action: #selector(TwoZeroFourEightView.exitGame), for: .touchUpInside)
}
override func layoutSubviews() {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-54-[v0(60)]-[v1(30)]-[v2(374)]-[v3(30)]-[v4(30)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": titleLabel, "v1": scoreTextLabel, "v2": tilesBackground, "v3": highScoreTextLabel, "v4": highScoreNumLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v0(30)]-[v1]-[v2(30)]-[v3(30)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": scoreNumLabel, "v1": tilesBackground, "v2": newButton, "v3": exitButton]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": titleLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-[v1(100)]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": scoreTextLabel, "v1": scoreNumLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0(374)]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": tilesBackground]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]-[v1(100)]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": highScoreTextLabel, "v1": newButton]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]-[v1(100)]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": highScoreNumLabel, "v1": exitButton]))
}
// MARK: event response
@objc func newGame() {
delegate?.newButtonAction()
}
@objc func exitGame() {
delegate?.exitButtonAction()
}
// MARK: getters and setters
fileprivate var titleLabel: UILabel = {
var label = UILabel()
label.text = LanguageManager.getGameString(forKey: "2048.titlelabel.text")
label.textColor = Color().Kokiake
label.font = UIFont.boldSystemFont(ofSize: 54)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate var scoreTextLabel: UILabel = {
var label = UILabel()
label.text = LanguageManager.getGameString(forKey: "2048.scoretextlabel.text")
label.textColor = Color().Kurotobi
label.font = UIFont.boldSystemFont(ofSize: 27)
label.textAlignment = .right
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate var scoreNumLabel: UILabel = {
var label = UILabel()
label.text = "0"
label.textColor = Color().Kakitsubata
label.font = UIFont.boldSystemFont(ofSize: 27)
label.textAlignment = .right
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate var tilesBackground: UIView = {
var view = UIView()
view.backgroundColor = Color().TileBackground
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
fileprivate var highScoreTextLabel: UILabel = {
var label = UILabel()
label.text = LanguageManager.getGameString(forKey: "2048.highscoretextlabel.text")
label.textColor = Color().Kurotobi
label.font = UIFont.boldSystemFont(ofSize: 27)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate var highScoreNumLabel: UILabel = {
var label = UILabel()
label.text = "0"
label.textColor = Color().Kakitsubata
label.font = UIFont.boldSystemFont(ofSize: 27)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate var newButton: UIButton = {
var button = UIButton(type: .system)
button.setTitleColor(Color().Kurotobi, for: UIControlState())
button.setTitle(LanguageManager.getGameString(forKey: "2048.newbutton.title"), for: UIControlState())
button.isExclusiveTouch = true
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
fileprivate var exitButton: UIButton = {
var button = UIButton(type: .system)
button.setTitleColor(Color().Kurotobi, for: UIControlState())
button.setTitle(LanguageManager.getPublicString(forKey: "exit"), for: UIControlState())
button.isExclusiveTouch = true
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
func setValueOfTile(_ index: Int, value: Int) {
let tile = tilesSet[index] as! TZFETileView
tile.value = value
}
func setValueOfScore(_ value: Int) {
scoreNumLabel.text = "\(value)"
}
func setValueOfHighScore(_ value: Int) {
highScoreNumLabel.text = "\(value)"
}
}
class TZFETileView: UIView {
fileprivate let colorMap = [
0: Color().mixColorBetween(Color().TileColor, colorB: Color().TileBackground),
2: Color().mixColorBetween(Color().TileColor, weightA: 1, colorB: Color().TileGoldColor, weightB: 0),
4: Color().mixColorBetween(Color().TileColor, weightA: 0.9, colorB: Color().TileGoldColor, weightB: 0.1),
8: Color().mixColorBetween(Color().BrightOrange, weightA: 0.55, colorB: Color().TileColor, weightB: 0.45),
16: Color().mixColorBetween(Color().BrightRed, weightA: 0.55, colorB: Color().TileColor, weightB: 0.45),
32: Color().mixColorBetween(Color().VividRed, weightA: 0.55, colorB: Color().TileColor, weightB: 0.45),
64: Color().mixColorBetween(Color().PureRed, weightA: 0.55, colorB: Color().TileColor, weightB: 0.45),
128: Color().mixColorBetween(Color().TileColor, weightA: 0.7, colorB: Color().TileGoldColor, weightB: 0.3),
256: Color().mixColorBetween(Color().TileColor, weightA: 0.6, colorB: Color().TileGoldColor, weightB: 0.4),
512: Color().mixColorBetween(Color().TileColor, weightA: 0.5, colorB: Color().TileGoldColor, weightB: 0.5),
1024: Color().mixColorBetween(Color().TileColor, weightA: 0.4, colorB: Color().TileGoldColor, weightB: 0.6),
2048: Color().mixColorBetween(Color().TileColor, weightA: 0.3, colorB: Color().TileGoldColor, weightB: 0.7)
]
var value: Int = 0 {
didSet {
if value > 2048 {
backgroundColor = UIColor.black
} else {
backgroundColor = colorMap[value]
}
if value == 0 {
contentLabel.text = ""
} else {
contentLabel.text = "\(value)"
show()
}
if value == 2 || value == 4 {
contentLabel.textColor = Color().DarkGrayishOrange
} else {
contentLabel.textColor = Color().LightGrayishOrange
}
}
}
lazy var contentLabel: UILabel = {
var label = UILabel()
label.textColor = UIColor.white
label.font = UIFont.boldSystemFont(ofSize: 27) // originContentFont
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
init(frame: CGRect, value: Int) {
super.init(frame: frame)
self.value = value
backgroundColor = colorMap[self.value]
self.contentLabel.text = (value == 0) ? "" : "\(self.value)"
addSubview(contentLabel)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": self.contentLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": self.contentLabel]))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: private methods
fileprivate func show() {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
}, completion: { (finished: Bool) -> Void in
UIView.animate(withDuration: 0.05, animations: { () -> Void in
self.transform = CGAffineTransform.identity
})
})
}
}
| a860af7677020fff7913a515e798231e | 39.416988 | 299 | 0.621609 | false | false | false | false |
VanHack/binners-project-ios | refs/heads/develop | ios-binners-project/BPMainTabBarController.swift | mit | 1 | //
// BPMainTabBarController.swift
// ios-binners-project
//
// Created by Matheus Ruschel on 1/15/16.
// Copyright © 2016 Rodrigo de Souza Reis. All rights reserved.
import UIKit
class BPMainTabBarController: UITabBarController {
var centerButton:UIButton?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupTabBar()
var tabItems = self.tabBar.items
let tabItem0 = tabItems![0]
let tabItem1 = tabItems![1]
let tabItem2 = tabItems![2]
let tabItem3 = tabItems![3]
let tabItem4 = tabItems![4]
tabItem0.title = "History"
tabItem1.title = "On-Going"
tabItem2.title = "New Pickup"
tabItem3.title = "Profile"
tabItem4.title = "Donate"
self.setupNavigationBar()
}
func setupTabBar() {
self.tabBar.tintColor = UIColor.white
self.tabBar.isTranslucent = false
let unselectedColor = UIColor.gray
self.tabBar.configureFlatTabBar(with: UIColor.white, selectedColor: unselectedColor)
UITabBarItem.appearance().setTitleTextAttributes(
[NSForegroundColorAttributeName:unselectedColor],
for: UIControlState())
UITabBarItem.appearance().setTitleTextAttributes(
[NSForegroundColorAttributeName:UIColor.white],
for: .selected)
UITabBar.appearance().selectionIndicatorImage =
UIImage().makeImageWithColorAndSize(
UIColor.binnersGreenColor(),
size: CGSize(
width: tabBar.frame.width/5,
height: tabBar.frame.height))
for item in self.tabBar.items! {
item.image = item.selectedImage?.imageWithColor(
unselectedColor).withRenderingMode(
UIImageRenderingMode.alwaysOriginal)
}
}
func showLateralMenu()
{
print("side menu")
}
func setupNavigationBar()
{
let button = UIBarButtonItem(
image: UIImage(named: "1455939101_menu-alt.png"),
style: .done, target: self,
action: #selector(BPMainTabBarController.showLateralMenu))
button.tintColor = UIColor.white
self.navigationItem.leftBarButtonItem = button
self.navigationController?.navigationBar.barTintColor = UIColor.binnersGreenColor()
self.navigationController?.navigationBar.topItem?.title = "Binner's Project"
self.navigationController?.navigationBar.titleTextAttributes =
[NSForegroundColorAttributeName : UIColor.white]
self.navigationController?.navigationBar.backgroundColor = UIColor.binnersGreenColor()
}
func addCenterButtonWithViewButtonView(_ target:AnyObject?,action:Selector)
{
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0.0, y: 0.0,width: 120.0, height: 120.0)
button.backgroundColor = UIColor.binnersGreenColor()
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.clipsToBounds = true
let heightDifference = button.frame.size.height - self.tabBar.frame.size.height
if heightDifference < 0
{
button.center = self.tabBar.center
} else {
let center = self.tabBar.center
button.center = center
}
button.addTarget(target, action: action, for: .touchUpInside)
self.view.addSubview(button)
self.centerButton = button
// label setup
let plusLabel = UILabel(frame: CGRect(
x: (button.frame.size.width / 2.0) - 15.0,
y: button.frame.size.height * 0.1,
width: 30.0,
height: 40.0))
plusLabel.text = "+"
plusLabel.font = UIFont.systemFont(ofSize: 40)
plusLabel.textColor = UIColor.white
plusLabel.backgroundColor = UIColor.clear
plusLabel.textAlignment = .center
button.addSubview(plusLabel)
let textLabel = UILabel(frame: CGRect(
x: (button.frame.size.width / 2.0) - (button.frame.size.width / 2.0),
y: plusLabel.frame.origin.y + plusLabel.frame.size.height,
width: button.frame.size.width,
height: 20.0))
textLabel.text = "New Pick-Up"
textLabel.font = UIFont.systemFont(ofSize: 10)
textLabel.textColor = UIColor.white
textLabel.backgroundColor = UIColor.clear
textLabel.textAlignment = .center
button.addSubview(textLabel)
}
func buttonPressed(_ sender:UIButton)
{
self.selectedIndex = 0
self.performSegue(withIdentifier: "newPickupSegue", sender: self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if let itemSelected = (tabBar.items)?[4] {
if item == itemSelected {
UIApplication.shared.openURL(
URL(string:"https://www.gifttool.com/donations/Donate?ID=1453&AID=503&PID=4805")!)
}
}
}
}
| 00f6f4c196b7e03a3d906919d2f38c0c | 31.430233 | 102 | 0.597885 | false | false | false | false |
tilltue/TLPhotoPicker | refs/heads/master | Example/TLPhotoPicker/ViewController.swift | mit | 1 | //
// ViewController.swift
// TLPhotoPicker
//
// Created by wade.hawk on 05/09/2017.
// Copyright (c) 2017 wade.hawk. All rights reserved.
//
import UIKit
import TLPhotoPicker
import Photos
class ViewController: UIViewController,TLPhotosPickerViewControllerDelegate {
var selectedAssets = [TLPHAsset]()
@IBOutlet var label: UILabel!
@IBOutlet var imageView: UIImageView!
@IBAction func pickerButtonTap() {
let viewController = CustomPhotoPickerViewController()
viewController.modalPresentationStyle = .fullScreen
viewController.delegate = self
viewController.didExceedMaximumNumberOfSelection = { [weak self] (picker) in
self?.showExceededMaximumAlert(vc: picker)
}
var configure = TLPhotosPickerConfigure()
configure.numberOfColumn = 3
viewController.configure = configure
viewController.selectedAssets = self.selectedAssets
viewController.logDelegate = self
self.present(viewController, animated: true, completion: nil)
}
@IBAction func onlyVideoRecording(_ sender: Any) {
let viewController = CustomPhotoPickerViewController()
viewController.delegate = self
viewController.didExceedMaximumNumberOfSelection = { [weak self] (picker) in
self?.showExceededMaximumAlert(vc: picker)
}
var configure = TLPhotosPickerConfigure()
configure.numberOfColumn = 3
configure.allowedPhotograph = false
configure.allowedVideoRecording = true
configure.mediaType = .video
viewController.configure = configure
viewController.selectedAssets = self.selectedAssets
viewController.logDelegate = self
self.present(viewController, animated: true, completion: nil)
}
@IBAction func pickerWithCustomCameraCell() {
let viewController = CustomPhotoPickerViewController()
viewController.delegate = self
viewController.didExceedMaximumNumberOfSelection = { [weak self] (picker) in
self?.showExceededMaximumAlert(vc: picker)
}
var configure = TLPhotosPickerConfigure()
configure.numberOfColumn = 3
if #available(iOS 10.2, *) {
configure.cameraCellNibSet = (nibName: "CustomCameraCell", bundle: Bundle.main)
}
viewController.configure = configure
viewController.selectedAssets = self.selectedAssets
self.present(viewController.wrapNavigationControllerWithoutBar(), animated: true, completion: nil)
}
@IBAction func pickerWithCustomBlackStyle() {
let viewController = CustomBlackStylePickerViewController()
viewController.modalPresentationStyle = .fullScreen
viewController.delegate = self
viewController.didExceedMaximumNumberOfSelection = { [weak self] (picker) in
self?.showExceededMaximumAlert(vc: picker)
}
var configure = TLPhotosPickerConfigure()
configure.numberOfColumn = 3
viewController.configure = configure
viewController.selectedAssets = self.selectedAssets
self.present(viewController, animated: true, completion: nil)
}
@IBAction func pickerWithNavigation() {
let viewController = PhotoPickerWithNavigationViewController()
viewController.delegate = self
viewController.didExceedMaximumNumberOfSelection = { [weak self] (picker) in
self?.showExceededMaximumAlert(vc: picker)
}
var configure = TLPhotosPickerConfigure()
configure.numberOfColumn = 3
viewController.configure = configure
viewController.selectedAssets = self.selectedAssets
self.present(viewController.wrapNavigationControllerWithoutBar(), animated: true, completion: nil)
}
@IBAction func pickerWithCustomRules() {
let viewController = PhotoPickerWithNavigationViewController()
viewController.delegate = self
viewController.didExceedMaximumNumberOfSelection = { [weak self] (picker) in
self?.showExceededMaximumAlert(vc: picker)
}
viewController.canSelectAsset = { [weak self] asset -> Bool in
if asset.pixelHeight != 300 && asset.pixelWidth != 300 {
self?.showUnsatisifiedSizeAlert(vc: viewController)
return false
}
return true
}
var configure = TLPhotosPickerConfigure()
configure.numberOfColumn = 3
configure.nibSet = (nibName: "CustomCell_Instagram", bundle: Bundle.main)
viewController.configure = configure
viewController.selectedAssets = self.selectedAssets
self.present(viewController.wrapNavigationControllerWithoutBar(), animated: true, completion: nil)
}
@IBAction func pickerWithCustomLayout() {
let viewController = TLPhotosPickerViewController()
viewController.delegate = self
viewController.didExceedMaximumNumberOfSelection = { [weak self] (picker) in
self?.showExceededMaximumAlert(vc: picker)
}
viewController.customDataSouces = CustomDataSources()
var configure = TLPhotosPickerConfigure()
configure.numberOfColumn = 3
configure.groupByFetch = .day
viewController.configure = configure
viewController.selectedAssets = self.selectedAssets
viewController.logDelegate = self
self.present(viewController, animated: true, completion: nil)
}
func dismissPhotoPicker(withTLPHAssets: [TLPHAsset]) {
// use selected order, fullresolution image
self.selectedAssets = withTLPHAssets
getFirstSelectedImage()
//iCloud or video
// getAsyncCopyTemporaryFile()
}
func exportVideo() {
if let asset = self.selectedAssets.first, asset.type == .video {
asset.exportVideoFile(progressBlock: { (progress) in
print(progress)
}) { (url, mimeType) in
print("completion\(url)")
print(mimeType)
}
}
}
func getAsyncCopyTemporaryFile() {
if let asset = self.selectedAssets.first {
asset.tempCopyMediaFile(convertLivePhotosToJPG: false, progressBlock: { (progress) in
print(progress)
}, completionBlock: { (url, mimeType) in
print("completion\(url)")
print(mimeType)
})
}
}
func getFirstSelectedImage() {
if let asset = self.selectedAssets.first {
if asset.type == .video {
asset.videoSize(completion: { [weak self] (size) in
self?.label.text = "video file size\(size)"
})
return
}
if let image = asset.fullResolutionImage {
print(image)
self.label.text = "local storage image"
self.imageView.image = image
}else {
print("Can't get image at local storage, try download image")
asset.cloudImageDownload(progressBlock: { [weak self] (progress) in
DispatchQueue.main.async {
self?.label.text = "download \(100*progress)%"
print(progress)
}
}, completionBlock: { [weak self] (image) in
if let image = image {
//use image
DispatchQueue.main.async {
self?.label.text = "complete download"
self?.imageView.image = image
}
}
})
}
}
}
func dismissPhotoPicker(withPHAssets: [PHAsset]) {
// if you want to used phasset.
}
func photoPickerDidCancel() {
// cancel
}
func dismissComplete() {
// picker dismiss completion
}
func didExceedMaximumNumberOfSelection(picker: TLPhotosPickerViewController) {
self.showExceededMaximumAlert(vc: picker)
}
func handleNoAlbumPermissions(picker: TLPhotosPickerViewController) {
picker.dismiss(animated: true) {
let alert = UIAlertController(title: "", message: "Denied albums permissions granted", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func handleNoCameraPermissions(picker: TLPhotosPickerViewController) {
let alert = UIAlertController(title: "", message: "Denied camera permissions granted", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
picker.present(alert, animated: true, completion: nil)
}
func showExceededMaximumAlert(vc: UIViewController) {
let alert = UIAlertController(title: "", message: "Exceed Maximum Number Of Selection", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
vc.present(alert, animated: true, completion: nil)
}
func showUnsatisifiedSizeAlert(vc: UIViewController) {
let alert = UIAlertController(title: "Oups!", message: "The required size is: 300 x 300", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
vc.present(alert, animated: true, completion: nil)
}
}
extension ViewController: TLPhotosPickerLogDelegate {
//For Log User Interaction
func selectedCameraCell(picker: TLPhotosPickerViewController) {
print("selectedCameraCell")
}
func selectedPhoto(picker: TLPhotosPickerViewController, at: Int) {
print("selectedPhoto")
}
func deselectedPhoto(picker: TLPhotosPickerViewController, at: Int) {
print("deselectedPhoto")
}
func selectedAlbum(picker: TLPhotosPickerViewController, title: String, at: Int) {
print("selectedAlbum")
}
}
| 5d63d89de6de75c4301299458717c2cf | 38.490272 | 122 | 0.638585 | false | true | false | false |
watson-developer-cloud/ios-sdk | refs/heads/master | Sources/SpeechToTextV1/SpeechToText.swift | apache-2.0 | 1 | /**
* (C) Copyright IBM Corp. 2022.
*
* 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.
**/
/**
* IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428
**/
// swiftlint:disable file_length
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
import IBMSwiftSDKCore
public typealias WatsonError = RestError
public typealias WatsonResponse = RestResponse
/**
The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce
transcripts of spoken audio. The service can transcribe speech from various languages and audio formats. In addition
to basic transcription, the service can produce detailed information about many different aspects of the audio. It
returns all JSON response content in the UTF-8 character set.
The service supports two types of models: previous-generation models that include the terms `Broadband` and
`Narrowband` in their names, and next-generation models that include the terms `Multimedia` and `Telephony` in their
names. Broadband and multimedia models have minimum sampling rates of 16 kHz. Narrowband and telephony models have
minimum sampling rates of 8 kHz. The next-generation models offer high throughput and greater transcription accuracy.
Effective 15 March 2022, previous-generation models for all languages other than Arabic and Japanese are deprecated.
The deprecated models remain available until 15 September 2022, when they will be removed from the service and the
documentation. You must migrate to the equivalent next-generation model by the end of service date. For more
information, see [Migrating to next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).{: deprecated}
For speech recognition, the service supports synchronous and asynchronous HTTP Representational State Transfer (REST)
interfaces. It also supports a WebSocket interface that provides a full-duplex, low-latency communication channel:
Clients send requests and audio to the service and receive results over a single connection asynchronously.
The service also offers two customization interfaces. Use language model customization to expand the vocabulary of a
base model with domain-specific terminology. Use acoustic model customization to adapt a base model for the acoustic
characteristics of your audio. For language model customization, the service also supports grammars. A grammar is a
formal language specification that lets you restrict the phrases that the service can recognize.
Language model customization and grammars are available for most previous- and next-generation models. Acoustic model
customization is available for all previous-generation models.
*/
public class SpeechToText {
/// The base URL to use when contacting the service.
public var serviceURL: String? = "https://api.us-south.speech-to-text.watson.cloud.ibm.com"
/// Service identifiers
public static let defaultServiceName = "speech_to_text"
// Service info for SDK headers
internal let serviceName = defaultServiceName
internal let serviceVersion = "v1"
internal let serviceSdkName = "speech_to_text"
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()
var session = URLSession(configuration: URLSessionConfiguration.default)
public let authenticator: Authenticator
#if os(Linux)
/**
Create a `SpeechToText` object.
If an authenticator is not supplied, the initializer will retrieve credentials from the environment or
a local credentials file and construct an appropriate authenticator using these credentials.
The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env.
Make sure to add the credentials file to your project so that it can be loaded at runtime.
If an authenticator is not supplied and credentials are not available in the environment or a local
credentials file, initialization will fail by throwing an exception.
In that case, try another initializer that directly passes in the credentials.
- parameter authenticator: The Authenticator object used to authenticate requests to the service
- serviceName: String = defaultServiceName
*/
public init(authenticator: Authenticator? = nil, serviceName: String = defaultServiceName) throws {
self.authenticator = try authenticator ?? ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceName)
if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceName) {
self.serviceURL = serviceURL
}
RestRequest.userAgent = Shared.userAgent
}
#else
/**
Create a `SpeechToText` object.
- parameter authenticator: The Authenticator object used to authenticate requests to the service
*/
public init(authenticator: Authenticator) {
self.authenticator = authenticator
RestRequest.userAgent = Shared.userAgent
}
#endif
#if !os(Linux)
/**
Allow network requests to a server without verification of the server certificate.
**IMPORTANT**: This should ONLY be used if truly intended, as it is unsafe otherwise.
*/
public func disableSSLVerification() {
session = InsecureConnection.session()
}
#endif
/**
Use the HTTP response and data received by the Speech to Text service to extract
information about the error that occurred.
- parameter data: Raw data returned by the service that may represent an error.
- parameter response: the URL response returned by the service.
*/
func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> RestError {
let statusCode = response.statusCode
var errorMessage: String?
var metadata = [String: Any]()
do {
let json = try JSON.decoder.decode([String: JSON].self, from: data)
metadata["response"] = json
if case let .some(.array(errors)) = json["errors"],
case let .some(.object(error)) = errors.first,
case let .some(.string(message)) = error["message"] {
errorMessage = message
} else if case let .some(.string(message)) = json["error"] {
errorMessage = message
} else if case let .some(.string(message)) = json["message"] {
errorMessage = message
} else {
errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode)
}
} catch {
metadata["response"] = data
errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode)
}
return RestError.http(statusCode: statusCode, message: errorMessage, metadata: metadata)
}
/**
List models.
Lists all language models that are available for use with the service. The information includes the name of the
model and its minimum sampling rate in Hertz, among other things. The ordering of the list of models can change
from call to call; do not rely on an alphabetized or static list of models.
**See also:** [Listing all
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list#models-list-all).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listModels(
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<SpeechModels>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + "/v1/models",
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Get a model.
Gets information for a single specified language model that is available for use with the service. The information
includes the name of the model and its minimum sampling rate in Hertz, among other things.
**See also:** [Listing a specific
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list#models-list-specific).
- parameter modelID: The identifier of the model in the form of its name from the output of the [List
models](#listmodels) method. (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use
`ar-MS_BroadbandModel` instead.).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getModel(
modelID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<SpeechModel>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/models/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Recognize audio.
Sends audio and returns transcription results for a recognition request. You can pass a maximum of 100 MB and a
minimum of 100 bytes of audio with a request. The service automatically detects the endianness of the incoming
audio and, for audio that includes multiple channels, downmixes the audio to one-channel mono during transcoding.
The method returns only final results; to enable interim results, use the WebSocket API. (With the `curl` command,
use the `--data-binary` option to upload the file for the request.)
**See also:** [Making a basic HTTP
request](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-http#HTTP-basic).
### Streaming mode
For requests to transcribe live audio as it becomes available, you must set the `Transfer-Encoding` header to
`chunked` to use streaming mode. In streaming mode, the service closes the connection (status code 408) if it does
not receive at least 15 seconds of audio (including silence) in any 30-second period. The service also closes the
connection (status code 400) if it detects no speech for `inactivity_timeout` seconds of streaming audio; use the
`inactivity_timeout` parameter to change the default of 30 seconds.
**See also:**
* [Audio transmission](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#transmission)
* [Timeouts](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#timeouts)
### Audio formats (content types)
The service accepts audio in the following formats (MIME types).
* For formats that are labeled **Required**, you must use the `Content-Type` header with the request to specify the
format of the audio.
* For all other formats, you can omit the `Content-Type` header or specify `application/octet-stream` with the
header to have the service automatically detect the format of the audio. (With the `curl` command, you can specify
either `"Content-Type:"` or `"Content-Type: application/octet-stream"`.)
Where indicated, the format that you specify must include the sampling rate and can optionally include the number
of channels and the endianness of the audio.
* `audio/alaw` (**Required.** Specify the sampling rate (`rate`) of the audio.)
* `audio/basic` (**Required.** Use only with narrowband models.)
* `audio/flac`
* `audio/g729` (Use only with narrowband models.)
* `audio/l16` (**Required.** Specify the sampling rate (`rate`) and optionally the number of channels (`channels`)
and endianness (`endianness`) of the audio.)
* `audio/mp3`
* `audio/mpeg`
* `audio/mulaw` (**Required.** Specify the sampling rate (`rate`) of the audio.)
* `audio/ogg` (The service automatically detects the codec of the input audio.)
* `audio/ogg;codecs=opus`
* `audio/ogg;codecs=vorbis`
* `audio/wav` (Provide audio with a maximum of nine channels.)
* `audio/webm` (The service automatically detects the codec of the input audio.)
* `audio/webm;codecs=opus`
* `audio/webm;codecs=vorbis`
The sampling rate of the audio must match the sampling rate of the model for the recognition request: for broadband
models, at least 16 kHz; for narrowband models, at least 8 kHz. If the sampling rate of the audio is higher than
the minimum required rate, the service down-samples the audio to the appropriate rate. If the sampling rate of the
audio is lower than the minimum required rate, the request fails.
**See also:** [Supported audio
formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats).
### Next-generation models
The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 kHz) models for many languages.
Next-generation models have higher throughput than the service's previous generation of `Broadband` and
`Narrowband` models. When you use next-generation models, the service can return transcriptions more quickly and
also provide noticeably better transcription accuracy.
You specify a next-generation model by using the `model` query parameter, as you do a previous-generation model.
Many next-generation models also support the `low_latency` parameter, which is not available with
previous-generation models. Next-generation models do not support all of the parameters that are available for use
with previous-generation models.
**Important:** Effective 15 March 2022, previous-generation models for all languages other than Arabic and Japanese
are deprecated. The deprecated models remain available until 15 September 2022, when they will be removed from the
service and the documentation. You must migrate to the equivalent next-generation model by the end of service date.
For more information, see [Migrating to next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).
**See also:**
* [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng)
* [Supported features for next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-features)
### Multipart speech recognition
**Note:** The asynchronous HTTP interface, WebSocket interface, and Watson SDKs do not support multipart speech
recognition.
The HTTP `POST` method of the service also supports multipart speech recognition. With multipart requests, you pass
all audio data as multipart form data. You specify some parameters as request headers and query parameters, but you
pass JSON metadata as form data to control most aspects of the transcription. You can use multipart recognition to
pass multiple audio files with a single request.
Use the multipart approach with browsers for which JavaScript is disabled or when the parameters used with the
request are greater than the 8 KB limit imposed by most HTTP servers and proxies. You can encounter this limit, for
example, if you want to spot a very large number of keywords.
**See also:** [Making a multipart HTTP
request](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-http#HTTP-multi).
- parameter audio: The audio to transcribe.
- parameter contentType: The format (MIME type) of the audio. For more information about specifying an audio
format, see **Audio formats (content types)** in the method description.
- parameter model: The identifier of the model that is to be used for the recognition request. (**Note:** The
model `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for speech
recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use).
- parameter languageCustomizationID: The customization ID (GUID) of a custom language model that is to be used
with the recognition request. The base model of the specified custom language model must match the model
specified with the `model` parameter. You must make the request with credentials for the instance of the service
that owns the custom model. By default, no custom language model is used. See [Using a custom language model for
speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse).
**Note:** Use this parameter instead of the deprecated `customization_id` parameter.
- parameter acousticCustomizationID: The customization ID (GUID) of a custom acoustic model that is to be used
with the recognition request. The base model of the specified custom acoustic model must match the model
specified with the `model` parameter. You must make the request with credentials for the instance of the service
that owns the custom model. By default, no custom acoustic model is used. See [Using a custom acoustic model for
speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acousticUse).
- parameter baseModelVersion: The version of the specified base model that is to be used with the recognition
request. Multiple versions of a base model can exist when a model is updated for internal improvements. The
parameter is intended primarily for use with custom models that have been upgraded for a new base model. The
default value depends on whether the parameter is used with or without a custom model. See [Making speech
recognition requests with upgraded custom
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade-use#custom-upgrade-use-recognition).
- parameter customizationWeight: If you specify the customization ID (GUID) of a custom language model with the
recognition request, the customization weight tells the service how much weight to give to words from the custom
language model compared to those from the base model for the current request.
Specify a value between 0.0 and 1.0. Unless a different customization weight was specified for the custom model
when it was trained, the default value is 0.3. A customization weight that you specify overrides a weight that
was specified when the custom model was trained.
The default value yields the best performance in general. Assign a higher value if your audio makes frequent use
of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy
of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases.
See [Using customization
weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight).
- parameter inactivityTimeout: The time in seconds after which, if only silence (no speech) is detected in
streaming audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission
from a live microphone when a user simply walks away. Use `-1` for infinity. See [Inactivity
timeout](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#timeouts-inactivity).
- parameter keywords: An array of keyword strings to spot in the audio. Each keyword string can include one or
more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any
keywords, you must also specify a keywords threshold. Omit the parameter or specify an empty array if you do not
need to spot keywords.
You can spot a maximum of 1000 keywords with a single request. A single keyword can have a maximum length of 1024
characters, though the maximum effective length for double-byte languages might be shorter. Keywords are
case-insensitive.
See [Keyword spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#keyword-spotting).
- parameter keywordsThreshold: A confidence value that is the lower bound for spotting a keyword. A word is
considered to match a keyword if its confidence is greater than or equal to the threshold. Specify a probability
between 0.0 and 1.0. If you specify a threshold, you must also specify one or more keywords. The service performs
no keyword spotting if you omit either parameter. See [Keyword
spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#keyword-spotting).
- parameter maxAlternatives: The maximum number of alternative transcripts that the service is to return. By
default, the service returns a single transcript. If you specify a value of `0`, the service uses the default
value, `1`. See [Maximum
alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#max-alternatives).
- parameter wordAlternativesThreshold: A confidence value that is the lower bound for identifying a hypothesis as
a possible word alternative (also known as "Confusion Networks"). An alternative word is considered if its
confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. By default, the
service computes no alternative words. See [Word
alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#word-alternatives).
- parameter wordConfidence: If `true`, the service returns a confidence measure in the range of 0.0 to 1.0 for
each word. By default, the service returns no word confidence scores. See [Word
confidence](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#word-confidence).
- parameter timestamps: If `true`, the service returns time alignment for each word. By default, no timestamps
are returned. See [Word
timestamps](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#word-timestamps).
- parameter profanityFilter: If `true`, the service filters profanity from all output except for keyword results
by replacing inappropriate words with a series of asterisks. Set the parameter to `false` to return results with
no censoring.
**Note:** The parameter can be used with US English and Japanese transcription only. See [Profanity
filtering](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#profanity-filtering).
- parameter smartFormatting: If `true`, the service converts dates, times, series of digits and numbers, phone
numbers, currency values, and internet addresses into more readable, conventional representations in the final
transcript of a recognition request. For US English, the service also converts certain keyword strings to
punctuation symbols. By default, the service performs no smart formatting.
**Note:** The parameter can be used with US English, Japanese, and Spanish (all dialects) transcription only.
See [Smart
formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting).
- parameter speakerLabels: If `true`, the response includes labels that identify which words were spoken by which
participants in a multi-person exchange. By default, the service returns no speaker labels. Setting
`speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify
`false` for the parameter.
* _For previous-generation models,_ the parameter can be used with Australian English, US English, German,
Japanese, Korean, and Spanish (both broadband and narrowband models) and UK English (narrowband model)
transcription only.
* _For next-generation models,_ the parameter can be used with Czech, English (Australian, Indian, UK, and US),
German, Japanese, Korean, and Spanish transcription only.
See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels).
- parameter customizationID: **Deprecated.** Use the `language_customization_id` parameter to specify the
customization ID (GUID) of a custom language model that is to be used with the recognition request. Do not
specify both parameters with a request.
- parameter grammarName: The name of a grammar that is to be used with the recognition request. If you specify a
grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language
model for which the grammar is defined. The service recognizes only strings that are recognized by the specified
grammar; it does not recognize other custom words from the model's words resource.
See [Using a grammar for speech
recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUse).
- parameter redaction: If `true`, the service redacts, or masks, numeric data from final transcripts. The feature
redacts any number that has three or more consecutive digits by replacing each digit with an `X` character. It is
intended to redact sensitive numeric data, such as credit card numbers. By default, the service performs no
redaction.
When you enable redaction, the service automatically enables smart formatting, regardless of whether you
explicitly disable that feature. To ensure maximum security, the service also disables keyword spotting (ignores
the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the
`max_alternatives` parameter to be `1`).
**Note:** The parameter can be used with US English, Japanese, and Korean transcription only.
See [Numeric
redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#numeric-redaction).
- parameter audioMetrics: If `true`, requests detailed information about the signal characteristics of the input
audio. The service returns audio metrics with the final transcription results. By default, the service returns no
audio metrics.
See [Audio metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#audio-metrics).
- parameter endOfPhraseSilenceTime: If `true`, specifies the duration of the pause interval at which the service
splits a transcript into multiple final results. If the service detects pauses or extended silence before it
reaches the end of the audio stream, its response can include multiple final results. Silence indicates a point
at which the speaker pauses between spoken words or phrases.
Specify a value for the pause interval in the range of 0.0 to 120.0.
* A value greater than 0 specifies the interval that the service is to use for speech recognition.
* A value of 0 indicates that the service is to use the default interval. It is equivalent to omitting the
parameter.
The default pause interval for most languages is 0.8 seconds; the default for Chinese is 0.6 seconds.
See [End of phrase silence
time](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#silence-time).
- parameter splitTranscriptAtPhraseEnd: If `true`, directs the service to split the transcript into multiple
final results based on semantic features of the input, for example, at the conclusion of meaningful phrases such
as sentences. The service bases its understanding of semantic features on the base language model that you use
with a request. Custom language models and grammars can also influence how and where the service splits a
transcript.
By default, the service splits transcripts based solely on the pause interval. If the parameters are used
together on the same request, `end_of_phrase_silence_time` has precedence over `split_transcript_at_phrase_end`.
See [Split transcript at phrase
end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#split-transcript).
- parameter speechDetectorSensitivity: The sensitivity of speech activity detection that the service is to
perform. Use the parameter to suppress word insertions from music, coughing, and other non-speech events. The
service biases the audio it passes for speech recognition by evaluating the input audio against prior models of
speech and non-speech activity.
Specify a value between 0.0 and 1.0:
* 0.0 suppresses all audio (no speech is transcribed).
* 0.5 (the default) provides a reasonable compromise for the level of sensitivity.
* 1.0 suppresses no audio (speech detection sensitivity is disabled).
The values increase on a monotonic curve.
The parameter is supported with all next-generation models and with most previous-generation models. See [Speech
detector
sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity)
and [Language model
support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support).
- parameter backgroundAudioSuppression: The level to which the service is to suppress background audio based on
its volume to prevent it from being transcribed as speech. Use the parameter to suppress side conversations or
background noise.
Specify a value in the range of 0.0 to 1.0:
* 0.0 (the default) provides no suppression (background audio suppression is disabled).
* 0.5 provides a reasonable level of audio suppression for general usage.
* 1.0 suppresses all audio (no audio is transcribed).
The values increase on a monotonic curve.
The parameter is supported with all next-generation models and with most previous-generation models. See
[Background audio
suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression)
and [Language model
support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support).
- parameter lowLatency: If `true` for next-generation `Multimedia` and `Telephony` models that support low
latency, directs the service to produce results even more quickly than it usually does. Next-generation models
produce transcription results faster than previous-generation models. The `low_latency` parameter causes the
models to produce results even more quickly, though the results might be less accurate when the parameter is
used.
The parameter is not available for previous-generation `Broadband` and `Narrowband` models. It is available only
for some next-generation models. For a list of next-generation models that support low latency, see [Supported
next-generation language
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported).
* For more information about the `low_latency` parameter, see [Low
latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func recognize(
audio: Data,
contentType: String? = nil,
model: String? = nil,
languageCustomizationID: String? = nil,
acousticCustomizationID: String? = nil,
baseModelVersion: String? = nil,
customizationWeight: Double? = nil,
inactivityTimeout: Int? = nil,
keywords: [String]? = nil,
keywordsThreshold: Double? = nil,
maxAlternatives: Int? = nil,
wordAlternativesThreshold: Double? = nil,
wordConfidence: Bool? = nil,
timestamps: Bool? = nil,
profanityFilter: Bool? = nil,
smartFormatting: Bool? = nil,
speakerLabels: Bool? = nil,
customizationID: String? = nil,
grammarName: String? = nil,
redaction: Bool? = nil,
audioMetrics: Bool? = nil,
endOfPhraseSilenceTime: Double? = nil,
splitTranscriptAtPhraseEnd: Bool? = nil,
speechDetectorSensitivity: Double? = nil,
backgroundAudioSuppression: Double? = nil,
lowLatency: Bool? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<SpeechRecognitionResults>?, WatsonError?) -> Void)
{
let body = audio
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "recognize")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let contentType = contentType {
headerParameters["Content-Type"] = contentType
}
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let model = model {
let queryParameter = URLQueryItem(name: "model", value: model)
queryParameters.append(queryParameter)
}
if let languageCustomizationID = languageCustomizationID {
let queryParameter = URLQueryItem(name: "language_customization_id", value: languageCustomizationID)
queryParameters.append(queryParameter)
}
if let acousticCustomizationID = acousticCustomizationID {
let queryParameter = URLQueryItem(name: "acoustic_customization_id", value: acousticCustomizationID)
queryParameters.append(queryParameter)
}
if let baseModelVersion = baseModelVersion {
let queryParameter = URLQueryItem(name: "base_model_version", value: baseModelVersion)
queryParameters.append(queryParameter)
}
if let customizationWeight = customizationWeight {
let queryParameter = URLQueryItem(name: "customization_weight", value: "\(customizationWeight)")
queryParameters.append(queryParameter)
}
if let inactivityTimeout = inactivityTimeout {
let queryParameter = URLQueryItem(name: "inactivity_timeout", value: "\(inactivityTimeout)")
queryParameters.append(queryParameter)
}
if let keywords = keywords {
let queryParameter = URLQueryItem(name: "keywords", value: keywords.joined(separator: ","))
queryParameters.append(queryParameter)
}
if let keywordsThreshold = keywordsThreshold {
let queryParameter = URLQueryItem(name: "keywords_threshold", value: "\(keywordsThreshold)")
queryParameters.append(queryParameter)
}
if let maxAlternatives = maxAlternatives {
let queryParameter = URLQueryItem(name: "max_alternatives", value: "\(maxAlternatives)")
queryParameters.append(queryParameter)
}
if let wordAlternativesThreshold = wordAlternativesThreshold {
let queryParameter = URLQueryItem(name: "word_alternatives_threshold", value: "\(wordAlternativesThreshold)")
queryParameters.append(queryParameter)
}
if let wordConfidence = wordConfidence {
let queryParameter = URLQueryItem(name: "word_confidence", value: "\(wordConfidence)")
queryParameters.append(queryParameter)
}
if let timestamps = timestamps {
let queryParameter = URLQueryItem(name: "timestamps", value: "\(timestamps)")
queryParameters.append(queryParameter)
}
if let profanityFilter = profanityFilter {
let queryParameter = URLQueryItem(name: "profanity_filter", value: "\(profanityFilter)")
queryParameters.append(queryParameter)
}
if let smartFormatting = smartFormatting {
let queryParameter = URLQueryItem(name: "smart_formatting", value: "\(smartFormatting)")
queryParameters.append(queryParameter)
}
if let speakerLabels = speakerLabels {
let queryParameter = URLQueryItem(name: "speaker_labels", value: "\(speakerLabels)")
queryParameters.append(queryParameter)
}
if let customizationID = customizationID {
let queryParameter = URLQueryItem(name: "customization_id", value: customizationID)
queryParameters.append(queryParameter)
}
if let grammarName = grammarName {
let queryParameter = URLQueryItem(name: "grammar_name", value: grammarName)
queryParameters.append(queryParameter)
}
if let redaction = redaction {
let queryParameter = URLQueryItem(name: "redaction", value: "\(redaction)")
queryParameters.append(queryParameter)
}
if let audioMetrics = audioMetrics {
let queryParameter = URLQueryItem(name: "audio_metrics", value: "\(audioMetrics)")
queryParameters.append(queryParameter)
}
if let endOfPhraseSilenceTime = endOfPhraseSilenceTime {
let queryParameter = URLQueryItem(name: "end_of_phrase_silence_time", value: "\(endOfPhraseSilenceTime)")
queryParameters.append(queryParameter)
}
if let splitTranscriptAtPhraseEnd = splitTranscriptAtPhraseEnd {
let queryParameter = URLQueryItem(name: "split_transcript_at_phrase_end", value: "\(splitTranscriptAtPhraseEnd)")
queryParameters.append(queryParameter)
}
if let speechDetectorSensitivity = speechDetectorSensitivity {
let queryParameter = URLQueryItem(name: "speech_detector_sensitivity", value: "\(speechDetectorSensitivity)")
queryParameters.append(queryParameter)
}
if let backgroundAudioSuppression = backgroundAudioSuppression {
let queryParameter = URLQueryItem(name: "background_audio_suppression", value: "\(backgroundAudioSuppression)")
queryParameters.append(queryParameter)
}
if let lowLatency = lowLatency {
let queryParameter = URLQueryItem(name: "low_latency", value: "\(lowLatency)")
queryParameters.append(queryParameter)
}
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/recognize",
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Register a callback.
Registers a callback URL with the service for use with subsequent asynchronous recognition requests. The service
attempts to register, or allowlist, the callback URL if it is not already registered by sending a `GET` request to
the callback URL. The service passes a random alphanumeric challenge string via the `challenge_string` parameter of
the request. The request includes an `Accept` header that specifies `text/plain` as the required response type.
To be registered successfully, the callback URL must respond to the `GET` request from the service. The response
must send status code 200 and must include the challenge string in its body. Set the `Content-Type` response header
to `text/plain`. Upon receiving this response, the service responds to the original registration request with
response code 201.
The service sends only a single `GET` request to the callback URL. If the service does not receive a reply with a
response code of 200 and a body that echoes the challenge string sent by the service within five seconds, it does
not allowlist the URL; it instead sends status code 400 in response to the request to register a callback. If the
requested callback URL is already allowlisted, the service responds to the initial registration request with
response code 200.
If you specify a user secret with the request, the service uses it as a key to calculate an HMAC-SHA1 signature of
the challenge string in its response to the `POST` request. It sends this signature in the `X-Callback-Signature`
header of its `GET` request to the URL during registration. It also uses the secret to calculate a signature over
the payload of every callback notification that uses the URL. The signature provides authentication and data
integrity for HTTP communications.
After you successfully register a callback URL, you can use it with an indefinite number of recognition requests.
You can register a maximum of 20 callback URLS in a one-hour span of time.
**See also:** [Registering a callback
URL](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#register).
- parameter callbackURL: An HTTP or HTTPS URL to which callback notifications are to be sent. To be allowlisted,
the URL must successfully echo the challenge string during URL verification. During verification, the client can
also check the signature that the service sends in the `X-Callback-Signature` header to verify the origin of the
request.
- parameter userSecret: A user-specified string that the service uses to generate the HMAC-SHA1 signature that it
sends via the `X-Callback-Signature` header. The service includes the header during URL verification and with
every notification sent to the callback URL. It calculates the signature over the payload of the notification. If
you omit the parameter, the service does not send the header.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func registerCallback(
callbackURL: String,
userSecret: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<RegisterStatus>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "registerCallback")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "callback_url", value: callbackURL))
if let userSecret = userSecret {
let queryParameter = URLQueryItem(name: "user_secret", value: userSecret)
queryParameters.append(queryParameter)
}
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/register_callback",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Unregister a callback.
Unregisters a callback URL that was previously allowlisted with a [Register a callback](#registercallback) request
for use with the asynchronous interface. Once unregistered, the URL can no longer be used with asynchronous
recognition requests.
**See also:** [Unregistering a callback
URL](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#unregister).
- parameter callbackURL: The callback URL that is to be unregistered.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func unregisterCallback(
callbackURL: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "unregisterCallback")
headerParameters.merge(sdkHeaders) { (_, new) in new }
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "callback_url", value: callbackURL))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/unregister_callback",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Create a job.
Creates a job for a new asynchronous recognition request. The job is owned by the instance of the service whose
credentials are used to create it. How you learn the status and results of a job depends on the parameters you
include with the job creation request:
* By callback notification: Include the `callback_url` parameter to specify a URL to which the service is to send
callback notifications when the status of the job changes. Optionally, you can also include the `events` and
`user_token` parameters to subscribe to specific events and to specify a string that is to be included with each
notification for the job.
* By polling the service: Omit the `callback_url`, `events`, and `user_token` parameters. You must then use the
[Check jobs](#checkjobs) or [Check a job](#checkjob) methods to check the status of the job, using the latter to
retrieve the results when the job is complete.
The two approaches are not mutually exclusive. You can poll the service for job status or obtain results from the
service manually even if you include a callback URL. In both cases, you can include the `results_ttl` parameter to
specify how long the results are to remain available after the job is complete. Using the HTTPS [Check a
job](#checkjob) method to retrieve results is more secure than receiving them via callback notification over HTTP
because it provides confidentiality in addition to authentication and data integrity.
The method supports the same basic parameters as other HTTP and WebSocket recognition requests. It also supports
the following parameters specific to the asynchronous interface:
* `callback_url`
* `events`
* `user_token`
* `results_ttl`
You can pass a maximum of 1 GB and a minimum of 100 bytes of audio with a request. The service automatically
detects the endianness of the incoming audio and, for audio that includes multiple channels, downmixes the audio to
one-channel mono during transcoding. The method returns only final results; to enable interim results, use the
WebSocket API. (With the `curl` command, use the `--data-binary` option to upload the file for the request.)
**See also:** [Creating a job](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#create).
### Streaming mode
For requests to transcribe live audio as it becomes available, you must set the `Transfer-Encoding` header to
`chunked` to use streaming mode. In streaming mode, the service closes the connection (status code 408) if it does
not receive at least 15 seconds of audio (including silence) in any 30-second period. The service also closes the
connection (status code 400) if it detects no speech for `inactivity_timeout` seconds of streaming audio; use the
`inactivity_timeout` parameter to change the default of 30 seconds.
**See also:**
* [Audio transmission](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#transmission)
* [Timeouts](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#timeouts)
### Audio formats (content types)
The service accepts audio in the following formats (MIME types).
* For formats that are labeled **Required**, you must use the `Content-Type` header with the request to specify the
format of the audio.
* For all other formats, you can omit the `Content-Type` header or specify `application/octet-stream` with the
header to have the service automatically detect the format of the audio. (With the `curl` command, you can specify
either `"Content-Type:"` or `"Content-Type: application/octet-stream"`.)
Where indicated, the format that you specify must include the sampling rate and can optionally include the number
of channels and the endianness of the audio.
* `audio/alaw` (**Required.** Specify the sampling rate (`rate`) of the audio.)
* `audio/basic` (**Required.** Use only with narrowband models.)
* `audio/flac`
* `audio/g729` (Use only with narrowband models.)
* `audio/l16` (**Required.** Specify the sampling rate (`rate`) and optionally the number of channels (`channels`)
and endianness (`endianness`) of the audio.)
* `audio/mp3`
* `audio/mpeg`
* `audio/mulaw` (**Required.** Specify the sampling rate (`rate`) of the audio.)
* `audio/ogg` (The service automatically detects the codec of the input audio.)
* `audio/ogg;codecs=opus`
* `audio/ogg;codecs=vorbis`
* `audio/wav` (Provide audio with a maximum of nine channels.)
* `audio/webm` (The service automatically detects the codec of the input audio.)
* `audio/webm;codecs=opus`
* `audio/webm;codecs=vorbis`
The sampling rate of the audio must match the sampling rate of the model for the recognition request: for broadband
models, at least 16 kHz; for narrowband models, at least 8 kHz. If the sampling rate of the audio is higher than
the minimum required rate, the service down-samples the audio to the appropriate rate. If the sampling rate of the
audio is lower than the minimum required rate, the request fails.
**See also:** [Supported audio
formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats).
### Next-generation models
The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 kHz) models for many languages.
Next-generation models have higher throughput than the service's previous generation of `Broadband` and
`Narrowband` models. When you use next-generation models, the service can return transcriptions more quickly and
also provide noticeably better transcription accuracy.
You specify a next-generation model by using the `model` query parameter, as you do a previous-generation model.
Many next-generation models also support the `low_latency` parameter, which is not available with
previous-generation models. Next-generation models do not support all of the parameters that are available for use
with previous-generation models.
**Important:** Effective 15 March 2022, previous-generation models for all languages other than Arabic and Japanese
are deprecated. The deprecated models remain available until 15 September 2022, when they will be removed from the
service and the documentation. You must migrate to the equivalent next-generation model by the end of service date.
For more information, see [Migrating to next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).
**See also:**
* [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng)
* [Supported features for next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-features).
- parameter audio: The audio to transcribe.
- parameter contentType: The format (MIME type) of the audio. For more information about specifying an audio
format, see **Audio formats (content types)** in the method description.
- parameter model: The identifier of the model that is to be used for the recognition request. (**Note:** The
model `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for speech
recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use).
- parameter callbackURL: A URL to which callback notifications are to be sent. The URL must already be
successfully allowlisted by using the [Register a callback](#registercallback) method. You can include the same
callback URL with any number of job creation requests. Omit the parameter to poll the service for job completion
and results.
Use the `user_token` parameter to specify a unique user-specified string with each job to differentiate the
callback notifications for the jobs.
- parameter events: If the job includes a callback URL, a comma-separated list of notification events to which to
subscribe. Valid events are
* `recognitions.started` generates a callback notification when the service begins to process the job.
* `recognitions.completed` generates a callback notification when the job is complete. You must use the [Check a
job](#checkjob) method to retrieve the results before they time out or are deleted.
* `recognitions.completed_with_results` generates a callback notification when the job is complete. The
notification includes the results of the request.
* `recognitions.failed` generates a callback notification if the service experiences an error while processing
the job.
The `recognitions.completed` and `recognitions.completed_with_results` events are incompatible. You can specify
only of the two events.
If the job includes a callback URL, omit the parameter to subscribe to the default events:
`recognitions.started`, `recognitions.completed`, and `recognitions.failed`. If the job does not include a
callback URL, omit the parameter.
- parameter userToken: If the job includes a callback URL, a user-specified string that the service is to include
with each callback notification for the job; the token allows the user to maintain an internal mapping between
jobs and notification events. If the job does not include a callback URL, omit the parameter.
- parameter resultsTtl: The number of minutes for which the results are to be available after the job has
finished. If not delivered via a callback, the results must be retrieved within this time. Omit the parameter to
use a time to live of one week. The parameter is valid with or without a callback URL.
- parameter languageCustomizationID: The customization ID (GUID) of a custom language model that is to be used
with the recognition request. The base model of the specified custom language model must match the model
specified with the `model` parameter. You must make the request with credentials for the instance of the service
that owns the custom model. By default, no custom language model is used. See [Using a custom language model for
speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse).
**Note:** Use this parameter instead of the deprecated `customization_id` parameter.
- parameter acousticCustomizationID: The customization ID (GUID) of a custom acoustic model that is to be used
with the recognition request. The base model of the specified custom acoustic model must match the model
specified with the `model` parameter. You must make the request with credentials for the instance of the service
that owns the custom model. By default, no custom acoustic model is used. See [Using a custom acoustic model for
speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acousticUse).
- parameter baseModelVersion: The version of the specified base model that is to be used with the recognition
request. Multiple versions of a base model can exist when a model is updated for internal improvements. The
parameter is intended primarily for use with custom models that have been upgraded for a new base model. The
default value depends on whether the parameter is used with or without a custom model. See [Making speech
recognition requests with upgraded custom
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade-use#custom-upgrade-use-recognition).
- parameter customizationWeight: If you specify the customization ID (GUID) of a custom language model with the
recognition request, the customization weight tells the service how much weight to give to words from the custom
language model compared to those from the base model for the current request.
Specify a value between 0.0 and 1.0. Unless a different customization weight was specified for the custom model
when it was trained, the default value is 0.3. A customization weight that you specify overrides a weight that
was specified when the custom model was trained.
The default value yields the best performance in general. Assign a higher value if your audio makes frequent use
of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy
of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases.
See [Using customization
weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight).
- parameter inactivityTimeout: The time in seconds after which, if only silence (no speech) is detected in
streaming audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission
from a live microphone when a user simply walks away. Use `-1` for infinity. See [Inactivity
timeout](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#timeouts-inactivity).
- parameter keywords: An array of keyword strings to spot in the audio. Each keyword string can include one or
more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any
keywords, you must also specify a keywords threshold. Omit the parameter or specify an empty array if you do not
need to spot keywords.
You can spot a maximum of 1000 keywords with a single request. A single keyword can have a maximum length of 1024
characters, though the maximum effective length for double-byte languages might be shorter. Keywords are
case-insensitive.
See [Keyword spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#keyword-spotting).
- parameter keywordsThreshold: A confidence value that is the lower bound for spotting a keyword. A word is
considered to match a keyword if its confidence is greater than or equal to the threshold. Specify a probability
between 0.0 and 1.0. If you specify a threshold, you must also specify one or more keywords. The service performs
no keyword spotting if you omit either parameter. See [Keyword
spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#keyword-spotting).
- parameter maxAlternatives: The maximum number of alternative transcripts that the service is to return. By
default, the service returns a single transcript. If you specify a value of `0`, the service uses the default
value, `1`. See [Maximum
alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#max-alternatives).
- parameter wordAlternativesThreshold: A confidence value that is the lower bound for identifying a hypothesis as
a possible word alternative (also known as "Confusion Networks"). An alternative word is considered if its
confidence is greater than or equal to the threshold. Specify a probability between 0.0 and 1.0. By default, the
service computes no alternative words. See [Word
alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#word-alternatives).
- parameter wordConfidence: If `true`, the service returns a confidence measure in the range of 0.0 to 1.0 for
each word. By default, the service returns no word confidence scores. See [Word
confidence](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#word-confidence).
- parameter timestamps: If `true`, the service returns time alignment for each word. By default, no timestamps
are returned. See [Word
timestamps](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#word-timestamps).
- parameter profanityFilter: If `true`, the service filters profanity from all output except for keyword results
by replacing inappropriate words with a series of asterisks. Set the parameter to `false` to return results with
no censoring.
**Note:** The parameter can be used with US English and Japanese transcription only. See [Profanity
filtering](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#profanity-filtering).
- parameter smartFormatting: If `true`, the service converts dates, times, series of digits and numbers, phone
numbers, currency values, and internet addresses into more readable, conventional representations in the final
transcript of a recognition request. For US English, the service also converts certain keyword strings to
punctuation symbols. By default, the service performs no smart formatting.
**Note:** The parameter can be used with US English, Japanese, and Spanish (all dialects) transcription only.
See [Smart
formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting).
- parameter speakerLabels: If `true`, the response includes labels that identify which words were spoken by which
participants in a multi-person exchange. By default, the service returns no speaker labels. Setting
`speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify
`false` for the parameter.
* _For previous-generation models,_ the parameter can be used with Australian English, US English, German,
Japanese, Korean, and Spanish (both broadband and narrowband models) and UK English (narrowband model)
transcription only.
* _For next-generation models,_ the parameter can be used with Czech, English (Australian, Indian, UK, and US),
German, Japanese, Korean, and Spanish transcription only.
See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels).
- parameter customizationID: **Deprecated.** Use the `language_customization_id` parameter to specify the
customization ID (GUID) of a custom language model that is to be used with the recognition request. Do not
specify both parameters with a request.
- parameter grammarName: The name of a grammar that is to be used with the recognition request. If you specify a
grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language
model for which the grammar is defined. The service recognizes only strings that are recognized by the specified
grammar; it does not recognize other custom words from the model's words resource.
See [Using a grammar for speech
recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUse).
- parameter redaction: If `true`, the service redacts, or masks, numeric data from final transcripts. The feature
redacts any number that has three or more consecutive digits by replacing each digit with an `X` character. It is
intended to redact sensitive numeric data, such as credit card numbers. By default, the service performs no
redaction.
When you enable redaction, the service automatically enables smart formatting, regardless of whether you
explicitly disable that feature. To ensure maximum security, the service also disables keyword spotting (ignores
the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the
`max_alternatives` parameter to be `1`).
**Note:** The parameter can be used with US English, Japanese, and Korean transcription only.
See [Numeric
redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#numeric-redaction).
- parameter processingMetrics: If `true`, requests processing metrics about the service's transcription of the
input audio. The service returns processing metrics at the interval specified by the
`processing_metrics_interval` parameter. It also returns processing metrics for transcription events, for
example, for final and interim results. By default, the service returns no processing metrics.
See [Processing
metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#processing-metrics).
- parameter processingMetricsInterval: Specifies the interval in real wall-clock seconds at which the service is
to return processing metrics. The parameter is ignored unless the `processing_metrics` parameter is set to
`true`.
The parameter accepts a minimum value of 0.1 seconds. The level of precision is not restricted, so you can
specify values such as 0.25 and 0.125.
The service does not impose a maximum value. If you want to receive processing metrics only for transcription
events instead of at periodic intervals, set the value to a large number. If the value is larger than the
duration of the audio, the service returns processing metrics only for transcription events.
See [Processing
metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#processing-metrics).
- parameter audioMetrics: If `true`, requests detailed information about the signal characteristics of the input
audio. The service returns audio metrics with the final transcription results. By default, the service returns no
audio metrics.
See [Audio metrics](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metrics#audio-metrics).
- parameter endOfPhraseSilenceTime: If `true`, specifies the duration of the pause interval at which the service
splits a transcript into multiple final results. If the service detects pauses or extended silence before it
reaches the end of the audio stream, its response can include multiple final results. Silence indicates a point
at which the speaker pauses between spoken words or phrases.
Specify a value for the pause interval in the range of 0.0 to 120.0.
* A value greater than 0 specifies the interval that the service is to use for speech recognition.
* A value of 0 indicates that the service is to use the default interval. It is equivalent to omitting the
parameter.
The default pause interval for most languages is 0.8 seconds; the default for Chinese is 0.6 seconds.
See [End of phrase silence
time](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#silence-time).
- parameter splitTranscriptAtPhraseEnd: If `true`, directs the service to split the transcript into multiple
final results based on semantic features of the input, for example, at the conclusion of meaningful phrases such
as sentences. The service bases its understanding of semantic features on the base language model that you use
with a request. Custom language models and grammars can also influence how and where the service splits a
transcript.
By default, the service splits transcripts based solely on the pause interval. If the parameters are used
together on the same request, `end_of_phrase_silence_time` has precedence over `split_transcript_at_phrase_end`.
See [Split transcript at phrase
end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#split-transcript).
- parameter speechDetectorSensitivity: The sensitivity of speech activity detection that the service is to
perform. Use the parameter to suppress word insertions from music, coughing, and other non-speech events. The
service biases the audio it passes for speech recognition by evaluating the input audio against prior models of
speech and non-speech activity.
Specify a value between 0.0 and 1.0:
* 0.0 suppresses all audio (no speech is transcribed).
* 0.5 (the default) provides a reasonable compromise for the level of sensitivity.
* 1.0 suppresses no audio (speech detection sensitivity is disabled).
The values increase on a monotonic curve.
The parameter is supported with all next-generation models and with most previous-generation models. See [Speech
detector
sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity)
and [Language model
support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support).
- parameter backgroundAudioSuppression: The level to which the service is to suppress background audio based on
its volume to prevent it from being transcribed as speech. Use the parameter to suppress side conversations or
background noise.
Specify a value in the range of 0.0 to 1.0:
* 0.0 (the default) provides no suppression (background audio suppression is disabled).
* 0.5 provides a reasonable level of audio suppression for general usage.
* 1.0 suppresses all audio (no audio is transcribed).
The values increase on a monotonic curve.
The parameter is supported with all next-generation models and with most previous-generation models. See
[Background audio
suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression)
and [Language model
support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support).
- parameter lowLatency: If `true` for next-generation `Multimedia` and `Telephony` models that support low
latency, directs the service to produce results even more quickly than it usually does. Next-generation models
produce transcription results faster than previous-generation models. The `low_latency` parameter causes the
models to produce results even more quickly, though the results might be less accurate when the parameter is
used.
The parameter is not available for previous-generation `Broadband` and `Narrowband` models. It is available only
for some next-generation models. For a list of next-generation models that support low latency, see [Supported
next-generation language
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported).
* For more information about the `low_latency` parameter, see [Low
latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func createJob(
audio: Data,
contentType: String? = nil,
model: String? = nil,
callbackURL: String? = nil,
events: String? = nil,
userToken: String? = nil,
resultsTtl: Int? = nil,
languageCustomizationID: String? = nil,
acousticCustomizationID: String? = nil,
baseModelVersion: String? = nil,
customizationWeight: Double? = nil,
inactivityTimeout: Int? = nil,
keywords: [String]? = nil,
keywordsThreshold: Double? = nil,
maxAlternatives: Int? = nil,
wordAlternativesThreshold: Double? = nil,
wordConfidence: Bool? = nil,
timestamps: Bool? = nil,
profanityFilter: Bool? = nil,
smartFormatting: Bool? = nil,
speakerLabels: Bool? = nil,
customizationID: String? = nil,
grammarName: String? = nil,
redaction: Bool? = nil,
processingMetrics: Bool? = nil,
processingMetricsInterval: Double? = nil,
audioMetrics: Bool? = nil,
endOfPhraseSilenceTime: Double? = nil,
splitTranscriptAtPhraseEnd: Bool? = nil,
speechDetectorSensitivity: Double? = nil,
backgroundAudioSuppression: Double? = nil,
lowLatency: Bool? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<RecognitionJob>?, WatsonError?) -> Void)
{
let body = audio
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createJob")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let contentType = contentType {
headerParameters["Content-Type"] = contentType
}
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let model = model {
let queryParameter = URLQueryItem(name: "model", value: model)
queryParameters.append(queryParameter)
}
if let callbackURL = callbackURL {
let queryParameter = URLQueryItem(name: "callback_url", value: callbackURL)
queryParameters.append(queryParameter)
}
if let events = events {
let queryParameter = URLQueryItem(name: "events", value: events)
queryParameters.append(queryParameter)
}
if let userToken = userToken {
let queryParameter = URLQueryItem(name: "user_token", value: userToken)
queryParameters.append(queryParameter)
}
if let resultsTtl = resultsTtl {
let queryParameter = URLQueryItem(name: "results_ttl", value: "\(resultsTtl)")
queryParameters.append(queryParameter)
}
if let languageCustomizationID = languageCustomizationID {
let queryParameter = URLQueryItem(name: "language_customization_id", value: languageCustomizationID)
queryParameters.append(queryParameter)
}
if let acousticCustomizationID = acousticCustomizationID {
let queryParameter = URLQueryItem(name: "acoustic_customization_id", value: acousticCustomizationID)
queryParameters.append(queryParameter)
}
if let baseModelVersion = baseModelVersion {
let queryParameter = URLQueryItem(name: "base_model_version", value: baseModelVersion)
queryParameters.append(queryParameter)
}
if let customizationWeight = customizationWeight {
let queryParameter = URLQueryItem(name: "customization_weight", value: "\(customizationWeight)")
queryParameters.append(queryParameter)
}
if let inactivityTimeout = inactivityTimeout {
let queryParameter = URLQueryItem(name: "inactivity_timeout", value: "\(inactivityTimeout)")
queryParameters.append(queryParameter)
}
if let keywords = keywords {
let queryParameter = URLQueryItem(name: "keywords", value: keywords.joined(separator: ","))
queryParameters.append(queryParameter)
}
if let keywordsThreshold = keywordsThreshold {
let queryParameter = URLQueryItem(name: "keywords_threshold", value: "\(keywordsThreshold)")
queryParameters.append(queryParameter)
}
if let maxAlternatives = maxAlternatives {
let queryParameter = URLQueryItem(name: "max_alternatives", value: "\(maxAlternatives)")
queryParameters.append(queryParameter)
}
if let wordAlternativesThreshold = wordAlternativesThreshold {
let queryParameter = URLQueryItem(name: "word_alternatives_threshold", value: "\(wordAlternativesThreshold)")
queryParameters.append(queryParameter)
}
if let wordConfidence = wordConfidence {
let queryParameter = URLQueryItem(name: "word_confidence", value: "\(wordConfidence)")
queryParameters.append(queryParameter)
}
if let timestamps = timestamps {
let queryParameter = URLQueryItem(name: "timestamps", value: "\(timestamps)")
queryParameters.append(queryParameter)
}
if let profanityFilter = profanityFilter {
let queryParameter = URLQueryItem(name: "profanity_filter", value: "\(profanityFilter)")
queryParameters.append(queryParameter)
}
if let smartFormatting = smartFormatting {
let queryParameter = URLQueryItem(name: "smart_formatting", value: "\(smartFormatting)")
queryParameters.append(queryParameter)
}
if let speakerLabels = speakerLabels {
let queryParameter = URLQueryItem(name: "speaker_labels", value: "\(speakerLabels)")
queryParameters.append(queryParameter)
}
if let customizationID = customizationID {
let queryParameter = URLQueryItem(name: "customization_id", value: customizationID)
queryParameters.append(queryParameter)
}
if let grammarName = grammarName {
let queryParameter = URLQueryItem(name: "grammar_name", value: grammarName)
queryParameters.append(queryParameter)
}
if let redaction = redaction {
let queryParameter = URLQueryItem(name: "redaction", value: "\(redaction)")
queryParameters.append(queryParameter)
}
if let processingMetrics = processingMetrics {
let queryParameter = URLQueryItem(name: "processing_metrics", value: "\(processingMetrics)")
queryParameters.append(queryParameter)
}
if let processingMetricsInterval = processingMetricsInterval {
let queryParameter = URLQueryItem(name: "processing_metrics_interval", value: "\(processingMetricsInterval)")
queryParameters.append(queryParameter)
}
if let audioMetrics = audioMetrics {
let queryParameter = URLQueryItem(name: "audio_metrics", value: "\(audioMetrics)")
queryParameters.append(queryParameter)
}
if let endOfPhraseSilenceTime = endOfPhraseSilenceTime {
let queryParameter = URLQueryItem(name: "end_of_phrase_silence_time", value: "\(endOfPhraseSilenceTime)")
queryParameters.append(queryParameter)
}
if let splitTranscriptAtPhraseEnd = splitTranscriptAtPhraseEnd {
let queryParameter = URLQueryItem(name: "split_transcript_at_phrase_end", value: "\(splitTranscriptAtPhraseEnd)")
queryParameters.append(queryParameter)
}
if let speechDetectorSensitivity = speechDetectorSensitivity {
let queryParameter = URLQueryItem(name: "speech_detector_sensitivity", value: "\(speechDetectorSensitivity)")
queryParameters.append(queryParameter)
}
if let backgroundAudioSuppression = backgroundAudioSuppression {
let queryParameter = URLQueryItem(name: "background_audio_suppression", value: "\(backgroundAudioSuppression)")
queryParameters.append(queryParameter)
}
if let lowLatency = lowLatency {
let queryParameter = URLQueryItem(name: "low_latency", value: "\(lowLatency)")
queryParameters.append(queryParameter)
}
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/recognitions",
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Check jobs.
Returns the ID and status of the latest 100 outstanding jobs associated with the credentials with which it is
called. The method also returns the creation and update times of each job, and, if a job was created with a
callback URL and a user token, the user token for the job. To obtain the results for a job whose status is
`completed` or not one of the latest 100 outstanding jobs, use the [Check a job[(#checkjob) method. A job and its
results remain available until you delete them with the [Delete a job](#deletejob) method or until the job's time
to live expires, whichever comes first.
**See also:** [Checking the status of the latest
jobs](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#jobs).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func checkJobs(
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<RecognitionJobs>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "checkJobs")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + "/v1/recognitions",
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Check a job.
Returns information about the specified job. The response always includes the status of the job and its creation
and update times. If the status is `completed`, the response includes the results of the recognition request. You
must use credentials for the instance of the service that owns a job to list information about it.
You can use the method to retrieve the results of any job, regardless of whether it was submitted with a callback
URL and the `recognitions.completed_with_results` event, and you can retrieve the results multiple times for as
long as they remain available. Use the [Check jobs](#checkjobs) method to request information about the most recent
jobs associated with the calling credentials.
**See also:** [Checking the status and retrieving the results of a
job](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#job).
- parameter id: The identifier of the asynchronous job that is to be used for the request. You must make the
request with credentials for the instance of the service that owns the job.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func checkJob(
id: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<RecognitionJob>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "checkJob")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/recognitions/\(id)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete a job.
Deletes the specified job. You cannot delete a job that the service is actively processing. Once you delete a job,
its results are no longer available. The service automatically deletes a job and its results when the time to live
for the results expires. You must use credentials for the instance of the service that owns a job to delete it.
**See also:** [Deleting a job](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-async#delete-async).
- parameter id: The identifier of the asynchronous job that is to be used for the request. You must make the
request with credentials for the instance of the service that owns the job.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteJob(
id: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteJob")
headerParameters.merge(sdkHeaders) { (_, new) in new }
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/recognitions/\(id)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Create a custom language model.
Creates a new custom language model for a specified base model. The custom language model can be used only with the
base model for which it is created. The model is owned by the instance of the service whose credentials are used to
create it.
You can create a maximum of 1024 custom language models per owning credentials. The service returns an error if you
attempt to create more than 1024 models. You do not lose any models, but you cannot create any more until your
model count is below the limit.
**Important:** Effective 15 March 2022, previous-generation models for all languages other than Arabic and Japanese
are deprecated. The deprecated models remain available until 15 September 2022, when they will be removed from the
service and the documentation. You must migrate to the equivalent next-generation model by the end of service date.
For more information, see [Migrating to next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).
**See also:**
* [Create a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#createModel-language)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter name: A user-defined name for the new custom language model. Use a name that is unique among all
custom language models that you own. Use a localized name that matches the language of the custom model. Use a
name that describes the domain of the custom model, such as `Medical custom model` or `Legal custom model`.
- parameter baseModelName: The name of the base language model that is to be customized by the new custom
language model. The new custom model can be used only with the base model that it customizes.
To determine whether a base model supports language model customization, use the [Get a model](#getmodel) method
and check that the attribute `custom_language_model` is set to `true`. You can also refer to [Language support
for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter dialect: The dialect of the specified language that is to be used with the custom language model.
_For all languages, it is always safe to omit this field._ The service automatically uses the language identifier
from the name of the base model. For example, the service automatically uses `en-US` for all US English models.
If you specify the `dialect` for a new custom model, follow these guidelines. _For non-Spanish
previous-generation models and for next-generation models,_ you must specify a value that matches the
five-character language identifier from the name of the base model. _For Spanish previous-generation models,_ you
must specify one of the following values:
* `es-ES` for Castilian Spanish (`es-ES` models)
* `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and `es-PE` models)
* `es-US` for Mexican (North American) Spanish (`es-MX` models)
All values that you pass for the `dialect` field are case-insensitive.
- parameter description: A description of the new custom language model. Use a localized description that matches
the language of the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func createLanguageModel(
name: String,
baseModelName: String,
dialect: String? = nil,
description: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<LanguageModel>?, WatsonError?) -> Void)
{
// construct body
let createLanguageModelRequest = CreateLanguageModelRequest(
name: name,
base_model_name: baseModelName,
dialect: dialect,
description: description)
guard let body = try? JSON.encoder.encode(createLanguageModelRequest) else {
completionHandler(nil, RestError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createLanguageModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/customizations",
headerParameters: headerParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
// Private struct for the createLanguageModel request body
private struct CreateLanguageModelRequest: Encodable {
// swiftlint:disable identifier_name
let name: String
let base_model_name: String
let dialect: String?
let description: String?
// swiftlint:enable identifier_name
}
/**
List custom language models.
Lists information about all custom language models that are owned by an instance of the service. Use the `language`
parameter to see all custom language models for the specified language. Omit the parameter to see all custom
language models for all languages. You must use credentials for the instance of the service that owns a model to
list information about it.
**See also:**
* [Listing custom language
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter language: The identifier of the language for which custom language or custom acoustic models are to
be returned. Specify the five-character language identifier; for example, specify `en-US` to see all custom
language or custom acoustic models that are based on US English models. Omit the parameter to see all custom
language or custom acoustic models that are owned by the requesting credentials. (**Note:** The identifier
`ar-AR` is deprecated; use `ar-MS` instead.)
To determine the languages for which customization is available, see [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listLanguageModels(
language: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<LanguageModels>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listLanguageModels")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let language = language {
let queryParameter = URLQueryItem(name: "language", value: language)
queryParameters.append(queryParameter)
}
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + "/v1/customizations",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Get a custom language model.
Gets information about a specified custom language model. You must use credentials for the instance of the service
that owns a model to list information about it.
**See also:**
* [Listing custom language
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getLanguageModel(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<LanguageModel>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getLanguageModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete a custom language model.
Deletes an existing custom language model. The custom model cannot be deleted if another request, such as adding a
corpus or grammar to the model, is currently being processed. You must use credentials for the instance of the
service that owns a model to delete it.
**See also:**
* [Deleting a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#deleteModel-language)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteLanguageModel(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteLanguageModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Train a custom language model.
Initiates the training of a custom language model with new resources such as corpora, grammars, and custom words.
After adding, modifying, or deleting resources for a custom language model, use this method to begin the actual
training of the model on the latest data. You can specify whether the custom language model is to be trained with
all words from its words resource or only with words that were added or modified by the user directly. You must use
credentials for the instance of the service that owns a model to train it.
The training method is asynchronous. It can take on the order of minutes to complete depending on the amount of
data on which the service is being trained and the current load on the service. The method returns an HTTP 200
response code to indicate that the training process has begun.
You can monitor the status of the training by using the [Get a custom language model](#getlanguagemodel) method to
poll the model's status. Use a loop to check the status every 10 seconds. The method returns a `LanguageModel`
object that includes `status` and `progress` fields. A status of `available` means that the custom model is trained
and ready to use. The service cannot accept subsequent training requests or requests to add new resources until the
existing request completes.
**See also:**
* [Train the custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support)
### Training failures
Training can fail to start for the following reasons:
* The service is currently handling another request for the custom model, such as another training request or a
request to add a corpus or grammar to the model.
* No training data have been added to the custom model.
* The custom model contains one or more invalid corpora, grammars, or words (for example, a custom word has an
invalid sounds-like pronunciation). You can correct the invalid resources or set the `strict` parameter to `false`
to exclude the invalid resources from the training. The model must contain at least one valid resource for training
to succeed.
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter wordTypeToAdd: _For custom models that are based on previous-generation models_, the type of words
from the custom language model's words resource on which to train the model:
* `all` (the default) trains the model on all new words, regardless of whether they were extracted from corpora
or grammars or were added or modified by the user.
* `user` trains the model only on custom words that were added or modified by the user directly. The model is not
trained on new words extracted from corpora or grammars.
_For custom models that are based on next-generation models_, the service ignores the parameter. The words
resource contains only custom words that the user adds or modifies directly, so the parameter is unnecessary.
- parameter customizationWeight: Specifies a customization weight for the custom language model. The
customization weight tells the service how much weight to give to words from the custom language model compared
to those from the base model for speech recognition. Specify a value between 0.0 and 1.0; the default is 0.3.
The default value yields the best performance in general. Assign a higher value if your audio makes frequent use
of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy
of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases.
The value that you assign is used for all recognition requests that use the model. You can override it for any
recognition request by specifying a customization weight for that request.
See [Using customization
weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func trainLanguageModel(
customizationID: String,
wordTypeToAdd: String? = nil,
customizationWeight: Double? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<TrainingResponse>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "trainLanguageModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let wordTypeToAdd = wordTypeToAdd {
let queryParameter = URLQueryItem(name: "word_type_to_add", value: wordTypeToAdd)
queryParameters.append(queryParameter)
}
if let customizationWeight = customizationWeight {
let queryParameter = URLQueryItem(name: "customization_weight", value: "\(customizationWeight)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/train"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Reset a custom language model.
Resets a custom language model by removing all corpora, grammars, and words from the model. Resetting a custom
language model initializes the model to its state when it was first created. Metadata such as the name and language
of the model are preserved, but the model's words resource is removed and must be re-created. You must use
credentials for the instance of the service that owns a model to reset it.
**See also:**
* [Resetting a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#resetModel-language)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func resetLanguageModel(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "resetLanguageModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/reset"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Upgrade a custom language model.
Initiates the upgrade of a custom language model to the latest version of its base language model. The upgrade
method is asynchronous. It can take on the order of minutes to complete depending on the amount of data in the
custom model and the current load on the service. A custom model must be in the `ready` or `available` state to be
upgraded. You must use credentials for the instance of the service that owns a model to upgrade it.
The method returns an HTTP 200 response code to indicate that the upgrade process has begun successfully. You can
monitor the status of the upgrade by using the [Get a custom language model](#getlanguagemodel) method to poll the
model's status. The method returns a `LanguageModel` object that includes `status` and `progress` fields. Use a
loop to check the status every 10 seconds.
While it is being upgraded, the custom model has the status `upgrading`. When the upgrade is complete, the model
resumes the status that it had prior to upgrade. The service cannot accept subsequent requests for the model until
the upgrade completes.
**See also:**
* [Upgrading a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func upgradeLanguageModel(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "upgradeLanguageModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/upgrade_model"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
List corpora.
Lists information about all corpora from a custom language model. The information includes the name, status, and
total number of words for each corpus. _For custom models that are based on previous-generation models_, it also
includes the number of out-of-vocabulary (OOV) words from the corpus. You must use credentials for the instance of
the service that owns a model to list its corpora.
**See also:** [Listing corpora for a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageCorpora#listCorpora).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listCorpora(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Corpora>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCorpora")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/corpora"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Add a corpus.
Adds a single corpus text file of new training data to a custom language model. Use multiple requests to submit
multiple corpus text files. You must use credentials for the instance of the service that owns a model to add a
corpus to it. Adding a corpus does not affect the custom language model until you train the model for the new data
by using the [Train a custom language model](#trainlanguagemodel) method.
Submit a plain text file that contains sample sentences from the domain of interest to enable the service to parse
the words in context. The more sentences you add that represent the context in which speakers use words from the
domain, the better the service's recognition accuracy.
The call returns an HTTP 201 response code if the corpus is valid. The service then asynchronously processes and
automatically extracts data from the contents of the corpus. This operation can take on the order of minutes to
complete depending on the current load on the service, the total number of words in the corpus, and, _for custom
models that are based on previous-generation models_, the number of new (out-of-vocabulary) words in the corpus.
You cannot submit requests to add additional resources to the custom model or to train the model until the
service's analysis of the corpus for the current request completes. Use the [Get a corpus](#getcorpus) method to
check the status of the analysis.
_For custom models that are based on previous-generation models_, the service auto-populates the model's words
resource with words from the corpus that are not found in its base vocabulary. These words are referred to as
out-of-vocabulary (OOV) words. After adding a corpus, you must validate the words resource to ensure that each OOV
word's definition is complete and valid. You can use the [List custom words](#listwords) method to examine the
words resource. You can use other words method to eliminate typos and modify how words are pronounced as needed.
To add a corpus file that has the same name as an existing corpus, set the `allow_overwrite` parameter to `true`;
otherwise, the request fails. Overwriting an existing corpus causes the service to process the corpus text file and
extract its data anew. _For a custom model that is based on a previous-generation model_, the service first removes
any OOV words that are associated with the existing corpus from the model's words resource unless they were also
added by another corpus or grammar, or they have been modified in some way with the [Add custom words](#addwords)
or [Add a custom word](#addword) method.
The service limits the overall amount of data that you can add to a custom model to a maximum of 10 million total
words from all sources combined. _For a custom model that is based on a previous-generation model_, you can add no
more than 90 thousand custom (OOV) words to a model. This includes words that the service extracts from corpora and
grammars, and words that you add directly.
**See also:**
* [Add a corpus to the custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addCorpus)
* [Working with corpora for previous-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingCorpora)
* [Working with corpora for next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingCorpora-ng)
* [Validating a words resource for previous-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel)
* [Validating a words resource for next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter corpusName: The name of the new corpus for the custom language model. Use a localized name that
matches the language of the custom model and reflects the contents of the corpus.
* Include a maximum of 128 characters in the name.
* Do not use characters that need to be URL-encoded. For example, do not use spaces, slashes, backslashes,
colons, ampersands, double quotes, plus signs, equals signs, questions marks, and so on in the name. (The service
does not prevent the use of these characters. But because they must be URL-encoded wherever used, their use is
strongly discouraged.)
* Do not use the name of an existing corpus or grammar that is already defined for the custom model.
* Do not use the name `user`, which is reserved by the service to denote custom words that are added or modified
by the user.
* Do not use the name `base_lm` or `default_lm`. Both names are reserved for future use by the service.
- parameter corpusFile: A plain text file that contains the training data for the corpus. Encode the file in
UTF-8 if it contains non-ASCII characters; the service assumes UTF-8 encoding if it encounters non-ASCII
characters.
Make sure that you know the character encoding of the file. You must use that same encoding when working with the
words in the custom language model. For more information, see [Character encoding for custom
words](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#charEncoding).
With the `curl` command, use the `--data-binary` option to upload the file for the request.
- parameter allowOverwrite: If `true`, the specified corpus overwrites an existing corpus with the same name. If
`false`, the request fails if a corpus with the same name already exists. The parameter has no effect if a corpus
with the same name does not already exist.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func addCorpus(
customizationID: String,
corpusName: String,
corpusFile: Data,
allowOverwrite: Bool? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct body
let multipartFormData = MultipartFormData()
multipartFormData.append(corpusFile, withName: "corpus_file", mimeType: "text/plain", fileName: "filename")
guard let body = try? multipartFormData.toData() else {
completionHandler(nil, RestError.serialization(values: "request multipart form data"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addCorpus")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = multipartFormData.contentType
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let allowOverwrite = allowOverwrite {
let queryParameter = URLQueryItem(name: "allow_overwrite", value: "\(allowOverwrite)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/corpora/\(corpusName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Get a corpus.
Gets information about a corpus from a custom language model. The information includes the name, status, and total
number of words for the corpus. _For custom models that are based on previous-generation models_, it also includes
the number of out-of-vocabulary (OOV) words from the corpus. You must use credentials for the instance of the
service that owns a model to list its corpora.
**See also:** [Listing corpora for a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageCorpora#listCorpora).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter corpusName: The name of the corpus for the custom language model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getCorpus(
customizationID: String,
corpusName: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Corpus>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCorpus")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/corpora/\(corpusName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete a corpus.
Deletes an existing corpus from a custom language model. Removing a corpus does not affect the custom model until
you train the model with the [Train a custom language model](#trainlanguagemodel) method. You must use credentials
for the instance of the service that owns a model to delete its corpora.
_For custom models that are based on previous-generation models_, the service removes any out-of-vocabulary (OOV)
words that are associated with the corpus from the custom model's words resource unless they were also added by
another corpus or grammar, or they were modified in some way with the [Add custom words](#addwords) or [Add a
custom word](#addword) method.
**See also:** [Deleting a corpus from a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageCorpora#deleteCorpus).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter corpusName: The name of the corpus for the custom language model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteCorpus(
customizationID: String,
corpusName: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCorpus")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/corpora/\(corpusName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
List custom words.
Lists information about custom words from a custom language model. You can list all words from the custom model's
words resource, only custom words that were added or modified by the user, or, _for a custom model that is based on
a previous-generation model_, only out-of-vocabulary (OOV) words that were extracted from corpora or are recognized
by grammars. You can also indicate the order in which the service is to return words; by default, the service lists
words in ascending alphabetical order. You must use credentials for the instance of the service that owns a model
to list information about its words.
**See also:** [Listing words from a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#listWords).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter wordType: The type of words to be listed from the custom language model's words resource:
* `all` (the default) shows all words.
* `user` shows only custom words that were added or modified by the user directly.
* `corpora` shows only OOV that were extracted from corpora.
* `grammars` shows only OOV words that are recognized by grammars.
_For a custom model that is based on a next-generation model_, only `all` and `user` apply. Both options return
the same results. Words from other sources are not added to custom models that are based on next-generation
models.
- parameter sort: Indicates the order in which the words are to be listed, `alphabetical` or by `count`. You can
prepend an optional `+` or `-` to an argument to indicate whether the results are to be sorted in ascending or
descending order. By default, words are sorted in ascending alphabetical order. For alphabetical ordering, the
lexicographical precedence is numeric values, uppercase letters, and lowercase letters. For count ordering,
values with the same count are ordered alphabetically. With the `curl` command, URL-encode the `+` symbol as
`%2B`.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listWords(
customizationID: String,
wordType: String? = nil,
sort: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Words>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listWords")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let wordType = wordType {
let queryParameter = URLQueryItem(name: "word_type", value: wordType)
queryParameters.append(queryParameter)
}
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/words"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Add custom words.
Adds one or more custom words to a custom language model. You can use this method to add words or to modify
existing words in a custom model's words resource. _For custom models that are based on previous-generation
models_, the service populates the words resource for a custom model with out-of-vocabulary (OOV) words from each
corpus or grammar that is added to the model. You can use this method to modify OOV words in the model's words
resource.
_For a custom model that is based on a previous-generation model_, the words resource for a model can contain a
maximum of 90 thousand custom (OOV) words. This includes words that the service extracts from corpora and grammars
and words that you add directly.
You must use credentials for the instance of the service that owns a model to add or modify custom words for the
model. Adding or modifying custom words does not affect the custom model until you train the model for the new data
by using the [Train a custom language model](#trainlanguagemodel) method.
You add custom words by providing a `CustomWords` object, which is an array of `CustomWord` objects, one per word.
Use the object's `word` parameter to identify the word that is to be added. You can also provide one or both of the
optional `display_as` or `sounds_like` fields for each word.
* The `display_as` field provides a different way of spelling the word in a transcript. Use the parameter when you
want the word to appear different from its usual representation or from its spelling in training data. For example,
you might indicate that the word `IBM` is to be displayed as `IBM™`.
* The `sounds_like` field, _which can be used only with a custom model that is based on a previous-generation
model_, provides an array of one or more pronunciations for the word. Use the parameter to specify how the word can
be pronounced by users. Use the parameter for words that are difficult to pronounce, foreign words, acronyms, and
so on. For example, you might specify that the word `IEEE` can sound like `i triple e`. You can specify a maximum
of five sounds-like pronunciations for a word. If you omit the `sounds_like` field, the service attempts to set the
field to its pronunciation of the word. It cannot generate a pronunciation for all words, so you must review the
word's definition to ensure that it is complete and valid.
If you add a custom word that already exists in the words resource for the custom model, the new definition
overwrites the existing data for the word. If the service encounters an error with the input data, it returns a
failure code and does not add any of the words to the words resource.
The call returns an HTTP 201 response code if the input data is valid. It then asynchronously processes the words
to add them to the model's words resource. The time that it takes for the analysis to complete depends on the
number of new words that you add but is generally faster than adding a corpus or grammar.
You can monitor the status of the request by using the [Get a custom language model](#getlanguagemodel) method to
poll the model's status. Use a loop to check the status every 10 seconds. The method returns a `Customization`
object that includes a `status` field. A status of `ready` means that the words have been added to the custom
model. The service cannot accept requests to add new data or to train the model until the existing request
completes.
You can use the [List custom words](#listwords) or [Get a custom word](#getword) method to review the words that
you add. Words with an invalid `sounds_like` field include an `error` field that describes the problem. You can use
other words-related methods to correct errors, eliminate typos, and modify how words are pronounced as needed.
**See also:**
* [Add words to the custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords)
* [Working with custom words for previous-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords)
* [Working with custom words for next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingWords-ng)
* [Validating a words resource for previous-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel)
* [Validating a words resource for next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter words: An array of `CustomWord` objects that provides information about each custom word that is to
be added to or updated in the custom language model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func addWords(
customizationID: String,
words: [CustomWord],
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct body
let addWordsRequest = AddWordsRequest(
words: words)
guard let body = try? JSON.encoder.encode(addWordsRequest) else {
completionHandler(nil, RestError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWords")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/words"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
messageBody: body
)
// execute REST request
request.response(completionHandler: completionHandler)
}
// Private struct for the addWords request body
private struct AddWordsRequest: Encodable {
// swiftlint:disable identifier_name
let words: [CustomWord]
// swiftlint:enable identifier_name
}
/**
Add a custom word.
Adds a custom word to a custom language model. You can use this method to add a word or to modify an existing word
in the words resource. _For custom models that are based on previous-generation models_, the service populates the
words resource for a custom model with out-of-vocabulary (OOV) words from each corpus or grammar that is added to
the model. You can use this method to modify OOV words in the model's words resource.
_For a custom model that is based on a previous-generation models_, the words resource for a model can contain a
maximum of 90 thousand custom (OOV) words. This includes words that the service extracts from corpora and grammars
and words that you add directly.
You must use credentials for the instance of the service that owns a model to add or modify a custom word for the
model. Adding or modifying a custom word does not affect the custom model until you train the model for the new
data by using the [Train a custom language model](#trainlanguagemodel) method.
Use the `word_name` parameter to specify the custom word that is to be added or modified. Use the `CustomWord`
object to provide one or both of the optional `display_as` or `sounds_like` fields for the word.
* The `display_as` field provides a different way of spelling the word in a transcript. Use the parameter when you
want the word to appear different from its usual representation or from its spelling in training data. For example,
you might indicate that the word `IBM` is to be displayed as `IBM™`.
* The `sounds_like` field, _which can be used only with a custom model that is based on a previous-generation
model_, provides an array of one or more pronunciations for the word. Use the parameter to specify how the word can
be pronounced by users. Use the parameter for words that are difficult to pronounce, foreign words, acronyms, and
so on. For example, you might specify that the word `IEEE` can sound like `i triple e`. You can specify a maximum
of five sounds-like pronunciations for a word. If you omit the `sounds_like` field, the service attempts to set the
field to its pronunciation of the word. It cannot generate a pronunciation for all words, so you must review the
word's definition to ensure that it is complete and valid.
If you add a custom word that already exists in the words resource for the custom model, the new definition
overwrites the existing data for the word. If the service encounters an error, it does not add the word to the
words resource. Use the [Get a custom word](#getword) method to review the word that you add.
**See also:**
* [Add words to the custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords)
* [Working with custom words for previous-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords)
* [Working with custom words for next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingWords-ng)
* [Validating a words resource for previous-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel)
* [Validating a words resource for next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter wordName: The custom word that is to be added to or updated in the custom language model. Do not
include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words.
URL-encode the word if it includes non-ASCII characters. For more information, see [Character
encoding](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#charEncoding).
- parameter word: For the [Add custom words](#addwords) method, you must specify the custom word that is to be
added to or updated in the custom model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore)
to connect the tokens of compound words.
Omit this parameter for the [Add a custom word](#addword) method.
- parameter soundsLike: _For a custom model that is based on a previous-generation model_, an array of
sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words,
acronyms, and so on can be pronounced by users.
* For a word that is not in the service's base vocabulary, omit the parameter to have the service automatically
generate a sounds-like pronunciation for the word.
* For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for
the word. You cannot override the default pronunciation of a word; pronunciations you add augment the
pronunciation from the base vocabulary.
A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not
including spaces.
_For a custom model that is based on a next-generation model_, omit this field. Custom models based on
next-generation models do not support the `sounds_like` field. The service ignores the field.
- parameter displayAs: An alternative spelling for the custom word when it appears in a transcript. Use the
parameter when you want the word to have a spelling that is different from its usual representation or from its
spelling in corpora training data.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func addWord(
customizationID: String,
wordName: String,
word: String? = nil,
soundsLike: [String]? = nil,
displayAs: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct body
let addWordRequest = AddWordRequest(
word: word,
sounds_like: soundsLike,
display_as: displayAs)
guard let body = try? JSON.encoder.encode(addWordRequest) else {
completionHandler(nil, RestError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWord")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/words/\(wordName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "PUT",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
messageBody: body
)
// execute REST request
request.response(completionHandler: completionHandler)
}
// Private struct for the addWord request body
private struct AddWordRequest: Encodable {
// swiftlint:disable identifier_name
let word: String?
let sounds_like: [String]?
let display_as: String?
// swiftlint:enable identifier_name
}
/**
Get a custom word.
Gets information about a custom word from a custom language model. You must use credentials for the instance of the
service that owns a model to list information about its words.
**See also:** [Listing words from a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#listWords).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter wordName: The custom word that is to be read from the custom language model. URL-encode the word if
it includes non-ASCII characters. For more information, see [Character
encoding](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#charEncoding).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getWord(
customizationID: String,
wordName: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Word>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getWord")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/words/\(wordName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete a custom word.
Deletes a custom word from a custom language model. You can remove any word that you added to the custom model's
words resource via any means. However, if the word also exists in the service's base vocabulary, the service
removes the word only from the words resource; the word remains in the base vocabulary. Removing a custom word does
not affect the custom model until you train the model with the [Train a custom language model](#trainlanguagemodel)
method. You must use credentials for the instance of the service that owns a model to delete its words.
**See also:** [Deleting a word from a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#deleteWord).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter wordName: The custom word that is to be deleted from the custom language model. URL-encode the word
if it includes non-ASCII characters. For more information, see [Character
encoding](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#charEncoding).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteWord(
customizationID: String,
wordName: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteWord")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/words/\(wordName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
List grammars.
Lists information about all grammars from a custom language model. For each grammar, the information includes the
name, status, and (for grammars that are based on previous-generation models) the total number of out-of-vocabulary
(OOV) words. You must use credentials for the instance of the service that owns a model to list its grammars.
**See also:**
* [Listing grammars from a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listGrammars(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Grammars>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listGrammars")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/grammars"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Add a grammar.
Adds a single grammar file to a custom language model. Submit a plain text file in UTF-8 format that defines the
grammar. Use multiple requests to submit multiple grammar files. You must use credentials for the instance of the
service that owns a model to add a grammar to it. Adding a grammar does not affect the custom language model until
you train the model for the new data by using the [Train a custom language model](#trainlanguagemodel) method.
The call returns an HTTP 201 response code if the grammar is valid. The service then asynchronously processes the
contents of the grammar and automatically extracts new words that it finds. This operation can take a few seconds
or minutes to complete depending on the size and complexity of the grammar, as well as the current load on the
service. You cannot submit requests to add additional resources to the custom model or to train the model until the
service's analysis of the grammar for the current request completes. Use the [Get a grammar](#getgrammar) method to
check the status of the analysis.
_For grammars that are based on previous-generation models,_ the service populates the model's words resource with
any word that is recognized by the grammar that is not found in the model's base vocabulary. These are referred to
as out-of-vocabulary (OOV) words. You can use the [List custom words](#listwords) method to examine the words
resource and use other words-related methods to eliminate typos and modify how words are pronounced as needed. _For
grammars that are based on next-generation models,_ the service extracts no OOV words from the grammars.
To add a grammar that has the same name as an existing grammar, set the `allow_overwrite` parameter to `true`;
otherwise, the request fails. Overwriting an existing grammar causes the service to process the grammar file and
extract OOV words anew. Before doing so, it removes any OOV words associated with the existing grammar from the
model's words resource unless they were also added by another resource or they have been modified in some way with
the [Add custom words](#addwords) or [Add a custom word](#addword) method.
_For grammars that are based on previous-generation models,_ the service limits the overall amount of data that you
can add to a custom model to a maximum of 10 million total words from all sources combined. Also, you can add no
more than 90 thousand OOV words to a model. This includes words that the service extracts from corpora and grammars
and words that you add directly.
**See also:**
* [Understanding
grammars](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUnderstand#grammarUnderstand)
* [Add a grammar to the custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarAdd#addGrammar)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter grammarName: The name of the new grammar for the custom language model. Use a localized name that
matches the language of the custom model and reflects the contents of the grammar.
* Include a maximum of 128 characters in the name.
* Do not use characters that need to be URL-encoded. For example, do not use spaces, slashes, backslashes,
colons, ampersands, double quotes, plus signs, equals signs, questions marks, and so on in the name. (The service
does not prevent the use of these characters. But because they must be URL-encoded wherever used, their use is
strongly discouraged.)
* Do not use the name of an existing grammar or corpus that is already defined for the custom model.
* Do not use the name `user`, which is reserved by the service to denote custom words that are added or modified
by the user.
* Do not use the name `base_lm` or `default_lm`. Both names are reserved for future use by the service.
- parameter grammarFile: A plain text file that contains the grammar in the format specified by the
`Content-Type` header. Encode the file in UTF-8 (ASCII is a subset of UTF-8). Using any other encoding can lead
to issues when compiling the grammar or to unexpected results in decoding. The service ignores an encoding that
is specified in the header of the grammar.
With the `curl` command, use the `--data-binary` option to upload the file for the request.
- parameter contentType: The format (MIME type) of the grammar file:
* `application/srgs` for Augmented Backus-Naur Form (ABNF), which uses a plain-text representation that is
similar to traditional BNF grammars.
* `application/srgs+xml` for XML Form, which uses XML elements to represent the grammar.
- parameter allowOverwrite: If `true`, the specified grammar overwrites an existing grammar with the same name.
If `false`, the request fails if a grammar with the same name already exists. The parameter has no effect if a
grammar with the same name does not already exist.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func addGrammar(
customizationID: String,
grammarName: String,
grammarFile: Data,
contentType: String,
allowOverwrite: Bool? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
let body = grammarFile
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addGrammar")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = contentType
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let allowOverwrite = allowOverwrite {
let queryParameter = URLQueryItem(name: "allow_overwrite", value: "\(allowOverwrite)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/grammars/\(grammarName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Get a grammar.
Gets information about a grammar from a custom language model. For each grammar, the information includes the name,
status, and (for grammars that are based on previous-generation models) the total number of out-of-vocabulary (OOV)
words. You must use credentials for the instance of the service that owns a model to list its grammars.
**See also:**
* [Listing grammars from a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter grammarName: The name of the grammar for the custom language model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getGrammar(
customizationID: String,
grammarName: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Grammar>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getGrammar")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/grammars/\(grammarName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete a grammar.
Deletes an existing grammar from a custom language model. _For grammars that are based on previous-generation
models,_ the service removes any out-of-vocabulary (OOV) words associated with the grammar from the custom model's
words resource unless they were also added by another resource or they were modified in some way with the [Add
custom words](#addwords) or [Add a custom word](#addword) method. Removing a grammar does not affect the custom
model until you train the model with the [Train a custom language model](#trainlanguagemodel) method. You must use
credentials for the instance of the service that owns a model to delete its grammar.
**See also:**
* [Deleting a grammar from a custom language
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#deleteGrammar)
* [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter grammarName: The name of the grammar for the custom language model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteGrammar(
customizationID: String,
grammarName: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteGrammar")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/customizations/\(customizationID)/grammars/\(grammarName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Create a custom acoustic model.
Creates a new custom acoustic model for a specified base model. The custom acoustic model can be used only with the
base model for which it is created. The model is owned by the instance of the service whose credentials are used to
create it.
You can create a maximum of 1024 custom acoustic models per owning credentials. The service returns an error if you
attempt to create more than 1024 models. You do not lose any models, but you cannot create any more until your
model count is below the limit.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**Important:** Effective 15 March 2022, previous-generation models for all languages other than Arabic and Japanese
are deprecated. The deprecated models remain available until 15 September 2022, when they will be removed from the
service and the documentation. You must migrate to the equivalent next-generation model by the end of service date.
For more information, see [Migrating to next-generation
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).
**See also:** [Create a custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#createModel-acoustic).
- parameter name: A user-defined name for the new custom acoustic model. Use a name that is unique among all
custom acoustic models that you own. Use a localized name that matches the language of the custom model. Use a
name that describes the acoustic environment of the custom model, such as `Mobile custom model` or `Noisy car
custom model`.
- parameter baseModelName: The name of the base language model that is to be customized by the new custom
acoustic model. The new custom model can be used only with the base model that it customizes. (**Note:** The
model `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.)
To determine whether a base model supports acoustic model customization, refer to [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter description: A description of the new custom acoustic model. Use a localized description that matches
the language of the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func createAcousticModel(
name: String,
baseModelName: String,
description: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<AcousticModel>?, WatsonError?) -> Void)
{
// construct body
let createAcousticModelRequest = CreateAcousticModelRequest(
name: name,
base_model_name: baseModelName,
description: description)
guard let body = try? JSON.encoder.encode(createAcousticModelRequest) else {
completionHandler(nil, RestError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createAcousticModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/acoustic_customizations",
headerParameters: headerParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
// Private struct for the createAcousticModel request body
private struct CreateAcousticModelRequest: Encodable {
// swiftlint:disable identifier_name
let name: String
let base_model_name: String
let description: String?
// swiftlint:enable identifier_name
}
/**
List custom acoustic models.
Lists information about all custom acoustic models that are owned by an instance of the service. Use the `language`
parameter to see all custom acoustic models for the specified language. Omit the parameter to see all custom
acoustic models for all languages. You must use credentials for the instance of the service that owns a model to
list information about it.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:** [Listing custom acoustic
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic).
- parameter language: The identifier of the language for which custom language or custom acoustic models are to
be returned. Specify the five-character language identifier; for example, specify `en-US` to see all custom
language or custom acoustic models that are based on US English models. Omit the parameter to see all custom
language or custom acoustic models that are owned by the requesting credentials. (**Note:** The identifier
`ar-AR` is deprecated; use `ar-MS` instead.)
To determine the languages for which customization is available, see [Language support for
customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listAcousticModels(
language: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<AcousticModels>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listAcousticModels")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let language = language {
let queryParameter = URLQueryItem(name: "language", value: language)
queryParameters.append(queryParameter)
}
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + "/v1/acoustic_customizations",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Get a custom acoustic model.
Gets information about a specified custom acoustic model. You must use credentials for the instance of the service
that owns a model to list information about it.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:** [Listing custom acoustic
models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic).
- parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getAcousticModel(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<AcousticModel>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getAcousticModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/acoustic_customizations/\(customizationID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete a custom acoustic model.
Deletes an existing custom acoustic model. The custom model cannot be deleted if another request, such as adding an
audio resource to the model, is currently being processed. You must use credentials for the instance of the service
that owns a model to delete it.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:** [Deleting a custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#deleteModel-acoustic).
- parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteAcousticModel(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteAcousticModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/acoustic_customizations/\(customizationID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Train a custom acoustic model.
Initiates the training of a custom acoustic model with new or changed audio resources. After adding or deleting
audio resources for a custom acoustic model, use this method to begin the actual training of the model on the
latest audio data. The custom acoustic model does not reflect its changed data until you train it. You must use
credentials for the instance of the service that owns a model to train it.
The training method is asynchronous. Training time depends on the cumulative amount of audio data that the custom
acoustic model contains and the current load on the service. When you train or retrain a model, the service uses
all of the model's audio data in the training. Training a custom acoustic model takes approximately as long as the
length of its cumulative audio data. For example, it takes approximately 2 hours to train a model that contains a
total of 2 hours of audio. The method returns an HTTP 200 response code to indicate that the training process has
begun.
You can monitor the status of the training by using the [Get a custom acoustic model](#getacousticmodel) method to
poll the model's status. Use a loop to check the status once a minute. The method returns an `AcousticModel` object
that includes `status` and `progress` fields. A status of `available` indicates that the custom model is trained
and ready to use. The service cannot train a model while it is handling another request for the model. The service
cannot accept subsequent training requests, or requests to add new audio resources, until the existing training
request completes.
You can use the optional `custom_language_model_id` parameter to specify the GUID of a separately created custom
language model that is to be used during training. Train with a custom language model if you have verbatim
transcriptions of the audio files that you have added to the custom model or you have either corpora (text files)
or a list of words that are relevant to the contents of the audio files. For training to succeed, both of the
custom models must be based on the same version of the same base model, and the custom language model must be fully
trained and available.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:**
* [Train the custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#trainModel-acoustic)
* [Using custom acoustic and custom language models
together](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-useBoth#useBoth)
### Training failures
Training can fail to start for the following reasons:
* The service is currently handling another request for the custom model, such as another training request or a
request to add audio resources to the model.
* The custom model contains less than 10 minutes or more than 200 hours of audio data.
* You passed a custom language model with the `custom_language_model_id` query parameter that is not in the
available state. A custom language model must be fully trained and available to be used to train a custom acoustic
model.
* You passed an incompatible custom language model with the `custom_language_model_id` query parameter. Both custom
models must be based on the same version of the same base model.
* The custom model contains one or more invalid audio resources. You can correct the invalid audio resources or set
the `strict` parameter to `false` to exclude the invalid resources from the training. The model must contain at
least one valid resource for training to succeed.
- parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter customLanguageModelID: The customization ID (GUID) of a custom language model that is to be used
during training of the custom acoustic model. Specify a custom language model that has been trained with verbatim
transcriptions of the audio resources or that contains words that are relevant to the contents of the audio
resources. The custom language model must be based on the same version of the same base model as the custom
acoustic model, and the custom language model must be fully trained and available. The credentials specified with
the request must own both custom models.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func trainAcousticModel(
customizationID: String,
customLanguageModelID: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<TrainingResponse>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "trainAcousticModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let customLanguageModelID = customLanguageModelID {
let queryParameter = URLQueryItem(name: "custom_language_model_id", value: customLanguageModelID)
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/acoustic_customizations/\(customizationID)/train"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Reset a custom acoustic model.
Resets a custom acoustic model by removing all audio resources from the model. Resetting a custom acoustic model
initializes the model to its state when it was first created. Metadata such as the name and language of the model
are preserved, but the model's audio resources are removed and must be re-created. The service cannot reset a model
while it is handling another request for the model. The service cannot accept subsequent requests for the model
until the existing reset request completes. You must use credentials for the instance of the service that owns a
model to reset it.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:** [Resetting a custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#resetModel-acoustic).
- parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func resetAcousticModel(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "resetAcousticModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/acoustic_customizations/\(customizationID)/reset"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Upgrade a custom acoustic model.
Initiates the upgrade of a custom acoustic model to the latest version of its base language model. The upgrade
method is asynchronous. It can take on the order of minutes or hours to complete depending on the amount of data in
the custom model and the current load on the service; typically, upgrade takes approximately twice the length of
the total audio contained in the custom model. A custom model must be in the `ready` or `available` state to be
upgraded. You must use credentials for the instance of the service that owns a model to upgrade it.
The method returns an HTTP 200 response code to indicate that the upgrade process has begun successfully. You can
monitor the status of the upgrade by using the [Get a custom acoustic model](#getacousticmodel) method to poll the
model's status. The method returns an `AcousticModel` object that includes `status` and `progress` fields. Use a
loop to check the status once a minute.
While it is being upgraded, the custom model has the status `upgrading`. When the upgrade is complete, the model
resumes the status that it had prior to upgrade. The service cannot upgrade a model while it is handling another
request for the model. The service cannot accept subsequent requests for the model until the existing upgrade
request completes.
If the custom acoustic model was trained with a separately created custom language model, you must use the
`custom_language_model_id` parameter to specify the GUID of that custom language model. The custom language model
must be upgraded before the custom acoustic model can be upgraded. Omit the parameter if the custom acoustic model
was not trained with a custom language model.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:** [Upgrading a custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-acoustic).
- parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter customLanguageModelID: If the custom acoustic model was trained with a custom language model, the
customization ID (GUID) of that custom language model. The custom language model must be upgraded before the
custom acoustic model can be upgraded. The custom language model must be fully trained and available. The
credentials specified with the request must own both custom models.
- parameter force: If `true`, forces the upgrade of a custom acoustic model for which no input data has been
modified since it was last trained. Use this parameter only to force the upgrade of a custom acoustic model that
is trained with a custom language model, and only if you receive a 400 response code and the message `No input
data modified since last training`. See [Upgrading a custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-acoustic).
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func upgradeAcousticModel(
customizationID: String,
customLanguageModelID: String? = nil,
force: Bool? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "upgradeAcousticModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let customLanguageModelID = customLanguageModelID {
let queryParameter = URLQueryItem(name: "custom_language_model_id", value: customLanguageModelID)
queryParameters.append(queryParameter)
}
if let force = force {
let queryParameter = URLQueryItem(name: "force", value: "\(force)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/acoustic_customizations/\(customizationID)/upgrade_model"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
List audio resources.
Lists information about all audio resources from a custom acoustic model. The information includes the name of the
resource and information about its audio data, such as its duration. It also includes the status of the audio
resource, which is important for checking the service's analysis of the resource in response to a request to add it
to the custom acoustic model. You must use credentials for the instance of the service that owns a model to list
its audio resources.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:** [Listing audio resources for a custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio).
- parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listAudio(
customizationID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<AudioResources>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listAudio")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/acoustic_customizations/\(customizationID)/audio"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Add an audio resource.
Adds an audio resource to a custom acoustic model. Add audio content that reflects the acoustic characteristics of
the audio that you plan to transcribe. You must use credentials for the instance of the service that owns a model
to add an audio resource to it. Adding audio data does not affect the custom acoustic model until you train the
model for the new data by using the [Train a custom acoustic model](#trainacousticmodel) method.
You can add individual audio files or an archive file that contains multiple audio files. Adding multiple audio
files via a single archive file is significantly more efficient than adding each file individually. You can add
audio resources in any format that the service supports for speech recognition.
You can use this method to add any number of audio resources to a custom model by calling the method once for each
audio or archive file. You can add multiple different audio resources at the same time. You must add a minimum of
10 minutes and a maximum of 200 hours of audio that includes speech, not just silence, to a custom acoustic model
before you can train it. No audio resource, audio- or archive-type, can be larger than 100 MB. To add an audio
resource that has the same name as an existing audio resource, set the `allow_overwrite` parameter to `true`;
otherwise, the request fails.
The method is asynchronous. It can take several seconds or minutes to complete depending on the duration of the
audio and, in the case of an archive file, the total number of audio files being processed. The service returns a
201 response code if the audio is valid. It then asynchronously analyzes the contents of the audio file or files
and automatically extracts information about the audio such as its length, sampling rate, and encoding. You cannot
submit requests to train or upgrade the model until the service's analysis of all audio resources for current
requests completes.
To determine the status of the service's analysis of the audio, use the [Get an audio resource](#getaudio) method
to poll the status of the audio. The method accepts the customization ID of the custom model and the name of the
audio resource, and it returns the status of the resource. Use a loop to check the status of the audio every few
seconds until it becomes `ok`.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:** [Add audio to the custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#addAudio).
### Content types for audio-type resources
You can add an individual audio file in any format that the service supports for speech recognition. For an
audio-type resource, use the `Content-Type` parameter to specify the audio format (MIME type) of the audio file,
including specifying the sampling rate, channels, and endianness where indicated.
* `audio/alaw` (Specify the sampling rate (`rate`) of the audio.)
* `audio/basic` (Use only with narrowband models.)
* `audio/flac`
* `audio/g729` (Use only with narrowband models.)
* `audio/l16` (Specify the sampling rate (`rate`) and optionally the number of channels (`channels`) and endianness
(`endianness`) of the audio.)
* `audio/mp3`
* `audio/mpeg`
* `audio/mulaw` (Specify the sampling rate (`rate`) of the audio.)
* `audio/ogg` (The service automatically detects the codec of the input audio.)
* `audio/ogg;codecs=opus`
* `audio/ogg;codecs=vorbis`
* `audio/wav` (Provide audio with a maximum of nine channels.)
* `audio/webm` (The service automatically detects the codec of the input audio.)
* `audio/webm;codecs=opus`
* `audio/webm;codecs=vorbis`
The sampling rate of an audio file must match the sampling rate of the base model for the custom model: for
broadband models, at least 16 kHz; for narrowband models, at least 8 kHz. If the sampling rate of the audio is
higher than the minimum required rate, the service down-samples the audio to the appropriate rate. If the sampling
rate of the audio is lower than the minimum required rate, the service labels the audio file as `invalid`.
**See also:** [Supported audio
formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats).
### Content types for archive-type resources
You can add an archive file (**.zip** or **.tar.gz** file) that contains audio files in any format that the
service supports for speech recognition. For an archive-type resource, use the `Content-Type` parameter to specify
the media type of the archive file:
* `application/zip` for a **.zip** file
* `application/gzip` for a **.tar.gz** file.
When you add an archive-type resource, the `Contained-Content-Type` header is optional depending on the format of
the files that you are adding:
* For audio files of type `audio/alaw`, `audio/basic`, `audio/l16`, or `audio/mulaw`, you must use the
`Contained-Content-Type` header to specify the format of the contained audio files. Include the `rate`, `channels`,
and `endianness` parameters where necessary. In this case, all audio files contained in the archive file must have
the same audio format.
* For audio files of all other types, you can omit the `Contained-Content-Type` header. In this case, the audio
files contained in the archive file can have any of the formats not listed in the previous bullet. The audio files
do not need to have the same format.
Do not use the `Contained-Content-Type` header when adding an audio-type resource.
### Naming restrictions for embedded audio files
The name of an audio file that is contained in an archive-type resource can include a maximum of 128 characters.
This includes the file extension and all elements of the name (for example, slashes).
- parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter audioName: The name of the new audio resource for the custom acoustic model. Use a localized name
that matches the language of the custom model and reflects the contents of the resource.
* Include a maximum of 128 characters in the name.
* Do not use characters that need to be URL-encoded. For example, do not use spaces, slashes, backslashes,
colons, ampersands, double quotes, plus signs, equals signs, questions marks, and so on in the name. (The service
does not prevent the use of these characters. But because they must be URL-encoded wherever used, their use is
strongly discouraged.)
* Do not use the name of an audio resource that has already been added to the custom model.
- parameter audioResource: The audio resource that is to be added to the custom acoustic model, an individual
audio file or an archive file.
With the `curl` command, use the `--data-binary` option to upload the file for the request.
- parameter contentType: For an audio-type resource, the format (MIME type) of the audio. For more information,
see **Content types for audio-type resources** in the method description.
For an archive-type resource, the media type of the archive file. For more information, see **Content types for
archive-type resources** in the method description.
- parameter containedContentType: _For an archive-type resource_, specify the format of the audio files that are
contained in the archive file if they are of type `audio/alaw`, `audio/basic`, `audio/l16`, or `audio/mulaw`.
Include the `rate`, `channels`, and `endianness` parameters where necessary. In this case, all audio files that
are contained in the archive file must be of the indicated type.
For all other audio formats, you can omit the header. In this case, the audio files can be of multiple types as
long as they are not of the types listed in the previous paragraph.
The parameter accepts all of the audio formats that are supported for use with speech recognition. For more
information, see **Content types for audio-type resources** in the method description.
_For an audio-type resource_, omit the header.
- parameter allowOverwrite: If `true`, the specified audio resource overwrites an existing audio resource with
the same name. If `false`, the request fails if an audio resource with the same name already exists. The
parameter has no effect if an audio resource with the same name does not already exist.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func addAudio(
customizationID: String,
audioName: String,
audioResource: Data,
contentType: String? = nil,
containedContentType: String? = nil,
allowOverwrite: Bool? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
let body = audioResource
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addAudio")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let contentType = contentType {
headerParameters["Content-Type"] = contentType
}
if let containedContentType = containedContentType {
headerParameters["Contained-Content-Type"] = containedContentType
}
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
if let allowOverwrite = allowOverwrite {
let queryParameter = URLQueryItem(name: "allow_overwrite", value: "\(allowOverwrite)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/acoustic_customizations/\(customizationID)/audio/\(audioName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Get an audio resource.
Gets information about an audio resource from a custom acoustic model. The method returns an `AudioListing` object
whose fields depend on the type of audio resource that you specify with the method's `audio_name` parameter:
* _For an audio-type resource_, the object's fields match those of an `AudioResource` object: `duration`, `name`,
`details`, and `status`.
* _For an archive-type resource_, the object includes a `container` field whose fields match those of an
`AudioResource` object. It also includes an `audio` field, which contains an array of `AudioResource` objects that
provides information about the audio files that are contained in the archive.
The information includes the status of the specified audio resource. The status is important for checking the
service's analysis of a resource that you add to the custom model.
* _For an audio-type resource_, the `status` field is located in the `AudioListing` object.
* _For an archive-type resource_, the `status` field is located in the `AudioResource` object that is returned in
the `container` field.
You must use credentials for the instance of the service that owns a model to list its audio resources.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:** [Listing audio resources for a custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio).
- parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter audioName: The name of the audio resource for the custom acoustic model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getAudio(
customizationID: String,
audioName: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<AudioListing>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getAudio")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/acoustic_customizations/\(customizationID)/audio/\(audioName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete an audio resource.
Deletes an existing audio resource from a custom acoustic model. Deleting an archive-type audio resource removes
the entire archive of files. The service does not allow deletion of individual files from an archive resource.
Removing an audio resource does not affect the custom model until you train the model on its updated data by using
the [Train a custom acoustic model](#trainacousticmodel) method. You can delete an existing audio resource from a
model while a different resource is being added to the model. You must use credentials for the instance of the
service that owns a model to delete its audio resources.
**Note:** Acoustic model customization is supported only for use with previous-generation models. It is not
supported for next-generation models.
**See also:** [Deleting an audio resource from a custom acoustic
model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#deleteAudio).
- parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the
request. You must make the request with credentials for the instance of the service that owns the custom model.
- parameter audioName: The name of the audio resource for the custom acoustic model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteAudio(
customizationID: String,
audioName: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteAudio")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct REST request
let path = "/v1/acoustic_customizations/\(customizationID)/audio/\(audioName)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
/**
Delete labeled data.
Deletes all data that is associated with a specified customer ID. The method deletes all data for the customer ID,
regardless of the method by which the information was added. The method has no effect if no data is associated with
the customer ID. You must issue the request with credentials for the same instance of the service that was used to
associate the customer ID with the data. You associate a customer ID with data by passing the `X-Watson-Metadata`
header with a request that passes the data.
**Note:** If you delete an instance of the service from the service console, all data associated with that service
instance is automatically deleted. This includes all custom language models, corpora, grammars, and words; all
custom acoustic models and audio resources; all registered endpoints for the asynchronous HTTP interface; and all
data related to speech recognition requests.
**See also:** [Information
security](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-information-security#information-security).
- parameter customerID: The customer ID for which all data is to be deleted.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteUserData(
customerID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData")
headerParameters.merge(sdkHeaders) { (_, new) in new }
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "customer_id", value: customerID))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + "/v1/user_data",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.response(completionHandler: completionHandler)
}
}
| 07392136bbb96e56463a286a1c69b0e9 | 57.728417 | 139 | 0.703743 | false | false | false | false |
samodom/TestableUIKit | refs/heads/master | TestableUIKit/UIResponder/UIView/UICollectionView/UICollectionViewReloadItemsSpy.swift | mit | 1 | //
// UICollectionViewReloadItemsSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/21/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import UIKit
import TestSwagger
import FoundationSwagger
public extension UICollectionView {
private static let reloadItemsCalledKeyString = UUIDKeyString()
private static let reloadItemsCalledKey =
ObjectAssociationKey(reloadItemsCalledKeyString)
private static let reloadItemsCalledReference =
SpyEvidenceReference(key: reloadItemsCalledKey)
private static let reloadItemsIndexPathsKeyString = UUIDKeyString()
private static let reloadItemsIndexPathsKey =
ObjectAssociationKey(reloadItemsIndexPathsKeyString)
private static let reloadItemsIndexPathsReference =
SpyEvidenceReference(key: reloadItemsIndexPathsKey)
private static let reloadItemsCoselectors = SpyCoselectors(
methodType: .instance,
original: #selector(UICollectionView.reloadItems(at:)),
spy: #selector(UICollectionView.spy_reloadItems(at:))
)
/// Spy controller for ensuring that a collection view has had `reloadItems(at:)` called on it.
public enum ReloadItemsSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UICollectionView.self
public static let vector = SpyVector.direct
public static let coselectors: Set = [reloadItemsCoselectors]
public static let evidence: Set = [
reloadItemsCalledReference,
reloadItemsIndexPathsReference
]
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `reloadItems(at:)`
dynamic public func spy_reloadItems(at indexPaths: [IndexPath]) {
reloadItemsCalled = true
reloadItemsIndexPaths = indexPaths
spy_reloadItems(at: indexPaths)
}
/// Indicates whether the `reloadItems(at:)` method has been called on this object.
public final var reloadItemsCalled: Bool {
get {
return loadEvidence(with: UICollectionView.reloadItemsCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: UICollectionView.reloadItemsCalledReference)
}
}
/// Provides the index paths passed to `reloadItems(at:)` if called.
public final var reloadItemsIndexPaths: [IndexPath]? {
get {
return loadEvidence(with: UICollectionView.reloadItemsIndexPathsReference) as? [IndexPath]
}
set {
let reference = UICollectionView.reloadItemsIndexPathsReference
guard let items = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(items, with: reference)
}
}
}
| 51c6213c107cd1185e1f281811af8d40 | 32.416667 | 102 | 0.697542 | false | false | false | false |
eBardX/XestiMonitors | refs/heads/master | Tests/UIKit/Other/KeyboardMonitorTests.swift | mit | 1 | //
// KeyboardMonitorTests.swift
// XestiMonitorsTests
//
// Created by J. G. Pusey on 2017-12-27.
//
// © 2017 J. G. Pusey (see LICENSE.md)
//
import UIKit
import XCTest
@testable import XestiMonitors
// swiftlint:disable type_body_length
internal class KeyboardMonitorTests: XCTestCase {
let notificationCenter = MockNotificationCenter()
override func setUp() {
super.setUp()
NotificationCenterInjector.inject = { self.notificationCenter }
}
func testMonitor_didChangeFrame() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeIn
let expectedAnimationDuration: TimeInterval = 0.15
let expectedFrameBegin = CGRect(x: 11, y: 21, width: 31, height: 41)
let expectedFrameEnd = CGRect(x: 51, y: 61, width: 71, height: 81)
let expectedIsLocal = true
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .didChangeFrame,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidChangeFrame(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didChangeFrame(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_didChangeFrame_badUserInfo() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeIn
let expectedAnimationDuration: TimeInterval = 0.15
let expectedFrameBegin = CGRect(x: 11, y: 21, width: 31, height: 41)
let expectedFrameEnd = CGRect(x: 51, y: 61, width: 71, height: 81)
let expectedIsLocal = false
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .didChangeFrame,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidChangeFrame(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal,
badUserInfo: true)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didChangeFrame(info) = event {
XCTAssertNotEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertNotEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertNotEqual(info.frameBegin, expectedFrameBegin)
XCTAssertNotEqual(info.frameEnd, expectedFrameEnd)
XCTAssertNotEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_didHide() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeOut
let expectedAnimationDuration: TimeInterval = 0.25
let expectedFrameBegin = CGRect(x: 12, y: 22, width: 32, height: 42)
let expectedFrameEnd = CGRect(x: 52, y: 62, width: 72, height: 82)
let expectedIsLocal = false
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .didHide,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidHide(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didHide(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_didShow() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeInOut
let expectedAnimationDuration: TimeInterval = 0.35
let expectedFrameBegin = CGRect(x: 13, y: 23, width: 33, height: 43)
let expectedFrameEnd = CGRect(x: 53, y: 63, width: 73, height: 83)
let expectedIsLocal = true
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .didShow,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidShow(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didShow(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_willChangeFrame() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeIn
let expectedAnimationDuration: TimeInterval = 0.45
let expectedFrameBegin = CGRect(x: 14, y: 24, width: 34, height: 44)
let expectedFrameEnd = CGRect(x: 54, y: 64, width: 74, height: 84)
let expectedIsLocal = false
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .willChangeFrame,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateWillChangeFrame(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .willChangeFrame(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_willHide() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeOut
let expectedAnimationDuration: TimeInterval = 0.55
let expectedFrameBegin = CGRect(x: 15, y: 25, width: 35, height: 45)
let expectedFrameEnd = CGRect(x: 55, y: 65, width: 75, height: 85)
let expectedIsLocal = true
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .willHide,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateWillHide(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .willHide(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_willShow() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeInOut
let expectedAnimationDuration: TimeInterval = 0.65
let expectedFrameBegin = CGRect(x: 16, y: 26, width: 36, height: 46)
let expectedFrameEnd = CGRect(x: 56, y: 66, width: 76, height: 86)
let expectedIsLocal = false
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .willShow,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateWillShow(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .willShow(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
private func makeUserInfo(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) -> [AnyHashable: Any] {
return [UIKeyboardAnimationCurveUserInfoKey: NSNumber(value: animationCurve.rawValue),
UIKeyboardAnimationDurationUserInfoKey: NSNumber(value: animationDuration),
UIKeyboardFrameBeginUserInfoKey: NSValue(cgRect: frameBegin),
UIKeyboardFrameEndUserInfoKey: NSValue(cgRect: frameEnd),
UIKeyboardIsLocalUserInfoKey: NSNumber(value: isLocal)]
}
private func simulateDidChangeFrame(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool,
badUserInfo: Bool = false) {
let userInfo: [AnyHashable: Any]?
if badUserInfo {
userInfo = nil
} else {
userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
}
notificationCenter.post(name: .UIKeyboardDidChangeFrame,
object: nil,
userInfo: userInfo)
}
private func simulateDidHide(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardDidHide,
object: nil,
userInfo: userInfo)
}
private func simulateDidShow(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardDidShow,
object: nil,
userInfo: userInfo)
}
private func simulateWillChangeFrame(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardWillChangeFrame,
object: nil,
userInfo: userInfo)
}
private func simulateWillHide(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardWillHide,
object: nil,
userInfo: userInfo)
}
private func simulateWillShow(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardWillShow,
object: nil,
userInfo: userInfo)
}
}
// swiftlint:enable type_body_length
| cf77e9af61a1c1d5e89c5b23ecaddd9e | 44.683292 | 94 | 0.549702 | false | false | false | false |
Ribeiro/Swifter | refs/heads/master | SwifterCommon/SwifterStreaming.swift | mit | 3 | //
// SwifterStreaming.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Swifter {
/*
POST statuses/filter
Returns public statuses that match one or more filter predicates. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Both GET and POST requests are supported, but GET requests with too many parameters may cause the request to be rejected for excessive URL length. Use a POST request to avoid long URLs.
The track, follow, and locations fields should be considered to be combined with an OR operator. track=foo&follow=1234 returns Tweets matching "foo" OR created by user 1234.
The default access level allows up to 400 track keywords, 5,000 follow userids and 25 0.1-360 degree location boxes. If you need elevated access to the Streaming API, you should explore our partner providers of Twitter data here: https://dev.twitter.com/programs/twitter-certified-products/products#Certified-Data-Products
At least one predicate parameter (follow, locations, or track) must be specified.
*/
func postStatusesFilter(follow: String[]?, track: String[]?, locations: String[]?, delimited: Bool?, stallWarnings: Bool?, progress: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler) {
assert(follow || track || locations, "At least one predicate parameter (follow, locations, or track) must be specified")
let path = "statuses/filter.json"
var parameters = Dictionary<String, AnyObject>()
if follow {
parameters["follow"] = follow!.bridgeToObjectiveC().componentsJoinedByString(",")
}
if track {
parameters["track"] = track!.bridgeToObjectiveC().componentsJoinedByString(",")
}
if locations {
parameters["locations"] = locations!.bridgeToObjectiveC().componentsJoinedByString(",")
}
if delimited {
parameters["delimited"] = delimited!
}
if stallWarnings {
parameters["stall_warnings"] = stallWarnings!
}
self.postJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: progress, success: nil, failure: failure)
}
/*
GET statuses/sample
Returns a small random sample of all public statuses. The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.
*/
func getStatusesSampleDelimited(delimited: Bool?, stallWarnings: Bool?, progress: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "statuses/sample.json"
var parameters = Dictionary<String, AnyObject>()
if delimited {
parameters["delimited"] = delimited!
}
if stallWarnings {
parameters["stall_warnings"] = stallWarnings!
}
self.getJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: progress, success: nil, failure: failure)
}
/*
GET statuses/firehose
This endpoint requires special permission to access.
Returns all public statuses. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.
*/
func getStatusesFirehose(count: Int?, delimited: Bool?, stallWarnings: Bool?, progress: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "statuses/firehose.json"
var parameters = Dictionary<String, AnyObject>()
if count {
parameters["count"] = count!
}
if delimited {
parameters["delimited"] = delimited!
}
if stallWarnings {
parameters["stall_warnings"] = stallWarnings!
}
self.getJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: progress, success: nil, failure: failure)
}
/*
GET user
Streams messages for a single user, as described in User streams https://dev.twitter.com/docs/streaming-apis/streams/user
*/
func getUserStreamDelimited(delimited: Bool?, stallWarnings: Bool?, includeMessagesFromFollowedAccounts: Bool?, includeReplies: Bool?, track: String[]?, locations: String[]?, stringifyFriendIDs: Bool?, progress: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "user.json"
var parameters = Dictionary<String, AnyObject>()
if delimited {
parameters["delimited"] = delimited!
}
if stallWarnings {
parameters["stall_warnings"] = stallWarnings!
}
if includeMessagesFromFollowedAccounts {
if includeMessagesFromFollowedAccounts! {
parameters["with"] = "user"
}
}
if includeReplies {
if includeReplies! {
parameters["replies"] = "all"
}
}
if track {
parameters["track"] = track!.bridgeToObjectiveC().componentsJoinedByString(",")
}
if locations {
parameters["locations"] = locations!.bridgeToObjectiveC().componentsJoinedByString(",")
}
if stringifyFriendIDs {
parameters["stringify_friend_ids"] = stringifyFriendIDs!
}
self.postJSONWithPath(path, baseURL: self.userStreamURL, parameters: parameters, uploadProgress: nil, downloadProgress: progress, success: nil, failure: failure)
}
/*
GET site
Streams messages for a set of users, as described in Site streams https://dev.twitter.com/docs/streaming-apis/streams/site
*/
func getSiteStreamDelimited(delimited: Bool?, stallWarnings: Bool?, restrictToUserMessages: Bool?, includeReplies: Bool?, stringifyFriendIDs: Bool?, progress: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let path = "site.json"
var parameters = Dictionary<String, AnyObject>()
if delimited {
parameters["delimited"] = delimited!
}
if stallWarnings {
parameters["stall_warnings"] = stallWarnings!
}
if restrictToUserMessages {
if restrictToUserMessages! {
parameters["with"] = "user"
}
}
if includeReplies {
if includeReplies! {
parameters["replies"] = "all"
}
}
if stringifyFriendIDs {
parameters["stringify_friend_ids"] = stringifyFriendIDs!
}
self.postJSONWithPath(path, baseURL: self.siteStreamURL, parameters: parameters, uploadProgress: nil, downloadProgress: progress, success: nil, failure: failure)
}
}
| 4f80c5d207282cce00334d71f0bc28ac | 43.988827 | 371 | 0.672669 | false | false | false | false |
Ivacker/swift | refs/heads/master | validation-test/compiler_crashers/27194-swift-pattern-foreachvariable.swift | apache-2.0 | 9 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
{
a {{
{{
( { {
{
{
{{:a
}}}let a{{
{
{ {d b{}}}}}b}}}}}}<T}}}class S<T{func a<h{func b<T where h.g=a
{
func a{
if true{
}
struct d<T where g
func
{init(
{ (( (( )
let f=A{
[:e
}}}protocol P{
{
let g{
{
[{A
{
{
func a{func {
{{
func x:
{ {
{{{
a{
struct d<T where g{
{
{ {
"
{ {
[ { ()a{let v:
{ (
{ (
a{
{protocol P{
"class c
{
if true{
{{
{
if true{
struct B<T where I:a{
"
{ {g:{(){
{
let v:d<T where I:a=g
[{func{ {d b{}}}}}b}}}}}}<T}}}class S<T{func a<h{func b<T where h.g=a
{
}let a<T where T{{
typealias b:a{{T:
{
func a{struct S<b{
struct d
{
func a{
a{g=F
func x:
{
{
{d b{}}}}}b}}}}}}<T}}}class S<T{func a<h{func b<T where h.g=a
class d<T where I:
[:a{
let(
{
func a{
{
a{
a{{let t=0
class b:C{
a typealias b:Int=i{
{ {struct B{
"
{
let h{{class c{func x
typealias F
{
{
}protocol a
var b:a{(
"class b{
protocol P{
{
}struct d
{
{{}}}}protocol P{{
{ :a{
{ {
{
func{ a{init()a{
{ (
{g
{{
{ (
{
protocol A{
{
{
{ {{
typealias e:a{
{{
"
{
{{
{ {struct d<b:
d
let v:a
{
{
if true{
{
{typealias e{
func f{
{ {
func a{protocol P{{T:
var b{typealias e{
{ a{typealias b{let a{
func a<b{{
[{
{protocol P{
a typealias b:a=F
{
{
{
if true{
let f{{
(({
{
{}let g{
protocol a<T where g{let h{{
""
{let h{{struct d<T where g
struct S
{( ){let t:
var b{
{ {
protocol{{
protocol P{
{
{
{ {
func
}}protocol A{{
let v:e
{
{ {protocol b:
{
{
struct S<T where T:a<b:
{
a typealias e{
{
{
{
{{typealias f{let v:(()
{:C{{{
{
{{{{
func a{
{
{
func a
{}}}enum S<b{
{
( : ( )
{( : ( : ( : ( { {
struct d
{
{
{
"
protocol P{
class b{((
a {
{
((x
{{
{typealias e
}
{{
{
{
[{
a {{
{ :d= .c{
{e a{}
}}}
{{
{ ({{func b{func a
[{(
(){A<T:
{ {:a{
{
{
{
[ { {
{
d
{ ({func x
{{:
class A<T where I:a{A{
{{A
{
{{
func a{{let t:C{
[ {
{
struct Q{
class b{func a{
class A
{
{{
{{func
{
{{let v:a
struct d<T where I:e:
struct d<h}}}protocol A<h{}enum S
let t=F=g:a{let a{
{(
:
{ {
let a{
| 97a4529f4a1b68d4ed129af238397d1d | 7.834746 | 87 | 0.516547 | false | false | false | false |
frootloops/swift | refs/heads/master | test/SILGen/objc_init_ref_delegation.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
extension Gizmo {
// CHECK-LABEL: sil hidden @_T0So5GizmoC24objc_init_ref_delegationE{{[_0-9a-zA-Z]*}}fc
convenience init(int i: Int) {
// CHECK: bb0([[I:%[0-9]+]] : @trivial $Int, [[ORIG_SELF:%[0-9]+]] : @owned $Gizmo):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Gizmo }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: store [[ORIG_SELF]] to [init] [[PB_BOX]] : $*Gizmo
// CHECK: [[SELF:%[0-9]+]] = load [take] [[PB_BOX]] : $*Gizmo
// CHECK: [[INIT_DELEG:%[0-9]+]] = objc_method [[SELF]] : $Gizmo, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: [[SELF_RET:%[0-9]+]] = apply [[INIT_DELEG]]([[I]], [[SELF]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: [[SELF4:%.*]] = load [copy] [[PB_BOX]]
// CHECK: destroy_value [[MARKED_SELF_BOX]]
// CHECK: return [[SELF4]] : $Gizmo
self.init(bellsOn:i)
}
}
| 7e02442ae3a311a0269b246a2051b4c3 | 55.826087 | 212 | 0.577659 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/ReplyModel.swift | gpl-2.0 | 1 | //
// ReplyModel.swift
// Telegram-Mac
//
// Created by keepcoder on 21/09/16.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import SwiftSignalKit
import Postbox
class ReplyModel: ChatAccessoryModel {
private(set) var replyMessage:Message?
private var disposable:MetaDisposable = MetaDisposable()
private let isPinned:Bool
private var previousMedia: Media?
private var isLoading: Bool = false
private let fetchDisposable = MetaDisposable()
private let makesizeCallback:(()->Void)?
private let autodownload: Bool
private let headerAsName: Bool
private let customHeader: String?
init(replyMessageId:MessageId, context: AccountContext, replyMessage:Message? = nil, isPinned: Bool = false, autodownload: Bool = false, presentation: ChatAccessoryPresentation? = nil, headerAsName: Bool = false, customHeader: String? = nil, drawLine: Bool = true, makesizeCallback: (()->Void)? = nil, dismissReply: (()->Void)? = nil) {
self.isPinned = isPinned
self.makesizeCallback = makesizeCallback
self.autodownload = autodownload
self.replyMessage = replyMessage
self.headerAsName = headerAsName
self.customHeader = customHeader
super.init(context: context, presentation: presentation, drawLine: drawLine)
let messageViewSignal: Signal<Message?, NoError> = context.account.postbox.messageView(replyMessageId)
|> map {
$0.message
} |> deliverOnMainQueue
if let replyMessage = replyMessage {
make(with :replyMessage, display: false)
self.nodeReady.set(.single(true))
} else {
make(with: nil, display: false)
}
if replyMessage == nil {
nodeReady.set(messageViewSignal |> map { [weak self] message -> Bool in
self?.make(with: message, isLoading: false, display: true)
if message == nil {
dismissReply?()
}
return message != nil
})
}
}
override weak var view:ChatAccessoryView? {
didSet {
updateImageIfNeeded()
}
}
override var frame: NSRect {
didSet {
updateImageIfNeeded()
}
}
override var leftInset: CGFloat {
var imageDimensions: CGSize?
if let message = replyMessage {
if !message.containsSecretMedia {
for media in message.media {
if let image = media as? TelegramMediaImage {
if let representation = largestRepresentationForPhoto(image) {
imageDimensions = representation.dimensions.size
}
break
} else if let file = media as? TelegramMediaFile, (file.isVideo || file.isSticker) && !file.isVideoSticker {
if let dimensions = file.dimensions {
imageDimensions = dimensions.size
} else if let representation = largestImageRepresentation(file.previewRepresentations), !file.isStaticSticker {
imageDimensions = representation.dimensions.size
} else if file.isAnimatedSticker {
imageDimensions = NSMakeSize(30, 30)
}
break
}
}
}
if let _ = imageDimensions {
return 30 + super.leftInset * 2
}
}
return super.leftInset
}
deinit {
disposable.dispose()
fetchDisposable.dispose()
}
func update() {
self.make(with: replyMessage, isLoading: isLoading, display: true)
}
private func updateImageIfNeeded() {
if let message = self.replyMessage, let view = self.view {
var updatedMedia: Media?
var imageDimensions: CGSize?
var hasRoundImage = false
if !message.containsSecretMedia {
for media in message.media {
if let image = media as? TelegramMediaImage {
updatedMedia = image
if let representation = largestRepresentationForPhoto(image) {
imageDimensions = representation.dimensions.size
}
break
} else if let file = media as? TelegramMediaFile, (file.isVideo || file.isSticker) && !file.isVideoSticker {
updatedMedia = file
if let dimensions = file.dimensions?.size {
imageDimensions = dimensions
} else if let representation = largestImageRepresentation(file.previewRepresentations) {
imageDimensions = representation.dimensions.size
} else if file.isAnimatedSticker {
imageDimensions = NSMakeSize(30, 30)
}
if file.isInstantVideo {
hasRoundImage = true
}
break
}
}
}
if let imageDimensions = imageDimensions {
let boundingSize = CGSize(width: 30.0, height: 30.0)
let arguments = TransformImageArguments(corners: ImageCorners(radius: 2.0), imageSize: imageDimensions.aspectFilled(boundingSize), boundingSize: boundingSize, intrinsicInsets: NSEdgeInsets())
if view.imageView == nil {
view.imageView = TransformImageView()
}
view.imageView?.setFrameSize(boundingSize)
if view.imageView?.superview == nil {
view.addSubview(view.imageView!)
}
view.imageView?.setFrameOrigin(super.leftInset + (self.isSideAccessory ? 10 : 0), floorToScreenPixels(System.backingScale, self.topOffset + (max(34, self.size.height) - self.topOffset - boundingSize.height)/2))
let mediaUpdated = true
var updateImageSignal: Signal<ImageDataTransformation, NoError>?
if mediaUpdated {
if let image = updatedMedia as? TelegramMediaImage {
updateImageSignal = chatMessagePhotoThumbnail(account: self.context.account, imageReference: ImageMediaReference.message(message: MessageReference(message), media: image), scale: view.backingScaleFactor, synchronousLoad: true)
} else if let file = updatedMedia as? TelegramMediaFile {
if file.isVideo {
updateImageSignal = chatMessageVideoThumbnail(account: self.context.account, fileReference: FileMediaReference.message(message: MessageReference(message), media: file), scale: view.backingScaleFactor, synchronousLoad: false)
} else if file.isAnimatedSticker {
updateImageSignal = chatMessageAnimatedSticker(postbox: self.context.account.postbox, file: FileMediaReference.message(message: MessageReference(message), media: file), small: true, scale: view.backingScaleFactor, size: imageDimensions.aspectFitted(boundingSize), fetched: true, isVideo: file.isVideoSticker)
} else if file.isSticker {
updateImageSignal = chatMessageSticker(postbox: self.context.account.postbox, file: FileMediaReference.message(message: MessageReference(message), media: file), small: true, scale: view.backingScaleFactor, fetched: true)
} else if let iconImageRepresentation = smallestImageRepresentation(file.previewRepresentations) {
let tmpImage = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: [iconImageRepresentation], immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: [])
updateImageSignal = chatWebpageSnippetPhoto(account: self.context.account, imageReference: ImageMediaReference.message(message: MessageReference(message), media: tmpImage), scale: view.backingScaleFactor, small: true, synchronousLoad: true)
}
}
}
if let updateImageSignal = updateImageSignal, let media = updatedMedia {
view.imageView?.setSignal(signal: cachedMedia(media: media, arguments: arguments, scale: System.backingScale), clearInstantly: false)
view.imageView?.setSignal(updateImageSignal, animate: true, synchronousLoad: true, cacheImage: { [weak media] result in
if let media = media {
cacheMedia(result, media: media, arguments: arguments, scale: System.backingScale)
}
})
if let media = media as? TelegramMediaImage {
self.fetchDisposable.set(chatMessagePhotoInteractiveFetched(account: self.context.account, imageReference: ImageMediaReference.message(message: MessageReference(message), media: media)).start())
}
view.imageView?.set(arguments: arguments)
if hasRoundImage {
view.imageView!.layer?.cornerRadius = 15
} else {
view.imageView?.layer?.cornerRadius = 0
}
}
} else {
view.imageView?.removeFromSuperview()
view.imageView = nil
}
self.previousMedia = updatedMedia
} else {
self.view?.imageView?.removeFromSuperview()
self.view?.imageView = nil
}
self.view?.updateModel(self, animated: false)
}
func make(with message:Message?, isLoading: Bool = true, display: Bool) -> Void {
self.replyMessage = message
self.isLoading = isLoading
var display: Bool = display
updateImageIfNeeded()
if let message = message {
var title: String? = message.effectiveAuthor?.displayTitle
if let info = message.forwardInfo {
title = info.authorTitle
}
for attr in message.attributes {
if let _ = attr as? SourceReferenceMessageAttribute {
if let info = message.forwardInfo {
title = info.authorTitle
}
break
}
}
let text = chatListText(account: context.account, for: message, isPremium: context.isPremium, isReplied: true)
if let header = customHeader {
self.header = .init(.initialize(string: header, color: presentation.title, font: .medium(.text)), maximumNumberOfLines: 1)
} else {
self.header = .init(.initialize(string: !isPinned || headerAsName ? title : strings().chatHeaderPinnedMessage, color: presentation.title, font: .medium(.text)), maximumNumberOfLines: 1)
}
let attr = NSMutableAttributedString()
attr.append(text)
attr.addAttribute(.foregroundColor, value: message.media.isEmpty || message.effectiveMedia is TelegramMediaWebpage ? presentation.enabledText : presentation.disabledText, range: attr.range)
attr.addAttribute(.font, value: NSFont.normal(.text), range: attr.range)
attr.fixUndefinedEmojies()
self.message = .init(attr, maximumNumberOfLines: 1)
} else {
self.header = nil
self.message = .init(.initialize(string: isLoading ? strings().messagesReplyLoadingLoading : strings().messagesDeletedMessage, color: presentation.disabledText, font: .normal(.text)), maximumNumberOfLines: 1)
display = true
}
if !isLoading {
measureSize(width, sizeToFit: sizeToFit)
display = true
}
if display {
self.view?.setFrameSize(self.size)
self.setNeedDisplay()
}
}
}
| 4e894bd0fed2ce62365e18e578751d18 | 46.085185 | 340 | 0.565327 | false | false | false | false |
eurofurence/ef-app_ios | refs/heads/release/4.0.0 | Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Objects/ExtendedDealerData.swift | mit | 1 | import Foundation
public struct ExtendedDealerData {
public var artistImagePNGData: Data?
public var dealersDenMapLocationGraphicPNGData: Data?
public var preferredName: String
public var alternateName: String?
public var categories: [String]
public var dealerShortDescription: String
public var isAttendingOnThursday: Bool
public var isAttendingOnFriday: Bool
public var isAttendingOnSaturday: Bool
public var isAfterDark: Bool
public var websiteName: String?
public var twitterUsername: String?
public var telegramUsername: String?
public var aboutTheArtist: String?
public var aboutTheArt: String?
public var artPreviewImagePNGData: Data?
public var artPreviewCaption: String?
public init(
artistImagePNGData: Data?,
dealersDenMapLocationGraphicPNGData: Data?,
preferredName: String,
alternateName: String?,
categories: [String],
dealerShortDescription: String,
isAttendingOnThursday: Bool,
isAttendingOnFriday: Bool,
isAttendingOnSaturday: Bool,
isAfterDark: Bool,
websiteName: String?,
twitterUsername: String?,
telegramUsername: String?,
aboutTheArtist: String?,
aboutTheArt: String?,
artPreviewImagePNGData: Data?,
artPreviewCaption: String?
) {
self.artistImagePNGData = artistImagePNGData
self.dealersDenMapLocationGraphicPNGData = dealersDenMapLocationGraphicPNGData
self.preferredName = preferredName
self.alternateName = alternateName
self.categories = categories
self.dealerShortDescription = dealerShortDescription
self.isAttendingOnThursday = isAttendingOnThursday
self.isAttendingOnFriday = isAttendingOnFriday
self.isAttendingOnSaturday = isAttendingOnSaturday
self.isAfterDark = isAfterDark
self.websiteName = websiteName
self.twitterUsername = twitterUsername
self.telegramUsername = telegramUsername
self.aboutTheArtist = aboutTheArtist
self.aboutTheArt = aboutTheArt
self.artPreviewImagePNGData = artPreviewImagePNGData
self.artPreviewCaption = artPreviewCaption
}
}
| 520b239ccd9219b21429fb034616d70e | 35.786885 | 86 | 0.717023 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/InputDataDateRowItem.swift | gpl-2.0 | 1 | //
// InputDataDateRowItem.swift
// Telegram
//
// Created by Mikhail Filimonov on 21/03/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import CalendarUtils
import TGModernGrowingTextView
import KeyboardKey
class InputDataDateRowItem: GeneralRowItem, InputDataRowDataValue {
fileprivate let placeholderLayout: TextViewLayout
fileprivate let dayHolderLayout: TextViewLayout
fileprivate let monthHolderLayout: TextViewLayout
fileprivate let yearHolderLayout: TextViewLayout
private let updated:()->Void
fileprivate var _value: InputDataValue {
didSet {
if _value != oldValue {
updated()
}
}
}
var value: InputDataValue {
return _value
}
init(_ initialSize: NSSize, stableId: AnyHashable, value: InputDataValue, error: InputDataValueError?, updated:@escaping()->Void, placeholder: String) {
self._value = value
self.updated = updated
placeholderLayout = TextViewLayout(.initialize(string: placeholder, color: theme.colors.text, font: .normal(.text)), maximumNumberOfLines: 1)
dayHolderLayout = TextViewLayout(.initialize(string: strings().inputDataDateDayPlaceholder1, color: theme.colors.text, font: .normal(.text)))
monthHolderLayout = TextViewLayout(.initialize(string: strings().inputDataDateMonthPlaceholder1, color: theme.colors.text, font: .normal(.text)))
yearHolderLayout = TextViewLayout(.initialize(string: strings().inputDataDateYearPlaceholder1, color: theme.colors.text, font: .normal(.text)))
dayHolderLayout.measure(width: .greatestFiniteMagnitude)
monthHolderLayout.measure(width: .greatestFiniteMagnitude)
yearHolderLayout.measure(width: .greatestFiniteMagnitude)
super.init(initialSize, height: 44, stableId: stableId, error: error)
_ = makeSize(initialSize.width, oldWidth: oldWidth)
}
override func makeSize(_ width: CGFloat, oldWidth: CGFloat) -> Bool {
let success = super.makeSize(width, oldWidth: oldWidth)
placeholderLayout.measure(width: 100)
return success
}
override func viewClass() -> AnyClass {
return InputDataDateRowView.self
}
}
final class InputDataDateRowView : GeneralRowView, TGModernGrowingDelegate {
private let placeholderTextView = TextView()
private let dayInput = TGModernGrowingTextView(frame: NSZeroRect)
private let monthInput = TGModernGrowingTextView(frame: NSZeroRect)
private let yearInput = TGModernGrowingTextView(frame: NSZeroRect)
private let firstSeparator = TextViewLabel()
private let secondSeparator = TextViewLabel()
private var ignoreChanges: Bool = false
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(placeholderTextView)
placeholderTextView.userInteractionEnabled = false
placeholderTextView.isSelectable = false
dayInput.delegate = self
monthInput.delegate = self
yearInput.delegate = self
dayInput.textFont = .normal(.text)
monthInput.textFont = .normal(.text)
yearInput.textFont = .normal(.text)
addSubview(dayInput)
addSubview(monthInput)
addSubview(yearInput)
firstSeparator.autosize = true
secondSeparator.autosize = true
addSubview(firstSeparator)
addSubview(secondSeparator)
}
public func maxCharactersLimit(_ textView: TGModernGrowingTextView!) -> Int32 {
switch true {
case textView === dayInput:
return 2
case textView === monthInput:
return 2
case textView === yearInput:
return 4
default:
return 0
}
}
func textViewHeightChanged(_ height: CGFloat, animated: Bool) {
var bp:Int = 0
bp += 1
}
func textViewSize(_ textView: TGModernGrowingTextView!) -> NSSize {
return textView.frame.size
}
func textViewEnterPressed(_ event:NSEvent) -> Bool {
if FastSettings.checkSendingAbility(for: event) {
return true
}
return false
}
func textViewIsTypingEnabled() -> Bool {
return true
}
func textViewNeedClose(_ textView: Any) {
}
func textViewTextDidChange(_ string: String) {
guard let item = item as? InputDataDateRowItem else {return}
guard !ignoreChanges else {return}
var day = String(dayInput.string().unicodeScalars.filter { CharacterSet.decimalDigits.contains($0)})
var month = String(monthInput.string().unicodeScalars.filter { CharacterSet.decimalDigits.contains($0)})
var year = String(yearInput.string().unicodeScalars.filter { CharacterSet.decimalDigits.contains($0)})
var _month:String?
var _year: String?
var _day: String?
if year.length == 4 {
year = "\(Int(year)!)"
_year = year
}
if month.length > 0 {
let _m = min(Int(month)!, 12)
if _m == 0 {
month = "0"
} else {
month = "\(month.length == 2 && _m < 10 ? "0\(_m)" : "\(_m)")"
}
_month = month == "0" ? nil : month
}
if day.length > 0 {
var _max:Int = 31
if let year = _year, let month = _month {
if let date = dateFormatter.date(from: "02.\(month).\(year)") {
_max = CalendarUtils.lastDay(ofTheMonth: date)
}
}
let _d = min(Int(day)!, _max)
if _d == 0 {
day = "0"
} else {
day = "\(day.length == 2 && _d < 10 ? "0\(_d)" : "\(_d)")"
}
_day = day == "0" ? nil : day
}
item._value = .date(_day != nil ? Int32(_day!) : nil, _month != nil ? Int32(_month!) : nil, _year != nil ? Int32(_year!) : nil)
dayInput.setString(day)
monthInput.setString(month)
yearInput.setString(year)
if month.length == 2, month.prefix(1) == "0" {
textViewDidReachedLimit(monthInput)
}
if day.length == 2, window?.firstResponder == dayInput.inputView {
textViewDidReachedLimit(dayInput)
}
if month.length == 2, window?.firstResponder == monthInput.inputView {
textViewDidReachedLimit(monthInput)
}
}
func textViewDidReachedLimit(_ textView: Any) {
if let responder = nextResponder() {
window?.makeFirstResponder(responder)
}
}
func controlTextDidChange(_ obj: Notification) {
}
func textViewTextDidChangeSelectedRange(_ range: NSRange) {
}
func textViewDidPaste(_ pasteboard: NSPasteboard) -> Bool {
return false
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
super.draw(layer, in: ctx)
guard let item = item as? InputDataDateRowItem else {return}
ctx.setFillColor(theme.colors.border.cgColor)
ctx.fill(NSMakeRect(item.inset.left, frame.height - .borderSize, frame.width - item.inset.left - item.inset.right, .borderSize))
}
override var mouseInsideField: Bool {
return yearInput._mouseInside() || dayInput._mouseInside() || monthInput._mouseInside()
}
override func hitTest(_ point: NSPoint) -> NSView? {
switch true {
case NSPointInRect(point, yearInput.frame):
return yearInput
case NSPointInRect(point, dayInput.frame):
return dayInput
case NSPointInRect(point, monthInput.frame):
return monthInput
default:
return super.hitTest(point)
}
}
override func hasFirstResponder() -> Bool {
return true
}
override var firstResponder: NSResponder? {
let isKeyDown = NSApp.currentEvent?.type == NSEvent.EventType.keyDown && NSApp.currentEvent?.keyCode == KeyboardKey.Tab.rawValue
switch true {
case yearInput._mouseInside() && !isKeyDown:
return yearInput.inputView
case dayInput._mouseInside() && !isKeyDown:
return dayInput.inputView
case monthInput._mouseInside() && !isKeyDown:
return monthInput.inputView
default:
switch true {
case yearInput.inputView == window?.firstResponder:
return yearInput.inputView
case dayInput.inputView == window?.firstResponder:
return dayInput.inputView
case monthInput.inputView == window?.firstResponder:
return monthInput.inputView
default:
return dayInput.inputView
}
}
}
override func nextResponder() -> NSResponder? {
if window?.firstResponder == dayInput.inputView {
return monthInput.inputView
}
if window?.firstResponder == monthInput.inputView {
return yearInput.inputView
}
return nil
}
override func layout() {
super.layout()
guard let item = item as? InputDataDateRowItem else {return}
placeholderTextView.setFrameOrigin(item.inset.left, 14)
let defaultLeftInset = item.inset.left + 100
dayInput.setFrameOrigin(defaultLeftInset, 15)
monthInput.setFrameOrigin(dayInput.frame.maxX + 8, 15)
yearInput.setFrameOrigin(monthInput.frame.maxX + 8, 15)
firstSeparator.setFrameOrigin(dayInput.frame.maxX - 7, 14)
secondSeparator.setFrameOrigin(monthInput.frame.maxX - 7, 14)
//
// dayPlaceholder.setFrameOrigin(defaultLeftInset, 14)
//
// monthPlaceholder.setFrameOrigin(defaultLeftInset, dayPlaceholder.frame.maxY + 5)
// monthSelector.setFrameOrigin(monthPlaceholder.frame.maxX + 3, monthPlaceholder.frame.minY - 3)
//
// yearPlaceholder.setFrameOrigin(defaultLeftInset, monthPlaceholder.frame.maxY + 5)
// yearSelector.setFrameOrigin(yearPlaceholder.frame.maxX + 3, yearPlaceholder.frame.minY - 3)
}
override func shakeView() {
guard let item = item as? InputDataDateRowItem else {return}
switch item.value {
case let .date(day, month, year):
if day == nil {
dayInput.shake()
}
if month == nil {
monthInput.shake()
}
if year == nil {
yearInput.shake()
}
if year != nil && month != nil && day != nil {
dayInput.shake()
monthInput.shake()
yearInput.shake()
}
default:
break
}
}
override func updateColors() {
placeholderTextView.backgroundColor = theme.colors.background
firstSeparator.backgroundColor = theme.colors.background
secondSeparator.backgroundColor = theme.colors.background
dayInput.textColor = theme.colors.text
monthInput.textColor = theme.colors.text
yearInput.textColor = theme.colors.text
dayInput.setBackgroundColor(backdorColor)
monthInput.setBackgroundColor(backdorColor)
yearInput.setBackgroundColor(backdorColor)
}
override func set(item: TableRowItem, animated: Bool) {
guard let item = item as? InputDataDateRowItem else {return}
placeholderTextView.update(item.placeholderLayout)
let dayLayout = TextViewLayout(.initialize(string: strings().inputDataDateDayPlaceholder1, color: theme.colors.grayText, font: .normal(.text)))
dayLayout.measure(width: .greatestFiniteMagnitude)
let monthLayout = TextViewLayout(.initialize(string: strings().inputDataDateMonthPlaceholder1, color: theme.colors.grayText, font: .normal(.text)))
monthLayout.measure(width: .greatestFiniteMagnitude)
let yearLayout = TextViewLayout(.initialize(string: strings().inputDataDateYearPlaceholder1, color: theme.colors.grayText, font: .normal(.text)))
yearLayout.measure(width: .greatestFiniteMagnitude)
dayInput.min_height = Int32(dayLayout.layoutSize.height)
dayInput.max_height = Int32(dayLayout.layoutSize.height)
dayInput.setFrameSize(NSMakeSize(dayLayout.layoutSize.width + 20, dayLayout.layoutSize.height))
monthInput.min_height = Int32(monthLayout.layoutSize.height)
monthInput.max_height = Int32(monthLayout.layoutSize.height)
monthInput.setFrameSize(NSMakeSize(monthLayout.layoutSize.width + 20, monthLayout.layoutSize.height))
yearInput.min_height = Int32(yearLayout.layoutSize.height)
yearInput.max_height = Int32(yearLayout.layoutSize.height)
yearInput.setFrameSize(NSMakeSize(yearLayout.layoutSize.width + 20, yearLayout.layoutSize.height))
firstSeparator.attributedString = .initialize(string: "/", color: theme.colors.text, font: .medium(.text))
secondSeparator.attributedString = .initialize(string: "/", color: theme.colors.text, font: .medium(.text))
firstSeparator.sizeToFit()
secondSeparator.sizeToFit()
ignoreChanges = true
switch item.value {
case let .date(day, month, year):
if let day = day {
dayInput.setString("\( day < 10 && day > 0 ? "\(day)" : "\(day)")", animated: false)
} else {
dayInput.setString("", animated: false)
}
if let month = month {
monthInput.setString("\( month < 10 && month > 0 ? "\(month)" : "\(month)")", animated: false)
} else {
monthInput.setString("", animated: false)
}
if let year = year {
yearInput.setString("\(year)", animated: false)
} else {
yearInput.setString("", animated: false)
}
default:
dayInput.setString("", animated: false)
monthInput.setString("", animated: false)
yearInput.setString("", animated: false)
}
ignoreChanges = false
dayInput.placeholderAttributedString = dayLayout.attributedString
monthInput.placeholderAttributedString = monthLayout.attributedString
yearInput.placeholderAttributedString = yearLayout.attributedString
super.set(item: item, animated: animated)
layout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| c9a9dcee06151adf34c1e7b605b5e259 | 34.411765 | 156 | 0.604718 | false | false | false | false |
Cunqi/CQPopupKit | refs/heads/master | CQPopupKit/PopupAppearance.swift | mit | 1 | //
// PopupAppearance.swift
// CQPopupViewController
//
// Created by Cunqi.X on 8/5/16.
// Copyright © 2016 Cunqi Xiao. All rights reserved.
//
import UIKit
/**
The position of containers
- center: The container has CenterX and CenterY equivalent with parent(aka. CQPopup.view)
- left: The container has CenterY and Leading equivalent with parent(aka. CQPopup.view)
- right: The container has CenterY and Trailing equivalent with parent(aka. CQPopup.view)
- top: The container has CenterX and Top equivalent with parent(aka. CQPopup.view)
- bottom: The container has CenterX and Bottom1980 equivalent with parent(aka. CQPopup.view)
*/
public enum AttachedPosition: Int {
case center = 0
case left = 1
case right = 2
case top = 3
case bottom = 4
}
/**
Popup transition animation style
- plain: Move without fade effect
- zoom: Zoom in and zoom out (Center direction ONLY)
- fade: Fade in and fade out
- bounce: Bounce in and bounce out
- custom: Custom implementation
*/
public enum PopupTransitionStyle: Int {
case plain = 0
case zoom = 1
case fade = 2
case bounce = 3
case custom = 4
}
/**
Popup transition animation direction
- leftToRight: From left to right
- rightToLeft: From right to left
- topToBottom: From top to bottom
- bottomToTop: From bottom to top
- center: Stay at center (For Zoom / Custom transition style ONLY!)
*/
public enum PopupTransitionDirection: Int {
case leftToRight = 0
case rightToLeft = 1
case topToBottom = 2
case bottomToTop = 3
case center = 4
case leftReverse = 5
case rightReverse = 6
}
/**
Current animation status of transition in / transition out
- transitIn: Transition in
- transitOut: Transition out
*/
public enum PopupAnimationStatus: Int {
case transitIn = 0
case transitOut = 1
}
/// CQPopupKit global appearance
open class CQAppearance: NSObject {
open static let appearance = CQAppearance()
/// Popup basic appearance
open var popup = PopupAppearance()
/// Popup animation appearance
open var animation = PopupAnimationAppearance()
/// Popup alert controller (alertView & actionSheet) appearance
open lazy var alert: PopupAlertControllerAppearance = {
return PopupAlertControllerAppearance()
}()
open lazy var dialogue: PopupDialogueAppearance = {
return PopupDialogueAppearance()
}()
// MARK: Initializer
/// For global appearance only
fileprivate override init(){}
}
/**
* Popup basic appearance
*/
public struct PopupAppearance {
/// Background color of pop up
public var popUpBackgroundColor = UIColor(white: 0, alpha: 0.5)
/// If true tap outside of the container will dismiss the popup, otherwise false, default is `true`
public var enableTouchOutsideToDismiss: Bool = true
/// Position of container, default is `Center`
public var viewAttachedPosition: AttachedPosition = .center
/// Padding space between container and popup's view, default is `UIEdgeInsetsZero`
public var containerPadding = UIEdgeInsets.zero
/// Control the width of container, maximum is 1.0, means container width equals to popup view width, default is `1.0`
public var widthMultiplier: CGFloat = 0.8
/// Control the width of container with fixed width value
public var popupWidth: CGFloat {
get {
return widthMultiplier * UIScreen.main.bounds.width
}
set {
widthMultiplier = newValue / UIScreen.main.bounds.width
}
}
/// Control the width of container, if this property is not 0, the width will always be fixed width in all orientation
public var fixedWidth: CGFloat = 0
/// Control the height of container, if this property is not 0, the height will always be fixed width in all orientation
public var fixedHeight: CGFloat = 0
/// Control the height of container, maximum is 1.0, means container height equals to popup view height, default is `1.0`
public var heightMultiplier: CGFloat = 0.8
/// Control the height of container with fixed height value
public var popupHeight: CGFloat {
get {
return heightMultiplier * UIScreen.main.bounds.height
}
set {
heightMultiplier = newValue / UIScreen.main.bounds.height
}
}
/// should auto rotate
public var autoRotate: Bool = false
/// Corner radius of container, default is `10`
public var cornerRadius: CGFloat = 8
/// Container's background color, default is `White`
public var containerBackgroundColor = UIColor.white
/// Container's border width, default is `0` (no border)
public var borderWidth: CGFloat = 0
/// Container's border color, (if border width is not 0)
public var borderColor = UIColor.init(white: 0.9, alpha: 1.0)
/// If true container will render shadow, otherwise, false, default is `true`
public var enableShadow = true
/// Container shadow radius, default is `3`
public var shadowRadius: CGFloat = 3
/// Container shadow opacity, default is `0.4`
public var shadowOpacity: CGFloat = 0.4
/// Container shadow offset, default is `(0.5, 0.5)`
public var shadowOffset = CGSize(width: 0.5, height: 0.5)
/// Container shadow color, default is `white`s
public var shadowColor = UIColor.darkGray
}
/**
* Popup animation appearance
*/
public struct PopupAnimationAppearance {
/// Popup transition style
public var transitionStyle: PopupTransitionStyle = .fade
/// Popup transition direction
public var transitionDirection: PopupTransitionDirection = .leftToRight
/// Popup transition in time duration
public var transitionInDuration: TimeInterval = 0.4
/// Popup transition out time duration
public var transitionOutDuration: TimeInterval = 0.2
}
/**
* Popup alert controller appearance
*/
public struct PopupAlertControllerAppearance {
/// Font of title
public var titleFont = UIFont.systemFont(ofSize: 18)
/// Font of message
public var messageFont = UIFont.systemFont(ofSize: 14)
/// Horizontal space(for left and right)
public var horizontalSpace: CGFloat = 16
/// Vertical space(for title and top of the view)
public var verticalSpaceBetweenTitleAndTop: CGFloat = 18
/// Vertical space(for title and message)
public var verticalSpaceBetweenTitleAndMessage: CGFloat = 8
/// Vertical space(for message and buttons)
public var verticalSpaceBetweenMessageAndButtons: CGFloat = 12
/// Height of alert button
public var alertButtonHeight: CGFloat = 44
/// Font of plain button
public var plainButtonFont = UIFont.systemFont(ofSize: 14)
/// Title color of plain button
public var plainButtonTitleColor = UIColor(red: 0.25, green: 0.53, blue: 0.91, alpha: 1)
/// Background color of plain button
public var plainButtonBackgroundColor = UIColor.white
/// Font of cancel button
public var cancelButtonFont = UIFont.boldSystemFont(ofSize: 14)
/// Title color of cancel button
public var cancelButtonTitleColor = UIColor(white: 0.4, alpha: 1)
/// Background color of cancel button
public var cancelButtonBackgroundColor = UIColor.white
/// If true buttons separator will be rendered, otherwise, false
public var enableButtonSeparator = true
/// Color of button separator
public var buttonSeparatorColor = UIColor(white: 0.9, alpha: 1.0)
}
/**
* Popup dialogue appearance
*/
public struct PopupDialogueAppearance {
/// Navigation bar background color
public var navBarBackgroundColor = UIColor(white: 0.97, alpha: 1.0)
/// Navigation title font
public var titleFont = UIFont.boldSystemFont(ofSize: 18)
/// Navigation title color
public var titleColor = UIColor.black
/// Navigation bottom separator color
public var separatorColor = UIColor(white: 0.8, alpha: 1.0)
}
| a8a8b2e5e3f3c6de338a1d06d78d9619 | 28.509506 | 123 | 0.718206 | false | false | false | false |
HenvyLuk/BabyGuard | refs/heads/master | testSwift/testSwift/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// testSwift
//
// Created by csh on 16/7/4.
// Copyright © 2016年 csh. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.sjgz.testSwift" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("testSwift", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 3f4280694f09ba50da60b3c3927dc8e3 | 53.720721 | 291 | 0.718966 | false | false | false | false |
BirdBrainTechnologies/Hummingbird-iOS-Support | refs/heads/master | BirdBlox/BirdBlox/SharedUtilities.swift | mit | 1 | //
// SharedUtilities.swift
// BirdBlox
//
// Created by birdbrain on 4/3/17.
// Copyright © 2017 Birdbrain Technologies LLC. All rights reserved.
//
// This file provides utility functions for converting and bounding data
//
import Foundation
import GLKit
/**
Takes an int and returns the unicode value for the int as a string
*/
public func getUnicode(_ num: UInt8) -> UInt8{
let scalars = String(num).unicodeScalars
return UInt8(scalars[scalars.startIndex].value)
}
/**
Gets the unicode value for a character
*/
public func getUnicode(_ char: Character) -> UInt8{
let scalars = String(char).unicodeScalars
var val = scalars[scalars.startIndex].value
if val > 255 {
NSLog("Unicode for character \(char) not supported.")
val = 254
}
return UInt8(val)
}
/**
Takes a string and splits it into a byte array with end of line characters
at the end
*/
public func StringToCommand(_ phrase: String) -> Data{
var result: [UInt8] = []
for character in phrase.utf8{
result.append(character)
}
result.append(0x0D)
result.append(0x0A)
return Data(bytes: UnsafePointer<UInt8>(result), count: result.count)
}
/**
Takes a string and splits it into a byte array
*/
public func StringToCommandNoEOL(_ phrase: String) -> Data{
var result: [UInt8] = []
for character in phrase.utf8{
result.append(character)
}
return Data(bytes: UnsafePointer<UInt8>(result), count: result.count)
}
/**
Bounds a UInt8 with a min and max value
*/
public func bound(_ value: UInt8, min: UInt8, max: UInt8) -> UInt8 {
var new_value = value < min ? min : value
new_value = value > max ? max : value
return new_value
}
/**
Bounds an Int with a min and max value
*/
public func bound(_ value: Int, min: Int, max: Int) -> Int {
var new_value = value < min ? min : value
new_value = value > max ? max : value
return new_value
}
/**
Converts an int to a UInt8 by bounding it to the range of a UInt8
*/
public func toUInt8(_ value: Int) -> UInt8 {
var new_value = value < 0 ? 0 : value
new_value = value > 255 ? 255 : value
return UInt8(new_value)
}
/**
Find the mode (most frequent value) of an NSNumber array
Failure returns 0
*/
public func mode(_ array: [NSNumber]) -> NSNumber {
var counts = [NSNumber: Int]()
array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
if let (value, _) = counts.max(by: {$0.1 < $1.1}) {
//return (value, count)
return value
}
return 0 //TODO: ?
}
//MARK: data Conversions
/**
* Convert a byte of data into an array of bits
*/
func byteToBits(_ byte: UInt8) -> [UInt8] {
var byte = byte
var bits = [UInt8](repeating: 0, count: 8)
for i in 0..<8 {
let currentBit = byte & 0x01
if currentBit != 0 {
bits[i] = 1
}
byte >>= 1
}
return bits
}
/**
* Convert an array of bits into a byte of data
*/
func bitsToByte(_ bits: [UInt8]) -> UInt8? {
var string = ""
for bit in bits {
string += String(bit)
}
return UInt8(string, radix: 2) ?? nil
}
/**
Converts a raw value from a robot into a temperature
*/
public func rawToTemp(_ raw_val: UInt8) -> Int{
//print("hi")
let temp: Int = Int(floor(((Double(raw_val) - 127.0)/2.4 + 25) * 100 / 100));
//print("ho")
return temp
}
/**
* Converts a raw value from a robot into a distance
* For use only with Hummingbird Duo distance sensors
*/
public func rawToDistance(_ raw_val: UInt8) -> Int{
var reading: Double = Double(raw_val) * 4.0
if(reading < 130){
return 100
}
else{//formula based on mathematical regression
reading = reading - 120.0
if(reading > 680.0){
return 5
}
else{
let sensor_val_square = reading * reading
let distance: Double = sensor_val_square * sensor_val_square * reading * -0.000000000004789 + sensor_val_square * sensor_val_square * 0.000000010057143 - sensor_val_square * reading * 0.000008279033021 + sensor_val_square * 0.003416264518201 - reading * 0.756893112198934 + 90.707167605683000;
return Int(distance)
}
}
}
/**
Converts a raw value from a robot into a voltage
*/
public func rawToVoltage(_ raw_val: UInt8) -> Double {
return Double(raw_val) * 0.0406
//return Int(floor((100.0 * Double(raw_val) / 51.0) / 100))
}
/**
Converts a raw value from a robot into a sound value
*/
public func rawToSound(_ raw_val: UInt8) -> Int{
return Int(raw_val)
}
/**
Converts a raw value from a robot into a percentage
*/
public func rawToPercent(_ raw_val: UInt8) -> Int{
return Int(floor(Double(raw_val)/2.55))
}
/**
Converts a percentage value into a raw value from a robot
*/
public func percentToRaw(_ percent_val: UInt8) -> UInt8{
return toUInt8(Int(floor(Double(percent_val) * 2.55)))
}
/**
* Convert raw value into a scaled magnetometer value
*/
public func rawToMagnetometer(_ msb: UInt8, _ lsb: UInt8) -> Int {
let scaledVal = rawToRawMag(msb, lsb) * 0.1 //scaling to put in units of uT
return Int(scaledVal.rounded())
}
public func rawToRawMag(_ msb: UInt8, _ lsb: UInt8) -> Double {
let uIntVal = (UInt16(msb) << 8) | UInt16(lsb)
let intVal = Int16(bitPattern: uIntVal)
return Double(intVal)
}
/**
* Convert raw value into a scaled accelerometer value
*/
public func rawToAccelerometer(_ raw_val: UInt8) -> Double {
let intVal = Int8(bitPattern: raw_val) //convert to 2's complement signed int
let scaledVal = Double(intVal) * 196/1280 //scaling from bambi
return scaledVal
}
/**
* Convert raw sensor values into a compass value
*/
public func rawToCompass(rawAcc: [UInt8], rawMag: [UInt8]) -> Int? {
//Compass value is undefined in the case of 0 z direction acceleration
if rawAcc[2] == 0 {
return nil
}
let mx = rawToRawMag(rawMag[0], rawMag[1])
let my = rawToRawMag(rawMag[2], rawMag[3])
let mz = rawToRawMag(rawMag[4], rawMag[5])
let ax = Double(Int8(bitPattern: rawAcc[0]))
let ay = Double(Int8(bitPattern: rawAcc[1]))
let az = Double(Int8(bitPattern: rawAcc[2]))
let phi = atan(-ay/az)
let theta = atan( ax / (ay*sin(phi) + az*cos(phi)) )
let xP = mx
let yP = my * cos(phi) - mz * sin(phi)
let zP = my * sin(phi) + mz * cos(phi)
let xPP = xP * cos(theta) + zP * sin(theta)
let yPP = yP
let angle = 180 + GLKMathRadiansToDegrees(Float(atan2(xPP, yPP)))
let roundedAngle = Int(angle.rounded())
return roundedAngle
}
/**
Converts the boards GAP name to a kid friendly name for the UI to display
Returns nil if the input name is malformed
*/
public func BBTkidNameFromMacSuffix(_ deviceName: String) -> String? {
// let deviceName = deviceNameS.utf8
//The name should be seven characters, with the first two identifying the type of device
//The last five characters should be from the device's MAC address
if deviceName.utf8.count == 7,
let namesPath = Bundle.main.path(forResource: "BluetoothDeviceNames", ofType: "plist"),
let namesDict = NSDictionary(contentsOfFile: namesPath),
let mac = Int(deviceName[deviceName.index(deviceName.startIndex,
offsetBy: 2)..<deviceName.endIndex], radix: 16) {
guard let namesDict = namesDict as? Dictionary<String, Array<String>>,
let firstNames = namesDict["first_names"], let middleNames = namesDict["middle_names"],
let lastNames = namesDict["last_names"], let badNames = namesDict["bad_names"] else {
NSLog("Could not load name dictionary.")
return nil
}
// grab bits from the MAC address (6 bits, 6 bits, 8 bits => last, middle, first)
// (5 digis of mac address is 20 bits) llllllmmmmmmffffffff
let macNumber = mac
let offset = (macNumber & 0xFF) % 16
let firstIndex = ((macNumber & 0xFF) + offset) % firstNames.count
var middleIndex = (((macNumber >> 8) & 0b111111) + offset) % middleNames.count
let lastIndex = (((macNumber >> (8+6)) & 0b111111) + offset) % lastNames.count
var name: String?
var abbreviatedName = ""
repeat {
let firstName = firstNames[firstIndex]
let middleName = middleNames[middleIndex]
let lastName = lastNames[lastIndex]
abbreviatedName = String(firstName.prefix(1) + middleName.prefix(1) + lastName.prefix(1))
name = firstName + " " + middleName + " " + lastName
print("\(deviceName) \(mac) \(firstIndex), \(middleIndex), \(lastIndex); \(abbreviatedName) \(name ?? "?")")
//if the abbreviation is in the bad words list, move to the next middle name
middleIndex = (middleIndex + 1) % middleNames.count
print(middleIndex)
} while badNames.contains(abbreviatedName)
return name
}
NSLog("Unable to parse GAP Name \"\(deviceName)\"")
return nil
}
func BBTgetDeviceNameForGAPName(_ gap: String) -> String {
if let kidName = BBTkidNameFromMacSuffix(gap) {
return kidName
}
//TODO: If the GAP name is the default hummingbird name, then grab the MAC address,
//set the GAP name to "HB\(last 5 of MAC)", and use that to generate a kid name
//Enter command mode with +++
//Get MAC address with AT+BLEGETADDR
//Set name with AT+GAPDEVNAME=BLEFriend
//Reset device with ATZ
return gap
}
/**
Converts an array of queries (such as the one we get from swifter) into a dictionary with
the parameters as keys and values as values.
There are so few parameters that a parallel version is not worth it.
*/
public func BBTSequentialQueryArrayToDict
(_ queryArray: Array<(String, String)>) -> Dictionary<String, String> {
var dict = [String: String]()
for (k, v) in queryArray {
dict[k] = v
}
return dict
}
struct FixedLengthArray<T: Equatable>: Equatable {
private var array: Array<T>
let length: Int
init(_ from: Array<T>) {
array = from
length = from.count
}
init(length: UInt, repeating: T) {
let arr = Array<T>(repeating: repeating, count: Int(length))
self.init(arr)
}
subscript (index: Int) -> T {
get {
return self.array[index]
}
set(value) {
self.array[index] = value
}
}
static func ==(inLeft: FixedLengthArray, inRight: FixedLengthArray) -> Bool {
return (inLeft.length == inRight.length) && (inLeft.array == inRight.array)
}
}
/**
Converts a note number to a period in microseconds (us)
See: https://newt.phys.unsw.edu.au/jw/notes.html
fm = (2^((m−69)/12))(440 Hz)
*/
public func noteToPeriod(_ note: UInt8) -> UInt16? {
let frequency = 440 * pow(Double(2), Double((Double(note) - 69)/12))
let period = (1/frequency) * 1000000
if period > 0 && period <= Double(UInt16.max) {
return UInt16(period)
} else {
return nil
}
}
enum BatteryStatus: Int {
case red = 0, yellow, green
}
enum BBTrobotConnectStatus {
case oughtToBeConnected, shouldBeDisconnected, attemptingConnection
}
| c3f50fa3452aff9be281a6263fb49233 | 27.567775 | 305 | 0.634288 | false | false | false | false |
marty-suzuki/QiitaWithFluxSample | refs/heads/master | Carthage/Checkouts/SwiftyUserDefaults/Tests/SwiftyUserDefaultsTests.swift | mit | 1 | import XCTest
@testable import SwiftyUserDefaults
class SwiftyUserDefaultsTests: XCTestCase {
override func setUp() {
// clear defaults before testing
for (key, _) in Defaults.dictionaryRepresentation() {
Defaults.removeObject(forKey: key)
}
super.tearDown()
}
func testNone() {
let key = "none"
XCTAssertNil(Defaults[key].string)
XCTAssertNil(Defaults[key].int)
XCTAssertNil(Defaults[key].double)
XCTAssertNil(Defaults[key].bool)
XCTAssertFalse(Defaults.hasKey(key))
//Return default value if doesn't exist
XCTAssertEqual(Defaults[key].stringValue, "")
XCTAssertEqual(Defaults[key].intValue, 0)
XCTAssertEqual(Defaults[key].doubleValue, 0)
XCTAssertEqual(Defaults[key].boolValue, false)
XCTAssertEqual(Defaults[key].arrayValue.count, 0)
XCTAssertEqual(Defaults[key].dictionaryValue.keys.count, 0)
XCTAssertEqual(Defaults[key].dataValue, Data())
}
func testString() {
// set and read
let key = "string"
let key2 = "string2"
Defaults[key] = "foo"
XCTAssertEqual(Defaults[key].string!, "foo")
XCTAssertNil(Defaults[key].int)
XCTAssertNil(Defaults[key].double)
XCTAssertNil(Defaults[key].bool)
// existance
XCTAssertTrue(Defaults.hasKey(key))
// removing
Defaults.remove(key)
XCTAssertFalse(Defaults.hasKey(key))
Defaults[key2] = nil
XCTAssertFalse(Defaults.hasKey(key2))
}
func testInt() {
// set and read
let key = "int"
Defaults[key] = 100
XCTAssertEqual(Defaults[key].string!, "100")
XCTAssertEqual(Defaults[key].int!, 100)
XCTAssertEqual(Defaults[key].double!, 100)
XCTAssertTrue(Defaults[key].bool!)
}
func testDouble() {
// set and read
let key = "double"
Defaults[key] = 3.14
XCTAssertEqual(Defaults[key].string!, "3.14")
XCTAssertEqual(Defaults[key].int!, 3)
XCTAssertEqual(Defaults[key].double!, 3.14)
XCTAssertTrue(Defaults[key].bool!)
XCTAssertEqual(Defaults[key].stringValue, "3.14")
XCTAssertEqual(Defaults[key].intValue, 3)
XCTAssertEqual(Defaults[key].doubleValue, 3.14)
XCTAssertEqual(Defaults[key].boolValue, true)
}
func testBool() {
// set and read
let key = "bool"
Defaults[key] = true
XCTAssertEqual(Defaults[key].string!, "1")
XCTAssertEqual(Defaults[key].int!, 1)
XCTAssertEqual(Defaults[key].double!, 1.0)
XCTAssertTrue(Defaults[key].bool!)
Defaults[key] = false
XCTAssertEqual(Defaults[key].string!, "0")
XCTAssertEqual(Defaults[key].int!, 0)
XCTAssertEqual(Defaults[key].double!, 0.0)
XCTAssertFalse(Defaults[key].bool!)
// existance
XCTAssertTrue(Defaults.hasKey(key))
}
func testData() {
let key = "data"
let data = "foo".data(using: .utf8, allowLossyConversion: false)!
Defaults[key] = data
XCTAssertEqual(Defaults[key].data!, data)
XCTAssertNil(Defaults[key].string)
XCTAssertNil(Defaults[key].int)
}
func testDate() {
let key = "date"
let date = Date()
Defaults[key] = date
XCTAssertEqual(Defaults[key].date!, date)
}
func testArray() {
let key = "array"
let array = [1, 2, "foo", true] as [Any]
Defaults[key] = array
let array2 = Defaults[key].array!
XCTAssertEqual(array2[0] as? Int, 1)
XCTAssertEqual(array2[1] as? Int, 2)
XCTAssertEqual(array2[2] as? String, "foo")
XCTAssertEqual(array2[3] as? Bool, true)
}
func testDict() {
let key = "dict"
let dict: [String: Any] = ["foo": 1, "bar": [1, 2, 3]]
Defaults[key] = dict
let dict2 = Defaults[key].dictionary!
XCTAssertEqual(dict2["foo"] as? Int, 1)
XCTAssertEqual((dict2["bar"] as? [Int])?.count, 3)
}
// --
@available(*, deprecated:1)
func testOperatorsInt() {
// +=
let key2 = "int2"
Defaults[key2] = 5
Defaults[key2] += 2
XCTAssertEqual(Defaults[key2].int!, 7)
let key3 = "int3"
Defaults[key3] += 2
XCTAssertEqual(Defaults[key3].int!, 2)
let key4 = "int4"
Defaults[key4] = "NaN"
Defaults[key4] += 2
XCTAssertEqual(Defaults[key4].int!, 2)
// ++
Defaults[key2]++
Defaults[key2]++
XCTAssertEqual(Defaults[key2].int!, 9)
let key5 = "int5"
Defaults[key5]++
XCTAssertEqual(Defaults[key5].int!, 1)
}
@available(*, deprecated:1)
func testOperatorsDouble() {
let key = "double"
Defaults[key] = 3.14
Defaults[key] += 1.5
XCTAssertEqual(Int(Defaults[key].double! * 100.0), 464)
let key2 = "double2"
Defaults[key2] = 3.14
Defaults[key2] += 1
XCTAssertEqual(Defaults[key2].double!, 4.0)
let key3 = "double3"
Defaults[key3] += 5.3
XCTAssertEqual(Defaults[key3].double!, 5.3)
}
@available(*, deprecated:1)
func testHuhEquals() {
// set and read
let key = "string"
Defaults[key] = "foo"
// ?=
Defaults[key] ?= "bar"
XCTAssertEqual(Defaults[key].string!, "foo")
let key2 = "string2"
Defaults[key2] ?= "bar"
XCTAssertEqual(Defaults[key2].string!, "bar")
Defaults[key2] ?= "baz"
XCTAssertEqual(Defaults[key2].string!, "bar")
}
// --
func testRemoveAll() {
Defaults["a"] = "test"
Defaults["b"] = "test2"
let count = Defaults.dictionaryRepresentation().count
XCTAssert(!Defaults.dictionaryRepresentation().isEmpty)
Defaults.removeAll()
XCTAssert(!Defaults.hasKey("a"))
XCTAssert(!Defaults.hasKey("b"))
// We'll still have the system keys present, but our two keys should be gone
XCTAssert(Defaults.dictionaryRepresentation().count == count - 2)
}
func testAnySubscriptGetter() {
// This should just return the Proxy value as Any
// Tests if it doesn't fall into infinite loop
let anyProxy: Any? = Defaults["test"]
XCTAssert(anyProxy is NSUserDefaults.Proxy)
// This also used to fall into infinite loop
XCTAssert(Defaults["test"] != nil)
}
// --
func testStaticStringOptional() {
let key = DefaultsKey<String?>("string")
XCTAssert(!Defaults.hasKey("string"))
XCTAssert(Defaults[key] == nil)
Defaults[key] = "foo"
XCTAssert(Defaults[key] == "foo")
XCTAssert(Defaults.hasKey("string"))
}
func testStaticString() {
let key = DefaultsKey<String>("string")
XCTAssert(Defaults[key] == "")
Defaults[key] = "foo"
Defaults[key] += "bar"
XCTAssert(Defaults[key] == "foobar")
}
func testStaticIntOptional() {
let key = DefaultsKey<Int?>("int")
XCTAssert(Defaults[key] == nil)
Defaults[key] = 10
XCTAssert(Defaults[key] == 10)
}
func testStaticInt() {
let key = DefaultsKey<Int>("int")
XCTAssert(Defaults[key] == 0)
Defaults[key] += 10
XCTAssert(Defaults[key] == 10)
}
func testStaticDoubleOptional() {
let key = DefaultsKey<Double?>("double")
XCTAssertNil(Defaults[key])
Defaults[key] = 10
XCTAssert(Defaults[key] == 10.0)
}
func testStaticDouble() {
let key = DefaultsKey<Double>("double")
XCTAssertEqual(Defaults[key], 0)
Defaults[key] = 2.14
Defaults[key] += 1
XCTAssertEqual(Defaults[key], 3.14)
}
func testStaticBoolOptional() {
let key = DefaultsKey<Bool?>("bool")
XCTAssert(Defaults[key] == nil)
Defaults[key] = true
XCTAssert(Defaults[key] == true)
Defaults[key] = false
XCTAssert(Defaults[key] == false)
}
func testStaticBool() {
let key = DefaultsKey<Bool>("bool")
XCTAssert(!Defaults.hasKey("bool"))
XCTAssert(Defaults[key] == false)
Defaults[key] = true
XCTAssert(Defaults[key] == true)
Defaults[key] = false
XCTAssert(Defaults[key] == false)
}
func testStaticAnyObject() {
let key = DefaultsKey<Any?>("object")
XCTAssert(Defaults[key] == nil)
Defaults[key] = "foo"
XCTAssert(Defaults[key] as? String == "foo")
Defaults[key] = 10
XCTAssert(Defaults[key] as? Int == 10)
Defaults[key] = Date.distantPast
XCTAssert(Defaults[key] as? Date == .distantPast)
}
func testStaticDataOptional() {
let key = DefaultsKey<Data?>("data")
XCTAssert(Defaults[key] == nil)
let data = "foobar".data(using: .utf8)!
Defaults[key] = data
XCTAssert(Defaults[key] == data)
}
func testStaticData() {
let key = DefaultsKey<Data>("data")
XCTAssert(Defaults[key] == Data())
let data = "foobar".data(using: .utf8)!
Defaults[key] = data
XCTAssert(Defaults[key] == data)
}
func testStaticDate() {
let key = DefaultsKey<Date?>("date")
XCTAssert(Defaults[key] == nil)
Defaults[key] = .distantPast
XCTAssert(Defaults[key] == .distantPast)
let now = Date()
Defaults[key] = now
XCTAssert(Defaults[key] == now)
}
func testStaticURL() {
let key = DefaultsKey<URL?>("url")
XCTAssert(Defaults[key] == nil)
Defaults[key] = URL(string: "https://github.com")
XCTAssert(Defaults[key]! == URL(string: "https://github.com"))
Defaults["url"] = "~/Desktop"
XCTAssert(Defaults[key]! == URL(fileURLWithPath: ("~/Desktop" as NSString).expandingTildeInPath))
}
func testStaticDictionaryOptional() {
let key = DefaultsKey<[String: Any]?>("dictionary")
XCTAssert(Defaults[key] == nil)
Defaults[key] = ["foo": "bar", "bar": 123, "baz": Data()]
XCTAssert(Defaults[key]! as NSDictionary == ["foo": "bar", "bar": 123, "baz": Data()])
}
func testStaticDictionary() {
let key = DefaultsKey<[String: Any]>("dictionary")
XCTAssert(Defaults[key] as NSDictionary == [:])
Defaults[key] = ["foo": "bar", "bar": 123, "baz": Data()]
XCTAssert(Defaults[key] as NSDictionary == ["foo": "bar", "bar": 123, "baz": Data()])
Defaults[key]["lol"] = Date.distantFuture
XCTAssert(Defaults[key]["lol"] as! Date == .distantFuture)
Defaults[key]["lol"] = nil
Defaults[key]["baz"] = nil
XCTAssert(Defaults[key] as NSDictionary == ["foo": "bar", "bar": 123])
}
// --
func testStaticArrayOptional() {
let key = DefaultsKey<[Any]?>("array")
XCTAssert(Defaults[key] == nil)
Defaults[key] = []
XCTAssertEqual(Defaults[key]?.count, 0)
Defaults[key] = [1, "foo", Data()]
XCTAssertEqual(Defaults[key]?.count, 3)
XCTAssertEqual(Defaults[key]?[0] as? Int, 1)
XCTAssertEqual(Defaults[key]?[1] as? String, "foo")
XCTAssertEqual(Defaults[key]?[2] as? Data, Data())
}
func testStaticArray() {
let key = DefaultsKey<[Any]>("array")
XCTAssertEqual(Defaults[key].count, 0)
Defaults[key].append(1)
Defaults[key].append("foo")
Defaults[key].append(Data())
XCTAssertEqual(Defaults[key].count, 3)
XCTAssertEqual(Defaults[key][0] as? Int, 1)
XCTAssertEqual(Defaults[key][1] as? String, "foo")
XCTAssertEqual(Defaults[key][2] as? Data, Data())
}
// --
func testStaticStringArrayOptional() {
let key = DefaultsKey<[String]?>("strings")
XCTAssert(Defaults[key] == nil)
Defaults[key] = ["foo", "bar"]
Defaults[key]?.append("baz")
XCTAssert(Defaults[key]! == ["foo", "bar", "baz"])
// bad types
Defaults["strings"] = [1, 2, false, "foo"]
XCTAssert(Defaults[key] == nil)
}
func testStaticStringArray() {
let key = DefaultsKey<[String]>("strings")
XCTAssert(Defaults[key] == [])
Defaults[key] = ["foo", "bar"]
Defaults[key].append("baz")
XCTAssert(Defaults[key] == ["foo", "bar", "baz"])
// bad types
Defaults["strings"] = [1, 2, false, "foo"]
XCTAssert(Defaults[key] == [])
}
func testStaticIntArrayOptional() {
let key = DefaultsKey<[Int]?>("ints")
XCTAssert(Defaults[key] == nil)
Defaults[key] = [1, 2, 3]
XCTAssert(Defaults[key]! == [1, 2, 3])
}
func testStaticIntArray() {
let key = DefaultsKey<[Int]>("ints")
XCTAssert(Defaults[key] == [])
Defaults[key] = [3, 2, 1]
Defaults[key].sort()
XCTAssert(Defaults[key] == [1, 2, 3])
}
func testStaticDoubleArrayOptional() {
let key = DefaultsKey<[Double]?>("doubles")
XCTAssert(Defaults[key] == nil)
Defaults[key] = [1.1, 2.2, 3.3]
XCTAssert(Defaults[key]! == [1.1, 2.2, 3.3])
}
func testStaticDoubleArray() {
let key = DefaultsKey<[Double]>("doubles")
XCTAssert(Defaults[key] == [])
Defaults[key] = [1.1, 2.2, 3.3]
XCTAssert(Defaults[key] == [1.1, 2.2, 3.3])
}
func testStaticBoolArrayOptional() {
let key = DefaultsKey<[Bool]?>("bools")
XCTAssert(Defaults[key] == nil)
Defaults[key] = [true, false, true]
XCTAssert(Defaults[key]! == [true, false, true])
}
func testStaticBoolArray() {
let key = DefaultsKey<[Bool]>("bools")
XCTAssert(Defaults[key] == [])
Defaults[key] = [true, false, true]
XCTAssert(Defaults[key] == [true, false, true])
}
func testStaticDataArrayOptional() {
let key = DefaultsKey<[Data]?>("datas")
XCTAssert(Defaults[key] == nil)
let data = "foobar".data(using: .utf8)!
Defaults[key] = [data, Data()]
XCTAssert(Defaults[key]! == [data, Data()])
}
func testStaticDataArray() {
let key = DefaultsKey<[Data]>("datas")
XCTAssert(Defaults[key] == [])
Defaults[key] = [Data()]
XCTAssert(Defaults[key] == [Data()])
}
func testStaticDateArrayOptional() {
let key = DefaultsKey<[Date]?>("dates")
XCTAssert(Defaults[key] == nil)
Defaults[key] = [.distantFuture]
XCTAssert(Defaults[key]! == [.distantFuture])
}
func testStaticDateArray() {
let key = DefaultsKey<[Date]>("dates")
XCTAssert(Defaults[key] == [])
Defaults[key] = [.distantFuture]
XCTAssert(Defaults[key] == [.distantFuture])
}
func testShortcutsAndExistence() {
XCTAssert(Defaults[.strings] == [])
XCTAssert(!Defaults.hasKey(.strings))
Defaults[.strings] = []
XCTAssert(Defaults[.strings] == [])
XCTAssert(Defaults.hasKey(.strings))
Defaults.remove(.strings)
XCTAssert(Defaults[.strings] == [])
XCTAssert(!Defaults.hasKey(.strings))
}
func testShortcutsAndExistence2() {
XCTAssert(Defaults[.optStrings] == nil)
XCTAssert(!Defaults.hasKey(.optStrings))
Defaults[.optStrings] = []
XCTAssert(Defaults[.optStrings]! == [])
XCTAssert(Defaults.hasKey(.optStrings))
Defaults[.optStrings] = nil
XCTAssert(Defaults[.optStrings] == nil)
XCTAssert(!Defaults.hasKey(.optStrings))
}
// --
func testArchiving() {
let key = DefaultsKey<NSColor?>("color")
XCTAssert(Defaults[key] == nil)
Defaults[key] = .white
XCTAssert(Defaults[key]! == NSColor.white)
Defaults[key] = nil
XCTAssert(Defaults[key] == nil)
}
func testArchiving2() {
let key = DefaultsKey<NSColor>("color")
XCTAssert(!Defaults.hasKey(key))
XCTAssert(Defaults[key] == NSColor.white)
Defaults[key] = .black
XCTAssert(Defaults[key] == NSColor.black)
}
func testArchiving3() {
let key = DefaultsKey<[NSColor]>("colors")
XCTAssert(Defaults[key] == [])
Defaults[key] = [.black]
Defaults[key].append(.white)
Defaults[key].append(.red)
XCTAssert(Defaults[key] == [.black, .white, .red])
}
// --
func testEnumArchiving() {
let key = DefaultsKey<TestEnum?>("enum")
XCTAssert(Defaults[key] == nil)
Defaults[key] = .A
XCTAssert(Defaults[key]! == .A)
Defaults[key] = .C
XCTAssert(Defaults[key]! == .C)
Defaults[key] = nil
XCTAssert(Defaults[key] == nil)
}
func testEnumArchiving2() {
let key = DefaultsKey<TestEnum>("enum")
XCTAssert(!Defaults.hasKey(key))
XCTAssert(Defaults[key] == .A)
Defaults[key] = .C
XCTAssert(Defaults[key] == .C)
Defaults.remove(key)
XCTAssert(!Defaults.hasKey(key))
XCTAssert(Defaults[key] == .A)
}
func testEnumArchiving3() {
let key = DefaultsKey<TestEnum2?>("enum")
XCTAssert(Defaults[key] == nil)
Defaults[key] = .ten
XCTAssert(Defaults[key]! == .ten)
Defaults[key] = .thirty
XCTAssert(Defaults[key]! == .thirty)
Defaults[key] = nil
XCTAssert(Defaults[key] == nil)
}
}
extension DefaultsKeys {
static let strings = DefaultsKey<[String]>("strings")
static let optStrings = DefaultsKey<[String]?>("strings")
}
| d82e8090c11b23860a367d1b78144ae7 | 30.732984 | 105 | 0.556124 | false | true | false | false |
adamnemecek/AudioKit | refs/heads/main | Sources/AudioKitEX/Automation/NodeParameter+Automation.swift | mit | 1 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AudioKit
import AVFoundation
import CAudioKitEX
// TODO: need unit tests (were moved to SoundpipeAudioKit)
/// Automation functions rely on CAudioKit, so they are in this extension in case we want to
/// make a pure-swift AudioKit.
extension NodeParameter {
/// Begin automation of the parameter.
///
/// If `startTime` is nil, the automation will be scheduled as soon as possible.
///
/// - Parameter events: automation curve
/// - Parameter startTime: optional time to start automation
public func automate(events: [AutomationEvent], startTime: AVAudioTime? = nil) {
var lastRenderTime = avAudioNode.lastRenderTime ?? AVAudioTime(sampleTime: 0, atRate: Settings.sampleRate)
if !lastRenderTime.isSampleTimeValid {
if let engine = avAudioNode.engine, engine.isInManualRenderingMode {
lastRenderTime = AVAudioTime(sampleTime: engine.manualRenderingSampleTime,
atRate: Settings.sampleRate)
} else {
lastRenderTime = AVAudioTime(sampleTime: 0, atRate: Settings.sampleRate)
}
}
var lastTime = startTime ?? lastRenderTime
if lastTime.isHostTimeValid {
// Convert to sample time.
let lastTimeSeconds = AVAudioTime.seconds(forHostTime: lastRenderTime.hostTime)
let startTimeSeconds = AVAudioTime.seconds(forHostTime: lastTime.hostTime)
lastTime = lastRenderTime.offset(seconds: startTimeSeconds - lastTimeSeconds)
}
assert(lastTime.isSampleTimeValid)
stopAutomation()
events.withUnsafeBufferPointer { automationPtr in
guard let automationBaseAddress = automationPtr.baseAddress else { return }
guard let observer = ParameterAutomationGetRenderObserver(parameter.address,
avAudioNode.auAudioUnit.scheduleParameterBlock,
Float(Settings.sampleRate),
Float(lastTime.sampleTime),
automationBaseAddress,
events.count) else { return }
renderObserverToken = avAudioNode.auAudioUnit.token(byAddingRenderObserver: observer)
}
}
/// Stop automation
public func stopAutomation() {
if let token = renderObserverToken {
avAudioNode.auAudioUnit.removeRenderObserver(token)
}
}
/// Ramp from a source value (which is ramped to over 20ms) to a target value
///
/// - Parameters:
/// - start: initial value
/// - target: destination value
/// - duration: duration to ramp to the target value in seconds
public func ramp(from start: AUValue, to target: AUValue, duration: Float) {
ramp(to: start, duration: 0.02, delay: 0)
ramp(to: target, duration: duration, delay: 0.02)
}
}
| d03bcaf1bb30545f8ed7ecf0fb7e6a5d | 42.168831 | 117 | 0.584838 | false | false | false | false |
zachwaugh/GIFKit | refs/heads/master | GIFKitTests/HeaderSpec.swift | mit | 1 | import Quick
import Nimble
@testable import GIFKit
class HeaderSpec: QuickSpec {
override func spec() {
describe(".hasValidSignature()") {
context("when there is valid signature") {
it("returns true") {
let data = "GIF89a".dataUsingEncoding(NSUTF8StringEncoding)!
let header = Header(data: data)
expect(header.hasValidSignature()) == true
}
}
context("when there is an invalid signature") {
it("returns false") {
let data = "PNG89a".dataUsingEncoding(NSUTF8StringEncoding)!
let header = Header(data: data)
expect(header.hasValidSignature()) == false
}
}
}
describe(".hasValidVersion()") {
context("when version is valid") {
it("returns true") {
var data = "GIF87a".dataUsingEncoding(NSUTF8StringEncoding)!
var header = Header(data: data)
expect(header.hasValidVersion()) == true
data = "GIF89a".dataUsingEncoding(NSUTF8StringEncoding)!
header = Header(data: data)
expect(header.hasValidVersion()) == true
}
}
context("when version is invalid") {
it("returns false") {
let data = "GIF89b".dataUsingEncoding(NSUTF8StringEncoding)!
let header = Header(data: data)
expect(header.hasValidVersion()) == false
}
}
}
}
}
| 9c4d4cd6942affa848dceed923fa458b | 34.787234 | 80 | 0.490488 | false | false | false | false |
Antuaaan/ECWeather | refs/heads/master | Calendouer/Pods/Spring/Spring/SpringView.swift | apache-2.0 | 18 | // 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
open class SpringView: UIView, Springable {
@IBInspectable public var autostart: Bool = false
@IBInspectable public var autohide: Bool = false
@IBInspectable public var animation: String = ""
@IBInspectable public var force: CGFloat = 1
@IBInspectable public var delay: CGFloat = 0
@IBInspectable public var duration: CGFloat = 0.7
@IBInspectable public var damping: CGFloat = 0.7
@IBInspectable public var velocity: CGFloat = 0.7
@IBInspectable public var repeatCount: Float = 1
@IBInspectable public var x: CGFloat = 0
@IBInspectable public var y: CGFloat = 0
@IBInspectable public var scaleX: CGFloat = 1
@IBInspectable public var scaleY: CGFloat = 1
@IBInspectable public var rotate: CGFloat = 0
@IBInspectable public var curve: String = ""
public var opacity: CGFloat = 1
public var animateFrom: Bool = false
lazy private var spring : Spring = Spring(self)
override open func awakeFromNib() {
super.awakeFromNib()
self.spring.customAwakeFromNib()
}
open override func layoutSubviews() {
super.layoutSubviews()
spring.customLayoutSubviews()
}
public func animate() {
self.spring.animate()
}
public func animateNext(completion: @escaping () -> ()) {
self.spring.animateNext(completion: completion)
}
public func animateTo() {
self.spring.animateTo()
}
public func animateToNext(completion: @escaping () -> ()) {
self.spring.animateToNext(completion: completion)
}
}
| 11331b6db6bfa028091266570d46244d | 37.492958 | 81 | 0.710209 | false | false | false | false |
nathan/hush | refs/heads/master | iOSHush/LengthViewController.swift | unlicense | 1 | import UIKit
@objc
class LengthViewController: UITableViewController {
static let lengths = [8,10,12,14,16,18,20,22,24,26]
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {return 1}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return LengthViewController.lengths.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let length = LengthViewController.lengths[indexPath.indexAtPosition(1)]
let current = ViewController.hashOptions.length
cell.textLabel?.text = "\(length) Letters"
cell.accessoryType = length == current ? UITableViewCellAccessoryType.Checkmark : .None
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let length = LengthViewController.lengths[indexPath.indexAtPosition(1)]
ViewController.hashOptions.length = length
for cell in tableView.visibleCells {
cell.accessoryType = UITableViewCellAccessoryType.None
}
guard let cell = tableView.cellForRowAtIndexPath(indexPath) else {return}
cell.setSelected(false, animated: true)
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
}
| 50eb0e17b8b721f19b41362311f4b38a | 43.483871 | 116 | 0.775925 | false | false | false | false |
DadosAbertosBrasil/swift-radar-politico | refs/heads/master | swift-radar-político/DeputadoCell.swift | gpl-2.0 | 1 | //
// DeputadoCell.swift
// swift-radar-político
//
// Created by Ulysses on 3/29/16.
// Copyright © 2016 Francisco José A. C. Souza. All rights reserved.
//
import UIKit
class DeputadoCell: UITableViewCell {
@IBOutlet weak var seguindoSwitch: UISwitch!
@IBOutlet weak var nomeLabel: UILabel!
@IBOutlet weak var partidoLabel: UILabel!
@IBOutlet weak var fotoImage: UIImageView!
private var deputado:CDDeputado?
@IBAction func seguirSwitch(sender: AnyObject) {
if self.deputado == nil{
return
}
if seguindoSwitch.on == false{
DeputadosDataController.sharedInstance.unfollowDeputadoWithId(Int(self.deputado!.ideCadastro))
}else{
DeputadosDataController.sharedInstance.followDeputadoWithId(Int(self.deputado!.ideCadastro))
}
}
func loadWithDeputado(deputado:CDDeputado){
self.deputado = deputado
self.nomeLabel.text = self.deputado?.nomeParlamentar.capitalizedString
let suplenteSufix = (self.deputado!.condicao! != "Titular" ? " - "+self.deputado!.condicao : "")
self.partidoLabel.text = (self.deputado?.partido)!+" - "+(self.deputado?.uf)!+suplenteSufix
self.fotoImage.layer.cornerRadius = 15;
self.fotoImage.layer.masksToBounds = true
self.fotoImage.layer.borderWidth = 1.0
self.fotoImage.layer.borderColor = UIColor(netHex: Constants.green).CGColor
self.deputado?.loadPhoto(self.fotoImage)
if DeputadosDataController.sharedInstance.isDeputadoFoollowed(Int(self.deputado!.ideCadastro)){
self.seguindoSwitch.on = true
}
}
override func awakeFromNib(){
self.seguindoSwitch.onImage = UIImage(named: "Unfollow")
self.seguindoSwitch.offImage = UIImage(named: "Follow")
}
override func prepareForReuse() {
self.deputado = nil
self.fotoImage.image = nil
self.seguindoSwitch.on = false
}
}
| 7449d3fc11183b29d84604f92390abbc | 29.597015 | 106 | 0.646341 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | Kickstarter-iOS/Features/Dashboard/Views/Cells/DashboardContextCell.swift | apache-2.0 | 1 | import KsApi
import Library
import Prelude
import Prelude_UIKit
import UIKit
internal final class DashboardContextCell: UITableViewCell, ValueCell {
@IBOutlet fileprivate var containerView: UIView!
@IBOutlet fileprivate var projectNameLabel: UILabel!
@IBOutlet fileprivate var separatorView: UIView!
@IBOutlet fileprivate var viewProjectButton: UIButton!
internal override func bindStyles() {
super.bindStyles()
_ = self
|> dashboardContextCellStyle
|> UITableViewCell.lens.selectionStyle .~ .gray
|> UITableViewCell.lens.accessibilityTraits .~ UIAccessibilityTraits.button
|> UITableViewCell.lens.accessibilityHint %~ { _ in
Strings.dashboard_tout_accessibility_hint_opens_project()
}
_ = self.containerView
|> containerViewBackgroundStyle
_ = self.projectNameLabel
|> dashboardStatTitleLabelStyle
_ = self.separatorView
|> separatorStyle
_ = self.viewProjectButton
|> dashboardViewProjectButtonStyle
|> UIButton.lens.isUserInteractionEnabled .~ false
|> UIButton.lens.accessibilityElementsHidden .~ true
}
internal func configureWith(value: Project) {
self.projectNameLabel.text = value.name
}
}
| 1d0b0d3ac0628c6f01eaf1ef75dcbb9d | 28.142857 | 81 | 0.731209 | false | false | false | false |
3squared/ios-charts | refs/heads/master | Charts/Classes/Data/ChartData.swift | apache-2.0 | 16 | //
// ChartData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
public class ChartData: NSObject
{
internal var _yMax = Double(0.0)
internal var _yMin = Double(0.0)
internal var _leftAxisMax = Double(0.0)
internal var _leftAxisMin = Double(0.0)
internal var _rightAxisMax = Double(0.0)
internal var _rightAxisMin = Double(0.0)
private var _yValueSum = Double(0.0)
private var _yValCount = Int(0)
/// the last start value used for calcMinMax
internal var _lastStart: Int = 0
/// the last end value used for calcMinMax
internal var _lastEnd: Int = 0
/// the average length (in characters) across all x-value strings
private var _xValAverageLength = Double(0.0)
internal var _xVals: [String?]!
internal var _dataSets: [ChartDataSet]!
public override init()
{
super.init()
_xVals = [String?]()
_dataSets = [ChartDataSet]()
}
public init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init()
_xVals = xVals == nil ? [String?]() : xVals
_dataSets = dataSets == nil ? [ChartDataSet]() : dataSets
self.initialize(_dataSets)
}
public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init()
_xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!)
_dataSets = dataSets == nil ? [ChartDataSet]() : dataSets
self.initialize(_dataSets)
}
public convenience init(xVals: [String?]?)
{
self.init(xVals: xVals, dataSets: [ChartDataSet]())
}
public convenience init(xVals: [NSObject]?)
{
self.init(xVals: xVals, dataSets: [ChartDataSet]())
}
public convenience init(xVals: [String?]?, dataSet: ChartDataSet?)
{
self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!])
}
public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?)
{
self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!])
}
internal func initialize(dataSets: [ChartDataSet])
{
checkIsLegal(dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
// calculates the average length (in characters) across all x-value strings
internal func calcXValAverageLength()
{
if (_xVals.count == 0)
{
_xValAverageLength = 1
return
}
var sum = 1
for (var i = 0; i < _xVals.count; i++)
{
sum += _xVals[i] == nil ? 0 : (_xVals[i]!).characters.count
}
_xValAverageLength = Double(sum) / Double(_xVals.count)
}
// Checks if the combination of x-values array and DataSet array is legal or not.
// :param: dataSets
internal func checkIsLegal(dataSets: [ChartDataSet]!)
{
if (dataSets == nil)
{
return
}
if self is ScatterChartData
{ // In scatter chart it makes sense to have more than one y-value value for an x-index
return
}
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].yVals.count > _xVals.count)
{
print("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.", terminator: "\n")
return
}
}
}
public func notifyDataChanged()
{
initialize(_dataSets)
}
/// calc minimum and maximum y value over all datasets
internal func calcMinMax(start start: Int, end: Int)
{
if (_dataSets == nil || _dataSets.count < 1)
{
_yMax = 0.0
_yMin = 0.0
}
else
{
_lastStart = start
_lastEnd = end
_yMin = DBL_MAX
_yMax = -DBL_MAX
for (var i = 0; i < _dataSets.count; i++)
{
_dataSets[i].calcMinMax(start: start, end: end)
if (_dataSets[i].yMin < _yMin)
{
_yMin = _dataSets[i].yMin
}
if (_dataSets[i].yMax > _yMax)
{
_yMax = _dataSets[i].yMax
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
// left axis
let firstLeft = getFirstLeft()
if (firstLeft !== nil)
{
_leftAxisMax = firstLeft!.yMax
_leftAxisMin = firstLeft!.yMin
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Left)
{
if (dataSet.yMin < _leftAxisMin)
{
_leftAxisMin = dataSet.yMin
}
if (dataSet.yMax > _leftAxisMax)
{
_leftAxisMax = dataSet.yMax
}
}
}
}
// right axis
let firstRight = getFirstRight()
if (firstRight !== nil)
{
_rightAxisMax = firstRight!.yMax
_rightAxisMin = firstRight!.yMin
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Right)
{
if (dataSet.yMin < _rightAxisMin)
{
_rightAxisMin = dataSet.yMin
}
if (dataSet.yMax > _rightAxisMax)
{
_rightAxisMax = dataSet.yMax
}
}
}
}
// in case there is only one axis, adjust the second axis
handleEmptyAxis(firstLeft, firstRight: firstRight)
}
}
/// calculates the sum of all y-values in all datasets
internal func calcYValueSum()
{
_yValueSum = 0
if (_dataSets == nil)
{
return
}
for (var i = 0; i < _dataSets.count; i++)
{
_yValueSum += fabs(_dataSets[i].yValueSum)
}
}
/// Calculates the total number of y-values across all ChartDataSets the ChartData represents.
internal func calcYValueCount()
{
_yValCount = 0
if (_dataSets == nil)
{
return
}
var count = 0
for (var i = 0; i < _dataSets.count; i++)
{
count += _dataSets[i].entryCount
}
_yValCount = count
}
/// - returns: the number of LineDataSets this object contains
public var dataSetCount: Int
{
if (_dataSets == nil)
{
return 0
}
return _dataSets.count
}
/// - returns: the average value across all entries in this Data object (all entries from the DataSets this data object holds)
public var average: Double
{
return yValueSum / Double(yValCount)
}
/// - returns: the smallest y-value the data object contains.
public var yMin: Double
{
return _yMin
}
public func getYMin() -> Double
{
return _yMin
}
public func getYMin(axis: ChartYAxis.AxisDependency) -> Double
{
if (axis == .Left)
{
return _leftAxisMin
}
else
{
return _rightAxisMin
}
}
/// - returns: the greatest y-value the data object contains.
public var yMax: Double
{
return _yMax
}
public func getYMax() -> Double
{
return _yMax
}
public func getYMax(axis: ChartYAxis.AxisDependency) -> Double
{
if (axis == .Left)
{
return _leftAxisMax
}
else
{
return _rightAxisMax
}
}
/// - returns: the average length (in characters) across all values in the x-vals array
public var xValAverageLength: Double
{
return _xValAverageLength
}
/// - returns: the total y-value sum across all DataSet objects the this object represents.
public var yValueSum: Double
{
return _yValueSum
}
/// - returns: the total number of y-values across all DataSet objects the this object represents.
public var yValCount: Int
{
return _yValCount
}
/// - returns: the x-values the chart represents
public var xVals: [String?]
{
return _xVals
}
///Adds a new x-value to the chart data.
public func addXValue(xVal: String?)
{
_xVals.append(xVal)
}
/// Removes the x-value at the specified index.
public func removeXValue(index: Int)
{
_xVals.removeAtIndex(index)
}
/// - returns: the array of ChartDataSets this object holds.
public var dataSets: [ChartDataSet]
{
get
{
return _dataSets
}
set
{
_dataSets = newValue
}
}
/// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not.
///
/// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.**
///
/// - parameter dataSets: the DataSet array to search
/// - parameter type:
/// - parameter ignorecase: if true, the search is not case-sensitive
/// - returns: the index of the DataSet Object with the given label. Sensitive or not.
internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int
{
if (ignorecase)
{
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].label == nil)
{
continue
}
if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame)
{
return i
}
}
}
else
{
for (var i = 0; i < dataSets.count; i++)
{
if (label == dataSets[i].label)
{
return i
}
}
}
return -1
}
/// - returns: the total number of x-values this ChartData object represents (the size of the x-values array)
public var xValCount: Int
{
return _xVals.count
}
/// - returns: the labels of all DataSets as a string array.
internal func dataSetLabels() -> [String]
{
var types = [String]()
for (var i = 0; i < _dataSets.count; i++)
{
if (dataSets[i].label == nil)
{
continue
}
types[i] = _dataSets[i].label!
}
return types
}
/// Get the Entry for a corresponding highlight object
///
/// - parameter highlight:
/// - returns: the entry that is highlighted
public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry?
{
if highlight.dataSetIndex >= dataSets.count
{
return nil
}
else
{
return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex)
}
}
/// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.**
///
/// - parameter label:
/// - parameter ignorecase:
/// - returns: the DataSet Object with the given label. Sensitive or not.
public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet?
{
let index = getDataSetIndexByLabel(label, ignorecase: ignorecase)
if (index < 0 || index >= _dataSets.count)
{
return nil
}
else
{
return _dataSets[index]
}
}
public func getDataSetByIndex(index: Int) -> ChartDataSet!
{
if (_dataSets == nil || index < 0 || index >= _dataSets.count)
{
return nil
}
return _dataSets[index]
}
public func addDataSet(d: ChartDataSet!)
{
if (_dataSets == nil)
{
return
}
_yValCount += d.entryCount
_yValueSum += d.yValueSum
if (_dataSets.count == 0)
{
_yMax = d.yMax
_yMin = d.yMin
if (d.axisDependency == .Left)
{
_leftAxisMax = d.yMax
_leftAxisMin = d.yMin
}
else
{
_rightAxisMax = d.yMax
_rightAxisMin = d.yMin
}
}
else
{
if (_yMax < d.yMax)
{
_yMax = d.yMax
}
if (_yMin > d.yMin)
{
_yMin = d.yMin
}
if (d.axisDependency == .Left)
{
if (_leftAxisMax < d.yMax)
{
_leftAxisMax = d.yMax
}
if (_leftAxisMin > d.yMin)
{
_leftAxisMin = d.yMin
}
}
else
{
if (_rightAxisMax < d.yMax)
{
_rightAxisMax = d.yMax
}
if (_rightAxisMin > d.yMin)
{
_rightAxisMin = d.yMin
}
}
}
_dataSets.append(d)
handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight())
}
public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?)
{
// in case there is only one axis, adjust the second axis
if (firstLeft === nil)
{
_leftAxisMax = _rightAxisMax
_leftAxisMin = _rightAxisMin
}
else if (firstRight === nil)
{
_rightAxisMax = _leftAxisMax
_rightAxisMin = _leftAxisMin
}
}
/// Removes the given DataSet from this data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: true if a DataSet was removed, false if no DataSet could be removed.
public func removeDataSet(dataSet: ChartDataSet!) -> Bool
{
if (_dataSets == nil || dataSet === nil)
{
return false
}
for (var i = 0; i < _dataSets.count; i++)
{
if (_dataSets[i] === dataSet)
{
return removeDataSetByIndex(i)
}
}
return false
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: true if a DataSet was removed, false if no DataSet could be removed.
public func removeDataSetByIndex(index: Int) -> Bool
{
if (_dataSets == nil || index >= _dataSets.count || index < 0)
{
return false
}
let d = _dataSets.removeAtIndex(index)
_yValCount -= d.entryCount
_yValueSum -= d.yValueSum
calcMinMax(start: _lastStart, end: _lastEnd)
return true
}
/// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list.
public func addEntry(e: ChartDataEntry, dataSetIndex: Int)
{
if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0)
{
let val = e.value
let set = _dataSets[dataSetIndex]
if (_yValCount == 0)
{
_yMin = val
_yMax = val
if (set.axisDependency == .Left)
{
_leftAxisMax = e.value
_leftAxisMin = e.value
}
else
{
_rightAxisMax = e.value
_rightAxisMin = e.value
}
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
if (set.axisDependency == .Left)
{
if (_leftAxisMax < e.value)
{
_leftAxisMax = e.value
}
if (_leftAxisMin > e.value)
{
_leftAxisMin = e.value
}
}
else
{
if (_rightAxisMax < e.value)
{
_rightAxisMax = e.value
}
if (_rightAxisMin > e.value)
{
_rightAxisMin = e.value
}
}
}
_yValCount += 1
_yValueSum += val
handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight())
set.addEntry(e)
}
else
{
print("ChartData.addEntry() - dataSetIndex our of range.", terminator: "\n")
}
}
/// Removes the given Entry object from the DataSet at the specified index.
public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool
{
// entry null, outofbounds
if (entry === nil || dataSetIndex >= _dataSets.count)
{
return false
}
// remove the entry from the dataset
let removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex)
if (removed)
{
let val = entry.value
_yValCount -= 1
_yValueSum -= val
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed
}
/// Removes the Entry object at the given xIndex from the ChartDataSet at the
/// specified index.
/// - returns: true if an entry was removed, false if no Entry was found that meets the specified requirements.
public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool
{
if (dataSetIndex >= _dataSets.count)
{
return false
}
let entry = _dataSets[dataSetIndex].entryForXIndex(xIndex)
if (entry?.xIndex != xIndex)
{
return false
}
return removeEntry(entry, dataSetIndex: dataSetIndex)
}
/// - returns: the DataSet that contains the provided Entry, or null, if no DataSet contains this entry.
public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet?
{
if (e == nil)
{
return nil
}
for (var i = 0; i < _dataSets.count; i++)
{
let set = _dataSets[i]
for (var j = 0; j < set.entryCount; j++)
{
if (e === set.entryForXIndex(e.xIndex))
{
return set
}
}
}
return nil
}
/// - returns: the index of the provided DataSet inside the DataSets array of this data object. -1 if the DataSet was not found.
public func indexOfDataSet(dataSet: ChartDataSet) -> Int
{
for (var i = 0; i < _dataSets.count; i++)
{
if (_dataSets[i] === dataSet)
{
return i
}
}
return -1
}
/// - returns: the first DataSet from the datasets-array that has it's dependency on the left axis. Returns null if no DataSet with left dependency could be found.
public func getFirstLeft() -> ChartDataSet?
{
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Left)
{
return dataSet
}
}
return nil
}
/// - returns: the first DataSet from the datasets-array that has it's dependency on the right axis. Returns null if no DataSet with right dependency could be found.
public func getFirstRight() -> ChartDataSet?
{
for dataSet in _dataSets
{
if (dataSet.axisDependency == .Right)
{
return dataSet
}
}
return nil
}
/// - returns: all colors used across all DataSet objects this object represents.
public func getColors() -> [UIColor]?
{
if (_dataSets == nil)
{
return nil
}
var clrcnt = 0
for (var i = 0; i < _dataSets.count; i++)
{
clrcnt += _dataSets[i].colors.count
}
var colors = [UIColor]()
for (var i = 0; i < _dataSets.count; i++)
{
let clrs = _dataSets[i].colors
for clr in clrs
{
colors.append(clr)
}
}
return colors
}
/// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience.
public func generateXVals(from: Int, to: Int) -> [String]
{
var xvals = [String]()
for (var i = from; i < to; i++)
{
xvals.append(String(i))
}
return xvals
}
/// Sets a custom ValueFormatter for all DataSets this data object contains.
public func setValueFormatter(formatter: NSNumberFormatter!)
{
for set in dataSets
{
set.valueFormatter = formatter
}
}
/// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains.
public func setValueTextColor(color: UIColor!)
{
for set in dataSets
{
set.valueTextColor = color ?? set.valueTextColor
}
}
/// Sets the font for all value-labels for all DataSets this data object contains.
public func setValueFont(font: UIFont!)
{
for set in dataSets
{
set.valueFont = font ?? set.valueFont
}
}
/// Enables / disables drawing values (value-text) for all DataSets this data object contains.
public func setDrawValues(enabled: Bool)
{
for set in dataSets
{
set.drawValuesEnabled = enabled
}
}
/// Enables / disables highlighting values for all DataSets this data object contains.
public var highlightEnabled: Bool
{
get
{
for set in dataSets
{
if (!set.highlightEnabled)
{
return false
}
}
return true
}
set
{
for set in dataSets
{
set.highlightEnabled = newValue
}
}
}
/// if true, value highlightning is enabled
public var isHighlightEnabled: Bool { return highlightEnabled }
/// Clears this data object from all DataSets and removes all Entries.
/// Don't forget to invalidate the chart after this.
public func clearValues()
{
dataSets.removeAll(keepCapacity: false)
notifyDataChanged()
}
/// Checks if this data object contains the specified Entry.
/// - returns: true if so, false if not.
public func contains(entry entry: ChartDataEntry) -> Bool
{
for set in dataSets
{
if (set.contains(entry))
{
return true
}
}
return false
}
/// Checks if this data object contains the specified DataSet.
/// - returns: true if so, false if not.
public func contains(dataSet dataSet: ChartDataSet) -> Bool
{
for set in dataSets
{
if (set.isEqual(dataSet))
{
return true
}
}
return false
}
/// MARK: - ObjC compatibility
/// - returns: the average length (in characters) across all values in the x-vals array
public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); }
}
| 2b0381c722b934ea0790ecac4db01247 | 26.004215 | 169 | 0.478909 | false | false | false | false |
YPaul/YXMusicPlayer | refs/heads/master | YXMusic音乐播放器/YXPlayingViewController.swift | apache-2.0 | 1 | //
// YXPlayingViewController.swift
// YXMusic音乐播放器
//
// Created by paul-y on 16/2/2.
// Copyright © 2016年 YinQiXing. All rights reserved.
//音乐详情界面
import UIKit
import MJExtension
import AVFoundation
class YXPlayingViewController: UIViewController,AVAudioPlayerDelegate {
//当控制器的view用xib描述时,为了兼容ios8.0,必须重写这个方法
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: "YXPlayingViewController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var progressTimer :NSTimer?
//当前的音乐播放器
private var player :AVAudioPlayer?{
didSet{
player!.delegate = self
//设置各个空间的属性
// 歌曲名字
musicNameLabel.text = playingMusic!.name
// 作者名字
singernameLabel.text = playingMusic!.singer
//歌曲总时间
musicTotalTimeLabel.text = timeIntervalToMinute(self.player!.duration)
// 歌曲图片
icon_music.image = UIImage(named:self.playingMusic!.icon!)
}
}
//拖拽时显示时间的label
@IBOutlet weak var currentTimeWhenPan_Button: UIButton!
/// 记录正在播放的音乐
private var playingMusic:MusicModal?
//模型数组
private lazy var musics = MusicModal.mj_objectArrayWithFilename("Musics.plist")
var rowSelected:Int?{//属性观察器
willSet{
if rowSelected != nil && newValue != rowSelected{
AudioTool.stopMusicWith(playingMusic!.filename!)
}
}didSet{
//设置当前正在播放的音乐
self.playingMusic = musics[rowSelected!] as? MusicModal
}
}
/// 下部分
@IBOutlet weak private var part_down: UIView!
//播放按钮
@IBOutlet weak private var playButton: UIButton!
/// 滑块
@IBOutlet weak private var slider: UIButton!
/// 歌曲总时间
@IBOutlet weak private var musicTotalTimeLabel: UILabel!
/// 进度条
@IBOutlet weak private var progressShowBar: UIView!
/// 歌曲图片
@IBOutlet weak private var icon_music: UIImageView!
/// 作者名字
@IBOutlet weak private var singernameLabel: UILabel!
/// 歌曲名字
@IBOutlet weak private var musicNameLabel: UILabel!
override func viewDidLoad() {
self.currentTimeWhenPan_Button.layer.cornerRadius = 10
//支持屏幕旋转,监听屏幕旋转通知
UIDevice.currentDevice().generatesDeviceOrientationNotifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleDeviceOrientationDidChange:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
/**
点击进度条执行
let x_change = (self.view.width - slider.width) * CGFloat(mPlayer.currentTime / mPlayer.duration)
*/
@IBAction func onTap(sender: UITapGestureRecognizer) {
let point = sender.locationInView(sender.view)
//重置滑块位置
self.slider.x = point.x
//判断是否guo界
let sliderMaxX = self.view.width - slider.width
if slider.x > sliderMaxX {
slider.x = sliderMaxX
}
//调整进度条
self.progressShowBar.width = slider.centerX
self.player!.currentTime = Double(point.x / (self.view.width - slider.width)) * self.player!.duration
slider.setTitle(timeIntervalToMinute(self.player!.currentTime), forState: .Normal)
}
/**
拖拽滑块执行
*/
@IBAction func onPan(sender: UIPanGestureRecognizer) {
//获得拖拽距离
let point = sender.translationInView(sender.view!)
sender.setTranslation(CGPointZero, inView: sender.view!)
//重置滑块位置
self.slider.x += point.x
//判断是否guo界
let sliderMaxX = self.view.width - slider.width
if slider.x < 0{
slider.x = 0
}else if slider.x > sliderMaxX {
slider.x = sliderMaxX
}
//调整进度条
self.progressShowBar.width = slider.centerX
//调到指定时间播放
self.player!.currentTime = Double(slider.x / (self.view.width - slider.width)) * self.player!.duration
slider.setTitle(timeIntervalToMinute(self.player!.currentTime), forState: .Normal)
//设置拖拽时显示的时间button
self.currentTimeWhenPan_Button.x = slider.x
currentTimeWhenPan_Button.setTitle(timeIntervalToMinute(self.player!.currentTime), forState: .Normal)
self.currentTimeWhenPan_Button.y = currentTimeWhenPan_Button.superview!.height - currentTimeWhenPan_Button.width - 15
// 如果是开始拖拽就停止定时器, 如果结束拖拽就开启定时器
if sender.state == .Began{
self.currentTimeWhenPan_Button.hidden = false
self.removeProgressTimer()
AudioTool.pauseMusicWith(playingMusic!.filename!)
}else if sender.state == .Ended{
self.currentTimeWhenPan_Button.hidden = true
self.addProgressTimer()
//如果暂停播放按钮是播放状态,就开始播放
if self.playButton.selected == false{
AudioTool.playMusicWith(playingMusic!.filename!)
}
}
}
/**
点击歌词按钮执行
*/
@IBAction private func lrc() {
}
/**
点击返回按钮执行
*/
@IBAction private func back() {
//获取主窗口
let window = UIApplication.sharedApplication().keyWindow!
//设置窗口的用户交互不可用
window.userInteractionEnabled = false
//动画
UIView.animateWithDuration(1.0, animations: { () -> Void in
self.view.y = window.height
}) { (Bool) -> Void in
//动画结束,设置窗口的用户交互可用,并设置view隐藏
window.userInteractionEnabled = true
self.view.hidden = true
}
}
/**
点击播放或者暂停按钮执行
*/
@IBAction private func playOrPause(sender:UIButton) {
if sender.selected == false{
AudioTool.pauseMusicWith(playingMusic!.filename!)
}else{
AudioTool.playMusicWith(playingMusic!.filename!)
}
sender.selected = !sender.selected
}
/**
点击上一首按钮执行
*/
@IBAction private func previous() {
slider.x = 0
progressShowBar.width = 0
slider.setTitle("0:0", forState: .Normal)
if rowSelected == 0{
rowSelected! = musics.count - 1
}else{
rowSelected = rowSelected! - 1
}
if playButton.selected == false{//如果当前的按钮状态是正在播放
self.player = AudioTool.playMusicWith(self.playingMusic!.filename!)
}else{//如果当前的按钮状态是暂停状态
self.player = AudioTool.playMusicWith(self.playingMusic!.filename!)
AudioTool.pauseMusicWith(playingMusic!.filename!)
}
}
/**
点击下一首按钮执行
*/
@IBAction private func next() {
//重置进度条
slider.x = 0
progressShowBar.width = 0
slider.setTitle("0:0", forState: .Normal)
if rowSelected == musics.count - 1{
rowSelected! = 0
}else{
rowSelected = rowSelected! + 1
}
if playButton.selected == false{//如果当前的按钮状态是正在播放
self.player = AudioTool.playMusicWith(self.playingMusic!.filename!)
}else{//如果当前的按钮状态是暂停状态
self.player = AudioTool.playMusicWith(self.playingMusic!.filename!)
AudioTool.pauseMusicWith(playingMusic!.filename!)
}
}
/**
显示播放音乐的详情
*/
func show(){
self.view.hidden = false
//获取主窗口
let window = UIApplication.sharedApplication().keyWindow!
self.view.frame = window.bounds
window.addSubview(self.view)
self.view.y = window.height
//设置窗口的用户交互不可用
window.userInteractionEnabled = false
//动画
UIView.animateWithDuration(1.0, animations: { () -> Void in
self.view.y = 0
}) { (Bool) -> Void in
//动画结束,设置窗口的用户交互可用,并播放音乐
window.userInteractionEnabled = true
self.player = AudioTool.playMusicWith(self.playingMusic!.filename!)
}
}
/**
将秒转化为分钟
*/
private func timeIntervalToMinute(timeInterval:NSTimeInterval)->String?{
let minute = timeInterval/60
let second = timeInterval%60
let timeStr = Int(minute).description + ":" + Int(second).description
return timeStr
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
addProgressTimer()
}
/**
更新滑块的位置
*/
@objc private func updateProhress(){
if let mPlayer = self.player{
if !mPlayer.playing{//如果没有播放音乐
return
}
let x_change = (self.view.width - slider.width) * CGFloat(mPlayer.currentTime / mPlayer.duration)
slider.frame.origin.x = x_change
progressShowBar.width = slider.centerX
slider.setTitle(timeIntervalToMinute(mPlayer.currentTime), forState: .Normal)
}
}
/**
AVAudioPlayerDelegate 代理方法
*/
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
playButton.selected = !playButton.selected
}
/**
屏幕旋转调用
*/
@objc func handleDeviceOrientationDidChange(not:NSNotification){
self.view.frame = self.view.window!.bounds
}
/**
添加定时器
*/
private func addProgressTimer(){
if self.progressTimer == nil{
self.progressTimer = NSTimer(timeInterval: 0.3, target: self, selector: "updateProhress", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(progressTimer!, forMode: NSRunLoopCommonModes)
}
}
/**
移除定时器
*/
private func removeProgressTimer(){
self.progressTimer!.invalidate()
self.progressTimer = nil
}
}
| b002024b2b979d223c120605eddbbb30 | 30.301587 | 170 | 0.596349 | false | false | false | false |
x331275955/- | refs/heads/master | 学习微博/学习微博/Classes/Model/UserAccount.swift | mit | 1 | //
// UserAccount.swift
// 我的微博
//
// Created by 刘凡 on 15/7/29.
// Copyright © 2015年 itheima. All rights reserved.
//
import UIKit
/// 用户账户类
class UserAccount: NSObject, NSCoding {
/// 全局账户信息
private static var sharedAccount: UserAccount?
class func sharedUserAccount() -> UserAccount? {
if sharedAccount == nil {
sharedAccount = UserAccount.loadAccount()
}
if let date = sharedAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
sharedAccount = nil
}
return sharedAccount
}
/// 用于调用access_token,接口获取授权后的access token
var access_token: String?
/// access_token的生命周期,单位是秒数
var expires_in: NSTimeInterval = 0
/// 过期日期
var expiresDate: NSDate?
/// 当前授权用户的UID
var uid: String?
private init(dict: [String: AnyObject]) {
super.init()
self.setValuesForKeysWithDictionary(dict)
expiresDate = NSDate(timeIntervalSinceNow: expires_in)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
override var description: String {
let dict = ["access_token", "expires_in", "uid", "expiresDate"]
return "\(dictionaryWithValuesForKeys(dict))"
}
// MARK: - 归档 & 解档
/// 归档保存路径
private static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("useraccount.plist")
/// 保存账户信息
class func saveAccount(dict: [String: AnyObject]) {
sharedAccount = UserAccount(dict: dict)
NSKeyedArchiver.archiveRootObject(sharedAccount!, toFile: accountPath)
}
/// 加载账户信息
private class func loadAccount() -> UserAccount? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
}
// MARK: - NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeDouble(expires_in, forKey: "expires_in")
aCoder.encodeObject(expiresDate, forKey: "expiresDate")
aCoder.encodeObject(uid, forKey: "uid")
}
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeDoubleForKey("expires_in")
expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
uid = aDecoder.decodeObjectForKey("uid") as? String
}
}
| 2196f4c9d23e36a2991953861118cbf5 | 31.3875 | 216 | 0.660749 | false | false | false | false |
xwu/swift | refs/heads/master | test/decl/nested/protocol.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -parse-as-library
// Protocols cannot be nested inside other types, and types cannot
// be nested inside protocols
struct OuterGeneric<D> {
protocol InnerProtocol { // expected-error{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
associatedtype Rooster
func flip(_ r: Rooster)
func flop(_ t: D) // expected-error{{cannot find type 'D' in scope}}
}
}
class OuterGenericClass<T> {
protocol InnerProtocol { // expected-error{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
associatedtype Rooster
func flip(_ r: Rooster)
func flop(_ t: T) // expected-error{{cannot find type 'T' in scope}}
}
}
protocol OuterProtocol {
associatedtype Hen
protocol InnerProtocol { // expected-error{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
associatedtype Rooster
func flip(_ r: Rooster)
func flop(_ h: Hen) // expected-error{{cannot find type 'Hen' in scope}}
}
}
struct ConformsToOuterProtocol : OuterProtocol {
typealias Hen = Int
func f() { let _ = InnerProtocol.self } // Ok
}
protocol Racoon {
associatedtype Stripes
class Claw<T> { // expected-error{{type 'Claw' cannot be nested in protocol 'Racoon'}}
func mangle(_ s: Stripes) {}
// expected-error@-1 {{cannot find type 'Stripes' in scope}}
}
struct Fang<T> { // expected-error{{type 'Fang' cannot be nested in protocol 'Racoon'}}
func gnaw(_ s: Stripes) {}
// expected-error@-1 {{cannot find type 'Stripes' in scope}}
}
enum Fur { // expected-error{{type 'Fur' cannot be nested in protocol 'Racoon'}}
case Stripes
}
}
enum SillyRawEnum : SillyProtocol.InnerClass {} // expected-error {{an enum with no cases cannot declare a raw type}}
// expected-error@-1 {{reference to generic type 'SillyProtocol.InnerClass' requires arguments in <...>}}
protocol SillyProtocol {
class InnerClass<T> {} // expected-error {{type 'InnerClass' cannot be nested in protocol 'SillyProtocol'}}
// expected-note@-1 {{generic type 'InnerClass' declared here}}
}
// N.B. Redeclaration checks don't see this case because `protocol A` is invalid.
enum OuterEnum {
protocol C {} // expected-error{{protocol 'C' cannot be nested inside another declaration}}
case C(C)
}
class OuterClass {
protocol InnerProtocol : OuterClass { }
// expected-error@-1{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
}
// 'InnerProtocol' does not inherit the generic parameters of
// 'OtherGenericClass', so the occurrence of 'OtherGenericClass'
// in 'InnerProtocol' is not "in context" with implicitly
// inferred generic arguments <T, U>.
class OtherGenericClass<T, U> { // expected-note {{generic type 'OtherGenericClass' declared here}}
protocol InnerProtocol : OtherGenericClass { }
// expected-error@-1{{protocol 'InnerProtocol' cannot be nested inside another declaration}}
// expected-error@-2{{reference to generic type 'OtherGenericClass' requires arguments in <...>}}
}
protocol SelfDotTest {
func f(_: Self.Class)
class Class {}
// expected-error@-1{{type 'Class' cannot be nested in protocol 'SelfDotTest'}}
}
struct Outer {
typealias E = NestedValidation.T
protocol NestedValidation { // expected-error {{protocol 'NestedValidation' cannot be nested inside another declaration}}
typealias T = A.B
class A { // expected-error {{type 'A' cannot be nested in protocol 'NestedValidation'}}
typealias B = Int
}
}
}
struct OuterForUFI {
@usableFromInline
protocol Inner { // expected-error {{protocol 'Inner' cannot be nested inside another declaration}}
func req()
}
}
extension OuterForUFI.Inner {
public func extMethod() {} // The 'public' puts this in a special path.
}
func testLookup(_ x: OuterForUFI.Inner) {
x.req()
x.extMethod()
}
func testLookup<T: OuterForUFI.Inner>(_ x: T) {
x.req()
x.extMethod()
}
| b2d8e7cb8e7c8b4a9377b806c503b627 | 32.87931 | 123 | 0.70687 | false | false | false | false |
agisboye/SwiftLMDB | refs/heads/master | Sources/LMDBError.swift | mit | 1 | //
// LMDBError.swift
// SwiftLMDB
//
// Created by August Heegaard on 30/09/2016.
// Copyright © 2016 August Heegaard. All rights reserved.
//
import Foundation
import LMDB
public enum LMDBError: Error {
// LMDB defined errors.
case keyExists
case notFound
case pageNotFound
case corrupted
case panic
case versionMismatch
case invalid
case mapFull
case dbsFull
case readersFull
case tlsFull
case txnFull
case cursorFull
case pageFull
case mapResized
case incompatible
case badReaderSlot
case badTransaction
case badValueSize
case badDBI
case problem
// OS errors
case operationNotPermitted
case invalidParameter
case outOfDiskSpace
case outOfMemory
case ioError
case accessViolation
case other(returnCode: Int32)
init(returnCode: Int32) {
switch returnCode {
case MDB_KEYEXIST: self = .keyExists
case MDB_NOTFOUND: self = .notFound
case MDB_PAGE_NOTFOUND: self = .pageNotFound
case MDB_CORRUPTED: self = .corrupted
case MDB_PANIC: self = .panic
case MDB_VERSION_MISMATCH: self = .versionMismatch
case MDB_INVALID: self = .invalid
case MDB_MAP_FULL: self = .mapFull
case MDB_DBS_FULL: self = .dbsFull
case MDB_READERS_FULL: self = .readersFull
case MDB_TLS_FULL: self = .tlsFull
case MDB_TXN_FULL: self = .txnFull
case MDB_CURSOR_FULL: self = .cursorFull
case MDB_PAGE_FULL: self = .pageFull
case MDB_MAP_RESIZED: self = .mapResized
case MDB_INCOMPATIBLE: self = .incompatible
case MDB_BAD_RSLOT: self = .badReaderSlot
case MDB_BAD_TXN: self = .badTransaction
case MDB_BAD_VALSIZE: self = .badValueSize
case MDB_BAD_DBI: self = .badDBI
case EPERM: self = .operationNotPermitted
case EINVAL: self = .invalidParameter
case ENOSPC: self = .outOfDiskSpace
case ENOMEM: self = .outOfMemory
case EIO: self = .ioError
case EACCES: self = .accessViolation
default: self = .other(returnCode: returnCode)
}
}
}
| 1f25274c93ac191f0985b52217d5d65b | 25.710843 | 58 | 0.633288 | false | false | false | false |
jmmaloney4/Conductor | refs/heads/renovate/fwal-setup-swift-1.x | Sources/Conductor/Game/Deck.swift | mpl-2.0 | 1 | // Copyright © 2017-2021 Jack Maloney. All Rights Reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
import Squall
public protocol Deck {
/// Returns Int.max if this is a uniform deck
var count: Int { get }
var type: DeckType { get }
mutating func draw() -> CardColor?
mutating func draw(_: Int) -> [CardColor?]
mutating func draw<T>(using: inout T) -> CardColor? where T: RandomNumberGenerator
mutating func draw<T>(_: Int, using: inout T) -> [CardColor?] where T: RandomNumberGenerator
mutating func discard(_: CardColor)
mutating func discard(_: [CardColor])
}
public extension Deck {
mutating func draw() -> CardColor? {
var rng = Gust()
return self.draw(using: &rng)
}
mutating func draw(_ count: Int) -> [CardColor?] {
var rng = Gust()
return (1 ... count).map { _ in self.draw(using: &rng) }
}
mutating func draw<T>(_: Int, using rng: inout T) -> [CardColor?] where T: RandomNumberGenerator {
(1 ... count).map { _ in self.draw(using: &rng) }
}
mutating func discard(_ cards: [CardColor]) {
cards.forEach { self.discard($0) }
}
}
public struct UniformDeck: Deck, Codable {
private var colors: [CardColor]
public var count: Int { Int.max }
public var type: DeckType { .uniform(colors: self.colors) }
public init(colors: [CardColor]) {
self.colors = colors
}
public mutating func draw<T>(using rng: inout T) -> CardColor? where T: RandomNumberGenerator {
self.colors.randomElement(using: &rng)
}
public func discard(_: CardColor) {}
}
public struct FiniteDeck: Deck, Codable {
private var initialCards: [CardColor]
private var cards: [CardColor]
public var count: Int { self.cards.count }
public var type: DeckType { .finite(cards: self.initialCards) }
public init(cards: [CardColor]) {
self.initialCards = cards
self.cards = self.initialCards
}
public mutating func draw<T>(using rng: inout T) -> CardColor? where T: RandomNumberGenerator {
guard !self.cards.isEmpty else { return nil }
let index = Int(rng.next(upperBound: UInt(self.cards.count)))
return self.cards.remove(at: index)
}
public mutating func discard(_ card: CardColor) { self.cards.append(card) }
}
| 58c8237a94a03a8c425063f9a32e454e | 30.3875 | 102 | 0.644763 | false | false | false | false |
scottsievert/Pythonic.swift | refs/heads/master | src/Pythonic.set.swift | mit | 1 | // The Swift standard library currently lacks a Set class. This is an
// attempt to fix that :-)
//
// "A set object is an unordered collection of distinct hashable
// objects. Common uses include membership testing, removing
// duplicates from a Sequence, and computing mathematical
// operations such as intersection, union, difference, and symmetric
// difference."
//
// Usage:
//
// var set1 = Set([0, 1, 2])
// set1.add(3)
// set1.add(3)
// assert(set1 == Set([0, 1, 2, 3]))
//
// var set2 = Set([2, 4, 8, 16])
// assert(set1 + set2 == Set([0, 1, 2, 3, 4, 8, 16]))
// assert(set1 - set2 == Set([0, 1, 3]))
// assert(set1 & set2 == Set([2]))
//
// assert(Set([1, 1, 1, 2, 2, 3, 3, 4]) == Set([1, 2, 3, 4]))
public final class Set<T : Hashable> : ArrayLiteralConvertible, CollectionType,
Comparable, Equatable, ExtensibleCollectionType, Hashable, BooleanType,
Printable, SequenceType {
// final to speed up things:
// "Is your dictionary an property (i.e. ivar) of a class? If so,
// this is probably a known problem where an extra copy of the
// dictionary is being made for no reason. As a workaround, try
// marking the property "final"." (quoting a dev forum post by
// Chris Lattner)
//
// Before final: 2000 inserts in 7.16 seconds.
// After final: 2000 inserts in 0.03 seconds.
// Speed-up: 239x
private final var internalDict = [T : Void]()
public required init() {
}
public init<R : SequenceType where R.Generator.Element == T>(_ initialSequenceType: R) {
self.extend(initialSequenceType)
}
// Implement ArrayLiteralConvertible (allows for "var set: Set<Int> = [2, 4, 8]")
public init(arrayLiteral: T...) {
self.extend(arrayLiteral)
}
public func contains(element: T) -> Bool {
// "return self.internalDict[element] != nil" gives …
// "error: 'T' is not convertible to 'DictionaryIndex<T, Void>'"
// Workaround:
if let _ = self.internalDict[element] {
return true
}
return false
}
public func add(element: T) {
self.internalDict[element] = Void()
}
public func remove(element: T) {
self.internalDict[element] = nil
}
public func discard(element: T) {
self.remove(element)
}
public func clear() {
self.internalDict = [T : Void]()
}
public func intersection(other: Set<T>) -> Set<T> {
var newSet = Set<T>()
for entry in self {
if other.contains(entry) {
newSet.add(entry)
}
}
return newSet
}
public func isDisjoint(other: Set<T>) -> Bool {
return self.intersection(other) == Set()
}
// Lowercase name for Python compatibility.
public func isdisjoint(other: Set<T>) -> Bool {
return self.isDisjoint(other)
}
// Implement Collection (allows for "countElements(set)", etc.)
public subscript (i: Int) -> T {
return Array(self.internalDict.keys)[i]
}
// Implement Collection (allows for "countElements(set)", etc.)
public var startIndex: Int {
return 0
}
// Implement Collection (allows for "countElements(set)", etc.)
public var endIndex: Int {
return self.internalDict.count
}
// Implement ExtensibleCollection
public func reserveCapacity(n: Int) {
// NOOP.
}
// Implement ExtensibleCollection
public func extend<R : SequenceType where R.Generator.Element == T>(SequenceType: R) {
let elements = [T](SequenceType)
for element in elements {
self.add(element)
}
}
// Implement ExtensibleCollection
public func append(element: T) {
self.add(element)
}
// Implement Hashable
public var hashValue: Int {
var totalHash = 0
for entry in self {
// Opt in to the overflow behavior when calculating totalHash
totalHash = totalHash &+ entry.hashValue
}
return totalHash
}
// Implement LogicValue (allows for "if set { … }")
public var boolValue: Bool {
return countElements(self) != 0
}
// Implement Printable (allows for "println(set)")
public var description: String {
var s = "Set(["
for (i, value) in enumerate(self) {
s += "\(value)"
if i != countElements(self) - 1 {
s += ", "
}
}
s += "])"
return s
}
// Implement SequenceType (allows for "for x in set")
public func generate() -> IndexingGenerator<[T]> {
return Array(self.internalDict.keys).generate()
}
}
// Implement Comparable (allows for "if set1 < set2 { … }")
public func <<T : Hashable>(lhs: Set<T>, rhs: Set<T>) -> Bool {
if lhs == rhs {
return false
}
for element in lhs {
if !rhs.contains(element) {
return false
}
}
return true
}
// Implement Equatable (allows for "if set1 == set2 { … }")
public func ==<T : Hashable>(lhs: Set<T>, rhs: Set<T>) -> Bool {
return lhs.hashValue == rhs.hashValue
}
public func +<T : Hashable>(lhs: Set<T>, rhs: Set<T>) -> Set<T> {
var newSet = Set<T>(lhs)
newSet.extend(rhs)
return newSet
}
public func -<T : Hashable>(lhs: Set<T>, rhs: Set<T>) -> Set<T> {
var newSet = Set<T>(lhs)
for entry in rhs {
newSet.remove(entry)
}
return newSet
}
public func &<T : Hashable>(lhs: Set<T>, rhs: Set<T>) -> Set<T> {
return lhs.intersection(rhs)
}
public func |<T : Hashable>(lhs: Set<T>, rhs: Set<T>) -> Set<T> {
return lhs + rhs
}
public func +=<T : Hashable>(inout lhs: Set<T>, rhs: Set<T>) {
lhs.extend(rhs)
}
public func |=<T : Hashable>(inout lhs: Set<T>, rhs: Set<T>) {
lhs.extend(rhs)
}
public func &=<T : Hashable>(inout lhs: Set<T>, rhs: Set<T>) {
for entry in lhs {
if rhs.contains(entry) {
lhs.add(entry)
} else {
lhs.remove(entry)
}
}
}
public func +=<T : Hashable>(inout lhs: Set<T>, rhs: T) {
lhs.add(rhs)
}
public func -=<T : Hashable>(inout lhs: Set<T>, rhs: Set<T>) {
for entry in rhs {
lhs.remove(entry)
}
}
public func -=<T : Hashable>(inout lhs: Set<T>, rhs: T) {
lhs.remove(rhs)
}
// For Python compatibility.
public func set<T : Hashable>() -> Set<T> {
return Set()
}
// For Python compatibility.
public func set<T : Hashable>(initialArray: [T]) -> Set<T> {
return Set(initialArray)
}
// For Python compatibility.
public func set<T : Hashable>(initialSet: Set<T>) -> Set<T> {
return Set(initialSet)
}
| 78ba18da7b740fe33525c2ecd2819920 | 25.86747 | 92 | 0.580269 | false | false | false | false |
Johnykutty/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Rules/ProhibitedSuperRule.swift | mit | 2 | //
// ProhibitedSuperRule.swift
// SwiftLint
//
// Created by Aaron McTavish on 12/12/16.
// Copyright © 2016 Realm. All rights reserved.
//
import SourceKittenFramework
public struct ProhibitedSuperRule: ConfigurationProviderRule, ASTRule, OptInRule {
public var configuration = ProhibitedSuperConfiguration()
public init() {}
public static let description = RuleDescription(
identifier: "prohibited_super_call",
name: "Prohibited calls to super",
description: "Some methods should not call super",
nonTriggeringExamples: [
"class VC: UIViewController {\n" +
"\toverride func loadView() {\n" +
"\t}\n" +
"}\n",
"class NSView {\n" +
"\tfunc updateLayer() {\n" +
"\t\tself.method1()" +
"\t}\n" +
"}\n"
],
triggeringExamples: [
"class VC: UIViewController {\n" +
"\toverride func loadView() ↓{\n" +
"\t\tsuper.loadView()\n" +
"\t}\n" +
"}\n",
"class VC: NSFileProviderExtension {\n" +
"\toverride func providePlaceholder(at url: URL," +
"completionHandler: @escaping (Error?) -> Void) ↓{\n" +
"\t\tself.method1()\n" +
"\t\tsuper.providePlaceholder(at:url, completionHandler: completionHandler)\n" +
"\t}\n" +
"}\n",
"class VC: NSView {\n" +
"\toverride func updateLayer() ↓{\n" +
"\t\tself.method1()\n" +
"\t\tsuper.updateLayer()\n" +
"\t\tself.method2()\n" +
"\t}\n" +
"}\n"
]
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard let offset = dictionary.bodyOffset,
let name = dictionary.name,
kind == .functionMethodInstance,
configuration.resolvedMethodNames.contains(name),
dictionary.enclosedSwiftAttributes.contains("source.decl.attribute.override"),
!dictionary.extractCallsToSuper(methodName: name).isEmpty
else { return [] }
return [StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset),
reason: "Method '\(name)' should not call to super function")]
}
}
| c476fb3b1ec7bc5ac6124f2636b7ed42 | 37.681159 | 100 | 0.521169 | false | true | false | false |
cfraz89/RxSwift | refs/heads/master | RxSwift/Observables/Implementations/Merge.swift | mit | 1 | //
// Merge.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
// MARK: Limited concurrency version
final class MergeLimitedSinkIter<S: ObservableConvertibleType, O: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType where S.E == O.E {
typealias E = O.E
typealias DisposeKey = CompositeDisposable.DisposeKey
typealias Parent = MergeLimitedSink<S, O>
private let _parent: Parent
private let _disposeKey: DisposeKey
var _lock: RecursiveLock {
return _parent._lock
}
init(parent: Parent, disposeKey: DisposeKey) {
_parent = parent
_disposeKey = disposeKey
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case .next:
_parent.forwardOn(event)
case .error:
_parent.forwardOn(event)
_parent.dispose()
case .completed:
_parent._group.remove(for: _disposeKey)
if let next = _parent._queue.dequeue() {
_parent.subscribe(next, group: _parent._group)
}
else {
_parent._activeCount = _parent._activeCount - 1
if _parent._stopped && _parent._activeCount == 0 {
_parent.forwardOn(.completed)
_parent.dispose()
}
}
}
}
}
final class MergeLimitedSink<S: ObservableConvertibleType, O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType where S.E == O.E {
typealias E = S
typealias QueueType = Queue<S>
fileprivate let _maxConcurrent: Int
let _lock = RecursiveLock()
// state
fileprivate var _stopped = false
fileprivate var _activeCount = 0
fileprivate var _queue = QueueType(capacity: 2)
fileprivate let _sourceSubscription = SingleAssignmentDisposable()
fileprivate let _group = CompositeDisposable()
init(maxConcurrent: Int, observer: O, cancel: Cancelable) {
_maxConcurrent = maxConcurrent
let _ = _group.insert(_sourceSubscription)
super.init(observer: observer, cancel: cancel)
}
func run(_ source: Observable<S>) -> Disposable {
let _ = _group.insert(_sourceSubscription)
let disposable = source.subscribe(self)
_sourceSubscription.setDisposable(disposable)
return _group
}
func subscribe(_ innerSource: E, group: CompositeDisposable) {
let subscription = SingleAssignmentDisposable()
let key = group.insert(subscription)
if let key = key {
let observer = MergeLimitedSinkIter(parent: self, disposeKey: key)
let disposable = innerSource.asObservable().subscribe(observer)
subscription.setDisposable(disposable)
}
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case .next(let value):
let subscribe: Bool
if _activeCount < _maxConcurrent {
_activeCount += 1
subscribe = true
}
else {
_queue.enqueue(value)
subscribe = false
}
if subscribe {
self.subscribe(value, group: _group)
}
case .error(let error):
forwardOn(.error(error))
dispose()
case .completed:
if _activeCount == 0 {
forwardOn(.completed)
dispose()
}
else {
_sourceSubscription.dispose()
}
_stopped = true
}
}
}
final class MergeLimited<S: ObservableConvertibleType> : Producer<S.E> {
private let _source: Observable<S>
private let _maxConcurrent: Int
init(source: Observable<S>, maxConcurrent: Int) {
_source = source
_maxConcurrent = maxConcurrent
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = MergeLimitedSink<S, O>(maxConcurrent: _maxConcurrent, observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
// MARK: Merge
final class MergeBasicSink<S: ObservableConvertibleType, O: ObserverType> : MergeSink<S, S, O> where O.E == S.E {
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: S) throws -> S {
return element
}
}
// MARK: flatMap
final class FlatMapSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : MergeSink<SourceType, S, O> where O.E == S.E {
typealias Selector = (SourceType) throws -> S
private let _selector: Selector
init(selector: @escaping Selector, observer: O, cancel: Cancelable) {
_selector = selector
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: SourceType) throws -> S {
return try _selector(element)
}
}
final class FlatMapWithIndexSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : MergeSink<SourceType, S, O> where O.E == S.E {
typealias Selector = (SourceType, Int) throws -> S
private var _index = 0
private let _selector: Selector
init(selector: @escaping Selector, observer: O, cancel: Cancelable) {
_selector = selector
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: SourceType) throws -> S {
return try _selector(element, try incrementChecked(&_index))
}
}
// MARK: FlatMapFirst
final class FlatMapFirstSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : MergeSink<SourceType, S, O> where O.E == S.E {
typealias Selector = (SourceType) throws -> S
private let _selector: Selector
override var subscribeNext: Bool {
return _group.count == MergeNoIterators
}
init(selector: @escaping Selector, observer: O, cancel: Cancelable) {
_selector = selector
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: SourceType) throws -> S {
return try _selector(element)
}
}
// It's value is one because initial source subscription is always in CompositeDisposable
private let MergeNoIterators = 1
final class MergeSinkIter<SourceType, S: ObservableConvertibleType, O: ObserverType> : ObserverType where O.E == S.E {
typealias Parent = MergeSink<SourceType, S, O>
typealias DisposeKey = CompositeDisposable.DisposeKey
typealias E = O.E
private let _parent: Parent
private let _disposeKey: DisposeKey
init(parent: Parent, disposeKey: DisposeKey) {
_parent = parent
_disposeKey = disposeKey
}
func on(_ event: Event<E>) {
switch event {
case .next(let value):
_parent._lock.lock(); defer { _parent._lock.unlock() } // lock {
_parent.forwardOn(.next(value))
// }
case .error(let error):
_parent._lock.lock(); defer { _parent._lock.unlock() } // lock {
_parent.forwardOn(.error(error))
_parent.dispose()
// }
case .completed:
_parent._group.remove(for: _disposeKey)
// If this has returned true that means that `Completed` should be sent.
// In case there is a race who will sent first completed,
// lock will sort it out. When first Completed message is sent
// it will set observer to nil, and thus prevent further complete messages
// to be sent, and thus preserving the sequence grammar.
if _parent._stopped && _parent._group.count == MergeNoIterators {
_parent._lock.lock(); defer { _parent._lock.unlock() } // lock {
_parent.forwardOn(.completed)
_parent.dispose()
// }
}
}
}
}
class MergeSink<SourceType, S: ObservableConvertibleType, O: ObserverType>
: Sink<O>
, ObserverType where O.E == S.E {
typealias ResultType = O.E
typealias Element = SourceType
fileprivate let _lock = RecursiveLock()
fileprivate var subscribeNext: Bool {
return true
}
// state
fileprivate let _group = CompositeDisposable()
fileprivate let _sourceSubscription = SingleAssignmentDisposable()
fileprivate var _stopped = false
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func performMap(_ element: SourceType) throws -> S {
rxAbstractMethod()
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let element):
if !subscribeNext {
return
}
do {
let value = try performMap(element)
subscribeInner(value.asObservable())
}
catch let e {
forwardOn(.error(e))
dispose()
}
case .error(let error):
_lock.lock(); defer { _lock.unlock() } // lock {
forwardOn(.error(error))
dispose()
// }
case .completed:
_lock.lock(); defer { _lock.unlock() } // lock {
_stopped = true
if _group.count == MergeNoIterators {
forwardOn(.completed)
dispose()
}
else {
_sourceSubscription.dispose()
}
//}
}
}
func subscribeInner(_ source: Observable<O.E>) {
let iterDisposable = SingleAssignmentDisposable()
if let disposeKey = _group.insert(iterDisposable) {
let iter = MergeSinkIter(parent: self, disposeKey: disposeKey)
let subscription = source.subscribe(iter)
iterDisposable.setDisposable(subscription)
}
}
func run(_ source: Observable<SourceType>) -> Disposable {
let _ = _group.insert(_sourceSubscription)
let subscription = source.subscribe(self)
_sourceSubscription.setDisposable(subscription)
return _group
}
}
// MARK: Producers
final class FlatMap<SourceType, S: ObservableConvertibleType>: Producer<S.E> {
typealias Selector = (SourceType) throws -> S
private let _source: Observable<SourceType>
private let _selector: Selector
init(source: Observable<SourceType>, selector: @escaping Selector) {
_source = source
_selector = selector
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = FlatMapSink(selector: _selector, observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
final class FlatMapWithIndex<SourceType, S: ObservableConvertibleType>: Producer<S.E> {
typealias Selector = (SourceType, Int) throws -> S
private let _source: Observable<SourceType>
private let _selector: Selector
init(source: Observable<SourceType>, selector: @escaping Selector) {
_source = source
_selector = selector
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = FlatMapWithIndexSink<SourceType, S, O>(selector: _selector, observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
final class FlatMapFirst<SourceType, S: ObservableConvertibleType>: Producer<S.E> {
typealias Selector = (SourceType) throws -> S
private let _source: Observable<SourceType>
private let _selector: Selector
init(source: Observable<SourceType>, selector: @escaping Selector) {
_source = source
_selector = selector
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = FlatMapFirstSink<SourceType, S, O>(selector: _selector, observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
final class Merge<S: ObservableConvertibleType> : Producer<S.E> {
private let _source: Observable<S>
init(source: Observable<S>) {
_source = source
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E {
let sink = MergeBasicSink<S, O>(observer: observer, cancel: cancel)
let subscription = sink.run(_source)
return (sink: sink, subscription: subscription)
}
}
| 7b612afd64de19739e35d2f1408fab98 | 30.699052 | 140 | 0.600583 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | Client/Cliqz/Frontend/Browser/Dashboard/Offrz/OffrView.swift | mpl-2.0 | 1 | //
// OffrView.swift
// Client
//
// Created by Sahakyan on 12/7/17.
// Copyright © 2017 Mozilla. All rights reserved.
//
import Foundation
class OffrView: UIView {
private var offr: Offr!
private let titleLabel = UILabel()
private let descriptionLabel = UILabel()
private let logoView = UIImageView()
private let promoCodeLabel = UILabel()
private let promoCodeButton = UIButton(type: .custom)
private let conditionsIcon = UIImageView()
private let conditionsLabel = UILabel()
private let conditionsDesc = UILabel()
private let myOffrzLogo = UIImageView()
private let offrButton = UIButton(type: .custom)
private var isExpanded = false
init(offr: Offr) {
super.init(frame: CGRect.zero)
self.offr = offr
self.setupComponents()
self.setStyles()
self.setConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addTapAction(_ target: Any?, action: Selector) {
self.offrButton.addTarget(target, action: action, for: .touchUpInside)
}
func expand() {
self.isExpanded = true
conditionsDesc.text = offr.conditions
setConstraints()
}
func shrink() {
self.isExpanded = false
self.conditionsDesc.removeFromSuperview()
setConstraints()
}
private func setupComponents() {
titleLabel.text = offr.title
descriptionLabel.text = offr.description
if let logoURL = offr.logoURL {
LogoLoader.downloadImage(logoURL, completed: { (logoImage, error) in
self.logoView.image = logoImage
})
}
promoCodeLabel.text = NSLocalizedString("MyOffrz Copy promocode", tableName: "Cliqz", comment: "[MyOffrz] copy promocode action hint")
promoCodeButton.setTitle(offr.code, for: .normal)
promoCodeButton.addTarget(self, action: #selector(copyCode), for: .touchUpInside)
conditionsLabel.text = NSLocalizedString("MyOffrz Conditions", tableName: "Cliqz", comment: "[MyOffrz] Conditions title")
conditionsIcon.image = UIImage(named: "trackerInfo")
offrButton.setTitle(offr.actionTitle, for: .normal)
self.addSubview(titleLabel)
self.addSubview(descriptionLabel)
self.addSubview(logoView)
self.addSubview(promoCodeLabel)
self.addSubview(promoCodeButton)
self.addSubview(conditionsIcon)
self.addSubview(conditionsLabel)
self.addSubview(conditionsDesc)
self.addSubview(myOffrzLogo)
self.addSubview(offrButton)
}
private func setStyles() {
self.layer.cornerRadius = 35
self.clipsToBounds = true
self.backgroundColor = UIColor.white
// self.dropShadow(color: UIColor.black, opacity: 0.12, offSet: CGSize(width: 0, height: 2), radius: 4)
titleLabel.font = UIFont.boldSystemFont(ofSize: 18)
titleLabel.numberOfLines = 0
descriptionLabel.numberOfLines = 0
logoView.contentMode = .scaleAspectFit
promoCodeLabel.textColor = UIConstants.CliqzThemeColor
promoCodeLabel.font = UIFont.boldSystemFont(ofSize: 11)
promoCodeButton.setTitleColor(UIConstants.CliqzThemeColor, for: .normal)
promoCodeButton.backgroundColor = UIColor(rgb: 0xE7ECEE)
promoCodeButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
conditionsIcon.tintColor = UIConstants.CliqzThemeColor
conditionsIcon.contentMode = .scaleAspectFit
conditionsLabel.textColor = UIColor.black
conditionsLabel.font = UIFont.boldSystemFont(ofSize: 10)
conditionsDesc.textColor = UIColor.black
conditionsDesc.font = UIFont.boldSystemFont(ofSize: 10)
conditionsDesc.numberOfLines = 0
myOffrzLogo.image = UIImage(named: "offrzLogo")
offrButton.backgroundColor = UIColor(rgb: 0xF67057)
offrButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 22)
}
private func setConstraints() {
titleLabel.snp.remakeConstraints { (make) in
make.left.right.equalTo(self).inset(15)
make.top.equalTo(self).inset(20)
make.height.greaterThanOrEqualTo(20)
}
descriptionLabel.snp.remakeConstraints { (make) in
make.left.right.equalTo(self).inset(15)
make.top.equalTo(titleLabel.snp.bottom).offset(10)
make.height.greaterThanOrEqualTo(60)
}
logoView.snp.remakeConstraints { (make) in
// make.top.equalTo(descriptionLabel.snp.bottom).offset(10)
make.center.equalTo(self)
make.width.lessThanOrEqualTo(self).offset(-10)
}
promoCodeLabel.snp.remakeConstraints { (make) in
make.bottom.equalTo(promoCodeButton.snp.top).offset(-4)
make.left.right.equalTo(self).inset(15)
}
promoCodeButton.snp.remakeConstraints { (make) in
make.bottom.equalTo(conditionsIcon.snp.top).offset(-10)
make.left.right.equalTo(self).inset(15)
}
conditionsIcon.snp.remakeConstraints { (make) in
make.bottom.equalTo(conditionsDesc.snp.top).offset(-10)
make.left.equalTo(self).inset(15)
}
conditionsLabel.snp.remakeConstraints { (make) in
make.bottom.equalTo(conditionsDesc.snp.top).offset(-11)
make.left.equalTo(conditionsIcon.snp.right).offset(5)
make.height.equalTo(15)
}
conditionsDesc.snp.remakeConstraints { (make) in
make.bottom.equalTo(offrButton.snp.top).offset(-11)
make.left.equalTo(self).inset(15)
make.right.equalTo(self).inset(10)
}
if (offr.conditions ?? "") == "" {
conditionsIcon.snp.remakeConstraints { (make) in
make.bottom.equalTo(conditionsDesc.snp.top).offset(-10)
make.left.equalTo(self).inset(15)
make.width.height.equalTo(0)
}
conditionsLabel.snp.remakeConstraints { (make) in
make.bottom.equalTo(conditionsDesc.snp.top).offset(-11)
make.left.equalTo(conditionsIcon.snp.right).offset(5)
make.height.equalTo(0)
}
conditionsDesc.snp.remakeConstraints { (make) in
make.bottom.equalTo(offrButton.snp.top).offset(-11)
make.left.equalTo(self).inset(15)
make.right.equalTo(self).inset(10)
make.height.equalTo(0)
}
}
myOffrzLogo.snp.remakeConstraints { (make) in
make.right.equalTo(self).offset(-8)
make.bottom.equalTo(offrButton.snp.top)
}
offrButton.snp.remakeConstraints { (make) in
make.bottom.equalTo(self)
make.left.right.equalTo(self)
make.height.equalTo(61)
}
}
@objc
private func copyCode() {
TelemetryLogger.sharedInstance.logEvent(.MyOffrz("copy", ["target" : "code"]))
let pastBoard = UIPasteboard.general
pastBoard.string = offr.code
self.promoCodeLabel.text = NSLocalizedString("MyOffrz Code copied", tableName: "Cliqz", comment: "[MyOffrz] copy promocode done")
}
}
| 5e12a3b1686dde6068985eb1170797ac | 34.398936 | 142 | 0.702179 | false | false | false | false |
danielsawin/cordova-plugin-novelty-watchface | refs/heads/master | src/ios/Watchface.swift | mit | 1 | //
// Watchface.swift
//
//
// Created by Daniel Sawin on 10/19/17.
//
import Photos
@objc(Watchface) class Watchface : CDVPlugin {
class CustomPhotoAlbum {
var albumName = "Album Name"
var assetCollection: PHAssetCollection!
func load() {
if let assetCollection = fetchAssetCollectionForAlbum() {
self.assetCollection = assetCollection
return
}
if PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.authorized {
PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) -> Void in
()
})
}
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
self.createAlbum()
} else {
PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler)
}
}
func requestAuthorizationHandler(status: PHAuthorizationStatus) {
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
// ideally this ensures the creation of the photo album even if authorization wasn't prompted till after init was done
print("trying again to create the album")
self.createAlbum()
} else {
print("should really prompt the user to let them know it's failed")
}
}
func createAlbum() {
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: self.albumName) // create an asset collection with the album name
}) { success, error in
if success {
self.assetCollection = self.fetchAssetCollectionForAlbum()
} else {
print("error \(String(describing: error))")
}
}
}
func fetchAssetCollectionForAlbum() -> PHAssetCollection? {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", self.albumName)
let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let _: AnyObject = collection.firstObject {
return collection.firstObject
}
return nil
}
func save(image: UIImage) {
if self.assetCollection == nil {
print("error")
return // if there was an error upstream, skip the save
}
PHPhotoLibrary.shared().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
let enumeration: NSArray = [assetPlaceHolder!]
albumChangeRequest!.addAssets(enumeration)
}, completionHandler: nil)
}
func reMoveImages(oldAlbum:PHAssetCollection) {
let oldFace = PHAsset.fetchKeyAssets(in: self.assetCollection, options: nil)!
if(oldFace.firstObject != nil){
PHPhotoLibrary.shared().performChanges({
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
albumChangeRequest!.removeAssets(oldFace)
}, completionHandler: nil)
PHPhotoLibrary.shared().performChanges({
let albumChangeRequest = PHAssetCollectionChangeRequest(for: oldAlbum)
albumChangeRequest!.addAssets(oldFace)
}, completionHandler: nil)
}else{
NSLog("no images to remove...")
}
}
}
func getAssetThumbnail(asset: PHAsset) -> UIImage {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
@objc(update:)
func update(command: CDVInvokedUrlCommand) {
//Fetch and Create Albums
let mainAlbum = CustomPhotoAlbum()
mainAlbum.albumName = "oneWatch"
mainAlbum.load()
let oldAlbum = CustomPhotoAlbum()
oldAlbum.albumName = "oneWatch Archive"
oldAlbum.load()
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
var dataURL: String
dataURL = command.arguments[0] as! String
//Create image with DataURL
var newFace: UIImage
if let decodedData = Data(base64Encoded: dataURL, options: .ignoreUnknownCharacters) {
let image = UIImage(data: decodedData)
newFace = image!
//Check if folders exist
if(mainAlbum.fetchAssetCollectionForAlbum() == nil){
NSLog("creating albums...")
mainAlbum.createAlbum()
oldAlbum.createAlbum()
mainAlbum.save(image: newFace)
pluginResult = CDVPluginResult(
status: CDVCommandStatus_OK
)
}else{
NSLog("removing images...")
mainAlbum.reMoveImages(oldAlbum: oldAlbum.assetCollection)
}
if(oldAlbum.fetchAssetCollectionForAlbum() == nil){
oldAlbum.createAlbum()
}else{
NSLog("saving new face...")
mainAlbum.save(image: newFace)
pluginResult = CDVPluginResult(
status: CDVCommandStatus_OK
)
}
}
//Send pluginResult
self.commandDelegate!.send(
pluginResult,
callbackId: command.callbackId
)
}
/*@objc(getCurrentFace:)
func getCurrentFace(command: CDVInvokedUrlCommand) {
let mainAlbum = CustomPhotoAlbum()
mainAlbum.albumName = "oneWatch"
mainAlbum.load()
let currentFace = PHAsset.fetchKeyAssets(in: mainAlbum.assetCollection, options: nil)!
let img = getAssetThumbnail(asset: currentFace.firstObject!)
let imageData = UIImageJPEGRepresentation(img, 0.5)
let strBase64 = imageData?.base64EncodedString(options: .lineLength64Characters)
print(strBase64 ?? "encoding failed...")
let pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR,
messageAs: strBase64
)
self.commandDelegate!.send(
pluginResult,
callbackId: command.callbackId
)
}*/
}
| dc39a59aaf438abeff097616fcce2ed0 | 36.832461 | 167 | 0.571409 | false | false | false | false |
groschovskiy/firebase-for-banking-app | refs/heads/master | Demo/Banking/BBIAirways.swift | apache-2.0 | 1 | //
// BBIAirways.swift
// Banking
//
// Created by Dmitriy Groschovskiy on 07/11/2016.
// Copyright © 2016 Barclays Bank, PLC. All rights reserved.
//
import UIKit
import Firebase
class BBIAirways: UIViewController {
var favoriteCreditCard: String = ""
@IBOutlet weak var passengerName: UILabel!
@IBOutlet weak var passengerPassport: UILabel!
@IBOutlet weak var tripLocation: UILabel!
@IBOutlet weak var tripCost: UILabel!
@IBOutlet weak var tripDate: UILabel!
@IBOutlet weak var tripClass: UILabel!
@IBOutlet weak var bookingIdent: UITextField!
@IBOutlet weak var ticketNumberBackground: UIView!
@IBOutlet weak var creditCardBackground: UIView!
@IBOutlet weak var informationBackground: UIView!
@IBOutlet weak var buttonViewBackground: UIView!
@IBOutlet weak var collectionView : UICollectionView!
var paymentCardsArray: [BBCardModel] = []
override func viewDidLoad() {
super.viewDidLoad()
self.ticketNumberBackground.layer.cornerRadius = 5
self.ticketNumberBackground.layer.masksToBounds = true
self.informationBackground.layer.cornerRadius = 5
self.informationBackground.layer.masksToBounds = true
self.informationBackground.layer.cornerRadius = 5
self.informationBackground.layer.masksToBounds = true
self.buttonViewBackground.layer.cornerRadius = 5
self.buttonViewBackground.layer.masksToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - UICollectionViewDataSource with credit cards
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.paymentCardsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! BBPaymentCardsCell
let cardItem = paymentCardsArray[indexPath.row]
//cell.creditCardHolder.text = cardItem.creditCardHolder
//cell.creditCardExpiration.text = cardItem.creditCardExpiration
//cell.creditCardNumber.text = "\(cardItem.creditCardNumber)"
//cell.creditCardBalance.text = String(format: "£%.2f", cardItem.creditCardAmount)
//cell.creditCardPIN.text = "\(cardItem.creditCardPIN)"
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.item)!")
}
@IBAction func receiveBoardPassInfo(sender: UIButton) {
let purchaseRef = FIRDatabase.database().reference(withPath: "Vouchers/\(bookingIdent.text!)")
purchaseRef.queryOrdered(byChild: "purchaseValue").observe(.value, with: { snapshot in
let dataSnapshot = snapshot.value as! [String: AnyObject]
self.passengerName.text = String(format: "%@", dataSnapshot["passengerName"] as! String!)
self.passengerPassport.text = String(format: "%@", dataSnapshot["passportCountry"] as! String!)
self.tripLocation.text = String(format: "%@", dataSnapshot["bookingWays"] as! String!)
self.tripCost.text = String(format: "£%.2f with comission", dataSnapshot["bookingPrice"] as! Double!)
self.tripDate.text = String(format: "%@", dataSnapshot["bookingDate"] as! String!)
self.tripClass.text = String(format: "%@", dataSnapshot["bookingClass"] as! String!)
})
}
@IBAction func payWithCreditCard(sender: UIButton) {
if (favoriteCreditCard == "") {
} else {
}
}
@IBAction func closeController(sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
}
| fcbb0873b64f600c52b27090d5740983 | 39.226804 | 134 | 0.690159 | false | false | false | false |
DonMag/ScratchPad | refs/heads/master | Swift3/scratchy/scratchy/StackWorkViewController.swift | mit | 1 | //
// StackWorkViewController.swift
// scratchy
//
// Created by Don Mag on 2/27/17.
// Copyright © 2017 DonMag. All rights reserved.
//
import UIKit
class StackWorkViewController: UIViewController {
@IBOutlet weak var theStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func testTap(_ sender: Any) {
if theStackView.arrangedSubviews.count > 2 {
// we already added the subviews
return
}
let clrs = [UIColor.red, UIColor.blue, UIColor.yellow, UIColor.green]
for i in 1...4 {
let v = SampleView()
v.theLabel.text = "\(i)"
v.backgroundColor = clrs[i % 4]
v.translatesAutoresizingMaskIntoConstraints = false
theStackView.addArrangedSubview(v)
}
}
}
| d5332b3df345adf74353be517be1f4a9 | 16.892857 | 71 | 0.649701 | false | false | false | false |
Chaosspeeder/YourGoals | refs/heads/master | YourGoals/Business/Data Model/Generator/StrategyGenerator.swift | lgpl-3.0 | 1 | //
// FitnessHistoryGenerator.swift
// YourFitnessPlan
//
// Created by André Claaßen on 03.06.16.
// Copyright © 2016 André Claaßen. All rights reserved.
//
import Foundation
import UIKit
class StrategyGenerator : Generator, GeneratorProtocol {
let goals = [
(prio: 1,
name: "YourGoals entwickeln",
image: "YourGoals",
reason: "Ich brauche eine App, die meinem Ziel der Zielentwicklung optimal gerecht wird. Und das ist visuell und gewohnheitsorientiert",
startDate: Date.dateWithYear(2017, month: 10, day: 15),
targetDate: Date.dateWithYear(2018, month: 05, day: 19)),
(prio: 2,
name: "YourDay fertig stellen",
image: "YourDay",
reason: "Ich möchte mein Journal in der Form in den Store stellen, dass es ein gutes Feedback gibt.",
startDate: Date.dateWithYear(2017, month: 10, day: 15),
targetDate: Date.dateWithYear(2018, month: 02, day: 39)),
]
// MARK: GeneratorProtocol
func generate() throws {
let strategy = try StrategyManager(manager: self.manager).assertValidActiveStrategy()
for tuple in goals {
let goal = self.manager.goalsStore.createPersistentObject()
goal.name = tuple.name
goal.reason = tuple.reason
goal.prio = Int16(tuple.prio)
goal.startDate = tuple.startDate
goal.targetDate = tuple.targetDate
goal.parentGoal = strategy
let imageData = self.manager.imageDataStore.createPersistentObject()
guard let image = UIImage(named: tuple.image) else {
NSLog("could not create an image from tuple data: (\tuple)")
continue
}
imageData.setImage(image: image)
goal.imageData = imageData
}
}
}
| 6c172947ad1a40ef569dc7d4235af6a0 | 33.527273 | 145 | 0.605055 | false | false | false | false |
danielsaidi/KeyboardKit | refs/heads/master | Sources/KeyboardKit/Extensions/UITextDocumentProxy+CurrentWord.swift | mit | 1 | //
// UITextDocumentProxy+CurrentWord.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2019-07-02.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import UIKit
public extension UITextDocumentProxy {
/**
The word that is currently being touched by the cursor.
*/
var currentWord: String? {
let pre = currentWordPreCursorPart
let post = currentWordPostCursorPart
if pre == nil && post == nil { return nil }
return (pre ?? "") + (post ?? "")
}
/**
The part of the current word that is before the cursor.
*/
var currentWordPreCursorPart: String? {
guard var string = documentContextBeforeInput else { return nil }
var result = ""
while let char = string.popLast() {
guard shouldIncludeCharacterInCurrentWord(char) else { return result }
result.insert(char, at: result.startIndex)
}
return result
}
/**
The part of the current word that is after the cursor.
*/
var currentWordPostCursorPart: String? {
guard let string = documentContextAfterInput else { return nil }
var reversed = String(string.reversed())
var result = ""
while let char = reversed.popLast() {
guard shouldIncludeCharacterInCurrentWord(char) else { return result }
result.append(char)
}
return result
}
/**
Whether or not the text document proxy cursor is at the
end of the current word.
*/
var isCursorAtTheEndOfTheCurrentWord: Bool {
if currentWord == nil { return false }
let postCount = currentWordPostCursorPart?.trimmingCharacters(in: .whitespaces).count ?? 0
if postCount > 0 { return false }
guard let pre = currentWordPreCursorPart else { return false }
let lastCharacter = String(pre.suffix(1))
return !wordDelimiters.contains(lastCharacter)
}
/**
Replace the current word with a replacement text.
*/
func replaceCurrentWord(with replacement: String) {
guard let word = currentWord else { return }
let offset = currentWordPostCursorPart?.count ?? 0
adjustTextPosition(byCharacterOffset: offset)
deleteBackward(times: word.count)
insertText(replacement)
}
}
// MARK: - Internal Properties
extension UITextDocumentProxy {
/**
Check if a certain character should be included in the
current word.
*/
func shouldIncludeCharacterInCurrentWord(_ character: Character?) -> Bool {
guard let character = character else { return false }
return !wordDelimiters.contains("\(character)")
}
}
| cadbb3c5984390c1db8a9ea2c27ada61 | 29.897727 | 98 | 0.633321 | false | false | false | false |
cuappdev/podcast-ios | refs/heads/master | old/Podcast/OnboardingViewController.swift | mit | 1 | //
// OnboardingViewController.swift
// Podcast
//
// Created by Natasha Armbrust on 2/28/18.
// Copyright © 2018 Cornell App Development. All rights reserved.
//
import UIKit
class OnboardingViewController: UIViewController {
var gradientBackgroundView: LoginBackgroundGradientView!
let types: [OnboardingType] = [.discover, .connect, .recast]
let onboardingViews: [OnboardingView]!
var onboardingDotStackView: UIStackView!
var nextButton: OnboardingButton!
var prevButton: OnboardingButton!
let onboardingButtonHeight: CGFloat = 42
let onboardingButtonWidth: CGFloat = 120
let onboardingButtonBottomPadding: CGFloat = 120
let onboardingButtonPadding: CGFloat = 20
let isDisabledAlpha: CGFloat = 0.30
var selectedIndex: Int = 0
init() {
onboardingViews = types.map({ type in OnboardingView(type: type)})
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
gradientBackgroundView = LoginBackgroundGradientView(frame: view.frame)
view.addSubview(gradientBackgroundView)
onboardingDotStackView = UIStackView(arrangedSubviews: types.map({ _ in OnboardingDotView()}))
onboardingDotStackView.axis = .horizontal
onboardingDotStackView.distribution = .fillEqually
onboardingDotStackView.alignment = .fill
onboardingDotStackView.spacing = OnboardingDotView.size
view.addSubview(onboardingDotStackView)
for onboardingView in onboardingViews {
view.addSubview(onboardingView)
onboardingView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
let tempView = UIView()
nextButton = OnboardingButton(title: "Next")
nextButton.addTarget(self, action: #selector(nextPress), for: .touchUpInside)
tempView.addSubview(nextButton)
prevButton = OnboardingButton(title: "Previous")
prevButton.addTarget(self, action: #selector(prevPress), for: .touchUpInside)
tempView.addSubview(prevButton)
view.addSubview(tempView)
nextButton.snp.makeConstraints { make in
make.bottom.top.trailing.equalToSuperview()
make.width.equalTo(onboardingButtonWidth)
make.height.equalTo(onboardingButtonHeight)
make.leading.equalTo(prevButton.snp.trailing).offset(onboardingButtonPadding)
}
prevButton.snp.makeConstraints { make in
make.bottom.top.leading.equalToSuperview()
make.width.equalTo(onboardingButtonWidth)
make.height.equalTo(onboardingButtonHeight)
}
// temp view to constraint buttons correctly
tempView.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.bottom.equalToSuperview().inset(onboardingButtonBottomPadding)
}
onboardingDotStackView.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.bottom.equalTo(nextButton.snp.top).inset(onboardingButtonBottomPadding)
make.height.equalTo(OnboardingDotView.size)
make.width.equalTo(CGFloat(types.count) * OnboardingDotView.size + CGFloat(types.count - 1) * OnboardingDotView.size)
}
updateSelectedIndex()
}
@objc func nextPress() {
selectedIndex += 1
if selectedIndex >= types.count {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
appDelegate.finishedOnboarding()
return
}
updateSelectedIndex()
}
@objc func prevPress() {
selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : 0 // don't go out of bounds
updateSelectedIndex()
}
func updateSelectedIndex() {
for (i,onboardingView) in onboardingViews.enumerated() {
onboardingView.isHidden = i != selectedIndex
(onboardingDotStackView.arrangedSubviews[i] as! OnboardingDotView).isSelected(i == selectedIndex)
}
prevButton.alpha = selectedIndex == 0 ? isDisabledAlpha : 1
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| f7fe5ffb55664825d5e306e3cbabf398 | 35.025424 | 129 | 0.675606 | false | false | false | false |
Ehrippura/firefox-ios | refs/heads/master | Storage/SQL/SQLiteHistoryRecommendations.swift | mpl-2.0 | 3 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
fileprivate let log = Logger.syncLogger
extension SQLiteHistory: HistoryRecommendations {
// Bookmarks Query
static let removeMultipleDomainsSubquery =
" INNER JOIN (SELECT \(ViewHistoryVisits).domain_id AS domain_id" +
" FROM \(ViewHistoryVisits)" +
" GROUP BY \(ViewHistoryVisits).domain_id) AS domains ON domains.domain_id = \(TableHistory).domain_id"
static let bookmarkHighlights =
"SELECT historyID, url, siteTitle, guid, is_bookmarked FROM (" +
" SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, \(TableHistory).title AS siteTitle, guid, \(TableHistory).domain_id, NULL AS visitDate, 1 AS is_bookmarked" +
" FROM (" +
" SELECT bmkUri" +
" FROM \(ViewBookmarksLocalOnMirror)" +
" WHERE \(ViewBookmarksLocalOnMirror).server_modified > ? OR \(ViewBookmarksLocalOnMirror).local_modified > ?" +
" )" +
" LEFT JOIN \(TableHistory) ON \(TableHistory).url = bmkUri" + removeMultipleDomainsSubquery +
" WHERE \(TableHistory).title NOT NULL and \(TableHistory).title != '' AND url NOT IN" +
" (SELECT \(TableActivityStreamBlocklist).url FROM \(TableActivityStreamBlocklist))" +
" LIMIT ?" +
")"
static let bookmarksQuery =
"SELECT historyID, url, siteTitle AS title, guid, is_bookmarked, iconID, iconURL, iconType, iconDate, iconWidth, \(TablePageMetadata).title AS metadata_title, media_url, type, description, provider_name " +
"FROM (\(bookmarkHighlights) ) " +
"LEFT JOIN \(ViewHistoryIDsWithWidestFavicons) ON \(ViewHistoryIDsWithWidestFavicons).id = historyID " +
"LEFT OUTER JOIN \(TablePageMetadata) ON \(TablePageMetadata).cache_key = url " +
"GROUP BY url"
// Highlights Query
static let highlightsLimit = 8
static let blacklistedHosts: Args = [
"google.com",
"google.ca",
"calendar.google.com",
"mail.google.com",
"mail.yahoo.com",
"search.yahoo.com",
"localhost",
"t.co"
]
static let blacklistSubquery = "SELECT \(TableDomains).id FROM \(TableDomains) WHERE \(TableDomains).domain IN " + BrowserDB.varlist(blacklistedHosts.count)
static let removeMultipleDomainsSubqueryFromHighlights =
" INNER JOIN (SELECT \(ViewHistoryVisits).domain_id AS domain_id, MAX(\(ViewHistoryVisits).visitDate) AS visit_date" +
" FROM \(ViewHistoryVisits)" +
" GROUP BY \(ViewHistoryVisits).domain_id) AS domains ON domains.domain_id = \(TableHistory).domain_id AND visitDate = domains.visit_date"
static let nonRecentHistory =
"SELECT historyID, url, siteTitle, guid, visitCount, visitDate, is_bookmarked, visitCount * icon_url_score * media_url_score AS score FROM (" +
" SELECT \(TableHistory).id as historyID, url, \(TableHistory).title AS siteTitle, guid, visitDate, \(TableHistory).domain_id," +
" (SELECT COUNT(1) FROM \(TableVisits) WHERE s = \(TableVisits).siteID) AS visitCount," +
" (SELECT COUNT(1) FROM \(ViewBookmarksLocalOnMirror) WHERE \(ViewBookmarksLocalOnMirror).bmkUri == url) AS is_bookmarked," +
" CASE WHEN iconURL IS NULL THEN 1 ELSE 2 END AS icon_url_score," +
" CASE WHEN media_url IS NULL THEN 1 ELSE 4 END AS media_url_score" +
" FROM (" +
" SELECT siteID AS s, MAX(date) AS visitDate" +
" FROM \(TableVisits)" +
" WHERE date < ?" +
" GROUP BY siteID" +
" ORDER BY visitDate DESC" +
" )" +
" LEFT JOIN \(TableHistory) ON \(TableHistory).id = s" +
removeMultipleDomainsSubqueryFromHighlights +
" LEFT OUTER JOIN \(ViewHistoryIDsWithWidestFavicons) ON" +
" \(ViewHistoryIDsWithWidestFavicons).id = \(TableHistory).id" +
" LEFT OUTER JOIN \(TablePageMetadata) ON" +
" \(TablePageMetadata).site_url = \(TableHistory).url" +
" WHERE visitCount <= 3 AND \(TableHistory).title NOT NULL AND \(TableHistory).title != '' AND is_bookmarked == 0 AND url NOT IN" +
" (SELECT url FROM \(TableActivityStreamBlocklist))" +
" AND \(TableHistory).domain_id NOT IN ("
+ blacklistSubquery + ")" +
")"
public func getHighlights() -> Deferred<Maybe<Cursor<Site>>> {
let highlightsProjection = [
"historyID",
"\(TableHighlights).cache_key AS cache_key",
"url",
"\(TableHighlights).title AS title",
"guid",
"visitCount",
"visitDate",
"is_bookmarked"
]
let faviconsProjection = ["iconID", "iconURL", "iconType", "iconDate", "iconWidth"]
let metadataProjections = [
"\(TablePageMetadata).title AS metadata_title",
"media_url",
"type",
"description",
"provider_name"
]
let allProjection = highlightsProjection + faviconsProjection + metadataProjections
let highlightsHistoryIDs =
"SELECT historyID FROM \(TableHighlights)"
// Search the history/favicon view with our limited set of highlight IDs
// to avoid doing a full table scan on history
let faviconSearch =
"SELECT * FROM \(ViewHistoryIDsWithWidestFavicons) WHERE id IN (\(highlightsHistoryIDs))"
let sql =
"SELECT \(allProjection.joined(separator: ",")) " +
"FROM \(TableHighlights) " +
"LEFT JOIN (\(faviconSearch)) AS f1 ON f1.id = historyID " +
"LEFT OUTER JOIN \(TablePageMetadata) ON " +
"\(TablePageMetadata).cache_key = \(TableHighlights).cache_key"
return self.db.runQuery(sql, args: nil, factory: SQLiteHistory.iconHistoryMetadataColumnFactory)
}
public func removeHighlightForURL(_ url: String) -> Success {
return self.db.run([("INSERT INTO \(TableActivityStreamBlocklist) (url) VALUES (?)", [url])])
}
private func repopulateHighlightsQuery() -> [(String, Args?)] {
let (query, args) = computeHighlightsQuery()
let clearHighlightsQuery = "DELETE FROM \(TableHighlights)"
let sql = "INSERT INTO \(TableHighlights) " +
"SELECT historyID, url as cache_key, url, title, guid, visitCount, visitDate, is_bookmarked " +
"FROM (\(query))"
return [(clearHighlightsQuery, nil), (sql, args)]
}
public func repopulate(invalidateTopSites shouldInvalidateTopSites: Bool, invalidateHighlights shouldInvalidateHighlights: Bool) -> Success {
var queries: [(String, Args?)] = []
if shouldInvalidateTopSites {
queries.append(contentsOf: self.refreshTopSitesQuery())
}
if shouldInvalidateHighlights {
queries.append(contentsOf: self.repopulateHighlightsQuery())
}
return self.db.run(queries)
}
public func getRecentBookmarks(_ limit: Int = 3) -> Deferred<Maybe<Cursor<Site>>> {
let fiveDaysAgo: UInt64 = Date.now() - (OneDayInMilliseconds * 5) // The data is joined with a millisecond not a microsecond one. (History)
let args = [fiveDaysAgo, fiveDaysAgo, limit] as Args
return self.db.runQuery(SQLiteHistory.bookmarksQuery, args: args, factory: SQLiteHistory.iconHistoryMetadataColumnFactory)
}
private func computeHighlightsQuery() -> (String, Args) {
let microsecondsPerMinute: UInt64 = 60_000_000 // 1000 * 1000 * 60
let now = Date.nowMicroseconds()
let thirtyMinutesAgo: UInt64 = now - 30 * microsecondsPerMinute
let highlightsQuery =
"SELECT historyID, url, siteTitle AS title, guid, visitCount, visitDate, is_bookmarked, score " +
"FROM ( \(SQLiteHistory.nonRecentHistory) ) " +
"GROUP BY url " +
"ORDER BY score DESC " +
"LIMIT \(SQLiteHistory.highlightsLimit)"
let args: Args = [thirtyMinutesAgo] + SQLiteHistory.blacklistedHosts
return (highlightsQuery, args)
}
}
| 24f8e02f0df0c20f38c8e3f8ba8a66ca | 48.952941 | 214 | 0.621762 | false | false | false | false |
dboyliao/NumSwift | refs/heads/master | NumSwift/Source/Power.swift | mit | 1 | //
// Dear maintainer:
//
// When I wrote this code, only I and God
// know what it was.
// Now, only God knows!
//
// So if you are done trying to 'optimize'
// this routine (and failed),
// please increment the following counter
// as warning to the next guy:
//
// var TotalHoursWastedHere = 0
//
// Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered
import Accelerate
/**
Raise each element in x to specific power.
- Parameters:
- x: An array of single precision floating numbers.
- power: the power to raise the elements in `x` to.
- Returns: An array of floating numbers with its i-th element be raised to
the `power`-th power of x[i].
*/
public func pow(_ x: [Float], power: Float) -> [Float] {
var y = [Float](repeating: 0.0, count: x.count)
let powers = [Float](repeating: power, count: x.count)
var N = Int32(x.count)
vvpowf(&y, x, powers, &N)
return y
}
/**
Raise each element in x to specific power.
- Parameters:
- x: An array of double precision floating numbers.
- power: the power to raise the elements in `x` to.
- Returns: An array of floating numbers with its i-th element be raised to
the `power`-th power of x[i].
*/
public func pow(_ x:[Double], power: Double) -> [Double] {
var y = [Double](repeating: 0.0, count: x.count)
let powers = [Double](repeating: power, count: x.count)
var N = Int32(x.count)
vvpow(&y, x, powers, &N)
return y
}
/**
Compute Square Root (Vectorized)
- Parameters:
- x: the input array of double precision floating numbers.
- Returns: A double precision floating number array with its i-th
element as the square root of `x[i]`
*/
public func sqrt(_ x:[Double]) -> [Double] {
var input = [Double](x)
var output = [Double](repeating: 0.0, count: x.count)
var N = Int32(x.count)
vvsqrt(&output, &input, &N)
return output
}
/**
Compute Square Root (Vectorized)
- Parameters:
- x: the input array of single precision floating numbers.
- Returns: A single precision floating number array with its i-th
element as the square root of `x[i]`
*/
public func sqrt(_ x:[Float]) -> [Float] {
var input = [Float](x)
var output = [Float](repeating: 0.0, count: x.count)
var N = Int32(x.count)
vvsqrtf(&output, &input, &N)
return output
}
| 39477b886b67cb78539f43b4f9626231 | 24.113402 | 121 | 0.640805 | false | false | false | false |
vowed21/HWSwiftyViewPager | refs/heads/master | HWSwiftyViewPagerDemo/HWSwiftyViewPagerDemo/TableViewCell.swift | mit | 1 | //
// TableViewCell.swift
// HWSwiftViewPager
//
// Created by HyunWoo Kim on 2016. 1. 11..
// Copyright © 2016년 KokohApps. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell, UICollectionViewDataSource, HWSwiftyViewPagerDelegate {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var pager: HWSwiftyViewPager!
override func awakeFromNib() {
super.awakeFromNib()
self.pager.dataSource = self
self.pager.pageSelectedDelegate = self
}
//MARK: CollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath)
return cell
}
//MARK: HWSwiftyViewPagerDelegate
func pagerDidSelecedPage(_ selectedPage: Int) {
let string = "SelectedPage = \(selectedPage)"
self.label.text = string
}
}
| 3dc2962ceb987909bd1d42aa78a4ee82 | 25.363636 | 121 | 0.681034 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | refs/heads/master | 04-App Architecture/Swift 3/Playgrounds/Closures.playground/Pages/Creating Asynchrnoous API's with CGD.xcplaygroundpage/Contents.swift | mit | 2 | //: [Previous](@previous)
import UIKit
import PlaygroundSupport
//: 
//: ## Creating an Asychronous API with GCD
//:
//: The following is needed to allow the execution of the playground to continue beyond the scope of the higher-order function.
PlaygroundPage.current.needsIndefiniteExecution = true
let deg2rad = { $0*M_PI/180.0 }
let rad2deg = { $0 * 180.0 / M_PI }
//: #### Grand Central Dispatch (alternative)
//: While we are on the subject of multi-threaded code, `NSOperationQueue` is built on a lower-level technology, *Grand Central Dispatch* (GCD). This is commonly used, so it is worth highlighting.
//: Let's return to the original synchronous function
func synchronousHillClimbWithInitialValue(_ xx : Double, 𝛌 : Double, maxIterations: Int, fn : @escaping (Double) -> Double ) -> (x: Double, y : Double)? {
var x0 = xx
func estimateSlope(_ x : Double) -> Double {
let 𝛅 = 1e-6
let 𝛅2 = 2*𝛅
return ( fn(x+𝛅)-fn(x-𝛅) ) / 𝛅2
}
var slope = estimateSlope(x0)
var iteration = 0
while (fabs(slope) > 1e-6) {
//For a positive slope, increase x
x0 += 𝛌 * slope
//Update the gradient estimate
slope = estimateSlope(x0)
//Update count
iteration += 1
if iteration == maxIterations {
return nil
}
}
return (x:x0, y:fn(x0))
}
//: Create / obtain a queue (separate thread) where all tasks can run concurrently
//let q = dispatch_queue_create("calc", DISPATCH_QUEUE_CONCURRENT) //Creates a new queue
let q = DispatchQueue.global(qos: .default) //Use an existing (from the global pool)
//: Dispatch the task on the queue
q.async {
//Call the (computationally intensive) function
let solution = synchronousHillClimbWithInitialValue(0.01, 𝛌: 0.01, maxIterations: 10000, fn: sin)
//: * Perform call-back on main thread. Again, the code is a parameterless trailing-closure.
DispatchQueue.main.sync {
if let s = solution {
print("GCD: Peak of value \(s.y) found at x=\(rad2deg(s.x)) degrees", separator: "")
} else {
print("GCD: Did not converge")
}
//This next line is just to stop the Playground Executing forever
PlaygroundPage.current.finishExecution()
}
}
//: A difficulty with such asychronous APIs is *managing state*, i.e. keeping track of what tasks have completed, including cases where operations may have been unsuccessful.
//:
//: You can think of the asychrounous callbacks as events posted into a run-loop. Different threads of execution can have their own run-loop (read up on `NSThread` and the Concurrency Programming Guide if you are curious).
//: Often, callbacks are *posted* on the runloop for the *main thread* making them much like an `Action` (e.g. tapping a `UIButton`). There are challenges in managing code that uses a lot of asychrnous APIs. I the *breadcrumbs' app (to follow), I am going too show you one that I tend to use: *finite state machines*.
//: [Next](@next)
| 6db80f2994264754c60f4b6412ad9bdf | 37.846154 | 317 | 0.677888 | false | false | false | false |
yoichitgy/SwinjectMVVMExample_ForBlog | refs/heads/master | ExampleViewTests/ImageSearchTableViewControllerSpec.swift | mit | 1 | //
// ImageSearchTableViewControllerSpec.swift
// SwinjectMVVMExample
//
// Created by Yoichi Tagaya on 9/1/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Quick
import Nimble
import ReactiveCocoa
import ExampleViewModel
@testable import ExampleView
class ImageSearchTableViewControllerSpec: QuickSpec {
// MARK: Mock
class MockViewModel: ImageSearchTableViewModeling {
let cellModels = PropertyOf(
MutableProperty<[ImageSearchTableViewCellModeling]>([]))
var startSearchCallCount = 0
func startSearch() {
startSearchCallCount++
}
}
// MARK: Spec
override func spec() {
it("starts searching images when the view is about to appear at the first time.") {
let viewModel = MockViewModel()
let storyboard = UIStoryboard(
name: "Main",
bundle: NSBundle(forClass: ImageSearchTableViewController.self))
let viewController = storyboard.instantiateViewControllerWithIdentifier(
"ImageSearchTableViewController")
as! ImageSearchTableViewController
viewController.viewModel = viewModel
expect(viewModel.startSearchCallCount) == 0
viewController.viewWillAppear(true)
expect(viewModel.startSearchCallCount) == 1
viewController.viewWillAppear(true)
expect(viewModel.startSearchCallCount) == 1
}
}
}
| 3b065400a86c41f7c3bd5e64d9f0ab98 | 31.956522 | 91 | 0.651715 | false | false | false | false |
victorchee/DynamicAnimator | refs/heads/master | DynamicAnimator/DynamicAnimator/PendulumViewController.swift | mit | 1 | //
// PendulumViewController.swift
// DynamicAnimator
//
// Created by qihaijun on 12/24/15.
// Copyright © 2015 VictorChee. All rights reserved.
//
import UIKit
class PendulumViewController: UIViewController {
@IBOutlet weak var attachmentView: UIView!
@IBOutlet weak var itemView: UIView!
var animator: UIDynamicAnimator!
var pendulumBehavior: PendulumBehavior!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Do any additional setup after loading the view.
animator = UIDynamicAnimator(referenceView: view)
let pendulumAttachmentPoint = attachmentView.center
pendulumBehavior = PendulumBehavior(item: itemView, suspendedFromPoint: pendulumAttachmentPoint)
animator.addBehavior(pendulumBehavior)
}
@IBAction func pan(_ sender: UIPanGestureRecognizer) {
let point = sender.location(in: view)
let velocity = sender.velocity(in: view)
if sender.state == .began {
pendulumBehavior.beginDraggingWeightAtPoint(point: point)
} else if sender.state == .ended {
pendulumBehavior.endDraggingWeightWithVelocity(velocity: velocity)
} else if sender.state == .cancelled {
sender.isEnabled = true
pendulumBehavior.endDraggingWeightWithVelocity(velocity: velocity)
} else if !itemView.bounds.contains(point) {
sender.isEnabled = false // cancel
} else {
pendulumBehavior.dragWeightToPoint(point: point)
}
}
}
| edab9e03da220fff19a15e878924fc19 | 33.933333 | 104 | 0.677481 | false | false | false | false |
return/swift | refs/heads/master | test/SILGen/dynamic.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | %FileCheck %s
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify
// REQUIRES: objc_interop
import Foundation
import gizmo
class Foo: Proto {
// Not objc or dynamic, so only a vtable entry
init(native: Int) {}
func nativeMethod() {}
var nativeProp: Int = 0
subscript(native native: Int) -> Int {
get { return native }
set {}
}
// @objc, so it has an ObjC entry point but can also be dispatched
// by vtable
@objc init(objc: Int) {}
@objc func objcMethod() {}
@objc var objcProp: Int = 0
@objc subscript(objc objc: AnyObject) -> Int {
get { return 0 }
set {}
}
// dynamic, so it has only an ObjC entry point
dynamic init(dynamic: Int) {}
dynamic func dynamicMethod() {}
dynamic var dynamicProp: Int = 0
dynamic subscript(dynamic dynamic: Int) -> Int {
get { return dynamic }
set {}
}
func overriddenByDynamic() {}
@NSManaged var managedProp: Int
}
protocol Proto {
func nativeMethod()
var nativeProp: Int { get set }
subscript(native native: Int) -> Int { get set }
func objcMethod()
var objcProp: Int { get set }
subscript(objc objc: AnyObject) -> Int { get set }
func dynamicMethod()
var dynamicProp: Int { get set }
subscript(dynamic dynamic: Int) -> Int { get set }
}
// ObjC entry points for @objc and dynamic entry points
// normal and @objc initializing ctors can be statically dispatched
// CHECK-LABEL: sil hidden @_T07dynamic3FooC{{.*}}tcfC
// CHECK: function_ref @_T07dynamic3FooC{{.*}}tcfc
// CHECK-LABEL: sil hidden @_T07dynamic3FooC{{.*}}tcfC
// CHECK: function_ref @_T07dynamic3FooC{{.*}}tcfc
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3{{[_0-9a-zA-Z]*}}fcTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC10objcMethod{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC8objcPropSifgTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC8objcPropSifsTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC9subscriptSiyXl4objc_tcfgTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC9subscriptSiyXl4objc_tcfsTo
// TODO: dynamic initializing ctor must be objc dispatched
// CHECK-LABEL: sil hidden @_T07dynamic3{{[_0-9a-zA-Z]*}}fC
// CHECK: function_ref @_T07dynamic3{{[_0-9a-zA-Z]*}}fcTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3{{[_0-9a-zA-Z]*}}fcTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.init!initializer.1.foreign :
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3{{[_0-9a-zA-Z]*}}fcTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC0A4PropSifgTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC0A4PropSifsTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC9subscriptS2iAA_tcfgTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC9subscriptS2iAA_tcfsTo
// Protocol witnesses use best appropriate dispatch
// Native witnesses use vtable dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP12nativeMethod{{[_0-9a-zA-Z]*}}FTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP10nativePropSifgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP10nativePropSifsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptS2i6native_tcfgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptS2i6native_tcfsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
// @objc witnesses use vtable dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP10objcMethod{{[_0-9a-zA-Z]*}}FTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP8objcPropSifgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP8objcPropSifsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptSiyXl4objc_tcfgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptSiyXl4objc_tcfsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
// Dynamic witnesses use objc dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP0A6Method{{[_0-9a-zA-Z]*}}FTW
// CHECK: function_ref @_T07dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP0A4PropSifgTW
// CHECK: function_ref @_T07dynamic3FooC0A4PropSifgTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC0A4PropSifgTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP0A4PropSifsTW
// CHECK: function_ref @_T07dynamic3FooC0A4PropSifsTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC0A4PropSifsTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptS2iAA_tcfgTW
// CHECK: function_ref @_T07dynamic3FooC9subscriptS2iAA_tcfgTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC9subscriptS2iAA_tcfgTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptS2iAA_tcfsTW
// CHECK: function_ref @_T07dynamic3FooC9subscriptS2iAA_tcfsTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC9subscriptS2iAA_tcfsTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign :
// Superclass dispatch
class Subclass: Foo {
// Native and objc methods can directly reference super members
override init(native: Int) {
super.init(native: native)
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC{{[_0-9a-zA-Z]*}}fC
// CHECK: function_ref @_T07dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc
override func nativeMethod() {
super.nativeMethod()
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC12nativeMethod{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @_T07dynamic3FooC12nativeMethodyyF : $@convention(method) (@guaranteed Foo) -> ()
override var nativeProp: Int {
get { return super.nativeProp }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC10nativePropSifg
// CHECK: function_ref @_T07dynamic3FooC10nativePropSifg : $@convention(method) (@guaranteed Foo) -> Int
set { super.nativeProp = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC10nativePropSifs
// CHECK: function_ref @_T07dynamic3FooC10nativePropSifs : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(native native: Int) -> Int {
get { return super[native: native] }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptS2i6native_tcfg
// CHECK: function_ref @_T07dynamic3FooC9subscriptS2i6native_tcfg : $@convention(method) (Int, @guaranteed Foo) -> Int
set { super[native: native] = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptS2i6native_tcfs
// CHECK: function_ref @_T07dynamic3FooC9subscriptS2i6native_tcfs : $@convention(method) (Int, Int, @guaranteed Foo) -> ()
}
override init(objc: Int) {
super.init(objc: objc)
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassCACSi4objc_tcfc
// CHECK: function_ref @_T07dynamic3FooCACSi4objc_tcfc : $@convention(method) (Int, @owned Foo) -> @owned Foo
override func objcMethod() {
super.objcMethod()
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC10objcMethod{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @_T07dynamic3FooC10objcMethodyyF : $@convention(method) (@guaranteed Foo) -> ()
override var objcProp: Int {
get { return super.objcProp }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC8objcPropSifg
// CHECK: function_ref @_T07dynamic3FooC8objcPropSifg : $@convention(method) (@guaranteed Foo) -> Int
set { super.objcProp = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC8objcPropSifs
// CHECK: function_ref @_T07dynamic3FooC8objcPropSifs : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(objc objc: AnyObject) -> Int {
get { return super[objc: objc] }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptSiyXl4objc_tcfg
// CHECK: function_ref @_T07dynamic3FooC9subscriptSiyXl4objc_tcfg : $@convention(method) (@owned AnyObject, @guaranteed Foo) -> Int
set { super[objc: objc] = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptSiyXl4objc_tcfs
// CHECK: function_ref @_T07dynamic3FooC9subscriptSiyXl4objc_tcfs : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> ()
}
// Dynamic methods are super-dispatched by objc_msgSend
override init(dynamic: Int) {
super.init(dynamic: dynamic)
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.init!initializer.1.foreign :
override func dynamicMethod() {
super.dynamicMethod()
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC0A6Method{{[_0-9a-zA-Z]*}}F
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicMethod!1.foreign :
override var dynamicProp: Int {
get { return super.dynamicProp }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC0A4PropSifg
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!getter.1.foreign :
set { super.dynamicProp = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC0A4PropSifs
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!setter.1.foreign :
}
override subscript(dynamic dynamic: Int) -> Int {
get { return super[dynamic: dynamic] }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptS2iAA_tcfg
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign :
set { super[dynamic: dynamic] = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptS2iAA_tcfs
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign :
}
dynamic override func overriddenByDynamic() {}
}
class SubclassWithInheritedInits: Foo {
// CHECK-LABEL: sil hidden @_T07dynamic26SubclassWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: super_method [volatile] {{%.*}} : $SubclassWithInheritedInits, #Foo.init!initializer.1.foreign :
}
class GrandchildWithInheritedInits: SubclassWithInheritedInits {
// CHECK-LABEL: sil hidden @_T07dynamic28GrandchildWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: super_method [volatile] {{%.*}} : $GrandchildWithInheritedInits, #SubclassWithInheritedInits.init!initializer.1.foreign :
}
class GrandchildOfInheritedInits: SubclassWithInheritedInits {
// Dynamic methods are super-dispatched by objc_msgSend
override init(dynamic: Int) {
super.init(dynamic: dynamic)
}
// CHECK-LABEL: sil hidden @_T07dynamic26GrandchildOfInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: super_method [volatile] {{%.*}} : $GrandchildOfInheritedInits, #SubclassWithInheritedInits.init!initializer.1.foreign :
}
// CHECK-LABEL: sil hidden @_T07dynamic20nativeMethodDispatchyyF : $@convention(thin) () -> ()
func nativeMethodDispatch() {
// CHECK: function_ref @_T07dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(native: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
c[native: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic18objcMethodDispatchyyF : $@convention(thin) () -> ()
func objcMethodDispatch() {
// CHECK: function_ref @_T07dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(objc: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 :
c.objcMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 :
c.objcProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
let y = c[objc: 0 as NSNumber]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
c[objc: 0 as NSNumber] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic0A14MethodDispatchyyF : $@convention(thin) () -> ()
func dynamicMethodDispatch() {
// CHECK: function_ref @_T07dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(dynamic: 0)
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign
c.dynamicMethod()
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign
let x = c.dynamicProp
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign
c.dynamicProp = x
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign
let y = c[dynamic: 0]
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic15managedDispatchyAA3FooCF
func managedDispatch(_ c: Foo) {
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign
let x = c.managedProp
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!setter.1.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden @_T07dynamic21foreignMethodDispatchyyF
func foreignMethodDispatch() {
// CHECK: function_ref @_T0So9GuisemeauC{{[_0-9a-zA-Z]*}}fC
let g = Guisemeau()!
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.frob!1.foreign
g.frob()
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!getter.1.foreign
let x = g.count
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!setter.1.foreign
g.count = x
// CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.1.foreign
let y: Any! = g[0]
// CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.1.foreign
g[0] = y
// CHECK: class_method [volatile] {{%.*}} : $NSObject, #NSObject.description!getter.1.foreign
_ = g.description
}
extension Gizmo {
// CHECK-LABEL: sil hidden @_T0So5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fc
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.init!initializer.1.foreign
convenience init(convenienceInExtension: Int) {
self.init(bellsOn: convenienceInExtension)
}
// CHECK-LABEL: sil hidden @_T0So5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign
convenience init(foreignClassFactory x: Int) {
self.init(stuff: x)
}
// CHECK-LABEL: sil hidden @_T0So5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign
convenience init(foreignClassExactFactory x: Int) {
self.init(exactlyStuff: x)
}
@objc func foreignObjCExtension() { }
dynamic func foreignDynamicExtension() { }
}
// CHECK-LABEL: sil hidden @_T07dynamic24foreignExtensionDispatchySo5GizmoCF
// CHECK: bb0([[ARG:%.*]] : $Gizmo):
func foreignExtensionDispatch(_ g: Gizmo) {
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.foreignObjCExtension!1.foreign : (Gizmo)
g.foreignObjCExtension()
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.foreignDynamicExtension!1.foreign
g.foreignDynamicExtension()
}
// CHECK-LABEL: sil hidden @_T07dynamic33nativeMethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func nativeMethodDispatchFromOtherFile() {
// CHECK: function_ref @_T07dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(native: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod!1 :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter.1 :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter.1 :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 :
c[native: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic31objcMethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func objcMethodDispatchFromOtherFile() {
// CHECK: function_ref @_T07dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(objc: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod!1 :
c.objcMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter.1 :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter.1 :
c.objcProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 :
let y = c[objc: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 :
c[objc: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic0A27MethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func dynamicMethodDispatchFromOtherFile() {
// CHECK: function_ref @_T07dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(dynamic: 0)
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!1.foreign
c.dynamicMethod()
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.1.foreign
let x = c.dynamicProp
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.1.foreign
c.dynamicProp = x
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1.foreign
let y = c[dynamic: 0]
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic28managedDispatchFromOtherFileyAA0deF0CF
func managedDispatchFromOtherFile(_ c: FromOtherFile) {
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign
let x = c.managedProp
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.1.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden @_T07dynamic0A16ExtensionMethodsyAA13ObjCOtherFileCF
func dynamicExtensionMethods(_ obj: ObjCOtherFile) {
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign
obj.extensionMethod()
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.1.foreign
_ = obj.extensionProp
// CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.1.foreign
// CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
_ = type(of: obj).extensionClassProp
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!1.foreign
obj.dynExtensionMethod()
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.1.foreign
_ = obj.dynExtensionProp
// CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.1.foreign
// CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
_ = type(of: obj).dynExtensionClassProp
}
public class Base {
dynamic var x: Bool { return false }
}
public class Sub : Base {
// CHECK-LABEL: sil hidden @_T07dynamic3SubC1xSbfg : $@convention(method) (@guaranteed Sub) -> Bool {
// CHECK: bb0([[SELF:%.*]] : $Sub):
// CHECK: [[AUTOCLOSURE:%.*]] = function_ref @_T07dynamic3SubC1xSbfgSbyKXKfu_ : $@convention(thin) (@owned Sub) -> (Bool, @error Error)
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: = partial_apply [[AUTOCLOSURE]]([[SELF_COPY]])
// CHECK: return {{%.*}} : $Bool
// CHECK: } // end sil function '_T07dynamic3SubC1xSbfg'
// CHECK-LABEL: sil private [transparent] @_T07dynamic3SubC1xSbfgSbyKXKfu_ : $@convention(thin) (@owned Sub) -> (Bool, @error Error) {
// CHECK: bb0([[VALUE:%.*]] : $Sub):
// CHECK: [[BORROWED_VALUE:%.*]] = begin_borrow [[VALUE]]
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[BORROWED_VALUE]]
// CHECK: [[CASTED_VALUE_COPY:%.*]] = upcast [[VALUE_COPY]]
// CHECK: [[BORROWED_CASTED_VALUE_COPY:%.*]] = begin_borrow [[CASTED_VALUE_COPY]]
// CHECK: [[DOWNCAST_FOR_SUPERMETHOD:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_VALUE_COPY]]
// CHECK: [[SUPER:%.*]] = super_method [volatile] [[DOWNCAST_FOR_SUPERMETHOD]] : $Sub, #Base.x!getter.1.foreign : (Base) -> () -> Bool, $@convention(objc_method) (Base) -> ObjCBool
// CHECK: end_borrow [[BORROWED_CASTED_VALUE_COPY]] from [[CASTED_VALUE_COPY]]
// CHECK: = apply [[SUPER]]([[CASTED_VALUE_COPY]])
// CHECK: destroy_value [[VALUE_COPY]]
// CHECK: end_borrow [[BORROWED_VALUE]] from [[VALUE]]
// CHECK: destroy_value [[VALUE]]
// CHECK: } // end sil function '_T07dynamic3SubC1xSbfgSbyKXKfu_'
override var x: Bool { return false || super.x }
}
public class BaseExt : NSObject {}
extension BaseExt {
@objc public var count: Int {
return 0
}
}
public class SubExt : BaseExt {
public override var count: Int {
return 1
}
}
public class GenericBase<T> {
public func method(_: T) {}
}
public class ConcreteDerived : GenericBase<Int> {
public override dynamic func method(_: Int) {}
}
// The dynamic override has a different calling convention than the base,
// so after re-abstracting the signature we must dispatch to the dynamic
// thunk.
// CHECK-LABEL: sil private @_T07dynamic15ConcreteDerivedC6methodySiFAA11GenericBaseCADyxFTV : $@convention(method) (@in Int, @guaranteed ConcreteDerived) -> ()
// CHECK: bb0(%0 : $*Int, %1 : $ConcreteDerived):
// CHECK-NEXT: [[VALUE:%.*]] = load [trivial] %0 : $*Int
// CHECK: [[DYNAMIC_THUNK:%.*]] = function_ref @_T07dynamic15ConcreteDerivedC6methodySiFTD : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
// CHECK-NEXT: apply [[DYNAMIC_THUNK]]([[VALUE]], %1) : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
// CHECK: return
// Vtable contains entries for native and @objc methods, but not dynamic ones
// CHECK-LABEL: sil_vtable Foo {
// CHECK-NEXT: #Foo.init!initializer.1: {{.*}} : _T07dynamic3FooCACSi6native_tcfc
// CHECK-NEXT: #Foo.nativeMethod!1: {{.*}} : _T07dynamic3FooC12nativeMethodyyF
// CHECK-NEXT: #Foo.nativeProp!getter.1: {{.*}} : _T07dynamic3FooC10nativePropSifg // dynamic.Foo.nativeProp.getter : Swift.Int
// CHECK-NEXT: #Foo.nativeProp!setter.1: {{.*}} : _T07dynamic3FooC10nativePropSifs // dynamic.Foo.nativeProp.setter : Swift.Int
// CHECK-NEXT: #Foo.nativeProp!materializeForSet.1
// CHECK-NEXT: #Foo.subscript!getter.1: {{.*}} : _T07dynamic3FooC9subscriptS2i6native_tcfg // dynamic.Foo.subscript.getter : (native: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!setter.1: {{.*}} : _T07dynamic3FooC9subscriptS2i6native_tcfs // dynamic.Foo.subscript.setter : (native: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!materializeForSet.1
// CHECK-NEXT: #Foo.init!initializer.1: {{.*}} : _T07dynamic3FooCACSi4objc_tcfc
// CHECK-NEXT: #Foo.objcMethod!1: {{.*}} : _T07dynamic3FooC10objcMethodyyF
// CHECK-NEXT: #Foo.objcProp!getter.1: {{.*}} : _T07dynamic3FooC8objcPropSifg // dynamic.Foo.objcProp.getter : Swift.Int
// CHECK-NEXT: #Foo.objcProp!setter.1: {{.*}} : _T07dynamic3FooC8objcPropSifs // dynamic.Foo.objcProp.setter : Swift.Int
// CHECK-NEXT: #Foo.objcProp!materializeForSet.1
// CHECK-NEXT: #Foo.subscript!getter.1: {{.*}} : _T07dynamic3FooC9subscriptSiyXl4objc_tcfg // dynamic.Foo.subscript.getter : (objc: Swift.AnyObject) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!setter.1: {{.*}} : _T07dynamic3FooC9subscriptSiyXl4objc_tcfs // dynamic.Foo.subscript.setter : (objc: Swift.AnyObject) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!materializeForSet
// CHECK-NEXT: #Foo.overriddenByDynamic!1: {{.*}} : _T07dynamic3FooC19overriddenByDynamic{{[_0-9a-zA-Z]*}}
// CHECK-NEXT: #Foo.deinit!deallocator: {{.*}}
// CHECK-NEXT: }
// Vtable uses a dynamic thunk for dynamic overrides
// CHECK-LABEL: sil_vtable Subclass {
// CHECK: #Foo.overriddenByDynamic!1: {{.*}} : public _T07dynamic8SubclassC19overriddenByDynamic{{[_0-9a-zA-Z]*}}FTD
// CHECK: }
// Check vtables for implicitly-inherited initializers
// CHECK-LABEL: sil_vtable SubclassWithInheritedInits {
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26SubclassWithInheritedInitsCACSi6native_tcfc
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26SubclassWithInheritedInitsCACSi4objc_tcfc
// CHECK-NOT: .init!
// CHECK: }
// CHECK-LABEL: sil_vtable GrandchildWithInheritedInits {
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic28GrandchildWithInheritedInitsCACSi6native_tcfc
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic28GrandchildWithInheritedInitsCACSi4objc_tcfc
// CHECK-NOT: .init!
// CHECK: }
// CHECK-LABEL: sil_vtable GrandchildOfInheritedInits {
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26GrandchildOfInheritedInitsCACSi6native_tcfc
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26GrandchildOfInheritedInitsCACSi4objc_tcfc
// CHECK-NOT: .init!
// CHECK: }
// No vtable entry for override of @objc extension property
// CHECK-LABEL: sil_vtable SubExt {
// CHECK-NEXT: #BaseExt.init!initializer.1: (BaseExt.Type) -> () -> BaseExt : _T07dynamic6SubExtCACycfc [override] // dynamic.SubExt.init() -> dynamic.SubExt
// CHECK-NEXT: #SubExt.deinit!deallocator: _T07dynamic6SubExtCfD // dynamic.SubExt.__deallocating_deinit
// CHECK-NEXT: }
// Dynamic thunk + vtable re-abstraction
// CHECK-LABEL: sil_vtable ConcreteDerived {
// CHECK-NEXT: #GenericBase.method!1: <T> (GenericBase<T>) -> (T) -> () : public _T07dynamic15ConcreteDerivedC6methodySiFAA11GenericBaseCADyxFTV [override] // vtable thunk for dynamic.GenericBase.method(A) -> () dispatching to dynamic.ConcreteDerived.method(Swift.Int) -> ()
// CHECK-NEXT: #GenericBase.init!initializer.1: <T> (GenericBase<T>.Type) -> () -> GenericBase<T> : _T07dynamic15ConcreteDerivedCACycfc [override] // dynamic.ConcreteDerived.init() -> dynamic.ConcreteDerived
// CHECK-NEXT: #ConcreteDerived.deinit!deallocator: _T07dynamic15ConcreteDerivedCfD // dynamic.ConcreteDerived.__deallocating_deinit
// CHECK-NEXT: }
| 2796afc194e876b3114b1bace4e00be0 | 50.142602 | 278 | 0.684814 | false | false | false | false |
darina/omim | refs/heads/master | iphone/Maps/Bookmarks/Catalog/UIViewController+Subscription.swift | apache-2.0 | 4 | extension UIViewController {
func checkInvalidSubscription(_ completion: ((_ deleted: Bool) -> Void)? = nil) {
BookmarksManager.shared().check { [weak self] hasInvalidSubscription in
guard hasInvalidSubscription else {
return
}
let onSubscribe = {
self?.dismiss(animated: true)
guard let parentViewController = self else {
return
}
let subscriptionDialog = AllPassSubscriptionBuilder.build(parentViewController: parentViewController,
source: kStatWebView,
successDialog: .none,
subscriptionGroupType: .allPass) { result in
if !result {
self?.checkInvalidSubscription(completion)
}
}
self?.present(subscriptionDialog, animated: true)
completion?(false)
}
let onDelete = {
self?.dismiss(animated: true)
BookmarksManager.shared().deleteExpiredCategories()
completion?(true)
}
let subscriptionExpiredDialog = SubscriptionExpiredViewController(onSubscribe: onSubscribe, onDelete: onDelete)
self?.present(subscriptionExpiredDialog, animated: true)
}
}
}
| 6bcbb0464c0b9a2fa31beb3793237a41 | 44.787879 | 117 | 0.50364 | false | false | false | false |
irisapp/das-quadrat | refs/heads/master | Source/Shared/Keychain.swift | bsd-2-clause | 1 | //
// FSKeychain.swift
// Quadrat
//
// Created by Constantine Fry on 26/10/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
import Security
/**
The error domain for errors returned by `Keychain Service`.
The `code` property will contain OSStatus. See SecBase.h for error codes.
The `userInfo` is always nil and there is no localized description provided.
*/
public let QuadratKeychainOSSatusErrorDomain = "QuadratKeychainOSSatusErrorDomain"
class Keychain {
var logger: Logger?
private let keychainQuery: [String:AnyObject]
init(configuration: Configuration) {
#if os(iOS)
let serviceAttribute = "Foursquare2API-FSKeychain"
#else
let serviceAttribute = "Foursquare Access Token"
#endif
var accountAttribute: String
if let userTag = configuration.userTag {
accountAttribute = configuration.client.identifier + "_" + userTag
} else {
accountAttribute = configuration.client.identifier
}
keychainQuery = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccessible as String : kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
kSecAttrService as String : serviceAttribute,
kSecAttrAccount as String : accountAttribute
]
}
func accessToken() throws -> String? {
var query = keychainQuery
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimitOne
/**
Fixes the issue with Keychain access in release mode.
https://devforums.apple.com/message/1070614#1070614
*/
var dataTypeRef: AnyObject? = nil
let status = withUnsafeMutablePointer(&dataTypeRef) {cfPointer -> OSStatus in
SecItemCopyMatching(query, UnsafeMutablePointer(cfPointer))
}
var accessToken: String? = nil
if status == errSecSuccess {
if let retrievedData = dataTypeRef as? NSData {
if retrievedData.length != 0 {
accessToken = NSString(data: retrievedData, encoding: NSUTF8StringEncoding) as? String
}
}
}
if status != errSecSuccess && status != errSecItemNotFound {
let error = errorWithStatus(status)
self.logger?.logError(error, withMessage: "Keychain can't read access token.")
throw error
}
return accessToken
}
func deleteAccessToken() throws {
let query = keychainQuery
let status = SecItemDelete(query)
if status != errSecSuccess && status != errSecItemNotFound {
let error = errorWithStatus(status)
self.logger?.logError(error, withMessage: "Keychain can't delete access token .")
throw error
}
}
func saveAccessToken(accessToken: String) throws {
do {
if let _ = try self.accessToken() {
try deleteAccessToken()
}
} catch {
}
var query = keychainQuery
let accessTokenData = accessToken.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
query[kSecValueData as String] = accessTokenData
let status = SecItemAdd(query, nil)
if status != errSecSuccess {
let error = errorWithStatus(status)
self.logger?.logError(error, withMessage: "Keychain can't add access token.")
throw error
}
}
private func errorWithStatus(status: OSStatus) -> NSError {
return NSError(domain: QuadratKeychainOSSatusErrorDomain, code: Int(status), userInfo: nil)
}
func allAllAccessTokens() -> [String] {
return [""]
}
}
| cd614bcfcb19d8d84a340ca7f91b26e4 | 34.081081 | 110 | 0.616333 | false | false | false | false |
wenbobao/SwiftStudy | refs/heads/master | sample.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
// ?一个可选的值,是一个具体的值或者 是 nil 以表示值缺失。
var str = "Hello, playground"
print(str)
let floatValue :Float = 32.1
let label = "hello"
let width = 35
let widthLabel = label + String(width)
let apple = 3
let orange = 1 + 3
let appleSummary = "I have \(apple) apples"
let shppingList = ["hello","good","nice"]
let numList = [1,2,3]
let emptyArray = [String]()
let emptyDictionry = [String : String]()
let scoreList = [80,76,98]
for score in scoreList {
if score < 80 {
print("\(score) 中")
}else if score > 90 {
print("\(score) 优")
}else {
print("\(score) 良")
}
}
var loop = 0
for i in 0..<4 {
loop += i
}
print(loop)
var firstloop = 0
for var i = 0 ; i < 4 ; i++ {
firstloop += i
}
print(firstloop)
var secondLoop = 0
for i in 0...4 {
secondLoop += i
}
print(secondLoop)
if apple > 2 {
print("hhaha")
}
var optionSting : NSString?
//var optionSting : NSString? = "hello"
print(optionSting == nil)
if let name = optionSting {
print("hello")
}
let nickName :String? = nil
let fullName :String = "Wenbo bao"
let information = "Hi \(nickName ?? fullName)"
let fruit = "apple"
switch fruit{
case "apple" :
print("apple")
case "orange" :
print("orange")
default:
print("nothing")
}
let testDictionary = ["1":"apple","2":"orange","3":"banana"]
for (key,value) in testDictionary{
}
//函数和闭包
func hello(name:String) -> String{
return "hello:\(name)"
}
hello("bob")
func helloDay(name:String,day:NSString) -> String{
return "hello:\(name),Today is \(day)"
}
helloDay("wenbo", day: "Friday")
func sumOf(numbers:Int...) -> Int{
var sum = 0
for number in numbers{
sum += number
}
return sum
}
sumOf(1,2,3)
func avageOf(numbers:Int...) -> Int {
var sum = 0
for number in numbers{
sum += number
}
return (sum / numbers.count)
}
avageOf(1,2,3)
//闭包 这个地方类似block
scoreList.map({ (number : Int) -> Int in
let result = 3 * number
return result
})
//对象和类
class Shape{
var numberOfSides = 0
func simpleDescription() -> String{
return "A shape with \(numberOfSides) sides"
}
}
var shape = Shape()
shape.numberOfSides = 7
shape.simpleDescription()
class NameShape{
var numberOfSides = 0
var name : String
init(name : String){
self.name = name
}
func simpleDescription() -> String{
return "\(name) shape with \(numberOfSides) sides"
}
}
var shape1 = NameShape(name: "Rectange")
shape1.numberOfSides = 4
shape1.simpleDescription()
class Square: NameShape {
var sideLength : Double
init(sideLength : Double, name : String){
self.sideLength = sideLength
super.init(name: name)
}
func area() ->Double{
return sideLength * sideLength
}
override func simpleDescription() -> String{
return "I am override!"
}
}
var square = Square(sideLength: 4.5, name: "Square")
square.simpleDescription()
square.area()
class RectangeShape: NameShape {
var sideLength : Double = 0.0
// init(sideLength : Double, name : String){
// self.sideLength = sideLength
// super.init(name: name)
// }
var perimeter : Double{
get{
return 3.0 * sideLength
}
set{
}
}
func area() ->Double{
return sideLength * sideLength
}
override func simpleDescription() -> String{
return "I am override!"
}
}
var rec = RectangeShape(name: "hello")
rec.sideLength = 5
rec.area()
rec.perimeter
//枚举
enum Rank : Int{
case Ace = 1
case Two
}
//结构体
struct Apple {
var width : Double
var length : Double
var color : UIColor
}
Apple(width: 15, length: 15, color:UIColor.redColor())
//协议和扩展
protocol ExampleProtocal{
}
//实现协议 用 继承
//范型
| 33a45dccd4f26be1f11ac144a8d225cc | 15.194215 | 60 | 0.598877 | false | false | false | false |
darthpelo/SurviveAmsterdam | refs/heads/develop | mobile/SurviveAmsterdam/Product/ViewControllers/ProductDetailViewController.swift | mit | 1 | //
// ProductDetailViewController.swift
// SurviveAmsterdam
//
// Created by Alessio Roberto on 11/03/16.
// Copyright © 2016 Alessio Roberto. All rights reserved.
//
import UIKit
class ProductDetailViewController: UIViewController {
@IBOutlet weak var productImageview: UIImageView!
@IBOutlet weak var productNameLabel: UILabel!
@IBOutlet weak var shopNameLabel: UILabel!
@IBOutlet weak var shareButton: UIButton!
var productId: String?
private var product: Product?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("edit", comment: ""), style: UIBarButtonItemStyle.Plain, target: self, action: .editProductButtonTapped)
navigationItem.rightBarButtonItem?.accessibilityHint = NSLocalizedString("editHint", comment: "")
let image = R.image.shareIcon()?.imageWithRenderingMode(.AlwaysTemplate)
shareButton.setImage(image, forState: .Normal)
shareButton.tintColor = UIColor.orangeColor()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// if let productId = productId {
// do {
// let result = try ModelManager().getProductMatchingID(productId)
// if let prod = result.first {
// product = Product()
// product?.copyFromProduct(prod)
// if let image = product?.productImage {
// self.productImageview.image = UIImage(data: image)
// }
// self.productNameLabel.text = product?.name
// self.shopNameLabel.text = product?.shops.first?.name
// }
// } catch {}
// }
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == R.segue.productDetailViewController.editProductSegue.identifier {
if let navBar = segue.destinationViewController as? UINavigationController,
let vc = navBar.topViewController as? EditProductViewController,
let product = self.product {
vc.product = product
}
}
}
func editProductButtonTapped() {
self.performSegueWithIdentifier(R.segue.productDetailViewController.editProductSegue.identifier, sender: self)
}
@IBAction func shareButtonTapped(sender: UIButton) {
// if let name = product?.name,
// let image = product?.productImage,
// let shopName = product?.shops.first?.name {
// let shop = shopName + (product?.shops.first?.address ?? "")
// let activityViewController = UIActivityViewController(activityItems: [name, shop, UIImage(data: image)!], applicationActivities: nil)
// activityViewController.excludedActivityTypes = [UIActivityTypePostToFacebook,
// UIActivityTypePostToTwitter,
// UIActivityTypePostToFlickr,
// UIActivityTypePrint,
// UIActivityTypePostToVimeo,
// UIActivityTypeAssignToContact,
// UIActivityTypePostToVimeo,
// UIActivityTypeAddToReadingList]
//
// presentViewController(activityViewController, animated: true, completion: nil)
// }
}
}
private extension Selector {
static let editProductButtonTapped = #selector(ProductDetailViewController.editProductButtonTapped)
}
| 2fee5fbd3e313f7a15cc538577b82458 | 43.609195 | 189 | 0.582324 | false | false | false | false |
oleander/bitbar | refs/heads/master | Sources/BitBar/MenuBase.swift | mit | 1 | import AppKit
import Async
import SwiftyBeaver
class MenuBase: NSMenu, NSMenuDelegate, GUI {
internal let log = SwiftyBeaver.self
internal let queue = MenuBase.newQueue(label: "MenuBase")
init() {
super.init(title: "")
self.delegate = self
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func menuWillOpen(_ menu: NSMenu) {
for item in items {
if let menu = item as? MenuItem {
menu.onWillBecomeVisible()
}
}
}
public func menuDidClose(_ menu: NSMenu) {
for item in items {
if let menu = item as? MenuItem {
menu.onWillBecomeInvisible()
}
}
}
public func add(submenu: NSMenuItem, at index: Int) {
perform { [weak self] in
self?.insertItem(submenu, at: index)
}
}
public func remove(at index: Int) {
perform { [weak self] in
self?.removeItem(at: index)
}
}
}
| 966b388df95777a7cc3be1cbd3ab5b60 | 19.977778 | 59 | 0.627119 | false | false | false | false |
CodaFi/swift | refs/heads/master | test/decl/typealias/dependent_types.swift | apache-2.0 | 5 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype Assoc = Self
}
struct X : P {
}
class Y<T: P> {
typealias Assoc = T.Assoc
}
func f<T: P>(_ x: T, y: Y<T>.Assoc) {
}
protocol P1 {
associatedtype A = Int
}
struct X1<T> : P1 {
init(_: X1.A) {
}
}
struct GenericStruct<T> { // expected-note 3{{generic type 'GenericStruct' declared here}}
typealias Alias = T
typealias MetaAlias = T.Type
typealias Concrete = Int
typealias ReferencesConcrete = Concrete
func methodOne() -> Alias.Type {}
func methodTwo() -> MetaAlias {}
func methodOne() -> Alias.BadType {}
// expected-error@-1 {{'BadType' is not a member type of 'GenericStruct<T>.Alias'}}
func methodTwo() -> MetaAlias.BadType {}
// expected-error@-1 {{'BadType' is not a member type of 'GenericStruct<T>.MetaAlias'}}
var propertyOne: Alias.BadType
// expected-error@-1 {{'BadType' is not a member type of 'GenericStruct<T>.Alias' (aka 'T')}}
var propertyTwo: MetaAlias.BadType
// expected-error@-1 {{'BadType' is not a member type of 'GenericStruct<T>.MetaAlias' (aka 'T.Type')}}
}
// This was accepted in Swift 3.0 and sort of worked... but we can't
// implement it correctly. In Swift 3.1 it triggered an assert.
// Make sure it's banned now with a proper diagnostic.
func foo() -> Int {}
func metaFoo() -> Int.Type {}
let _: GenericStruct.Alias = foo()
// expected-error@-1 {{reference to generic type 'GenericStruct' requires arguments in <...>}}
let _: GenericStruct.MetaAlias = metaFoo()
// expected-error@-1 {{reference to generic type 'GenericStruct' requires arguments in <...>}}
// ... but if the typealias has a fully concrete underlying type,
// we are OK.
let _: GenericStruct.Concrete = foo()
let _: GenericStruct.ReferencesConcrete = foo()
// expected-error@-1 {{reference to generic type 'GenericStruct' requires arguments in <...>}}
class SuperG<T, U> {
typealias Composed = (T, U)
}
class SubG<T> : SuperG<T, T> { }
typealias SubGX<T> = SubG<T?>
func checkSugar(gs: SubGX<Int>.Composed) {
let i4: Int = gs // expected-error{{cannot convert value of type 'SubGX<Int>.Composed' (aka '(Optional<Int>, Optional<Int>)') to specified type 'Int'}}
}
| a5a549dff3ff91704d196bf585e3726f | 27.815789 | 153 | 0.675799 | false | false | false | false |
huonw/swift | refs/heads/master | test/SILGen/toplevel_errors.swift | apache-2.0 | 1 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
enum MyError : Error {
case A, B
}
throw MyError.A
// CHECK: sil @main
// CHECK: [[ERR:%.*]] = alloc_existential_box $Error, $MyError
// CHECK: [[ADDR:%.*]] = project_existential_box $MyError in [[ERR]] : $Error
// CHECK: [[T0:%.*]] = enum $MyError, #MyError.A!enumelt
// CHECK: store [[T0]] to [trivial] [[ADDR]] : $*MyError
// CHECK: builtin "willThrow"([[ERR]] : $Error)
// CHECK: br bb2([[ERR]] : $Error)
// CHECK: bb1([[T0:%.*]] : $Int32):
// CHECK: return [[T0]] : $Int32
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "errorInMain"([[T0]] : $Error)
// CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 1
// CHECK: [[T1:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
// CHECK: br bb1([[T1]] : $Int32)
| a2c6872df20c84f3f8db8359e4bbbe04 | 31.375 | 77 | 0.567568 | false | false | false | false |
SweetzpotAS/TCXZpot-Swift | refs/heads/master | TCXZpot-SwiftTests/ActivityTest.swift | apache-2.0 | 1 | //
// ActivityTest.swift
// TCXZpot
//
// Created by Tomás Ruiz López on 24/5/17.
// Copyright 2017 SweetZpot AS
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TCXZpot
class ActivityTest: XCTestCase {
func testSerializesCorrectly() {
let activity = Activity(id: TCXDate(day: 1, month: 1, year: 2017, hour: 0, minute: 0, second: 0)!,
laps: [Lap(startTime: TCXDate(day: 1, month: 1, year: 2017, hour: 0, minute: 0, second: 0)!,
totalTime: 60,
distance: 10,
calories: 15,
intensity: Intensity.active,
triggerMethod: TriggerMethod.manual,
tracks: nil),
],
notes: Notes(text: "Some notes"),
creator: Application(name: "SweetZpot Rowing",
build: Build(version: Version(versionMajor: 1, versionMinor: 0)),
languageID: "en",
partNumber: "123-45678-90"),
sport: Sport.running)
let serializer = MockSerializer()
activity.serialize(to: serializer)
XCTAssertTrue(serializer.hasPrinted("<Activity Sport=\"Running\">"))
XCTAssertTrue(serializer.hasPrinted("<Lap StartTime=\"2017-01-01T00:00:00.000Z\">"))
XCTAssertTrue(serializer.hasPrinted("<Notes>Some notes</Notes>"))
XCTAssertTrue(serializer.hasPrinted("<Creator xsi:type=\"Application_t\">"))
XCTAssertTrue(serializer.hasPrinted("</Activity>"))
}
}
| 292c114192cf630c7d9d92ba7434cba5 | 45.5 | 124 | 0.531844 | false | true | false | false |
IceSnow/AppleWatchApp | refs/heads/master | NetworkRequestManager/NetworkManager.swift | mit | 1 | //
// NetworkManager.swift
// AppleWatchApp
//
// Created by Roster on 19/10/2017.
// Copyright © 2017 杨昌达. All rights reserved.
//
import Foundation
/// 网络管理
class NetworkManager: NSObject {
/// 获取二进制数据
class func get(_ urlStr: String, finshed: @escaping (_ data: Data?)->(), failure: @escaping (_ error: Error)->()) -> URLSessionDataTask? {
guard let url = URL(string: urlStr) else {
failure(NSError(domain: "无效URL字符串", code: 1, userInfo: nil))
return nil
}
// 会话配置
let sessionConf = URLSessionConfiguration.default
if #available(iOS 11.0, *) {
sessionConf.waitsForConnectivity = true
} else {
// Fallback on earlier versions
}
sessionConf.timeoutIntervalForRequest = 12
let session = URLSession(configuration: sessionConf)
let task = session.dataTask(with: url) { (data, response, error) in
if (error != nil) {
failure(error!)
} else {
finshed(data)
}
}
task.resume()
return task
}
/// 获取对象
class func getObj(_ urlStr: String, finshed: @escaping (_ obj: Any?)->(), failure: @escaping (_ error: Error)->()) -> URLSessionDataTask? {
guard let url = URL(string: urlStr) else {
failure(NSError(domain: "无效URL字符串", code: 1, userInfo: nil))
return nil
}
// 会话配置
let sessionConf = URLSessionConfiguration.default
if #available(iOS 11.0, *) {
sessionConf.waitsForConnectivity = true
} else {
// Fallback on earlier versions
}
sessionConf.timeoutIntervalForRequest = 12
let session = URLSession(configuration: sessionConf)
let task = session.dataTask(with: url) { (data, response, error) in
if (error != nil) {
failure(error!)
} else {
if let data = data {
let text = String(data: data, encoding: .utf8)
print("response: " + (text == nil ? "nil" : "\(text!)"))
let obj = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
finshed(obj)
} else {
finshed(nil)
}
}
}
task.resume()
return task
}
}
| c38d356dd4f6155729ca9333a78f80fd | 27.473118 | 143 | 0.483761 | false | false | false | false |
huangboju/QMUI.swift | refs/heads/master | QMUI.swift/Demo/Modules/Demos/UIKit/QDFontViewController.swift | mit | 1 | //
// QDFontViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/24.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDFontViewController: QDCommonGroupListViewController {
override func initDataSource() {
super.initDataSource()
let od1 = QMUIOrderedDictionary(
dictionaryLiteral:
("UIFontMake", ""),
("UIFontItalicMake", ""),
("UIFontBoldMake", ""),
("UIFontLightMake", ""))
let od2 = QMUIOrderedDictionary(
dictionaryLiteral:
("UIDynamicFontMake", ""),
("UIDynamicFontBoldMake", ""),
("UIDynamicFontLightMake", ""))
dataSource = QMUIOrderedDictionary(
dictionaryLiteral:
("默认", od1), ("动态字体", od2))
}
override func setNavigationItems(_ isInEditMode: Bool, animated: Bool) {
super.setNavigationItems(isInEditMode, animated: animated)
title = "UIFont+QMUI"
}
override func contentSizeCategoryDidChanged(_ notification: Notification) {
super.contentSizeCategoryDidChanged(notification)
// QMUICommonTableViewController 默认会在这个方法里响应动态字体大小变化,并自动调用 [self.tableView reloadData],所以使用者只需要保证在 cellForRow 里更新动态字体大小即可,不需要手动监听动态字体的变化。
}
// MARK: QMUITableViewDataSource, QMUITableViewDelegate
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.accessoryType = .none
cell.selectionStyle = .none
let key = keyName(at: indexPath)
var font: UIFont?
let pointSize: CGFloat = 15
if key == "UIFontMake" {
font = UIFontMake(pointSize)
} else if key == "UIFontItalicMake" {
font = UIFontItalicMake(pointSize)
} else if key == "UIFontBoldMake" {
font = UIFontBoldMake(pointSize)
} else if key == "UIFontLightMake" {
font = UIFontLightMake(pointSize)
} else if key == "UIDynamicFontMake" {
font = UIDynamicFontMake(pointSize)
} else if key == "UIDynamicFontBoldMake" {
font = UIDynamicFontBoldMake(pointSize)
} else if key == "UIDynamicFontLightMake" {
font = UIDynamicFontLightMake(pointSize)
}
cell.textLabel?.font = font
return cell
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 1 {
let path = IS_SIMULATOR ? "设置-通用-辅助功能-Larger Text" : "设置-显示与亮度-文字大小"
return "请到“\(path)”里修改文字大小再观察当前界面的变化"
}
return nil
}
}
| 10a773ff271f30809cd16bb40e61edd9 | 34.101266 | 145 | 0.608366 | false | false | false | false |
pmhicks/Spindle-Player | refs/heads/master | Spindle Player/InfoTableController.swift | mit | 1 | // Spindle Player
// Copyright (C) 2015 Mike Hicks
//
// 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 Cocoa
public class InfoTableController: NSObject, NSTableViewDataSource, NSTableViewDelegate {
weak var table:NSTableView?
public override init() {
super.init()
let center = NSNotificationCenter.defaultCenter()
center.addObserverForName(SpindleConfig.kSongChanged, object: nil, queue: NSOperationQueue.mainQueue()) { [weak self] _ in
if let s = self {
if let tab = s.table {
tab.reloadData()
}
}
}
}
//MARK: Data Source
public func tableView(aTableView: NSTableView, objectValueForTableColumn aTableColumn: NSTableColumn?, row rowIndex: Int) -> AnyObject? {
let cfg = SpindleConfig.sharedInstance
if let song = cfg.currentSong {
if aTableView.identifier == "samples" {
if aTableColumn?.identifier == "text" {
return song.samples[rowIndex]
}
return String(format: "%02d", rowIndex + 1)
}
if aTableView.identifier == "instruments" {
if aTableColumn?.identifier == "text" {
return song.instruments[rowIndex]
}
return String(format: "%02d", rowIndex + 1)
}
}
return nil
}
public func numberOfRowsInTableView(aTableView: NSTableView) -> Int {
self.table = aTableView
let cfg = SpindleConfig.sharedInstance
if let song = cfg.currentSong {
if aTableView.identifier == "samples" {
return song.samples.count
}
if aTableView.identifier == "instruments" {
return song.instruments.count
}
}
return 0
}
//MARK: Delegate
} | 0cc6d07d54638fa11c4c623e8376cf50 | 36.658228 | 141 | 0.626429 | false | false | false | false |
wookay/Look | refs/heads/master | Look/Pods/C4/C4/UI/C4Font.swift | mit | 3 | // Copyright © 2014 C4
//
// 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 QuartzCore
import UIKit
/// C4Font objects represent fonts to an application, providing access to characteristics of the font and assistance in laying out glyphs relative to one another.
public class C4Font : NSObject {
internal var internalFont: UIFont!
/// The UIFont representation of the receiver.
///
/// ````
/// let uif = font.UIFont
/// ````
public var uiifont : UIFont {
get {
return internalFont
}
}
/// Initializes a new C4Font using the specified font name and size.
///
/// ````
/// let f = C4Font("Helvetica", 20)
/// ````
public init?(name: String, size: Double) {
super.init()
guard let font = UIFont(name: name, size: CGFloat(size)) else {
return nil
}
internalFont = font
}
/// Initializes a new C4Font using the specified font name and default size of 12.0 pt.
///
/// ````
/// let f = C4Font("Helvetica")
/// ````
public convenience init?(name: String) {
self.init(name: name, size: 12.0)
}
/// Initializes a new C4Font using a specified UIFont.
///
/// ````
/// if let uif = UIFont(name: "Helvetica", size: 24) {
/// let f = C4Font(font: uif)
/// }
/// ````
public init(font: UIFont) {
internalFont = font
}
/// Returns an array of font family names available on the system.
///
/// - returns: An array of String objects, each of which contains the name of a font family.
public class func familyNames() -> [AnyObject] {
return UIFont.familyNames()
}
/// Returns an array of font names available in a particular font family.
///
/// ````
/// for n in C4Font.fontNames("Avenir Next") {
/// println(n)
/// }
/// ````
///
/// - parameter familyName: The name of the font family.
///
/// - returns: An array of String objects, each of which contains a font name associated with the specified family.
public class func fontNames(familyName: String) -> [AnyObject] {
return UIFont.fontNamesForFamilyName(familyName)
}
/// Returns the font object used for standard interface items in the specified size.
///
/// ````
/// let f = C4Font.systemFont(20)
/// ````
///
/// - parameter fontSize: The size (in points) to which the font is scaled.
///
/// - returns: A font object of the specified size.
public class func systemFont(size: Double) -> C4Font {
return C4Font(font: UIFont.systemFontOfSize(CGFloat(size)))
}
/// Returns the font object used for standard interface items that are rendered in boldface type in the specified size.
///
/// ````
/// let f = C4Font.boldSystemFont(20)
/// ````
///
/// - parameter fontSize: The size (in points) to which the font is scaled.
///
/// - returns: A font object of the specified size.
public class func boldSystemFont(size: Double) -> C4Font {
return C4Font(font: UIFont.boldSystemFontOfSize(CGFloat(size)))
}
/// Returns the font object used for standard interface items that are rendered in italic type in the specified size.
///
/// ````
/// let f = C4Font.italicSystemFont(20)
/// ````
///
/// - parameter fontSize: The size (in points) to which the font is scaled.
///
/// - returns: A font object of the specified size.
public class func italicSystemFont(size: Double) -> C4Font {
return C4Font(font: UIFont.italicSystemFontOfSize(CGFloat(size)))
}
/// Returns a font object that is the same as the receiver but which has the specified size instead.
///
/// ````
/// let f = C4Font(name: "Avenir Next")
/// let f2 = f.font(20)
/// ````
///
/// - parameter fontSize: The desired size (in points) of the new font object.
///
/// - returns: A font object of the specified size.
public func font(size: Double) -> C4Font {
return C4Font(font: internalFont!.fontWithSize(CGFloat(size)))
}
/// The font family name. (read-only)
/// A family name is a name such as Times New Roman that identifies one or more specific fonts. The value in this property
/// is intended for an application’s internal usage only and should not be displayed.
public var familyName : String {
get {
return internalFont!.familyName
}
}
/// The font face name. (read-only)
/// The font name is a name such as HelveticaBold that incorporates the family name and any specific style information for
/// the font. The value in this property is intended for an application’s internal usage only and should not be displayed.
///
/// ````
/// let f = C4Font(name: "Avenir Next")
/// let n = f.fontName
/// ````
public var fontName : String {
get {
return internalFont!.fontName
}
}
/// The receiver’s point size, or the effective vertical point size for a font with a nonstandard matrix. (read-only) Defaults to 12.0
public var pointSize : Double {
get {
return Double(internalFont!.pointSize)
}
}
/// The top y-coordinate, offset from the baseline, of the receiver’s longest ascender. (read-only)
/// The ascender value is measured in points.
public var ascender : Double {
get {
return Double(internalFont!.ascender)
}
}
/// The bottom y-coordinate, offset from the baseline, of the receiver’s longest descender. (read-only)
/// The descender value is measured in points. This value may be positive or negative. For example, if the longest descender
/// extends 2 points below the baseline, this method returns -2.0 .
public var descender : Double {
get {
return Double(internalFont!.descender)
}
}
/// The receiver’s cap height information. (read-only)
/// This value measures (in points) the height of a capital character.
public var capHeight : Double {
get {
return Double(internalFont!.capHeight)
}
}
/// The x-height of the receiver. (read-only)
/// This value measures (in points) the height of the lowercase character "x".
public var xHeight : Double {
get {
return Double(internalFont!.xHeight)
}
}
/// The height of text lines (measured in points). (read-only)
public var lineHeight : Double {
get {
return Double(internalFont!.lineHeight)
}
}
/// Returns the standard font size used for labels.
///
/// - returns: The standard label font size in points.
public var labelFontSize : Double {
get {
return Double(UIFont.labelFontSize())
}
}
/// Returns the standard font size used for buttons.
///
/// - returns: The standard button font size in points.
public var buttonFontSize : Double {
get {
return Double(UIFont.buttonFontSize())
}
}
/// Returns the size of the standard system font.
///
/// - returns: The standard system font size in points.
public var systemFontSize : Double {
get {
return Double(UIFont.systemFontSize())
}
}
/// Returns the size of the standard small system font.
///
/// - returns: The standard small system font size in points.
public var smallSystemFontSize : Double {
get {
return Double(UIFont.smallSystemFontSize())
}
}
/// Returns a CGFontRef version of the receiver.
public var CGFont : CGFontRef? {
get {
return CGFontCreateWithFontName(fontName as NSString)
}
}
/// Returns a CTFontRef version of the receiver.
public var CTFont : CTFontRef {
get {
return CTFontCreateWithNameAndOptions(fontName as CFString!, CGFloat(pointSize), nil, [])
}
}
} | 749bcb45d6d5f2cb1d354832b0b6549b | 33.642857 | 162 | 0.616779 | false | false | false | false |
Shaunthehugo/Study-Buddy | refs/heads/master | StudyBuddy/SettingsTableViewController.swift | mit | 1 | //
// SettingsTableViewController.swift
// StudyBuddy
//
// Created by Shaun Dougherty on 2/21/16.
// Copyright © 2016 foru. All rights reserved.
//
import UIKit
import Parse
import Crashlytics
class SettingsTableViewController: UITableViewController {
@IBOutlet weak var tutorCell: UITableViewCell!
@IBOutlet weak var availablitySwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
if availablitySwitch.on {
PFUser.currentUser()!["available"] = true
PFUser.currentUser()!["availableText"] = "true"
} else {
PFUser.currentUser()!["available"] = false
PFUser.currentUser()!["availableText"] = "false"
}
PFUser.currentUser()?.saveInBackground()
tableView.beginUpdates()
tableView.endUpdates()
}
override func viewDidAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ConversationViewController.loadMessages), name: "checkStatus", object: nil)
getStatus()
if availablitySwitch.on {
PFUser.currentUser()!["available"] = true
PFUser.currentUser()!["availableText"] = "true"
} else {
PFUser.currentUser()!["available"] = false
PFUser.currentUser()!["availableText"] = "false"
}
PFUser.currentUser()?.saveInBackground()
tableView.beginUpdates()
tableView.endUpdates()
}
func getStatus() {
PFUser.currentUser()?.fetchInBackgroundWithBlock({ (object: PFObject?, error: NSError?) in
let status: Bool = PFUser.currentUser()!["available"] as! Bool
if status == true {
self.availablitySwitch.setOn(true, animated: true)
} else {
self.availablitySwitch.setOn(false, animated: true)
}
})
}
@IBAction func switchValueChanged(sender: UISwitch) {
tableView.beginUpdates()
tableView.endUpdates()
if availablitySwitch.on {
PFUser.currentUser()!["available"] = true
PFUser.currentUser()!["availableText"] = "true"
} else {
PFUser.currentUser()!["available"] = false
PFUser.currentUser()!["availableText"] = "false"
}
PFUser.currentUser()?.saveInBackground()
}
@IBAction func logOutTapped(sender: AnyObject) {
PFUser.logOutInBackgroundWithBlock { (error: NSError?) -> Void in
if error == nil {
self.performSegueWithIdentifier("LogOut", sender: self)
} else {
Crashlytics.sharedInstance().recordError(error!)
print(error?.localizedDescription)
}
}
print(PFUser.currentUser())
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 6
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 3 {
performSegueWithIdentifier("changeEmail", sender: self)
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 && PFUser.currentUser()!["tutor"] as! Bool == false {
return 0
}
return 44
}
}
| 9df0d47adae6a2a1531e4b61d78b8fb5 | 29.017241 | 158 | 0.670017 | false | false | false | false |
shial4/api-loltracker | refs/heads/master | Sources/App/Models/Champions.swift | mit | 1 | //
// Champions.swift
// lolTracker-API
//
// Created by Shial on 13/01/2017.
//
//
import Foundation
import Vapor
import Fluent
final class Champions: Model {
var exists: Bool = false
public var id: Node?
var summonerId: Node?
var name: String
var level: Int = 0
init(name: String, level: Int, summonerId: Node? = nil) {
self.id = nil
self.summonerId = summonerId
self.name = name
self.level = level
}
required init(node: Node, in context: Context) throws {
id = try node.extract("id")
name = try node.extract("name")
level = try node.extract("level")
summonerId = try node.extract("summoner_id")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"name": name,
"level": level,
"summoner_id": summonerId
])
}
}
extension Champions: Preparation {
static func prepare(_ database: Database) throws {
try database.create(entity, closure: { (champion) in
champion.id()
champion.string("name")
champion.int("level")
champion.parent(Summoner.self, optional: false)
})
}
static func revert(_ database: Database) throws {
try database.delete(entity)
}
}
extension Champions {
func summoner() throws -> Summoner? {
return try parent(summonerId, nil, Summoner.self).get()
}
}
| 1efb755e92c187e107a50ee5adb48cb3 | 22.625 | 63 | 0.569444 | false | false | false | false |
DeepestDesire/GC | refs/heads/master | Pods/ReactiveSwift/Sources/Event.swift | apache-2.0 | 3 | import Result
import Foundation
extension Signal {
/// Represents a signal event.
///
/// Signals must conform to the grammar:
/// `value* (failed | completed | interrupted)?`
public enum Event {
/// A value provided by the signal.
case value(Value)
/// The signal terminated because of an error. No further events will be
/// received.
case failed(Error)
/// The signal successfully terminated. No further events will be received.
case completed
/// Event production on the signal has been interrupted. No further events
/// will be received.
///
/// - important: This event does not signify the successful or failed
/// completion of the signal.
case interrupted
/// Whether this event is a completed event.
public var isCompleted: Bool {
switch self {
case .completed:
return true
case .value, .failed, .interrupted:
return false
}
}
/// Whether this event indicates signal termination (i.e., that no further
/// events will be received).
public var isTerminating: Bool {
switch self {
case .value:
return false
case .failed, .completed, .interrupted:
return true
}
}
/// Lift the given closure over the event's value.
///
/// - important: The closure is called only on `value` type events.
///
/// - parameters:
/// - f: A closure that accepts a value and returns a new value
///
/// - returns: An event with function applied to a value in case `self` is a
/// `value` type of event.
public func map<U>(_ f: (Value) -> U) -> Signal<U, Error>.Event {
switch self {
case let .value(value):
return .value(f(value))
case let .failed(error):
return .failed(error)
case .completed:
return .completed
case .interrupted:
return .interrupted
}
}
/// Lift the given closure over the event's error.
///
/// - important: The closure is called only on failed type event.
///
/// - parameters:
/// - f: A closure that accepts an error object and returns
/// a new error object
///
/// - returns: An event with function applied to an error object in case
/// `self` is a `.Failed` type of event.
public func mapError<F>(_ f: (Error) -> F) -> Signal<Value, F>.Event {
switch self {
case let .value(value):
return .value(value)
case let .failed(error):
return .failed(f(error))
case .completed:
return .completed
case .interrupted:
return .interrupted
}
}
/// Unwrap the contained `value` value.
public var value: Value? {
if case let .value(value) = self {
return value
} else {
return nil
}
}
/// Unwrap the contained `Error` value.
public var error: Error? {
if case let .failed(error) = self {
return error
} else {
return nil
}
}
}
}
extension Signal.Event where Value: Equatable, Error: Equatable {
public static func == (lhs: Signal<Value, Error>.Event, rhs: Signal<Value, Error>.Event) -> Bool {
switch (lhs, rhs) {
case let (.value(left), .value(right)):
return left == right
case let (.failed(left), .failed(right)):
return left == right
case (.completed, .completed):
return true
case (.interrupted, .interrupted):
return true
default:
return false
}
}
}
extension Signal.Event: CustomStringConvertible {
public var description: String {
switch self {
case let .value(value):
return "VALUE \(value)"
case let .failed(error):
return "FAILED \(error)"
case .completed:
return "COMPLETED"
case .interrupted:
return "INTERRUPTED"
}
}
}
/// Event protocol for constraining signal extensions
public protocol EventProtocol {
/// The value type of an event.
associatedtype Value
/// The error type of an event. If errors aren't possible then `NoError` can
/// be used.
associatedtype Error: Swift.Error
/// Extracts the event from the receiver.
var event: Signal<Value, Error>.Event { get }
}
extension Signal.Event: EventProtocol {
public var event: Signal<Value, Error>.Event {
return self
}
}
// Event Transformations
//
// Operators backed by event transformations have such characteristics:
//
// 1. Unary
// The operator applies to only one stream.
//
// 2. Serial
// The outcome need not be synchronously emitted, but all events must be delivered in
// serial order.
//
// 3. No side effect upon interruption.
// The operator must not perform any side effect upon receving `interrupted`.
//
// Examples of ineligible operators (for now):
//
// 1. `timeout`
// This operator forwards the `failed` event on a different scheduler.
//
// 2. `combineLatest`
// This operator applies to two or more streams.
//
// 3. `SignalProducer.then`
// This operator starts a second stream when the first stream completes.
//
// 4. `on`
// This operator performs side effect upon interruption.
extension Signal.Event {
internal typealias Transformation<U, E: Swift.Error> = (@escaping Signal<U, E>.Observer.Action, Lifetime) -> Signal<Value, Error>.Observer.Action
internal static func filter(_ isIncluded: @escaping (Value) -> Bool) -> Transformation<Value, Error> {
return { action, _ in
return { event in
switch event {
case let .value(value):
if isIncluded(value) {
action(.value(value))
}
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func filterMap<U>(_ transform: @escaping (Value) -> U?) -> Transformation<U, Error> {
return { action, _ in
return { event in
switch event {
case let .value(value):
if let newValue = transform(value) {
action(.value(newValue))
}
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func map<U>(_ transform: @escaping (Value) -> U) -> Transformation<U, Error> {
return { action, _ in
return { event in
switch event {
case let .value(value):
action(.value(transform(value)))
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func mapError<E>(_ transform: @escaping (Error) -> E) -> Transformation<Value, E> {
return { action, _ in
return { event in
switch event {
case let .value(value):
action(.value(value))
case .completed:
action(.completed)
case let .failed(error):
action(.failed(transform(error)))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static var materialize: Transformation<Signal<Value, Error>.Event, NoError> {
return { action, _ in
return { event in
action(.value(event))
switch event {
case .interrupted:
action(.interrupted)
case .completed, .failed:
action(.completed)
case .value:
break
}
}
}
}
internal static func attemptMap<U>(_ transform: @escaping (Value) -> Result<U, Error>) -> Transformation<U, Error> {
return { action, _ in
return { event in
switch event {
case let .value(value):
switch transform(value) {
case let .success(value):
action(.value(value))
case let .failure(error):
action(.failed(error))
}
case let .failed(error):
action(.failed(error))
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func attempt(_ action: @escaping (Value) -> Result<(), Error>) -> Transformation<Value, Error> {
return attemptMap { value -> Result<Value, Error> in
return action(value).map { _ in value }
}
}
}
extension Signal.Event where Error == AnyError {
internal static func attempt(_ action: @escaping (Value) throws -> Void) -> Transformation<Value, AnyError> {
return attemptMap { value in
try action(value)
return value
}
}
internal static func attemptMap<U>(_ transform: @escaping (Value) throws -> U) -> Transformation<U, AnyError> {
return attemptMap { value in
ReactiveSwift.materialize { try transform(value) }
}
}
}
extension Signal.Event {
internal static func take(first count: Int) -> Transformation<Value, Error> {
assert(count >= 1)
return { action, _ in
var taken = 0
return { event in
guard let value = event.value else {
action(event)
return
}
if taken < count {
taken += 1
action(.value(value))
}
if taken == count {
action(.completed)
}
}
}
}
internal static func take(last count: Int) -> Transformation<Value, Error> {
return { action, _ in
var buffer: [Value] = []
buffer.reserveCapacity(count)
return { event in
switch event {
case let .value(value):
// To avoid exceeding the reserved capacity of the buffer,
// we remove then add. Remove elements until we have room to
// add one more.
while (buffer.count + 1) > count {
buffer.remove(at: 0)
}
buffer.append(value)
case let .failed(error):
action(.failed(error))
case .completed:
buffer.forEach { action(.value($0)) }
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func take(while shouldContinue: @escaping (Value) -> Bool) -> Transformation<Value, Error> {
return { action, _ in
return { event in
if let value = event.value, !shouldContinue(value) {
action(.completed)
} else {
action(event)
}
}
}
}
internal static func skip(first count: Int) -> Transformation<Value, Error> {
precondition(count > 0)
return { action, _ in
var skipped = 0
return { event in
if case .value = event, skipped < count {
skipped += 1
} else {
action(event)
}
}
}
}
internal static func skip(while shouldContinue: @escaping (Value) -> Bool) -> Transformation<Value, Error> {
return { action, _ in
var isSkipping = true
return { event in
switch event {
case let .value(value):
isSkipping = isSkipping && shouldContinue(value)
if !isSkipping {
fallthrough
}
case .failed, .completed, .interrupted:
action(event)
}
}
}
}
}
extension Signal.Event where Value: EventProtocol {
internal static var dematerialize: Transformation<Value.Value, Value.Error> {
return { action, _ in
return { event in
switch event {
case let .value(innerEvent):
action(innerEvent.event)
case .failed:
fatalError("NoError is impossible to construct")
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
extension Signal.Event where Value: OptionalProtocol {
internal static var skipNil: Transformation<Value.Wrapped, Error> {
return filterMap { $0.optional }
}
}
/// A reference type which wraps an array to auxiliate the collection of values
/// for `collect` operator.
private final class CollectState<Value> {
var values: [Value] = []
/// Collects a new value.
func append(_ value: Value) {
values.append(value)
}
/// Check if there are any items remaining.
///
/// - note: This method also checks if there weren't collected any values
/// and, in that case, it means an empty array should be sent as the
/// result of collect.
var isEmpty: Bool {
/// We use capacity being zero to determine if we haven't collected any
/// value since we're keeping the capacity of the array to avoid
/// unnecessary and expensive allocations). This also guarantees
/// retro-compatibility around the original `collect()` operator.
return values.isEmpty && values.capacity > 0
}
/// Removes all values previously collected if any.
func flush() {
// Minor optimization to avoid consecutive allocations. Can
// be useful for sequences of regular or similar size and to
// track if any value was ever collected.
values.removeAll(keepingCapacity: true)
}
}
extension Signal.Event {
internal static var collect: Transformation<[Value], Error> {
return collect { _, _ in false }
}
internal static func collect(count: Int) -> Transformation<[Value], Error> {
precondition(count > 0)
return collect { values in values.count == count }
}
internal static func collect(_ shouldEmit: @escaping (_ collectedValues: [Value]) -> Bool) -> Transformation<[Value], Error> {
return { action, _ in
let state = CollectState<Value>()
return { event in
switch event {
case let .value(value):
state.append(value)
if shouldEmit(state.values) {
action(.value(state.values))
state.flush()
}
case .completed:
if !state.isEmpty {
action(.value(state.values))
}
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func collect(_ shouldEmit: @escaping (_ collected: [Value], _ latest: Value) -> Bool) -> Transformation<[Value], Error> {
return { action, _ in
let state = CollectState<Value>()
return { event in
switch event {
case let .value(value):
if shouldEmit(state.values, value) {
action(.value(state.values))
state.flush()
}
state.append(value)
case .completed:
if !state.isEmpty {
action(.value(state.values))
}
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
/// Implementation detail of `combinePrevious`. A default argument of a `nil` initial
/// is deliberately avoided, since in the case of `Value` being an optional, the
/// `nil` literal would be materialized as `Optional<Value>.none` instead of `Value`,
/// thus changing the semantic.
internal static func combinePrevious(initial: Value?) -> Transformation<(Value, Value), Error> {
return { action, _ in
var previous = initial
return { event in
switch event {
case let .value(value):
if let previous = previous {
action(.value((previous, value)))
}
previous = value
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func skipRepeats(_ isEquivalent: @escaping (Value, Value) -> Bool) -> Transformation<Value, Error> {
return { action, _ in
var previous: Value?
return { event in
switch event {
case let .value(value):
if let previous = previous, isEquivalent(previous, value) {
return
}
previous = value
fallthrough
case .completed, .interrupted, .failed:
action(event)
}
}
}
}
internal static func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> Transformation<Value, Error> {
return { action, _ in
var seenValues: Set<Identity> = []
return { event in
switch event {
case let .value(value):
let identity = transform(value)
let (inserted, _) = seenValues.insert(identity)
if inserted {
fallthrough
}
case .failed, .completed, .interrupted:
action(event)
}
}
}
}
internal static func scan<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Transformation<U, Error> {
return { action, _ in
var accumulator = initialResult
return { event in
action(event.map { value in
nextPartialResult(&accumulator, value)
return accumulator
})
}
}
}
internal static func scan<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Transformation<U, Error> {
return scan(into: initialResult) { $0 = nextPartialResult($0, $1) }
}
internal static func reduce<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Transformation<U, Error> {
return { action, _ in
var accumulator = initialResult
return { event in
switch event {
case let .value(value):
nextPartialResult(&accumulator, value)
case .completed:
action(.value(accumulator))
action(.completed)
case .interrupted:
action(.interrupted)
case let .failed(error):
action(.failed(error))
}
}
}
}
internal static func reduce<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Transformation<U, Error> {
return reduce(into: initialResult) { $0 = nextPartialResult($0, $1) }
}
internal static func observe(on scheduler: Scheduler) -> Transformation<Value, Error> {
return { action, lifetime in
lifetime.observeEnded {
scheduler.schedule {
action(.interrupted)
}
}
return { event in
scheduler.schedule {
if !lifetime.hasEnded {
action(event)
}
}
}
}
}
internal static func lazyMap<U>(on scheduler: Scheduler, transform: @escaping (Value) -> U) -> Transformation<U, Error> {
return { action, lifetime in
let box = Atomic<Value?>(nil)
let completionDisposable = SerialDisposable()
let valueDisposable = SerialDisposable()
lifetime += valueDisposable
lifetime += completionDisposable
lifetime.observeEnded {
scheduler.schedule {
action(.interrupted)
}
}
return { event in
switch event {
case let .value(value):
// Schedule only when there is no prior outstanding value.
if box.swap(value) == nil {
valueDisposable.inner = scheduler.schedule {
if let value = box.swap(nil) {
action(.value(transform(value)))
}
}
}
case .completed, .failed:
// Completion and failure should not discard the outstanding
// value.
completionDisposable.inner = scheduler.schedule {
action(event.map(transform))
}
case .interrupted:
// `interrupted` overrides any outstanding value and any
// scheduled completion/failure.
valueDisposable.dispose()
completionDisposable.dispose()
scheduler.schedule {
action(.interrupted)
}
}
}
}
}
internal static func delay(_ interval: TimeInterval, on scheduler: DateScheduler) -> Transformation<Value, Error> {
precondition(interval >= 0)
return { action, lifetime in
lifetime.observeEnded {
scheduler.schedule {
action(.interrupted)
}
}
return { event in
switch event {
case .failed, .interrupted:
scheduler.schedule {
action(event)
}
case .value, .completed:
let date = scheduler.currentDate.addingTimeInterval(interval)
scheduler.schedule(after: date) {
if !lifetime.hasEnded {
action(event)
}
}
}
}
}
}
internal static func throttle(_ interval: TimeInterval, on scheduler: DateScheduler) -> Transformation<Value, Error> {
precondition(interval >= 0)
return { action, lifetime in
let state: Atomic<ThrottleState<Value>> = Atomic(ThrottleState())
let schedulerDisposable = SerialDisposable()
lifetime.observeEnded {
schedulerDisposable.dispose()
scheduler.schedule { action(.interrupted) }
}
return { event in
guard let value = event.value else {
schedulerDisposable.inner = scheduler.schedule {
action(event)
}
return
}
let scheduleDate: Date = state.modify { state in
state.pendingValue = value
let proposedScheduleDate: Date
if let previousDate = state.previousDate, previousDate.compare(scheduler.currentDate) != .orderedDescending {
proposedScheduleDate = previousDate.addingTimeInterval(interval)
} else {
proposedScheduleDate = scheduler.currentDate
}
switch proposedScheduleDate.compare(scheduler.currentDate) {
case .orderedAscending:
return scheduler.currentDate
case .orderedSame: fallthrough
case .orderedDescending:
return proposedScheduleDate
}
}
schedulerDisposable.inner = scheduler.schedule(after: scheduleDate) {
let pendingValue: Value? = state.modify { state in
defer {
if state.pendingValue != nil {
state.pendingValue = nil
state.previousDate = scheduleDate
}
}
return state.pendingValue
}
if let pendingValue = pendingValue {
action(.value(pendingValue))
}
}
}
}
}
internal static func debounce(_ interval: TimeInterval, on scheduler: DateScheduler) -> Transformation<Value, Error> {
precondition(interval >= 0)
return { action, lifetime in
let d = SerialDisposable()
lifetime.observeEnded {
d.dispose()
scheduler.schedule { action(.interrupted) }
}
return { event in
switch event {
case let .value(value):
let date = scheduler.currentDate.addingTimeInterval(interval)
d.inner = scheduler.schedule(after: date) {
action(.value(value))
}
case .completed, .failed, .interrupted:
d.inner = scheduler.schedule {
action(event)
}
}
}
}
}
}
private struct ThrottleState<Value> {
var previousDate: Date?
var pendingValue: Value?
}
extension Signal.Event where Error == NoError {
internal static func promoteError<F>(_: F.Type) -> Transformation<Value, F> {
return { action, _ in
return { event in
switch event {
case let .value(value):
action(.value(value))
case .failed:
fatalError("NoError is impossible to construct")
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
extension Signal.Event where Value == Never {
internal static func promoteValue<U>(_: U.Type) -> Transformation<U, Error> {
return { action, _ in
return { event in
switch event {
case .value:
fatalError("Never is impossible to construct")
case let .failed(error):
action(.failed(error))
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
| 7ead3d09a53f85a579db8746e03b58b1 | 23.297685 | 146 | 0.645703 | false | false | false | false |
pixelmaid/palette-knife | refs/heads/master | Palette-Knife/FabricatorView.swift | mit | 2 | //
// FabricatorView.swift
// PaletteKnife
//
// Created by JENNIFER MARY JACOBS on 10/17/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import Foundation
import UIKit
class FabricatorView: UIImageView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override func drawRect(rect: CGRect) {
}
func clear(){
self.image = nil
}
func drawFabricatorPosition(x:Float,y:Float,z:Float) {
self.clear();
UIGraphicsBeginImageContext(self.frame.size)
let context = UIGraphicsGetCurrentContext()!
self.image?.drawInRect(CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
let color = Color(r:0,g:255,b:0)
let _x = Numerical.map(x, istart:0, istop: GCodeGenerator.inX, ostart: 0, ostop: GCodeGenerator.pX)
let _y = Numerical.map(y, istart:0, istop:GCodeGenerator.inY, ostart: GCodeGenerator.pY, ostop: 0 )
let fromPoint = CGPoint(x:CGFloat(_x),y:CGFloat(_y));
let toPoint = CGPoint(x:CGFloat(_x),y:CGFloat(_y));
CGContextSetLineCap(context, CGLineCap.Round)
CGContextSetLineWidth(context, CGFloat(10))
CGContextSetStrokeColorWithColor(context, color.toCGColor())
CGContextSetBlendMode(context, CGBlendMode.Normal)
CGContextMoveToPoint(context, fromPoint.x,fromPoint.y)
CGContextAddLineToPoint(context, toPoint.x,toPoint.y)
CGContextStrokePath(context)
self.image = UIGraphicsGetImageFromCurrentImageContext()
self.alpha = 1
UIGraphicsEndImageContext()
}
}
| 174fa63c05bd9ab9221483e5425ac9cd | 30.20339 | 112 | 0.645845 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Constraints/sr10324.swift | apache-2.0 | 10 | // RUN: %target-swift-frontend -typecheck -verify %s
// REQUIRES: rdar65007946
struct A {
static func * (lhs: A, rhs: A) -> B { return B() }
static func * (lhs: B, rhs: A) -> B { return B() }
static func * (lhs: A, rhs: B) -> B { return B() }
}
struct B {}
let (x, y, z) = (A(), A(), A())
let w = A() * A() * A() // works
// Should all work
let a = x * y * z
let b = x * (y * z)
let c = (x * y) * z
let d = x * (y * z as B)
let e = (x * y as B) * z
| a51a17c9f9ba27f00d4d320e197b0bb5 | 21.380952 | 54 | 0.478723 | false | false | false | false |
victor/SwiftCLI | refs/heads/master | SwiftCLI/Commands/ChainableCommand.swift | mit | 1 | //
// ChainableCommand.swift
// SwiftCLI
//
// Created by Jake Heiser on 7/25/14.
// Copyright (c) 2014 jakeheis. All rights reserved.
//
import Foundation
class ChainableCommand: LightweightCommand {
override init(commandName: String) {
super.init(commandName: commandName)
}
func withSignature(signature: String) -> ChainableCommand {
lightweightCommandSignature = signature
return self
}
func withShortDescription(shortDescription: String) -> ChainableCommand {
lightweightCommandShortDescription = shortDescription
return self
}
func withShortcut(shortcut: String) -> ChainableCommand {
lightweightCommandShortcut = shortcut
return self
}
// MARK: - Options
func withFlagsHandled(flags: [String], block: OptionsFlagBlock?, usage: String) -> ChainableCommand {
handleFlags(flags, block: block, usage: usage)
return self
}
func withKeysHandled(keys: [String], block: OptionsKeyBlock?, usage: String = "", valueSignature: String = "value") -> ChainableCommand {
handleKeys(keys, block: block, usage: usage, valueSignature: valueSignature)
return self
}
func withNoHelpShownOnHFlag() -> ChainableCommand {
shouldShowHelpOnHFlag = false
return self
}
func withPrintingBehaviorOnUnrecgonizedOptions(behavior: UnrecognizedOptionsPrintingBehavior) -> ChainableCommand {
printingBehaviorOnUnrecognizedOptions = behavior
return self
}
func withAllFlagsAndOptionsAllowed() -> ChainableCommand {
shouldFailOnUnrecognizedOptions = false
return self
}
// MARK: - Execution
func withExecutionBlock(execution: CommandExecutionBlock) -> ChainableCommand {
lightweightExecutionBlock = execution
return self
}
} | a85f39e8de7469d2efb69d91844c0f04 | 27.863636 | 141 | 0.672794 | false | false | false | false |
lojals/QRGen | refs/heads/master | QRGen/MenuViewController.swift | mit | 1 | //
// MenuViewController.swift
// QRGen
//
// Created by Jorge Raul Ovalle Zuleta on 1/31/16.
// Copyright © 2016 jorgeovalle. All rights reserved.
//
import UIKit
import AVFoundation
import QRCodeReader.Swift
class MenuViewController: GenericViewController,QRCodeReaderViewControllerDelegate {
var container:UIView!
lazy var reader = QRCodeReaderViewController(metadataObjectTypes: [AVMetadataObjectTypeQRCode])
override func viewDidLoad() {
super.viewDidLoad()
container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(container)
let logo = UIImageView(image: UIImage(named: "intro"))
logo.tag = 1
logo.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(logo)
let btnCreate = UIButton()
btnCreate.tag = 2
btnCreate.translatesAutoresizingMaskIntoConstraints = false
btnCreate.setImage(UIImage(named: "Btn_create"), forState: .Normal)
btnCreate.addTarget(self, action: Selector("createQRCode"), forControlEvents: .TouchUpInside)
container.addSubview(btnCreate)
let line = UIImageView(image: UIImage(named: "Line"))
line.tag = 3
line.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(line)
let btnRead = UIButton()
btnRead.tag = 4
btnRead.translatesAutoresizingMaskIntoConstraints = false
btnRead.setImage(UIImage(named: "Btn_read"), forState: .Normal)
btnRead.addTarget(self, action: Selector("readQRCode"), forControlEvents: .TouchUpInside)
container.addSubview(btnRead)
let cc = UIImageView(image: UIImage(named: "cc"))
cc.tag = 5
cc.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(cc)
self.addConstraints()
}
func addConstraints(){
self.view.addConstraint(NSLayoutConstraint(item: self.container, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.container, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0))
self.container.addConstraint(NSLayoutConstraint(item: self.container, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 226))
self.container.addConstraint(NSLayoutConstraint(item: self.container, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 380))
self.view.addConstraint(NSLayoutConstraint(item: self.container.viewWithTag(1)!, attribute: .CenterX, relatedBy: .Equal, toItem: self.container, attribute: .CenterX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.container.viewWithTag(1)!, attribute: .Top, relatedBy: .Equal, toItem: self.container, attribute: .Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.container.viewWithTag(2)!, attribute: .CenterX, relatedBy: .Equal, toItem: self.container, attribute: .CenterX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.container.viewWithTag(2)!, attribute: .Top, relatedBy: .Equal, toItem: self.container.viewWithTag(1), attribute: .Bottom, multiplier: 1, constant: 73))
self.view.addConstraint(NSLayoutConstraint(item: self.container.viewWithTag(3)!, attribute: .CenterX, relatedBy: .Equal, toItem: self.container, attribute: .CenterX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.container.viewWithTag(3)!, attribute: .Top, relatedBy: .Equal, toItem: self.container.viewWithTag(2), attribute: .Bottom, multiplier: 1, constant: 32))
self.view.addConstraint(NSLayoutConstraint(item: self.container.viewWithTag(4)!, attribute: .CenterX, relatedBy: .Equal, toItem: self.container, attribute: .CenterX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.container.viewWithTag(4)!, attribute: .Top, relatedBy: .Equal, toItem: self.container.viewWithTag(3), attribute: .Bottom, multiplier: 1, constant: 32))
self.view.addConstraint(NSLayoutConstraint(item: self.view.viewWithTag(5)!, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.view.viewWithTag(5)!, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: -13))
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
func createQRCode(){
let actionSheet = UIAlertController(title: "QR Code type", message: "Choose the QR Code you want to generate", preferredStyle: UIAlertControllerStyle.ActionSheet)
let option0 = UIAlertAction(title: "Text/Phone", style: UIAlertActionStyle.Default, handler: {(actionSheet: UIAlertAction!) in (
self.showAlertText()
)})
let option1 = UIAlertAction(title: "URL", style: UIAlertActionStyle.Default, handler: {(actionSheet: UIAlertAction!) in (
self.showAlertURL()
)})
let option2 = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {(actionSheet: UIAlertAction!) in ()})
actionSheet.addAction(option0)
actionSheet.addAction(option1)
actionSheet.addAction(option2)
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func showAlertText(){
let alertController = UIAlertController(title: "QRCode Text", message: "Enter your text/phone to generate your QR Code", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
txtField.placeholder = "Bla bla bla"
txtField.keyboardType = UIKeyboardType.ASCIICapable
})
alertController.addAction(UIAlertAction(title: "Generate", style: UIAlertActionStyle.Default,handler: {
(alert: UIAlertAction!) in
if let text = alertController.textFields?.first?.text{
let QRView = QRViewController(text: text, type: 1)
self.navigationController?.pushViewController(QRView, animated: false)
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel,handler: {
(alert: UIAlertAction!) in
}))
self.presentViewController(alertController, animated: true, completion: nil)
}
func showAlertURL(){
let alertController = UIAlertController(title: "QRCode URL", message: "Enter your url to generate your QR Code", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
txtField.placeholder = "http://example.com"
txtField.keyboardType = UIKeyboardType.ASCIICapable
})
alertController.addAction(UIAlertAction(title: "Generate", style: UIAlertActionStyle.Default,handler: {
(alert: UIAlertAction!) in
if let text = alertController.textFields?.first?.text{
let QRView = QRViewController(text: text, type: 0)
self.navigationController?.pushViewController(QRView, animated: false)
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel,handler: {
(alert: UIAlertAction!) in
}))
self.presentViewController(alertController, animated: true, completion: nil)
}
func readQRCode(){
reader.delegate = self
reader.modalPresentationStyle = .FormSheet
presentViewController(reader, animated: true, completion: nil)
}
func reader(reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult){
print(result.value)
if result.value.containsString("http"){
if let url = NSURL(string: result.value) {
reader.dismissViewControllerAnimated(true, completion: nil)
UIApplication.sharedApplication().openURL(url)
}
}else{
reader.dismissViewControllerAnimated(true, completion: nil)
let textView = TextViewController()
textView.txt = result.value
self.navigationController?.pushViewController(textView, animated: true)
}
}
func readerDidCancel(reader: QRCodeReaderViewController) {
reader.dismissViewControllerAnimated(true, completion: nil)
}
}
| 70505455250a1679a9046301b8b2b38d | 55.0875 | 213 | 0.691331 | false | false | false | false |
toadzky/SLF4Swift | refs/heads/master | SLF4Swift/LogLevelType.swift | mit | 1 | //
// Protocole.swift
// SLF4Swift
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
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
/* level to filter message */
internal protocol LogLevelType {
/* integer to compare log level */
var level: Int {get}
/* name of level, used to print level if necessarry */
var name: String {get}
}
public enum SLFLogLevel: Int, LogLevelType, Equatable, Comparable, CustomStringConvertible {
case Off, Severe, Error, Warn, Info, Debug, Verbose, All
public static var levels: [SLFLogLevel] {return [Off, Severe, Error, Warn, Info, Debug, Verbose, All]}
public static var config: [SLFLogLevel] {return [Off, All]}
public static var issues: [SLFLogLevel] {return [Severe, Error, Warn]}
public var level: Int {
return rawValue
}
public var name: String {
switch(self) {
case Off: return "Off"
case Severe: return "Severe" // Critical, Fatal
case Error: return "Error"
case Warn: return "Warn"
case Info: return "Info"
case Debug: return "Debug"
case Verbose: return "Verbose" // Trace
case All: return "All"
}
}
public var description : String { return self.name }
public var shortDescription : String {
let d = self.description
return String(d[d.startIndex])
}
public func isIssues() -> Bool {
return SLFLogLevel.issues.contains(self)
}
public func isConfig() -> Bool {
return SLFLogLevel.config.contains(self)
}
public func isFlag() -> Bool {
return !isConfig()
}
}
public func ==(lhs: SLFLogLevel, rhs: SLFLogLevel) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public func <(lhs: SLFLogLevel, rhs: SLFLogLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
| 4fa36c379930fb5118b4b596644f92bf | 33.047619 | 106 | 0.692308 | false | false | false | false |
CybercomPoland/CPLKeyboardManager | refs/heads/master | Example/Source/RootCoordinator.swift | mit | 1 | //
// RootCoordinator.swift
// CPLKeyboardManager
//
// Created by Michal Zietera on 17.03.2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class RootCoordinator: MenuViewControllerDelegate {
let navigationController: UINavigationController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
init(withNavigationController navCon: UINavigationController) {
navigationController = navCon
}
func tappedTableViewButton() {
let tableVC = storyboard.instantiateViewController(withIdentifier: "TableViewController")
let navCon = UINavigationController(rootViewController: tableVC)
tableVC.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismiss))
navigationController.present(navCon, animated: true, completion: nil)
}
func tappedScrollViewButton() {
let scrollVC = storyboard.instantiateViewController(withIdentifier: "ScrollViewController")
let navCon = UINavigationController(rootViewController: scrollVC)
scrollVC.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismiss))
navigationController.present(navCon, animated: true, completion: nil)
}
func tappedBottomConstraintButton() {
let scrollVC = storyboard.instantiateViewController(withIdentifier: "ConstraintViewController")
let navCon = UINavigationController(rootViewController: scrollVC)
scrollVC.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismiss))
navigationController.present(navCon, animated: true, completion: nil)
}
@objc func dismiss() {
navigationController.dismiss(animated: true, completion: nil)
}
}
| 6f5ccc980638f33eab9bd5f581c70c7e | 42.325581 | 138 | 0.749866 | false | false | false | false |
colemancda/Linchi | refs/heads/master | Linchi/Socket/ActiveSocket-Respond.swift | mit | 4 | //
// ActiveSocket-Respond.swift
// Linchi
//
import Darwin
extension ActiveSocket {
/// Sends the HTTPResponse to the receiver of the socket
func respond(response: HTTPResponse, keepAlive: Bool) {
var content = ""
content += "HTTP/1.1 \(response.status.code()) \(response.status.reason())\r\n"
content += "Server: Linchi\r\n"
if keepAlive { content += "Connection: keep-alive\r\n" }
for (name, value) in response.status.headers() {
content += "\(name): \(value)\r\n"
}
for (name, value) in response.headers {
content += "\(name): \(value)\r\n"
}
content += "Content-Length: \(response.body.count)\r\n"
content += "\r\n"
do {
try writeData(content.toUTF8Bytes())
try writeData(response.body)
}
catch ActiveSocket.Error.WriteFailed {
print("could not respond because send() failed")
release()
}
catch { fatalError("writeData can only throw SocketError.WriteFailed") }
}
/// Sends the given data to the receiver of the socket
func writeData(data: [UInt8]) throws {
var sent = 0
let dataBuffer = UnsafePointer<UInt8>(data)
while sent < data.count {
let sentBytes = send(fd, dataBuffer + sent, Int(data.count - sent), 0)
guard sentBytes != -1 else { throw ActiveSocket.Error.WriteFailed }
sent += sentBytes
}
}
}
| 875bb9b5f78d3933d8a23ddf06fc9e45 | 26.535714 | 87 | 0.555772 | false | false | false | false |
LinShiwei/HealthyDay | refs/heads/master | HealthyDay/MainInformationView.swift | mit | 1 | //
// MainInformationView.swift
// HealthyDay
//
// Created by Linsw on 16/10/2.
// Copyright © 2016年 Linsw. All rights reserved.
//
import UIKit
internal protocol MainInfoViewTapGestureDelegate {
func didTap(inLabel label:UILabel)
}
internal class MainInformationView: UIView{
//MARK: Property
private var stepCountLabel : StepCountLabel!
private var distanceWalkingRunningLabel : DistanceWalkingRunningLabel!
private let containerView = UIView()
private let dot = UIView()
private let labelMaskView = UIView()
private let decorativeView = UIView()
private let gradientLayer = CAGradientLayer()
private var bottomDecorativeCurveView : BottomDecorativeCurve?
private let bottomDecorativeCurveRotateDegree : CGFloat = CGFloat.pi/180*2
internal var stepCount = 0{
didSet{
stepCountLabel.stepCount = stepCount
}
}
internal var distance = 0{
didSet{
distanceWalkingRunningLabel.text = String(format:"%.2f",Double(distance)/1000)
}
}
internal var delegate : MainInfoViewTapGestureDelegate?
//MARK: View
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
initGradientLayer()
initContainerView(rotateRadius: frame.height)
initDotView()
initBottomDecorativeView()
addGestureToSelf()
}
//MARK: Custom View
private func initGradientLayer(){
guard gradientLayer.superlayer == nil else {return}
gradientLayer.frame = bounds
gradientLayer.colors = [theme.lightThemeColor.cgColor,theme.darkThemeColor.cgColor]
layer.addSublayer(gradientLayer)
}
private func initContainerView(rotateRadius radius:CGFloat){
guard containerView.superview == nil else{return}
containerView.center = CGPoint(x: frame.width/2, y: frame.height/2+radius)
distanceWalkingRunningLabel = DistanceWalkingRunningLabel(frame:CGRect(x: -containerView.center.x, y: -containerView.center.y+frame.height*0.17, width: frame.width, height: frame.height*0.6))
stepCountLabel = StepCountLabel(size: CGSize(width:frame.width,height:frame.height*0.47), center: CGPoint(x: radius*sin(CGFloat.pi/3), y: -radius*sin(CGFloat.pi/6)))
containerView.addSubview(stepCountLabel)
containerView.addSubview(distanceWalkingRunningLabel)
addSubview(containerView)
}
private func initDotView(){
guard dot.superview == nil else{return}
dot.frame.size = CGSize(width: 10, height: 10)
dot.center = CGPoint(x: frame.width*2/5, y: 66)
dot.layer.cornerRadius = dot.frame.width
dot.layer.backgroundColor = UIColor.white.cgColor
addSubview(dot)
}
private func initBottomDecorativeView(){
guard decorativeView.superview == nil else{return}
let height = frame.height*0.24
let width = frame.width
decorativeView.frame = CGRect(x: 0, y: frame.height-height, width: width, height: height)
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: height))
path.addCurve(to: CGPoint(x: width, y:height), controlPoint1: CGPoint(x:width/3,y:height/2), controlPoint2: CGPoint(x:width/3*2,y:height/2))
path.addLine(to: CGPoint(x: 0, y: height))
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.lineWidth = 1
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.fillColor = UIColor.white.cgColor
decorativeView.layer.addSublayer(shapeLayer)
if bottomDecorativeCurveView == nil {
bottomDecorativeCurveView = BottomDecorativeCurve(withMainInfoViewFrame: frame, andBottomDecorativeViewSize: CGSize(width: width, height: height))
decorativeView.addSubview(bottomDecorativeCurveView!)
}
addSubview(decorativeView)
}
//MARK: Gesture Helper
private func addGestureToSelf(){
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(MainInformationView.didTap(_:)))
addGestureRecognizer(tapGesture)
}
internal func didTap(_ sender: UITapGestureRecognizer){
if pointIsInLabelText(point:sender.location(in: stepCountLabel), label:stepCountLabel){
delegate?.didTap(inLabel: stepCountLabel)
}
if pointIsInLabelText(point: sender.location(in: distanceWalkingRunningLabel), label: distanceWalkingRunningLabel){
delegate?.didTap(inLabel: distanceWalkingRunningLabel)
}
}
private func pointIsInLabelText(point:CGPoint, label:UILabel)->Bool{
if (abs(point.x-label.bounds.width/2) < label.textRect(forBounds: label.bounds, limitedToNumberOfLines: 0).width/2)&&(abs(point.y-label.bounds.height/2) < label.textRect(forBounds: label.bounds, limitedToNumberOfLines: 0).height/2){
return true
}else{
return false
}
}
//MARK: Animation helper
private func hideDistanceWalkingRunningSublabel(alpha:CGFloat){
guard distanceWalkingRunningLabel.subviewsAlpha != alpha else {return}
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: {[unowned self] in
self.distanceWalkingRunningLabel.subviewsAlpha = alpha
}, completion: nil)
}
private func hideStepCountSublabel(alpha:CGFloat){
guard stepCountLabel.subviewsAlpha != alpha else {return}
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: {[unowned self] in
self.stepCountLabel.subviewsAlpha = alpha
}, completion: nil)
}
private func swipeClockwise(){
containerView.transform = .identity
dot.center.x = frame.width*2/5
bottomDecorativeCurveView?.transform = .identity
}
private func swipeCounterclockwise(){
containerView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi/3)
dot.center.x = frame.width*3/5
bottomDecorativeCurveView?.transform = CGAffineTransform(rotationAngle: -bottomDecorativeCurveRotateDegree)
}
internal func panAnimation(progress: CGFloat, currentState: MainVCState){
assert(progress >= -1 && progress <= 1)
switch progress {
case 1:
swipeClockwise()
hideDistanceWalkingRunningSublabel(alpha: 1)
hideStepCountSublabel(alpha: 1)
case -1:
swipeCounterclockwise()
hideDistanceWalkingRunningSublabel(alpha: 1)
hideStepCountSublabel(alpha: 1)
default:
switch currentState{
case .running:
hideDistanceWalkingRunningSublabel(alpha: 0)
hideStepCountSublabel(alpha: 1)
if progress > 0 {
containerView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/3*progress/2)
dot.center.x = frame.width*2/5 //可以去掉吗
bottomDecorativeCurveView?.transform = .identity
}
if progress < 0 {
containerView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/3*progress)
dot.center.x = frame.width*2/5-frame.width/5*progress
bottomDecorativeCurveView?.transform = CGAffineTransform(rotationAngle: bottomDecorativeCurveRotateDegree*progress)
}
case .step:
hideDistanceWalkingRunningSublabel(alpha: 1)
hideStepCountSublabel(alpha: 0)
if progress > 0 {
containerView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/3*(progress-1))
dot.center.x = frame.width*3/5-frame.width/5*progress
bottomDecorativeCurveView?.transform = CGAffineTransform(rotationAngle: -bottomDecorativeCurveRotateDegree*(1-progress))
}
if progress < 0 {
containerView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/3*(progress/2-1))
dot.center.x = frame.width*3/5
bottomDecorativeCurveView?.transform = CGAffineTransform(rotationAngle: -bottomDecorativeCurveRotateDegree)
}
}
}
}
internal func refreshAnimations(){
bottomDecorativeCurveView?.refreshAnimation()
}
}
| e689c33018fe8ec7f35ed499f35fe5c1 | 39.909524 | 240 | 0.655453 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom/MailPageInteractor.swift | lgpl-2.1 | 2 | //
// MailPageInteractor.swift
// Neocom
//
// Created by Artem Shimanski on 11/2/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
import CloudData
import EVEAPI
class MailPageInteractor: TreeInteractor {
typealias Presenter = MailPagePresenter
typealias Content = ESI.Result<Value>
weak var presenter: Presenter?
struct Value {
var headers: [ESI.Mail.Header]
var contacts: [Int64: Contact]
}
required init(presenter: Presenter) {
self.presenter = presenter
}
var api = Services.api.current
func load(cachePolicy: URLRequest.CachePolicy) -> Future<Content> {
return load(from: nil, cachePolicy: cachePolicy)
}
func load(from lastMailID: Int64?, cachePolicy: URLRequest.CachePolicy) -> Future<Content> {
guard let input = presenter?.view?.input, let labelID = input.labelID else { return .init(.failure(NCError.invalidInput(type: type(of: self))))}
let headers = api.mailHeaders(lastMailID: lastMailID, labels: [Int64(labelID)], cachePolicy: cachePolicy)
return headers.then(on: .main) { mails -> Future<Content> in
return self.contacts(for: mails.value).then(on: .main) { contacts -> Content in
return mails.map { Value(headers: $0, contacts: contacts) }
}
}
}
func contacts(for mails: [ESI.Mail.Header]) -> Future<[Int64: Contact]> {
var ids = Set(mails.compactMap { mail in mail.recipients?.map{Int64($0.recipientID)} }.joined())
ids.formUnion(mails.compactMap {$0.from.map{Int64($0)}})
guard !ids.isEmpty else {return .init([:])}
return api.contacts(with: ids)
}
private var didChangeAccountObserver: NotificationObserver?
func configure() {
didChangeAccountObserver = NotificationCenter.default.addNotificationObserver(forName: .didChangeAccount, object: nil, queue: .main) { [weak self] _ in
self?.api = Services.api.current
_ = self?.presenter?.reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { presentation in
self?.presenter?.view?.present(presentation, animated: true)
}
}
}
func delete(_ mail: ESI.Mail.Header) -> Future<Void> {
guard let mailID = mail.mailID else { return .init(.failure(NCError.invalidArgument(type: type(of: self), function: #function, argument: "mail", value: mail)))}
return api.delete(mailID: Int64(mailID)).then { _ -> Void in}
}
func markRead(_ mail: ESI.Mail.Header) {
_ = api.markRead(mail: mail)
}
}
| e226832778c507dd1a972aafd148eaea | 33.811594 | 162 | 0.714821 | false | false | false | false |
pompopo/LayoutManager | refs/heads/master | LayoutManagerDemo/LayoutManagerDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// LayoutManagerDemo
//
// Created by pom on 2014/09/19.
// Copyright (c) 2014年 com.gmail.pompopo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var manager:LayoutManager? = nil;
override func viewDidLoad() {
super.viewDidLoad()
self.manager = LayoutManager(view: self.view, type:.Vertical)
var blackView:UIView = UIView()
blackView.backgroundColor = UIColor.blackColor()
var grayView:UIView = UIView()
grayView.backgroundColor = UIColor.grayColor()
var blueView = UIView()
blueView.backgroundColor = UIColor.blueColor()
var greenView = UIView()
greenView.backgroundColor = UIColor.greenColor()
var redView = UIView()
redView.backgroundColor = UIColor.redColor()
self.manager?.addView(blackView, size: SizeClassPair.anySize(), layout: [.Width: 100, .Height: 100, .Top: 50])
self.manager?.addView(blackView, size: SizeClassPair.iPhonePortrait(), layout: [.Left:30])
self.manager?.addView(blackView, size: SizeClassPair.iPhoneLandscape(), layout: [.Right:-30])
self.manager?.addView(grayView, size: SizeClassPair.anySize(), layout: [.Width:50, .Height:50, .Left:30, .Top:10])
self.manager?.addView(blueView, layout: [.Top: 50, .Left:10, .Right:-10, .Height: 100])
let manager2 = LayoutManager(view: blueView, type: .Horizontal)
manager2 .addView(greenView, size: SizeClassPair.iPhonePortrait(),layout: [.Left: 10, .Top: 10, .Bottom:-10, .Width:100])
manager2 .addView(redView, layout: [.Left: 10, .Top: 10, .Bottom:-10, .Width:100])
manager?.addManager(manager2)
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection) {
super.traitCollectionDidChange(previousTraitCollection);
manager?.layout()
}
}
| 995f66a37daf7e8cda08d7bd939975f5 | 36.461538 | 129 | 0.657084 | false | false | false | false |
Subsets and Splits