repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iOSDevLog/iOSDevLog
|
201. UI Test/Swift/ListerKitOSX/CheckBox.swift
|
1
|
1544
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A layer-backed custom check box that is IBDesignable and IBInspectable.
*/
import Cocoa
@IBDesignable public class CheckBox: NSButton {
// MARK: Properties
@IBInspectable public var tintColor: NSColor {
get {
return NSColor(CGColor: checkBoxLayer.tintColor)!
}
set {
checkBoxLayer.tintColor = newValue.CGColor
}
}
@IBInspectable public var isChecked: Bool {
get {
return checkBoxLayer.isChecked
}
set {
checkBoxLayer.isChecked = newValue
}
}
private var checkBoxLayer: CheckBoxLayer {
return layer as! CheckBoxLayer
}
override public var intrinsicContentSize: NSSize {
return NSSize(width: 40, height: 40)
}
// MARK: View Life Cycle
override public func awakeFromNib() {
super.awakeFromNib()
wantsLayer = true
layer = CheckBoxLayer()
layer!.setNeedsDisplay()
}
// MARK: Events
override public func mouseDown(event: NSEvent) {
isChecked = !isChecked
cell!.performClick(self)
}
override public func viewDidChangeBackingProperties() {
super.viewDidChangeBackingProperties()
if let window = window {
layer?.contentsScale = window.backingScaleFactor
}
}
}
|
mit
|
34f711582b98150ad8dbc0f7f75546bb
| 22.378788 | 75 | 0.594682 | 5.586957 | false | false | false | false |
iOSDevLog/iOSDevLog
|
183. Core Image Video/CoreImageVideo/VideoSampleBufferSource.swift
|
1
|
1515
|
//
// Library.swift
// CoreImageVideo
//
// Created by Chris Eidhof on 03/04/15.
// Copyright (c) 2015 objc.io. All rights reserved.
//
import Foundation
import AVFoundation
import GLKit
let pixelBufferDict: [String:AnyObject] =
[kCVPixelBufferPixelFormatTypeKey as String: NSNumber(unsignedInt: kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)]
class VideoSampleBufferSource: NSObject {
lazy var displayLink: CADisplayLink =
CADisplayLink(target: self, selector: "displayLinkDidRefresh:")
let videoOutput: AVPlayerItemVideoOutput
let consumer: CVPixelBuffer -> ()
let player: AVPlayer
init?(url: NSURL, consumer callback: CVPixelBuffer -> ()) {
player = AVPlayer(URL: url)
consumer = callback
videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: pixelBufferDict)
player.currentItem!.addOutput(videoOutput)
super.init()
start()
player.play()
}
func start() {
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
func displayLinkDidRefresh(link: CADisplayLink) {
let itemTime = videoOutput.itemTimeForHostTime(CACurrentMediaTime())
if videoOutput.hasNewPixelBufferForItemTime(itemTime) {
var presentationItemTime = kCMTimeZero
let pixelBuffer = videoOutput.copyPixelBufferForItemTime(itemTime, itemTimeForDisplay: &presentationItemTime)
consumer(pixelBuffer!)
}
}
}
|
mit
|
0fe00260b332dc5e1c5f2e6f676206c8
| 28.72549 | 121 | 0.69769 | 5 | false | false | false | false |
airspeedswift/swift
|
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-4conformance-1distinct_use.swift
|
3
|
13613
|
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$sytN" = external{{( dllimport)?}} global %swift.full_type
// CHECK: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i8**,
// CHECK-SAME: i8**,
// CHECK-SAME: i8**,
// CHECK-SAME: i8**,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** @"$sB[[INT]]_WV",
// i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1PAAWP", i32 0, i32 0),
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1QAAWP", i32 0, i32 0),
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1RAAWP", i32 0, i32 0),
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1SAAWP", i32 0, i32 0),
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
protocol P {}
protocol Q {}
protocol R {}
protocol S {}
extension Int : P {}
extension Int : Q {}
extension Int : R {}
extension Int : S {}
struct Value<First : P & Q & R & S> {
let first: First
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i8**, i8**, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Value(first: 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, i8** %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_ARGUMENT_BUFFER:%[0-9]+]] = bitcast i8** %1 to i8*
// CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_1]]:
// CHECK: [[ERASED_TYPE_ADDRESS:%[0-9]+]] = getelementptr i8*, i8** %1, i64 0
// CHECK: %"load argument at index 0 from buffer" = load i8*, i8** [[ERASED_TYPE_ADDRESS]]
// CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), %"load argument at index 0 from buffer"
// CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]]
// CHECK: [[POINTER_TO_ERASED_TABLE_1:%[0-9]+]] = getelementptr i8*, i8** %1, i64 1
// CHECK: [[ERASED_TABLE_1:%"load argument at index 1 from buffer"]] = load i8*, i8** [[POINTER_TO_ERASED_TABLE_1]], align 1
// CHECK: [[UNERASED_TABLE_1:%[0-9]+]] = bitcast i8* [[ERASED_TABLE_1]] to i8**
// CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_1:%[0-9]+]] = load i8*, i8** [[UNERASED_TABLE_1]], align 1
// CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR_1:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_1]] to %swift.protocol_conformance_descriptor*
// CHECK-arm64e: [[ERASED_TABLE_INT_1:%[0-9]+]] = ptrtoint i8* [[ERASED_TABLE_1]] to i64
// CHECK-arm64e: [[TABLE_SIGNATURE_1:%[0-9]+]] = call i64 @llvm.ptrauth.blend.i64(i64 [[ERASED_TABLE_INT_1]], i64 50923)
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_1:%[0-9]+]] = call i64 @llvm.ptrauth.auth.i64(i64 %13, i32 2, i64 [[TABLE_SIGNATURE_1]])
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_1:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_1]] to %swift.protocol_conformance_descriptor*
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_1:%[0-9]+]] = ptrtoint %swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_1]] to i64
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_1:%[0-9]+]] = call i64 @llvm.ptrauth.sign.i64(i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_1]], i32 2, i64 50923)
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_1:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_1]] to %swift.protocol_conformance_descriptor*
// CHECK: [[EQUAL_DESCRIPTORS_1:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors(
// CHECK-SAME: %swift.protocol_conformance_descriptor*
// CHECK-arm64e-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_1]],
// CHECK-i386-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-x86_64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7s-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7k-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-arm64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-SAME: %swift.protocol_conformance_descriptor*
// CHECK-SAME: $sSi4main1PAAMc
// CHECK-SAME: )
// CHECK: [[EQUAL_ARGUMENTS_1:%[0-9]+]] = and i1 [[EQUAL_TYPES]], [[EQUAL_DESCRIPTORS_1]]
// CHECK: [[POINTER_TO_ERASED_TABLE_2:%[0-9]+]] = getelementptr i8*, i8** %1, i64 2
// CHECK: [[ERASED_TABLE_2:%"load argument at index 2 from buffer"]] = load i8*, i8** [[POINTER_TO_ERASED_TABLE_2]], align 1
// CHECK: [[UNERASED_TABLE_2:%[0-9]+]] = bitcast i8* [[ERASED_TABLE_2]] to i8**
// CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_2:%[0-9]+]] = load i8*, i8** [[UNERASED_TABLE_2]], align 1
// CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR_2:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_2]] to %swift.protocol_conformance_descriptor*
// CHECK-arm64e: [[ERASED_TABLE_INT_2:%[0-9]+]] = ptrtoint i8* [[ERASED_TABLE_2]] to i64
// CHECK-arm64e: [[TABLE_SIGNATURE_2:%[0-9]+]] = call i64 @llvm.ptrauth.blend.i64(i64 [[ERASED_TABLE_INT_2]], i64 50923)
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_2:%[0-9]+]] = call i64 @llvm.ptrauth.auth.i64(i64 %13, i32 2, i64 [[TABLE_SIGNATURE_2]])
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_2:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_2]] to %swift.protocol_conformance_descriptor*
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_2:%[0-9]+]] = ptrtoint %swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_2]] to i64
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_2:%[0-9]+]] = call i64 @llvm.ptrauth.sign.i64(i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_2]], i32 2, i64 50923)
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_2:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_2]] to %swift.protocol_conformance_descriptor*
// CHECK: [[EQUAL_DESCRIPTORS_2:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors(
// CHECK-SAME: %swift.protocol_conformance_descriptor*
// CHECK-arm64e-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_2]],
// CHECK-i386-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-x86_64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7s-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7k-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-arm64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-SAME: %swift.protocol_conformance_descriptor*
// CHECK-SAME: $sSi4main1QAAMc
// CHECK-SAME: )
// CHECK: [[EQUAL_ARGUMENTS_2:%[0-9]+]] = and i1 [[EQUAL_ARGUMENTS_1]], [[EQUAL_DESCRIPTORS_2]]
// CHECK: [[POINTER_TO_ERASED_TABLE_3:%[0-9]+]] = getelementptr i8*, i8** %1, i64 3
// CHECK: [[ERASED_TABLE_3:%"load argument at index 3 from buffer"]] = load i8*, i8** [[POINTER_TO_ERASED_TABLE_3]], align 1
// CHECK: [[UNERASED_TABLE_3:%[0-9]+]] = bitcast i8* [[ERASED_TABLE_3]] to i8**
// CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_3:%[0-9]+]] = load i8*, i8** [[UNERASED_TABLE_3]], align 1
// CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR_3:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_3]] to %swift.protocol_conformance_descriptor*
// CHECK-arm64e: [[ERASED_TABLE_INT_3:%[0-9]+]] = ptrtoint i8* [[ERASED_TABLE_3]] to i64
// CHECK-arm64e: [[TABLE_SIGNATURE_3:%[0-9]+]] = call i64 @llvm.ptrauth.blend.i64(i64 [[ERASED_TABLE_INT_3]], i64 50923)
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_3:%[0-9]+]] = call i64 @llvm.ptrauth.auth.i64(i64 %13, i32 2, i64 [[TABLE_SIGNATURE_3]])
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_3:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_3]] to %swift.protocol_conformance_descriptor*
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_3:%[0-9]+]] = ptrtoint %swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_3]] to i64
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_3:%[0-9]+]] = call i64 @llvm.ptrauth.sign.i64(i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_3]], i32 2, i64 50923)
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_3:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_3]] to %swift.protocol_conformance_descriptor*
// CHECK: [[EQUAL_DESCRIPTORS_3:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors(
// CHECK-SAME: %swift.protocol_conformance_descriptor*
// CHECK-arm64e-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_3]],
// CHECK-i386-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-x86_64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7s-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7k-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-arm64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-SAME: %swift.protocol_conformance_descriptor*
// CHECK-SAME: $sSi4main1RAAMc
// CHECK-SAME: )
// CHECK: [[EQUAL_ARGUMENTS_3:%[0-9]+]] = and i1 [[EQUAL_ARGUMENTS_2]], [[EQUAL_DESCRIPTORS_3]]
// CHECK: [[POINTER_TO_ERASED_TABLE_4:%[0-9]+]] = getelementptr i8*, i8** %1, i64 4
// CHECK: [[ERASED_TABLE_4:%"load argument at index 4 from buffer"]] = load i8*, i8** [[POINTER_TO_ERASED_TABLE_4]], align 1
// CHECK: [[UNERASED_TABLE_4:%[0-9]+]] = bitcast i8* [[ERASED_TABLE_4]] to i8**
// CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_4:%[0-9]+]] = load i8*, i8** [[UNERASED_TABLE_4]], align 1
// CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR_4:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_4]] to %swift.protocol_conformance_descriptor*
// CHECK-arm64e: [[ERASED_TABLE_INT_4:%[0-9]+]] = ptrtoint i8* [[ERASED_TABLE_4]] to i64
// CHECK-arm64e: [[TABLE_SIGNATURE_4:%[0-9]+]] = call i64 @llvm.ptrauth.blend.i64(i64 [[ERASED_TABLE_INT_4]], i64 50923)
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_4:%[0-9]+]] = call i64 @llvm.ptrauth.auth.i64(i64 %13, i32 2, i64 [[TABLE_SIGNATURE_4]])
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_4:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_4]] to %swift.protocol_conformance_descriptor*
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_4:%[0-9]+]] = ptrtoint %swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_4]] to i64
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_4:%[0-9]+]] = call i64 @llvm.ptrauth.sign.i64(i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_4]], i32 2, i64 50923)
// CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_4:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_4]] to %swift.protocol_conformance_descriptor*
// CHECK: [[EQUAL_DESCRIPTORS_4:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors(
// CHECK-SAME: %swift.protocol_conformance_descriptor*
// CHECK-arm64e-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_4]],
// CHECK-i386-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-x86_64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7s-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-armv7k-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-arm64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]],
// CHECK-SAME: %swift.protocol_conformance_descriptor*
// CHECK-SAME: $sSi4main1SAAMc
// CHECK-SAME: )
// CHECK: [[EQUAL_ARGUMENTS_4:%[0-9]+]] = and i1 [[EQUAL_ARGUMENTS_3]], [[EQUAL_DESCRIPTORS_4]]
// CHECK: br i1 [[EQUAL_ARGUMENTS_4]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i8**, i8**, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @swift_getGenericMetadata([[INT]] %0, i8* [[ERASED_ARGUMENT_BUFFER]], %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
|
apache-2.0
|
d1f59bc41076408ae1f4d2e3c3f5522c
| 75.909605 | 356 | 0.659076 | 2.85328 | false | false | false | false |
kstaring/swift
|
validation-test/compiler_crashers_fixed/01066-swift-typebase-getcanonicaltype.swift
|
11
|
680
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
protocol b {
struct e = e> () {
class C) {
}
}
class A<T -> {
func x(seq: Int = Swift.Iterator.d(b<f == A<S {
convenience init({
func a: T.f = """""""]()
}
}
protocol a {
func b> {
}
typealias d>(() -> String {
func c, """
protocol A {
})
protocol a {
}
typealias e : d = F>)
}
}
var e(b
|
apache-2.0
|
2aa274aa1d683a6c5683111ac0b1f009
| 20.25 | 78 | 0.655882 | 3.090909 | false | false | false | false |
ta2yak/FontAwesome.swift
|
FontAwesome/FontAwesome.swift
|
1
|
32094
|
// FontAwesome.swift
//
// Copyright (c) 2014-2015 Thi Doan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreText
private class FontLoader {
class func loadFont(name: String) {
let bundle = NSBundle(forClass: FontLoader.self)
var fontURL = NSURL()
let identifier = bundle.bundleIdentifier
if identifier?.hasPrefix("org.cocoapods") == true {
// If this framework is added using CocoaPods, resources is placed under a subdirectory
fontURL = bundle.URLForResource(name, withExtension: "otf", subdirectory: "FontAwesome.swift.bundle")!
} else {
fontURL = bundle.URLForResource(name, withExtension: "otf")!
}
let data = NSData(contentsOfURL: fontURL)!
let provider = CGDataProviderCreateWithCFData(data)
let font = CGFontCreateWithDataProvider(provider)!
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(font, &error) {
let errorDescription: CFStringRef = CFErrorCopyDescription(error!.takeUnretainedValue())
let nsError = error!.takeUnretainedValue() as CFError
NSException(name: NSInternalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise()
}
}
}
public extension UIFont {
public class func fontAwesomeOfSize(fontSize: CGFloat) -> UIFont {
struct Static {
static var onceToken : dispatch_once_t = 0
}
let name = "FontAwesome"
if (UIFont.fontNamesForFamilyName(name).count == 0) {
dispatch_once(&Static.onceToken) {
FontLoader.loadFont(name)
}
}
return UIFont(name: name, size: fontSize)!
}
}
public extension String {
public static func fontAwesomeIconWithName(name: FontAwesome) -> String {
return name.rawValue.substringToIndex(advance(name.rawValue.startIndex, 1))
}
}
public extension UIImage {
public class func fontAwesomeIconWithName(name: FontAwesome, textColor: UIColor, size: CGSize) -> UIImage {
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = NSLineBreakMode.ByWordWrapping
paragraph.alignment = .Center
let attributedString = NSAttributedString(string: String.fontAwesomeIconWithName(name) as String, attributes: [NSFontAttributeName: UIFont.fontAwesomeOfSize(max(size.width, size.height)), NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName:paragraph])
let size = attributedString.sizeWithMaxWidth(size.width)
UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
attributedString.drawInRect(CGRectMake(0, 0, size.width, size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
public extension NSAttributedString {
public func sizeWithMaxWidth(maxWidth: CGFloat) -> CGSize {
return self.boundingRectWithSize(CGSizeMake(maxWidth, 1000), options:(NSStringDrawingOptions.UsesLineFragmentOrigin), context: nil).size
}
}
public extension String {
public static func fontAwesomeIconWithCode(code: String) -> String? {
let dict = [
"fa-500px" : "\u{f26e}",
"fa-adjust" : "\u{f042}",
"fa-adn" : "\u{f170}",
"fa-align-center" : "\u{f037}",
"fa-align-justify" : "\u{f039}",
"fa-align-left" : "\u{f036}",
"fa-align-right" : "\u{f038}",
"fa-amazon" : "\u{f270}",
"fa-ambulance" : "\u{f0f9}",
"fa-anchor" : "\u{f13d}",
"fa-android" : "\u{f17b}",
"fa-angellist" : "\u{f209}",
"fa-angle-double-down" : "\u{f103}",
"fa-angle-double-left" : "\u{f100}",
"fa-angle-double-right" : "\u{f101}",
"fa-angle-double-up" : "\u{f102}",
"fa-angle-down" : "\u{f107}",
"fa-angle-left" : "\u{f104}",
"fa-angle-right" : "\u{f105}",
"fa-angle-up" : "\u{f106}",
"fa-apple" : "\u{f179}",
"fa-archive" : "\u{f187}",
"fa-area-chart" : "\u{f1fe}",
"fa-arrow-circle-down" : "\u{f0ab}",
"fa-arrow-circle-left" : "\u{f0a8}",
"fa-arrow-circle-o-down" : "\u{f01a}",
"fa-arrow-circle-o-left" : "\u{f190}",
"fa-arrow-circle-o-right" : "\u{f18e}",
"fa-arrow-circle-o-up" : "\u{f01b}",
"fa-arrow-circle-right" : "\u{f0a9}",
"fa-arrow-circle-up" : "\u{f0aa}",
"fa-arrow-down" : "\u{f063}",
"fa-arrow-left" : "\u{f060}",
"fa-arrow-right" : "\u{f061}",
"fa-arrow-up" : "\u{f062}",
"fa-arrows" : "\u{f047}",
"fa-arrows-alt" : "\u{f0b2}",
"fa-arrows-h" : "\u{f07e}",
"fa-arrows-v" : "\u{f07d}",
"fa-asterisk" : "\u{f069}",
"fa-at" : "\u{f1fa}",
"fa-automobile" : "\u{f1b9}",
"fa-backward" : "\u{f04a}",
"fa-balance-scale" : "\u{f24e}",
"fa-ban" : "\u{f05e}",
"fa-bank" : "\u{f19c}",
"fa-bar-chart" : "\u{f080}",
"fa-bar-chart-o" : "\u{f080}",
"fa-barcode" : "\u{f02a}",
"fa-bars" : "\u{f0c9}",
"fa-battery-0" : "\u{f244}",
"fa-battery-1" : "\u{f243}",
"fa-battery-2" : "\u{f242}",
"fa-battery-3" : "\u{f241}",
"fa-battery-4" : "\u{f240}",
"fa-battery-empty" : "\u{f244}",
"fa-battery-full" : "\u{f240}",
"fa-battery-half" : "\u{f242}",
"fa-battery-quarter" : "\u{f243}",
"fa-battery-three-quarters" : "\u{f241}",
"fa-bed" : "\u{f236}",
"fa-beer" : "\u{f0fc}",
"fa-behance" : "\u{f1b4}",
"fa-behance-square" : "\u{f1b5}",
"fa-bell" : "\u{f0f3}",
"fa-bell-o" : "\u{f0a2}",
"fa-bell-slash" : "\u{f1f6}",
"fa-bell-slash-o" : "\u{f1f7}",
"fa-bicycle" : "\u{f206}",
"fa-binoculars" : "\u{f1e5}",
"fa-birthday-cake" : "\u{f1fd}",
"fa-bitbucket" : "\u{f171}",
"fa-bitbucket-square" : "\u{f172}",
"fa-bitcoin" : "\u{f15a}",
"fa-black-tie" : "\u{f27e}",
"fa-bold" : "\u{f032}",
"fa-bolt" : "\u{f0e7}",
"fa-bomb" : "\u{f1e2}",
"fa-book" : "\u{f02d}",
"fa-bookmark" : "\u{f02e}",
"fa-bookmark-o" : "\u{f097}",
"fa-briefcase" : "\u{f0b1}",
"fa-btc" : "\u{f15a}",
"fa-bug" : "\u{f188}",
"fa-building" : "\u{f1ad}",
"fa-building-o" : "\u{f0f7}",
"fa-bullhorn" : "\u{f0a1}",
"fa-bullseye" : "\u{f140}",
"fa-bus" : "\u{f207}",
"fa-buysellads" : "\u{f20d}",
"fa-cab" : "\u{f1ba}",
"fa-calculator" : "\u{f1ec}",
"fa-calendar" : "\u{f073}",
"fa-calendar-check-o" : "\u{f274}",
"fa-calendar-minus-o" : "\u{f272}",
"fa-calendar-o" : "\u{f133}",
"fa-calendar-plus-o" : "\u{f271}",
"fa-calendar-times-o" : "\u{f273}",
"fa-camera" : "\u{f030}",
"fa-camera-retro" : "\u{f083}",
"fa-car" : "\u{f1b9}",
"fa-caret-down" : "\u{f0d7}",
"fa-caret-left" : "\u{f0d9}",
"fa-caret-right" : "\u{f0da}",
"fa-caret-square-o-down" : "\u{f150}",
"fa-caret-square-o-left" : "\u{f191}",
"fa-caret-square-o-right" : "\u{f152}",
"fa-caret-square-o-up" : "\u{f151}",
"fa-caret-up" : "\u{f0d8}",
"fa-cart-arrow-down" : "\u{f218}",
"fa-cart-plus" : "\u{f217}",
"fa-cc" : "\u{f20a}",
"fa-cc-amex" : "\u{f1f3}",
"fa-cc-diners-club" : "\u{f24c}",
"fa-cc-discover" : "\u{f1f2}",
"fa-cc-jcb" : "\u{f24b}",
"fa-cc-mastercard" : "\u{f1f1}",
"fa-cc-paypal" : "\u{f1f4}",
"fa-cc-stripe" : "\u{f1f5}",
"fa-cc-visa" : "\u{f1f0}",
"fa-certificate" : "\u{f0a3}",
"fa-chain" : "\u{f0c1}",
"fa-chain-broken" : "\u{f127}",
"fa-check" : "\u{f00c}",
"fa-check-circle" : "\u{f058}",
"fa-check-circle-o" : "\u{f05d}",
"fa-check-square" : "\u{f14a}",
"fa-check-square-o" : "\u{f046}",
"fa-chevron-circle-down" : "\u{f13a}",
"fa-chevron-circle-left" : "\u{f137}",
"fa-chevron-circle-right" : "\u{f138}",
"fa-chevron-circle-up" : "\u{f139}",
"fa-chevron-down" : "\u{f078}",
"fa-chevron-left" : "\u{f053}",
"fa-chevron-right" : "\u{f054}",
"fa-chevron-up" : "\u{f077}",
"fa-child" : "\u{f1ae}",
"fa-chrome" : "\u{f268}",
"fa-circle" : "\u{f111}",
"fa-circle-o" : "\u{f10c}",
"fa-circle-o-notch" : "\u{f1ce}",
"fa-circle-thin" : "\u{f1db}",
"fa-clipboard" : "\u{f0ea}",
"fa-clock-o" : "\u{f017}",
"fa-clone" : "\u{f24d}",
"fa-close" : "\u{f00d}",
"fa-cloud" : "\u{f0c2}",
"fa-cloud-download" : "\u{f0ed}",
"fa-cloud-upload" : "\u{f0ee}",
"fa-cny" : "\u{f157}",
"fa-code" : "\u{f121}",
"fa-code-fork" : "\u{f126}",
"fa-codepen" : "\u{f1cb}",
"fa-coffee" : "\u{f0f4}",
"fa-cog" : "\u{f013}",
"fa-cogs" : "\u{f085}",
"fa-columns" : "\u{f0db}",
"fa-comment" : "\u{f075}",
"fa-comment-o" : "\u{f0e5}",
"fa-commenting" : "\u{f27a}",
"fa-commenting-o" : "\u{f27b}",
"fa-comments" : "\u{f086}",
"fa-comments-o" : "\u{f0e6}",
"fa-compass" : "\u{f14e}",
"fa-compress" : "\u{f066}",
"fa-connectdevelop" : "\u{f20e}",
"fa-contao" : "\u{f26d}",
"fa-copy" : "\u{f0c5}",
"fa-copyright" : "\u{f1f9}",
"fa-creative-commons" : "\u{f25e}",
"fa-credit-card" : "\u{f09d}",
"fa-crop" : "\u{f125}",
"fa-crosshairs" : "\u{f05b}",
"fa-css3" : "\u{f13c}",
"fa-cube" : "\u{f1b2}",
"fa-cubes" : "\u{f1b3}",
"fa-cut" : "\u{f0c4}",
"fa-cutlery" : "\u{f0f5}",
"fa-dashboard" : "\u{f0e4}",
"fa-dashcube" : "\u{f210}",
"fa-database" : "\u{f1c0}",
"fa-dedent" : "\u{f03b}",
"fa-delicious" : "\u{f1a5}",
"fa-desktop" : "\u{f108}",
"fa-deviantart" : "\u{f1bd}",
"fa-diamond" : "\u{f219}",
"fa-digg" : "\u{f1a6}",
"fa-dollar" : "\u{f155}",
"fa-dot-circle-o" : "\u{f192}",
"fa-download" : "\u{f019}",
"fa-dribbble" : "\u{f17d}",
"fa-dropbox" : "\u{f16b}",
"fa-drupal" : "\u{f1a9}",
"fa-edit" : "\u{f044}",
"fa-eject" : "\u{f052}",
"fa-ellipsis-h" : "\u{f141}",
"fa-ellipsis-v" : "\u{f142}",
"fa-empire" : "\u{f1d1}",
"fa-envelope" : "\u{f0e0}",
"fa-envelope-o" : "\u{f003}",
"fa-envelope-square" : "\u{f199}",
"fa-eraser" : "\u{f12d}",
"fa-eur" : "\u{f153}",
"fa-euro" : "\u{f153}",
"fa-exchange" : "\u{f0ec}",
"fa-exclamation" : "\u{f12a}",
"fa-exclamation-circle" : "\u{f06a}",
"fa-exclamation-triangle" : "\u{f071}",
"fa-expand" : "\u{f065}",
"fa-expeditedssl" : "\u{f23e}",
"fa-external-link" : "\u{f08e}",
"fa-external-link-square" : "\u{f14c}",
"fa-eye" : "\u{f06e}",
"fa-eye-slash" : "\u{f070}",
"fa-eyedropper" : "\u{f1fb}",
"fa-facebook" : "\u{f09a}",
"fa-facebook-f" : "\u{f09a}",
"fa-facebook-official" : "\u{f230}",
"fa-facebook-square" : "\u{f082}",
"fa-fast-backward" : "\u{f049}",
"fa-fast-forward" : "\u{f050}",
"fa-fax" : "\u{f1ac}",
"fa-feed" : "\u{f09e}",
"fa-female" : "\u{f182}",
"fa-fighter-jet" : "\u{f0fb}",
"fa-file" : "\u{f15b}",
"fa-file-archive-o" : "\u{f1c6}",
"fa-file-audio-o" : "\u{f1c7}",
"fa-file-code-o" : "\u{f1c9}",
"fa-file-excel-o" : "\u{f1c3}",
"fa-file-image-o" : "\u{f1c5}",
"fa-file-movie-o" : "\u{f1c8}",
"fa-file-o" : "\u{f016}",
"fa-file-pdf-o" : "\u{f1c1}",
"fa-file-photo-o" : "\u{f1c5}",
"fa-file-picture-o" : "\u{f1c5}",
"fa-file-powerpoint-o" : "\u{f1c4}",
"fa-file-sound-o" : "\u{f1c7}",
"fa-file-text" : "\u{f15c}",
"fa-file-text-o" : "\u{f0f6}",
"fa-file-video-o" : "\u{f1c8}",
"fa-file-word-o" : "\u{f1c2}",
"fa-file-zip-o" : "\u{f1c6}",
"fa-files-o" : "\u{f0c5}",
"fa-film" : "\u{f008}",
"fa-filter" : "\u{f0b0}",
"fa-fire" : "\u{f06d}",
"fa-fire-extinguisher" : "\u{f134}",
"fa-firefox" : "\u{f269}",
"fa-flag" : "\u{f024}",
"fa-flag-checkered" : "\u{f11e}",
"fa-flag-o" : "\u{f11d}",
"fa-flash" : "\u{f0e7}",
"fa-flask" : "\u{f0c3}",
"fa-flickr" : "\u{f16e}",
"fa-floppy-o" : "\u{f0c7}",
"fa-folder" : "\u{f07b}",
"fa-folder-o" : "\u{f114}",
"fa-folder-open" : "\u{f07c}",
"fa-folder-open-o" : "\u{f115}",
"fa-font" : "\u{f031}",
"fa-fonticons" : "\u{f280}",
"fa-forumbee" : "\u{f211}",
"fa-forward" : "\u{f04e}",
"fa-foursquare" : "\u{f180}",
"fa-frown-o" : "\u{f119}",
"fa-futbol-o" : "\u{f1e3}",
"fa-gamepad" : "\u{f11b}",
"fa-gavel" : "\u{f0e3}",
"fa-gbp" : "\u{f154}",
"fa-ge" : "\u{f1d1}",
"fa-gear" : "\u{f013}",
"fa-gears" : "\u{f085}",
"fa-genderless" : "\u{f22d}",
"fa-get-pocket" : "\u{f265}",
"fa-gg" : "\u{f260}",
"fa-gg-circle" : "\u{f261}",
"fa-gift" : "\u{f06b}",
"fa-git" : "\u{f1d3}",
"fa-git-square" : "\u{f1d2}",
"fa-github" : "\u{f09b}",
"fa-github-alt" : "\u{f113}",
"fa-github-square" : "\u{f092}",
"fa-gittip" : "\u{f184}",
"fa-glass" : "\u{f000}",
"fa-globe" : "\u{f0ac}",
"fa-google" : "\u{f1a0}",
"fa-google-plus" : "\u{f0d5}",
"fa-google-plus-square" : "\u{f0d4}",
"fa-google-wallet" : "\u{f1ee}",
"fa-graduation-cap" : "\u{f19d}",
"fa-gratipay" : "\u{f184}",
"fa-group" : "\u{f0c0}",
"fa-h-square" : "\u{f0fd}",
"fa-hacker-news" : "\u{f1d4}",
"fa-hand-grab-o" : "\u{f255}",
"fa-hand-lizard-o" : "\u{f258}",
"fa-hand-o-down" : "\u{f0a7}",
"fa-hand-o-left" : "\u{f0a5}",
"fa-hand-o-right" : "\u{f0a4}",
"fa-hand-o-up" : "\u{f0a6}",
"fa-hand-paper-o" : "\u{f256}",
"fa-hand-peace-o" : "\u{f25b}",
"fa-hand-pointer-o" : "\u{f25a}",
"fa-hand-rock-o" : "\u{f255}",
"fa-hand-scissors-o" : "\u{f257}",
"fa-hand-spock-o" : "\u{f259}",
"fa-hand-stop-o" : "\u{f256}",
"fa-hdd-o" : "\u{f0a0}",
"fa-header" : "\u{f1dc}",
"fa-headphones" : "\u{f025}",
"fa-heart" : "\u{f004}",
"fa-heart-o" : "\u{f08a}",
"fa-heartbeat" : "\u{f21e}",
"fa-history" : "\u{f1da}",
"fa-home" : "\u{f015}",
"fa-hospital-o" : "\u{f0f8}",
"fa-hotel" : "\u{f236}",
"fa-hourglass" : "\u{f254}",
"fa-hourglass-1" : "\u{f251}",
"fa-hourglass-2" : "\u{f252}",
"fa-hourglass-3" : "\u{f253}",
"fa-hourglass-end" : "\u{f253}",
"fa-hourglass-half" : "\u{f252}",
"fa-hourglass-o" : "\u{f250}",
"fa-hourglass-start" : "\u{f251}",
"fa-houzz" : "\u{f27c}",
"fa-html5" : "\u{f13b}",
"fa-i-cursor" : "\u{f246}",
"fa-ils" : "\u{f20b}",
"fa-image" : "\u{f03e}",
"fa-inbox" : "\u{f01c}",
"fa-indent" : "\u{f03c}",
"fa-industry" : "\u{f275}",
"fa-info" : "\u{f129}",
"fa-info-circle" : "\u{f05a}",
"fa-inr" : "\u{f156}",
"fa-instagram" : "\u{f16d}",
"fa-institution" : "\u{f19c}",
"fa-internet-explorer" : "\u{f26b}",
"fa-intersex" : "\u{f224}",
"fa-ioxhost" : "\u{f208}",
"fa-italic" : "\u{f033}",
"fa-joomla" : "\u{f1aa}",
"fa-jpy" : "\u{f157}",
"fa-jsfiddle" : "\u{f1cc}",
"fa-key" : "\u{f084}",
"fa-keyboard-o" : "\u{f11c}",
"fa-krw" : "\u{f159}",
"fa-language" : "\u{f1ab}",
"fa-laptop" : "\u{f109}",
"fa-lastfm" : "\u{f202}",
"fa-lastfm-square" : "\u{f203}",
"fa-leaf" : "\u{f06c}",
"fa-leanpub" : "\u{f212}",
"fa-legal" : "\u{f0e3}",
"fa-lemon-o" : "\u{f094}",
"fa-level-down" : "\u{f149}",
"fa-level-up" : "\u{f148}",
"fa-life-bouy" : "\u{f1cd}",
"fa-life-buoy" : "\u{f1cd}",
"fa-life-ring" : "\u{f1cd}",
"fa-life-saver" : "\u{f1cd}",
"fa-lightbulb-o" : "\u{f0eb}",
"fa-line-chart" : "\u{f201}",
"fa-link" : "\u{f0c1}",
"fa-linkedin" : "\u{f0e1}",
"fa-linkedin-square" : "\u{f08c}",
"fa-linux" : "\u{f17c}",
"fa-list" : "\u{f03a}",
"fa-list-alt" : "\u{f022}",
"fa-list-ol" : "\u{f0cb}",
"fa-list-ul" : "\u{f0ca}",
"fa-location-arrow" : "\u{f124}",
"fa-lock" : "\u{f023}",
"fa-long-arrow-down" : "\u{f175}",
"fa-long-arrow-left" : "\u{f177}",
"fa-long-arrow-right" : "\u{f178}",
"fa-long-arrow-up" : "\u{f176}",
"fa-magic" : "\u{f0d0}",
"fa-magnet" : "\u{f076}",
"fa-mail-forward" : "\u{f064}",
"fa-mail-reply" : "\u{f112}",
"fa-mail-reply-all" : "\u{f122}",
"fa-male" : "\u{f183}",
"fa-map" : "\u{f279}",
"fa-map-marker" : "\u{f041}",
"fa-map-o" : "\u{f278}",
"fa-map-pin" : "\u{f276}",
"fa-map-signs" : "\u{f277}",
"fa-mars" : "\u{f222}",
"fa-mars-double" : "\u{f227}",
"fa-mars-stroke" : "\u{f229}",
"fa-mars-stroke-h" : "\u{f22b}",
"fa-mars-stroke-v" : "\u{f22a}",
"fa-maxcdn" : "\u{f136}",
"fa-meanpath" : "\u{f20c}",
"fa-medium" : "\u{f23a}",
"fa-medkit" : "\u{f0fa}",
"fa-meh-o" : "\u{f11a}",
"fa-mercury" : "\u{f223}",
"fa-microphone" : "\u{f130}",
"fa-microphone-slash" : "\u{f131}",
"fa-minus" : "\u{f068}",
"fa-minus-circle" : "\u{f056}",
"fa-minus-square" : "\u{f146}",
"fa-minus-square-o" : "\u{f147}",
"fa-mobile" : "\u{f10b}",
"fa-mobile-phone" : "\u{f10b}",
"fa-money" : "\u{f0d6}",
"fa-moon-o" : "\u{f186}",
"fa-mortar-board" : "\u{f19d}",
"fa-motorcycle" : "\u{f21c}",
"fa-mouse-pointer" : "\u{f245}",
"fa-music" : "\u{f001}",
"fa-navicon" : "\u{f0c9}",
"fa-neuter" : "\u{f22c}",
"fa-newspaper-o" : "\u{f1ea}",
"fa-object-group" : "\u{f247}",
"fa-object-ungroup" : "\u{f248}",
"fa-odnoklassniki" : "\u{f263}",
"fa-odnoklassniki-square" : "\u{f264}",
"fa-opencart" : "\u{f23d}",
"fa-openid" : "\u{f19b}",
"fa-opera" : "\u{f26a}",
"fa-optin-monster" : "\u{f23c}",
"fa-outdent" : "\u{f03b}",
"fa-pagelines" : "\u{f18c}",
"fa-paint-brush" : "\u{f1fc}",
"fa-paper-plane" : "\u{f1d8}",
"fa-paper-plane-o" : "\u{f1d9}",
"fa-paperclip" : "\u{f0c6}",
"fa-paragraph" : "\u{f1dd}",
"fa-paste" : "\u{f0ea}",
"fa-pause" : "\u{f04c}",
"fa-paw" : "\u{f1b0}",
"fa-paypal" : "\u{f1ed}",
"fa-pencil" : "\u{f040}",
"fa-pencil-square" : "\u{f14b}",
"fa-pencil-square-o" : "\u{f044}",
"fa-phone" : "\u{f095}",
"fa-phone-square" : "\u{f098}",
"fa-photo" : "\u{f03e}",
"fa-picture-o" : "\u{f03e}",
"fa-pie-chart" : "\u{f200}",
"fa-pied-piper" : "\u{f1a7}",
"fa-pied-piper-alt" : "\u{f1a8}",
"fa-pinterest" : "\u{f0d2}",
"fa-pinterest-p" : "\u{f231}",
"fa-pinterest-square" : "\u{f0d3}",
"fa-plane" : "\u{f072}",
"fa-play" : "\u{f04b}",
"fa-play-circle" : "\u{f144}",
"fa-play-circle-o" : "\u{f01d}",
"fa-plug" : "\u{f1e6}",
"fa-plus" : "\u{f067}",
"fa-plus-circle" : "\u{f055}",
"fa-plus-square" : "\u{f0fe}",
"fa-plus-square-o" : "\u{f196}",
"fa-power-off" : "\u{f011}",
"fa-print" : "\u{f02f}",
"fa-puzzle-piece" : "\u{f12e}",
"fa-qq" : "\u{f1d6}",
"fa-qrcode" : "\u{f029}",
"fa-question" : "\u{f128}",
"fa-question-circle" : "\u{f059}",
"fa-quote-left" : "\u{f10d}",
"fa-quote-right" : "\u{f10e}",
"fa-ra" : "\u{f1d0}",
"fa-random" : "\u{f074}",
"fa-rebel" : "\u{f1d0}",
"fa-recycle" : "\u{f1b8}",
"fa-reddit" : "\u{f1a1}",
"fa-reddit-square" : "\u{f1a2}",
"fa-refresh" : "\u{f021}",
"fa-registered" : "\u{f25d}",
"fa-remove" : "\u{f00d}",
"fa-renren" : "\u{f18b}",
"fa-reorder" : "\u{f0c9}",
"fa-repeat" : "\u{f01e}",
"fa-reply" : "\u{f112}",
"fa-reply-all" : "\u{f122}",
"fa-retweet" : "\u{f079}",
"fa-rmb" : "\u{f157}",
"fa-road" : "\u{f018}",
"fa-rocket" : "\u{f135}",
"fa-rotate-left" : "\u{f0e2}",
"fa-rotate-right" : "\u{f01e}",
"fa-rouble" : "\u{f158}",
"fa-rss" : "\u{f09e}",
"fa-rss-square" : "\u{f143}",
"fa-rub" : "\u{f158}",
"fa-ruble" : "\u{f158}",
"fa-rupee" : "\u{f156}",
"fa-safari" : "\u{f267}",
"fa-save" : "\u{f0c7}",
"fa-scissors" : "\u{f0c4}",
"fa-search" : "\u{f002}",
"fa-search-minus" : "\u{f010}",
"fa-search-plus" : "\u{f00e}",
"fa-sellsy" : "\u{f213}",
"fa-send" : "\u{f1d8}",
"fa-send-o" : "\u{f1d9}",
"fa-server" : "\u{f233}",
"fa-share" : "\u{f064}",
"fa-share-alt" : "\u{f1e0}",
"fa-share-alt-square" : "\u{f1e1}",
"fa-share-square" : "\u{f14d}",
"fa-share-square-o" : "\u{f045}",
"fa-shekel" : "\u{f20b}",
"fa-sheqel" : "\u{f20b}",
"fa-shield" : "\u{f132}",
"fa-ship" : "\u{f21a}",
"fa-shirtsinbulk" : "\u{f214}",
"fa-shopping-cart" : "\u{f07a}",
"fa-sign-in" : "\u{f090}",
"fa-sign-out" : "\u{f08b}",
"fa-signal" : "\u{f012}",
"fa-simplybuilt" : "\u{f215}",
"fa-sitemap" : "\u{f0e8}",
"fa-skyatlas" : "\u{f216}",
"fa-skype" : "\u{f17e}",
"fa-slack" : "\u{f198}",
"fa-sliders" : "\u{f1de}",
"fa-slideshare" : "\u{f1e7}",
"fa-smile-o" : "\u{f118}",
"fa-soccer-ball-o" : "\u{f1e3}",
"fa-sort" : "\u{f0dc}",
"fa-sort-alpha-asc" : "\u{f15d}",
"fa-sort-alpha-desc" : "\u{f15e}",
"fa-sort-amount-asc" : "\u{f160}",
"fa-sort-amount-desc" : "\u{f161}",
"fa-sort-asc" : "\u{f0de}",
"fa-sort-desc" : "\u{f0dd}",
"fa-sort-down" : "\u{f0dd}",
"fa-sort-numeric-asc" : "\u{f162}",
"fa-sort-numeric-desc" : "\u{f163}",
"fa-sort-up" : "\u{f0de}",
"fa-soundcloud" : "\u{f1be}",
"fa-space-shuttle" : "\u{f197}",
"fa-spinner" : "\u{f110}",
"fa-spoon" : "\u{f1b1}",
"fa-spotify" : "\u{f1bc}",
"fa-square" : "\u{f0c8}",
"fa-square-o" : "\u{f096}",
"fa-stack-exchange" : "\u{f18d}",
"fa-stack-overflow" : "\u{f16c}",
"fa-star" : "\u{f005}",
"fa-star-half" : "\u{f089}",
"fa-star-half-empty" : "\u{f123}",
"fa-star-half-full" : "\u{f123}",
"fa-star-half-o" : "\u{f123}",
"fa-star-o" : "\u{f006}",
"fa-steam" : "\u{f1b6}",
"fa-steam-square" : "\u{f1b7}",
"fa-step-backward" : "\u{f048}",
"fa-step-forward" : "\u{f051}",
"fa-stethoscope" : "\u{f0f1}",
"fa-sticky-note" : "\u{f249}",
"fa-sticky-note-o" : "\u{f24a}",
"fa-stop" : "\u{f04d}",
"fa-street-view" : "\u{f21d}",
"fa-strikethrough" : "\u{f0cc}",
"fa-stumbleupon" : "\u{f1a4}",
"fa-stumbleupon-circle" : "\u{f1a3}",
"fa-subscript" : "\u{f12c}",
"fa-subway" : "\u{f239}",
"fa-suitcase" : "\u{f0f2}",
"fa-sun-o" : "\u{f185}",
"fa-superscript" : "\u{f12b}",
"fa-support" : "\u{f1cd}",
"fa-table" : "\u{f0ce}",
"fa-tablet" : "\u{f10a}",
"fa-tachometer" : "\u{f0e4}",
"fa-tag" : "\u{f02b}",
"fa-tags" : "\u{f02c}",
"fa-tasks" : "\u{f0ae}",
"fa-taxi" : "\u{f1ba}",
"fa-television" : "\u{f26c}",
"fa-tencent-weibo" : "\u{f1d5}",
"fa-terminal" : "\u{f120}",
"fa-text-height" : "\u{f034}",
"fa-text-width" : "\u{f035}",
"fa-th" : "\u{f00a}",
"fa-th-large" : "\u{f009}",
"fa-th-list" : "\u{f00b}",
"fa-thumb-tack" : "\u{f08d}",
"fa-thumbs-down" : "\u{f165}",
"fa-thumbs-o-down" : "\u{f088}",
"fa-thumbs-o-up" : "\u{f087}",
"fa-thumbs-up" : "\u{f164}",
"fa-ticket" : "\u{f145}",
"fa-times" : "\u{f00d}",
"fa-times-circle" : "\u{f057}",
"fa-times-circle-o" : "\u{f05c}",
"fa-tint" : "\u{f043}",
"fa-toggle-down" : "\u{f150}",
"fa-toggle-left" : "\u{f191}",
"fa-toggle-off" : "\u{f204}",
"fa-toggle-on" : "\u{f205}",
"fa-toggle-right" : "\u{f152}",
"fa-toggle-up" : "\u{f151}",
"fa-trademark" : "\u{f25c}",
"fa-train" : "\u{f238}",
"fa-transgender" : "\u{f224}",
"fa-transgender-alt" : "\u{f225}",
"fa-trash" : "\u{f1f8}",
"fa-trash-o" : "\u{f014}",
"fa-tree" : "\u{f1bb}",
"fa-trello" : "\u{f181}",
"fa-tripadvisor" : "\u{f262}",
"fa-trophy" : "\u{f091}",
"fa-truck" : "\u{f0d1}",
"fa-try" : "\u{f195}",
"fa-tty" : "\u{f1e4}",
"fa-tumblr" : "\u{f173}",
"fa-tumblr-square" : "\u{f174}",
"fa-turkish-lira" : "\u{f195}",
"fa-tv" : "\u{f26c}",
"fa-twitch" : "\u{f1e8}",
"fa-twitter" : "\u{f099}",
"fa-twitter-square" : "\u{f081}",
"fa-umbrella" : "\u{f0e9}",
"fa-underline" : "\u{f0cd}",
"fa-undo" : "\u{f0e2}",
"fa-university" : "\u{f19c}",
"fa-unlink" : "\u{f127}",
"fa-unlock" : "\u{f09c}",
"fa-unlock-alt" : "\u{f13e}",
"fa-unsorted" : "\u{f0dc}",
"fa-upload" : "\u{f093}",
"fa-usd" : "\u{f155}",
"fa-user" : "\u{f007}",
"fa-user-md" : "\u{f0f0}",
"fa-user-plus" : "\u{f234}",
"fa-user-secret" : "\u{f21b}",
"fa-user-times" : "\u{f235}",
"fa-users" : "\u{f0c0}",
"fa-venus" : "\u{f221}",
"fa-venus-double" : "\u{f226}",
"fa-venus-mars" : "\u{f228}",
"fa-viacoin" : "\u{f237}",
"fa-video-camera" : "\u{f03d}",
"fa-vimeo" : "\u{f27d}",
"fa-vimeo-square" : "\u{f194}",
"fa-vine" : "\u{f1ca}",
"fa-vk" : "\u{f189}",
"fa-volume-down" : "\u{f027}",
"fa-volume-off" : "\u{f026}",
"fa-volume-up" : "\u{f028}",
"fa-warning" : "\u{f071}",
"fa-wechat" : "\u{f1d7}",
"fa-weibo" : "\u{f18a}",
"fa-weixin" : "\u{f1d7}",
"fa-whatsapp" : "\u{f232}",
"fa-wheelchair" : "\u{f193}",
"fa-wifi" : "\u{f1eb}",
"fa-wikipedia-w" : "\u{f266}",
"fa-windows" : "\u{f17a}",
"fa-won" : "\u{f159}",
"fa-wordpress" : "\u{f19a}",
"fa-wrench" : "\u{f0ad}",
"fa-xing" : "\u{f168}",
"fa-xing-square" : "\u{f169}",
"fa-y-combinator" : "\u{f23b}",
"fa-y-combinator-square" : "\u{f1d4}",
"fa-yahoo" : "\u{f19e}",
"fa-yc" : "\u{f23b}",
"fa-yc-square" : "\u{f1d4}",
"fa-yelp" : "\u{f1e9}",
"fa-yen" : "\u{f157}",
"fa-youtube" : "\u{f167}",
"fa-youtube-play" : "\u{f16a}",
"fa-youtube-square" : "\u{f166}",
]
if let raw = dict[code] {
if let icon = FontAwesome(rawValue: raw) {
return self.fontAwesomeIconWithName(icon)
}
}
return nil
}
}
|
mit
|
e33f1c4e5ced08844e8a4922cfed407f
| 39.780178 | 280 | 0.418489 | 2.864257 | false | false | false | false |
HJianBo/Mqtt
|
Sources/Mqtt/Packet/PubRelPacket.swift
|
1
|
1820
|
//
// PubrelPacket.swift
// Mqtt
//
// Created by Heee on 16/2/2.
// Copyright © 2016年 hjianbo.me. All rights reserved.
//
import Foundation
/**
A PUBREL Packet is the response to a PUBREC Packet. It is the third packet of the QoS 2 protocol exchange
**Fixed Header:**
1. Bits 3,2,1,and 0 of the fixed header in the PUBREL Control Packet are reserved and MUST be set
to 0,0,1,and 0 respectovely. The Server MUST treat any other value as malformed and close the
Network Connection.
2. *Remaining Length field:* This is the length of the variable header. For the PUBREL Packet
this has the value 2.
**Variable Header:**
The variable header contains the same Packet Identifier as the PUBREC Packet that is being
acknowledged.
**Payload:**
The PUBREL Packet has no payload.
*/
struct PubRelPacket: Packet {
/// flag is reserved, the value is 0010
var fixedHeader: FixedHeader
var packetId: UInt16
var varHeader: Array<UInt8> {
return packetId.bytes
}
var payload = [UInt8]()
init(packetId: UInt16) {
fixedHeader = FixedHeader(type: .pubrel)
// set flag to 0010
fixedHeader.qos = .qos1
self.packetId = packetId
}
}
extension PubRelPacket: InitializeWithResponse {
init(header: FixedHeader, bytes: [UInt8]) throws {
guard header.type == .pubrel else {
throw PacketError.typeIllegal
}
guard bytes.count == 2 else {
throw PacketError.byteCountIllegal
}
fixedHeader = header
packetId = UInt16(bytes[0])*256+UInt16(bytes[1])
}
}
extension PubRelPacket {
public var description: String {
return "PubRel(packetId: \(packetId))"
}
}
|
mit
|
cb774f2e34e7c841a9f47ed852d01ad1
| 24.236111 | 106 | 0.629609 | 4.046771 | false | false | false | false |
ivankorobkov/net
|
swift/Netx/RpcClient.swift
|
2
|
9790
|
//
// RpcClient.swift
// Netx
//
// Created by Ivan Korobkov on 27/04/16.
// Copyright © 2016 Ivan Korobkov. All rights reserved.
//
import Foundation
public protocol RpcClientDelegate: class {
func clientWillConnect(client: RpcClient)
func clientDidConnect(client: RpcClient)
func clientDidDisconnect(client: RpcClient, error: ErrorType?)
}
public typealias RpcClientCallback = (RpcResponse?, ErrorType?) -> Void
public class RpcClient: MuxConnDelegate {
public let logger: Logger
private let queue: dispatch_queue_t
private let address: Address
private weak var delegate: RpcClientDelegate?
private var conn: MuxConn?
private var connected: Bool
private var connectCallbacks: [(MuxConn?, ErrorType?) -> Void]
public convenience init(address: Address) {
self.init(address: address, delegate: nil)
}
public init(address: Address, delegate: RpcClientDelegate?) {
self.logger = NewLogger("Netx.RpcClient")
self.queue = dispatch_queue_create("com.github.ivankorobkov.netx.RpcClient", DISPATCH_QUEUE_SERIAL)
self.address = address
self.delegate = delegate
self.conn = nil
self.connected = false
self.connectCallbacks = []
}
// Connecting
public func connect() {
self.connect{ (_, _) in }
}
public func connect(callback: (MuxConn?, ErrorType?) -> Void) {
dispatch_async(self.queue) {
// Execute the callback if already connected.
// Otherwise, save it.
guard !self.connected else {
callback(self.conn!, nil)
return
}
self.connectCallbacks.append(callback)
// Return if already connecting.
guard self.conn == nil else {
return
}
// Connect.
self.logger.debug("Will connect to \(self.address)")
self.delegate?.clientWillConnect(self)
let conn = Connect(self.address)
guard conn != nil else {
self.didDisconnect(IOError.ConnRefused)
return
}
self.conn = NewMuxConn(conn!, server: false, delegate: self)
}
}
public func disconnect() {
dispatch_async(self.queue) {
guard let conn = self.conn else {
return
}
conn.close()
}
}
private func didConnect() {
self.logger.info("Did connect to \(self.address), conn=\(self.conn!)")
self.connected = true
for callback in self.connectCallbacks {
callback(self.conn, nil)
}
self.connectCallbacks.removeAll()
self.delegate?.clientDidConnect(self)
}
private func didDisconnect(error: ErrorType) {
self.logger.info("Did disconnect from address=\(self.address), error=\(error)")
self.conn = nil
self.connected = false
for callback in self.connectCallbacks {
callback(nil, error)
}
self.connectCallbacks.removeAll()
self.delegate?.clientDidDisconnect(self, error: error)
}
// MuxConnDelegate
public func muxConnDidConnect(conn: MuxConn) {
dispatch_async(self.queue) {
self.didConnect()
}
}
public func muxConnDidDisconnect(conn: MuxConn, error: ErrorType?) {
dispatch_async(self.queue) {
self.didDisconnect(error ?? IOError.ConnRefused)
}
}
// Calling
public func call(request: RpcRequest, callback: RpcClientCallback) -> Closer {
// Guarded by the queue.
var closed = false
var stream: MuxStream? = nil
let method = request.method
self.logger.info("'\(method)' request=\(request)")
// Get a connection.
self.connect{ (conn0, error) in
dispatch_async(self.queue, {
guard !closed else {
return
}
guard error == nil else {
self.logger.debug("\(method) failed to get a connection, error=\(error)")
callback(nil, error)
return
}
guard let conn = conn0 else {
self.logger.debug("\(method) failed to get a connection")
callback(nil, IOError.ConnRefused)
return
}
// Open a new stream.
conn.connect { (stream0, error) in
dispatch_async(self.queue) {
guard !closed else {
return
}
guard error == nil else {
self.logger.debug("'\(method)' failed to get a stream, error=\(error)")
callback(nil, error)
return
}
guard stream0 != nil else {
self.logger.debug("'\(method)' failed to get a stream")
callback(nil, IOError.ConnRefused)
return
}
stream = stream0
self.logger.debug("'\(method)' opened a stream")
// Write a request.
request.write(stream!) { error in
dispatch_async(self.queue) {
guard !closed else {
return
}
guard error == nil else {
self.logger.debug("'\(method)' request failed, error=\(error)")
stream!.close()
callback(nil, error)
return
}
// Read a response.
self.logger.debug("'\(method)' sent a request")
RpcResponse.read(stream!) { (response0, error) in
dispatch_async(self.queue) {
guard !closed else {
return
}
guard error == nil else {
self.logger.debug("'\(method)' response failed, error=\(error)")
stream!.close()
callback(nil, error)
return
}
guard let response = response0 else {
let error = RpcError.Error(status: RpcStatus.RpcNoResponse, text: "No response")
self.logger.debug("'\(method)' response failed, error=\(error)")
stream!.close()
callback(nil, error)
return
}
// It's OK to close the stream if no body.
if response.bodyLen == 0 {
stream!.close()
}
// Handle the response.
self.logger.info("'\(method)' response=\(response)")
switch response.status {
case RpcStatus.RpcError:
callback(nil, RpcError.Error(status: response.status, text: ""))
case RpcStatus.InternalError:
callback(nil, RpcError.InternalError)
case RpcStatus.RpcNoResponse:
callback(nil, RpcError.NoResponse)
case RpcStatus.RpcInvalidArgs:
callback(nil, RpcError.InvalidArgs)
case RpcStatus.RpcMethodNotFound:
callback(nil, RpcError.MethodNotFound)
default:
callback(response, nil)
}
}
}
}
}
}
}
})
}
return AnonymousCloser{
dispatch_async(self.queue) {
closed = true;
stream?.close();
self.logger.debug("'\(method)' cancelled")
}
}
}
}
|
apache-2.0
|
1dd5d249b02e85391363858ab8243324
| 37.089494 | 124 | 0.406987 | 6.275 | false | false | false | false |
loudnate/Loop
|
Loop/Extensions/NightscoutUploader.swift
|
1
|
3025
|
//
// NightscoutUploader.swift
// Loop
//
// Copyright © 2017 LoopKit Authors. All rights reserved.
//
import LoopKit
import NightscoutUploadKit
extension NightscoutUploader: CarbStoreSyncDelegate {
static let logger = DiagnosticLogger.shared.forCategory("NightscoutUploader")
public func carbStore(_ carbStore: CarbStore, hasEntriesNeedingUpload entries: [StoredCarbEntry], completion: @escaping ([StoredCarbEntry]) -> Void) {
var created = [StoredCarbEntry]()
var modified = [StoredCarbEntry]()
for entry in entries {
if entry.externalID != nil {
modified.append(entry)
} else {
created.append(entry)
}
}
upload(created.map { MealBolusNightscoutTreatment(carbEntry: $0) }) { (result) in
switch result {
case .success(let ids):
for (index, id) in ids.enumerated() {
created[index].externalID = id
created[index].isUploaded = true
}
completion(created)
case .failure(let error):
NightscoutUploader.logger.error(error)
completion(created)
}
}
modifyTreatments(modified.map { MealBolusNightscoutTreatment(carbEntry: $0) }) { (error) in
if let error = error {
NightscoutUploader.logger.error(error)
} else {
for index in modified.startIndex..<modified.endIndex {
modified[index].isUploaded = true
}
}
completion(modified)
}
}
public func carbStore(_ carbStore: CarbStore, hasDeletedEntries entries: [DeletedCarbEntry], completion: @escaping ([DeletedCarbEntry]) -> Void) {
var deleted = entries
deleteTreatmentsById(deleted.map { $0.externalID }) { (error) in
if let error = error {
NightscoutUploader.logger.error(error)
} else {
for index in deleted.startIndex..<deleted.endIndex {
deleted[index].isUploaded = true
}
}
completion(deleted)
}
}
}
extension NightscoutUploader {
func upload(_ events: [PersistedPumpEvent], fromSource source: String, completion: @escaping (NightscoutUploadKit.Either<[URL], Error>) -> Void) {
var objectIDURLs = [URL]()
var treatments = [NightscoutTreatment]()
for event in events {
objectIDURLs.append(event.objectIDURL)
guard let treatment = event.treatment(enteredBy: source) else {
continue
}
treatments.append(treatment)
}
self.upload(treatments) { (result) in
switch result {
case .success( _):
completion(.success(objectIDURLs))
case .failure(let error):
completion(.failure(error))
}
}
}
}
|
apache-2.0
|
3347d3e31dd228427edfc3b2908bb092
| 30.175258 | 154 | 0.561508 | 5.04 | false | false | false | false |
starboychina/WechatKit
|
WechatKit/WechatRoute.swift
|
1
|
6247
|
//
// WechatRoute.swift
// WechatKit
//
// Created by starboychina on 2015/12/03.
// Copyright © 2015年 starboychina. All rights reserved.
//
enum WechatRoute {
static let baseURLString = "https://api.weixin.qq.com/sns"
case userinfo
case accessToken(String)
case refreshToken
case checkToken
var path: String {
switch self {
case .userinfo:
return "/userinfo"
case .accessToken:
return "/oauth2/access_token"
case .refreshToken:
return "/oauth2/refresh_token"
case .checkToken:
return "/auth"
}
}
var parameters: [String: String] {
switch self {
case .userinfo:
return [
"openid": WechatManager.shared.openid ?? "",
"access_token": WechatManager.shared.accessToken ?? ""
]
case .accessToken(let code):
return [
"appid": WechatManager.appid,
"secret": WechatManager.appSecret,
"code": code,
"grant_type": "authorization_code"
]
case .refreshToken:
return [
"appid": WechatManager.appid,
"refresh_token": WechatManager.shared.refreshToken ?? "",
"grant_type": "refresh_token"
]
case .checkToken:
return [
"openid": WechatManager.shared.openid ?? "",
"access_token": WechatManager.shared.accessToken ?? ""
]
}
}
// MARK: URLRequestConvertible
var request: URLRequest {
var url = URL(string: WechatRoute.baseURLString)!
url.appendPathComponent(path)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "GET"
urlRequest.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
if var urlComponents = URLComponents(url: url,
resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "")
+ query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
return urlRequest
}
/// Creates percent-escaped, URL encoded query string components
/// from the given key-value pair using recursion.
///
/// - parameter key: The key of the query component.
/// - parameter value: The value of the query component.
///
/// - returns: The percent-escaped, URL encoded query string components.
private func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: Any] {
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
} else if let array = value as? [Any] {
for value in array {
components += queryComponents(fromKey: "\(key)[]", value: value)
}
} else if let bool = value as? Bool {
components.append((escape(key), escape((bool ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// RFC 3986 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// In RFC 3986 - Section 3.4, it states that
/// the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore,
/// all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
private func escape(_ string: String) -> String {
// does not include "?" or "/" due to RFC 3986 - Section 3.4
let generalDelimitersToEncode = ":#[]@"
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
let characters = "\(generalDelimitersToEncode)\(subDelimitersToEncode)"
allowedCharacterSet.remove(charactersIn: characters)
return string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
}
private func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
}
class AlamofireController {
private static let session = URLSession.shared
class func request(_ route: WechatRoute,
completion: @escaping (_ result: [String: Any] ) -> Void ) {
let task = session.dataTask(with: route.request) { (data, response, error) in
guard error == nil else { return }
guard response is HTTPURLResponse else {
WechatManager.shared.completionHandler?(.failure(Int32(400)))
return
}
guard let validData = data, !validData.isEmpty else {
WechatManager.shared.completionHandler?(.failure(Int32(204)))
return
}
let jsonObject = try? JSONSerialization.jsonObject(with: validData,
options: .allowFragments)
guard let json = jsonObject as? [String: Any] else {
WechatManager.shared.completionHandler?(.failure(Int32(500)))
return
}
completion(json)
}
task.resume()
}
}
|
mit
|
c65fea39bdf53f94b94b8b21d08de4c6
| 34.276836 | 99 | 0.557655 | 5.039548 | false | false | false | false |
asp2insp/Twittercism
|
Twittercism/TweetView.swift
|
1
|
5191
|
//
// TweetCell.swift
// Twittercism
//
// Created by Josiah Gaskin on 5/18/15.
// Copyright (c) 2015 Josiah Gaskin. All rights reserved.
//
import Foundation
import UIKit
class TweetView : UITableViewCell {
@IBOutlet weak var timestamp: UILabel!
@IBOutlet weak var sourceIcon: UIImageView!
@IBOutlet weak var sourceText: UILabel!
@IBOutlet weak var localizedName: UILabel!
@IBOutlet weak var handleLabel: UILabel!
@IBOutlet weak var profilePic: UIButton!
@IBOutlet weak var tweetContent: UILabel!
@IBOutlet weak var starButton: UIButton!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var replyButton: UIButton!
@IBOutlet weak var retweetHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var retweetCountLabel: UILabel!
@IBOutlet weak var favoriteCountLabel: UILabel!
let reactor = TwitterApi.sharedInstance.reactor
let star = UIImage(named: "star.png")!
let star_yellow = UIImage(named: "star_yellow.png")!
let retweet = UIImage(named: "retweet.png")!
let retweet_green = UIImage(named: "retweet_green.png")!
var tweetIdString : String!
var replyName : String!
var tweet : Immutable.State = Immutable.State.None {
didSet {
var contentTweet : Immutable.State = tweet
if let favorited = tweet.getIn(["favorited"]).toSwift() as? Bool where favorited {
starButton.setImage(star_yellow, forState: UIControlState.Normal)
} else {
starButton.setImage(star, forState: UIControlState.Normal)
}
if let retweeted = tweet.getIn(["retweeted"]).toSwift() as? Bool where retweeted {
retweetButton.setImage(retweet_green, forState: UIControlState.Normal)
} else {
retweetButton.setImage(retweet, forState: UIControlState.Normal)
}
if tweet.containsKey("retweeted_status") {
retweetHeightConstraint.constant = 24
sourceText.hidden = false
let retweetAuthor = tweet.getIn(["user", "name"]).toSwift() as? String ?? "Unknown"
sourceText.text = "\(retweetAuthor) retweeted"
contentTweet = tweet.getIn(["retweeted_status"])
} else {
retweetHeightConstraint.constant = 0
sourceText.hidden = true
}
tweetContent.text = contentTweet.getIn(["text"]).toSwift() as? String ?? "Lorem Ipsum dolor sit amet..."
let authorHandle = contentTweet.getIn(["user", "screen_name"]).toSwift() as? String ?? "Unknown"
handleLabel.text = "@\(authorHandle)"
let authorName = contentTweet.getIn(["user", "name"]).toSwift() as? String ?? "Unknown"
localizedName.text = authorName
if let profileUrl = contentTweet.getIn(["user", "profile_image_url"]).toSwift() as? String {
let largerUrl = profileUrl.stringByReplacingOccurrencesOfString("normal", withString: "bigger")
profilePic.setBackgroundImageForState(UIControlState.Normal, withURL: NSURL(string: largerUrl))
profilePic.layer.cornerRadius = 10;
profilePic.clipsToBounds = true;
}
if let retweetCount = contentTweet.getIn(["retweet_count"]).toSwift() as? Int where retweetCount > 0 {
retweetCountLabel.text = "\(retweetCount)"
} else {
retweetCountLabel.text = ""
}
if let favoriteCount = contentTweet.getIn(["favorite_count"]).toSwift() as? Int where favoriteCount > 0 {
favoriteCountLabel.text = "\(favoriteCount)"
} else {
favoriteCountLabel.text = ""
}
timestamp.text = formatTime(contentTweet.getIn(["created_at"]).toSwift() as! String)
tweetIdString = contentTweet.getIn(["id_str"]).toSwift() as! String
replyName = contentTweet.getIn(["user", "screen_name"]).toSwift() as! String
}
}
func formatTime(timestamp: String) -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "EEE MMM dd HH:mm:ss +0000 yyyy"
let date = formatter.dateFromString(timestamp)
let seconds = abs(NSDate().timeIntervalSinceDate(date!))
if seconds > 86400 {
formatter.dateFormat = "MMM dd"
return formatter.stringFromDate(date!)
} else {
return "\(Int(round(seconds/3600)))h"
}
}
@IBAction func doAction(sender: UIButton) {
switch sender {
case starButton:
reactor.dispatch("toggleFavoriteTweet", payload: tweetIdString)
case retweetButton:
reactor.dispatch("retweet", payload: tweetIdString)
case replyButton:
reactor.dispatch("setReply", payload: replyName)
case profilePic:
reactor.dispatch("setTimelineUser", payload: replyName)
default:
NSLog("Unknown Sender")
}
}
}
|
mit
|
5550b80de0adae98790d0ae7abc67b3b
| 41.211382 | 117 | 0.602774 | 5.030039 | false | false | false | false |
scottkawai/sendgrid-swift
|
Sources/SendGrid/API/V3/Mail/Send/Settings/Mail/Footer.swift
|
1
|
1533
|
import Foundation
/// The `Footer` mail setting allows you to specify a footer that will be
/// appended to the bottom of every email.
public struct Footer: Encodable {
// MARK: - Properties
/// The plain text content of your footer.
public let text: String?
/// The HTML content of your footer.
public let html: String?
/// A `Bool` indicating if the setting is enabled or not.
public let enable: Bool
// MARK: - Initialization
/// Initializes the setting with plain text and HTML to use in the footer.
/// This will enable the setting for this email and use the provided
/// content.
///
/// If the footer setting is enabled by default on your SendGrid account and
/// you want to disable it for this email, use the `init()` initializer
/// instead.
///
/// - Parameters:
/// - text: The plain text content of your footer.
/// - html: The HTML content of your footer.
public init(text: String, html: String) {
self.text = text
self.html = html
self.enable = true
}
/// Initializes the setting with no templates, indicating that the footer
/// setting should be disabled for this particular email (assuming it's
/// normally enabled on the SendGrid account).
///
/// If you want to enable the footer setting, use the `init(text:html:)`
/// initializer instead.
public init() {
self.text = nil
self.html = nil
self.enable = false
}
}
|
mit
|
e9e8dacc92f9c2f3f8f0986988c212da
| 31.617021 | 80 | 0.626223 | 4.603604 | false | false | false | false |
icylydia/PlayWithLeetCode
|
476. Number Complement/Solution.swift
|
1
|
203
|
class Solution {
func findComplement(_ num: Int) -> Int {
var flip = ~num
var index = 63
while (flip & (1 << index)) != 0 {
flip &= ~(1 << index)
index -= 1
}
return flip
}
}
|
mit
|
d7c48bffa8bbe839ac136d8def59ed3d
| 17.545455 | 44 | 0.502463 | 3.075758 | false | false | false | false |
i-schuetz/SwiftCharts
|
SwiftCharts/Layers/ChartCoordsSpaceLayer.swift
|
1
|
4324
|
//
// ChartCoordsSpaceLayer.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartCoordsSpaceLayer: ChartLayerBase {
public let xAxis: ChartAxis
public let yAxis: ChartAxis
public init(xAxis: ChartAxis, yAxis: ChartAxis) {
self.xAxis = xAxis
self.yAxis = yAxis
}
open func modelLocToScreenLoc(x: Double, y: Double) -> CGPoint {
return CGPoint(x: modelLocToScreenLoc(x: x), y: modelLocToScreenLoc(y: y))
}
open func modelLocToScreenLoc(x: Double) -> CGFloat {
return xAxis.innerScreenLocForScalar(x) / (chart?.contentView.transform.a ?? 1)
}
open func modelLocToScreenLoc(y: Double) -> CGFloat {
return yAxis.innerScreenLocForScalar(y) / (chart?.contentView.transform.d ?? 1)
}
open func modelLocToContainerScreenLoc(x: Double, y: Double) -> CGPoint {
return CGPoint(x: modelLocToContainerScreenLoc(x: x), y: modelLocToContainerScreenLoc(y: y))
}
open func modelLocToContainerScreenLoc(x: Double) -> CGFloat {
return xAxis.screenLocForScalar(x) - (chart?.containerFrame.origin.x ?? 0)
}
open func modelLocToContainerScreenLoc(y: Double) -> CGFloat {
return yAxis.screenLocForScalar(y) - (chart?.containerFrame.origin.y ?? 0)
}
open func modelLocToGlobalScreenLoc(x: Double, y: Double) -> CGPoint {
return CGPoint(x: modelLocToGlobalScreenLoc(x: x), y: modelLocToGlobalScreenLoc(y: y))
}
open func modelLocToGlobalScreenLoc(x: Double) -> CGFloat {
return xAxis.screenLocForScalar(x)
}
open func modelLocToGlobalScreenLoc(y: Double) -> CGFloat {
return yAxis.screenLocForScalar(y)
}
open func scalarForScreenLoc(x: CGFloat) -> Double {
return xAxis.innerScalarForScreenLoc(x * (chart?.contentView.transform.a ?? 1))
}
open func scalarForScreenLoc(y: CGFloat) -> Double {
return yAxis.innerScalarForScreenLoc(y * (chart?.contentView.transform.d ?? 1))
}
open func globalToDrawersContainerCoordinates(_ point: CGPoint) -> CGPoint? {
return globalToContainerCoordinates(point)
}
open func globalToContainerCoordinates(_ point: CGPoint) -> CGPoint? {
guard let chart = chart else {return nil}
return point.substract(chart.containerView.frame.origin)
}
open func globalToContentCoordinates(_ point: CGPoint) -> CGPoint? {
guard let chart = chart else {return nil}
guard let containerCoords = globalToContainerCoordinates(point) else {return nil}
return CGPoint(
x: (containerCoords.x - chart.contentView.frame.origin.x) / chart.contentView.transform.a,
y: (containerCoords.y - chart.contentView.frame.origin.y) / chart.contentView.transform.d
)
}
open func containerToGlobalCoordinates(_ point: CGPoint) -> CGPoint? {
guard let chart = chart else {return nil}
return point.add(chart.containerView.frame.origin)
}
open func contentToContainerCoordinates(_ point: CGPoint) -> CGPoint? {
guard let chart = chart else {return nil}
let containerX = (point.x * chart.contentView.transform.a) + chart.contentView.frame.minX
let containerY = (point.y * chart.contentView.transform.d) + chart.contentView.frame.minY
return CGPoint(x: containerX, y: containerY)
}
open func contentToGlobalCoordinates(_ point: CGPoint) -> CGPoint? {
return contentToContainerCoordinates(point).flatMap{containerToGlobalCoordinates($0)}
}
// TODO review method, variable names
open func contentToGlobalScreenLoc(_ chartPoint: ChartPoint) -> CGPoint? {
let containerScreenLoc = CGPoint(x: modelLocToScreenLoc(x: chartPoint.x.scalar), y: modelLocToScreenLoc(y: chartPoint.y.scalar))
return containerToGlobalCoordinates(containerScreenLoc)
}
open func containerToGlobalScreenLoc(_ chartPoint: ChartPoint) -> CGPoint? {
let containerScreenLoc = CGPoint(x: modelLocToContainerScreenLoc(x: chartPoint.x.scalar), y: modelLocToContainerScreenLoc(y: chartPoint.y.scalar))
return containerToGlobalCoordinates(containerScreenLoc)
}
}
|
apache-2.0
|
59506d7e3e410f8e13972c9e480ec0d5
| 38.669725 | 154 | 0.682701 | 4.251721 | false | false | false | false |
the-grid/Disc
|
Disc/Networking/Helpers/StringParser.swift
|
1
|
602
|
import Result
import Swish
struct StringParser: Parser {
typealias Representation = String
static func parse(_ j: AnyObject) -> Result<String, SwishError> {
guard let data = j as? NSData else {
let error = NSError.error("Bad data!")
return .failure(.urlSessionError(error))
}
guard let string = String(data: data as Data, encoding: String.Encoding.utf8) else {
let error = NSError.error("Couldn't NSData convert to string!")
return .failure(.urlSessionError(error))
}
return .success(string)
}
}
|
mit
|
cb3c504d6d72e311df660379ec04a055
| 32.444444 | 92 | 0.61794 | 4.526316 | false | false | false | false |
tiagomnh/LicensingViewController
|
LicensingViewController/LicensingItemCell.swift
|
1
|
2086
|
//
// LicensingItemCell.swift
// LicensingViewController
//
// Created by Tiago Henriques on 15/07/15.
// Copyright (c) 2015 Tiago Henriques. All rights reserved.
//
import UIKit
class LicensingItemCell: UITableViewCell {
// MARK: - Constants
let spacing = 15
// MARK: - Properties
let titleLabel = UILabel()
let noticeLabel = UILabel()
// MARK: - Lifecycle
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
titleLabel.text = ""
noticeLabel.text = ""
}
// MARK: - Views
func setupSubviews() {
titleLabel.numberOfLines = 0
titleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(titleLabel)
noticeLabel.numberOfLines = 0
noticeLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(noticeLabel)
setupConstraints()
}
func setupConstraints() {
let views = [
"titleLabel": titleLabel,
"noticeLabel": noticeLabel
]
let metrics = [
"spacing": spacing
]
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-spacing-[titleLabel]-spacing-|",
options: [],
metrics: metrics,
views: views
))
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-spacing-[titleLabel]-[noticeLabel]-spacing-|",
options: [],
metrics: metrics,
views: views
))
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-spacing-[noticeLabel]-spacing-|",
options: [],
metrics: metrics,
views: views
))
}
}
|
mit
|
506fcbf38093712e7990e48a2d20c4ca
| 22.704545 | 135 | 0.610738 | 5.460733 | false | false | false | false |
e-how/kingTrader
|
kingTrader/kingTrader/Common/swift.swift
|
1
|
688
|
//
// swift.swift
// kingTrader
//
// Created by kt on 15/10/16.
// Copyright © 2015年 张益豪. All rights reserved.
// 连接jwt 加密类库
import Foundation
import JWT
class JWTEncodeTests : NSObject {
func testEncodingJWT(str:AnyObject)->String {
// print("----",str["test"])
// let payload = ["name": "zhangyihao123","id":str,"exp":str] as Payload
let payload = ["name": "zhangyihao123","id":str,"exp":str] as Payload
let dic:Dictionary<String,String> = ["name":"123"]
print("payload=",dic);
let jwt = JWT.encode(dic, algorithm: .HS256("weisd"))
print(jwt)
return jwt
}
}
|
apache-2.0
|
9bc46f529be59c6bf4d45297ab200c42
| 22.857143 | 79 | 0.571214 | 3.351759 | false | true | false | false |
tempestrock/CarPlayer
|
CarPlayer/ModalViewController.swift
|
1
|
2910
|
//
// ModalViewController.swift
// CarPlayer
//
// Created by Peter Störmer on 22.12.14.
// Copyright (c) 2014 Tempest Rock Studios. All rights reserved.
//
import Foundation
import UIKit
//
// Some basics for a modal view.
//
class ModalViewController: UIViewController {
// Dimensions:
var widthOfView: Int {
get {
return MyBasics.screenWidth * 90 / 100
}
}
var heightOfView: Int {
get {
return MyBasics.screenHeight * 90 / 100
}
}
var xPosOfView: Int {
get {
return (MyBasics.screenWidth - widthOfView) / 2
}
}
var yPosOfView: Int {
get {
return (MyBasics.screenHeight - heightOfView) / 2
}
}
//
// Paint the basic stuff, i.e. the black opaque box and an underlying close button.
//
override func viewDidLoad() {
super.viewDidLoad()
paintBasics(view)
}
//
// Paints a "close" button and the underlying black rectangle.
//
func paintBasics(view: UIView) {
// Create an underlying button that closes the view without further action:
let closeButton = UIButton(type: UIButtonType.Custom)
closeButton.frame = CGRectMake(0.0, 0.0, CGFloat(MyBasics.screenWidth), CGFloat(MyBasics.screenHeight))
closeButton.addTarget(self, action: #selector(ModalViewController.closeViewWithoutAction), forControlEvents: .TouchUpInside)
view.addSubview(closeButton)
// Create white, opaque background rectangle:
let imageSize = CGSize(width: widthOfView, height: heightOfView)
let image = drawBlackOpaqueBox(imageSize)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: xPosOfView, y: yPosOfView), size: imageSize))
imageView.image = image
view.addSubview(imageView)
}
//
// Draws the black but slightly opaque box as the background.
//
func drawBlackOpaqueBox(size: CGSize) -> UIImage {
// Setup our context
let bounds = CGRect(origin: CGPoint.zero, size: size)
let opaque = false
let scale: CGFloat = 0
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
let context = UIGraphicsGetCurrentContext()
// Setup complete, do drawing here
CGContextSetLineWidth(context, 0.0)
CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
CGContextSetAlpha(context, 0.8)
CGContextFillRect(context, bounds)
// Drawing complete, retrieve the finished image and cleanup
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
//
// Closes the view without any further action.
//
func closeViewWithoutAction() {
dismissViewControllerAnimated(true, completion: nil)
}
}
|
gpl-3.0
|
6172e0c5bd59f59ca4e26dd5e25d5265
| 25.944444 | 132 | 0.640083 | 4.808264 | false | false | false | false |
lumoslabs/realm-cocoa
|
examples/ios/swift-2.0/Backlink/AppDelegate.swift
|
6
|
2179
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import UIKit
import RealmSwift
class Dog: Object {
dynamic var name = ""
dynamic var age = 0
var owners: [Person] {
// Realm doesn't persist this property because it only has a getter defined
// Define "owners" as the inverse relationship to Person.dogs
return linkingObjects(Person.self, forProperty: "dogs")
}
}
class Person: Object {
dynamic var name = ""
let dogs = List<Dog>()
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
try! NSFileManager.defaultManager().removeItemAtPath(Realm.defaultPath)
let realm = try! Realm()
realm.write {
realm.create(Person.self, value: ["John", [["Fido", 1]]])
realm.create(Person.self, value: ["Mary", [["Rex", 2]]])
}
// Log all dogs and their owners using the "owners" inverse relationship
let allDogs = realm.objects(Dog)
for dog in allDogs {
let ownerNames = dog.owners.map { $0.name }
print("\(dog.name) has \(ownerNames.count) owners (\(ownerNames))")
}
return true
}
}
|
apache-2.0
|
01eb648cdfc12b417c6b824e55f3df83
| 33.046875 | 128 | 0.619091 | 4.789011 | false | false | false | false |
iWeslie/Ant
|
Ant/Ant/LunTan/JobSearch/View/JobSearchInfoView.swift
|
2
|
6503
|
//
// JobSearchInfoView.swift
// Ant
//
// Created by LiuXinQiang on 2017/8/1.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
fileprivate let cellID = "cellID"
class JobSearchInfoView: UITableView,UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate {
var tableView = UITableView()
var textField : UITextField?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
tableView = self
tableView.delegate = self
tableView.dataSource = self
tableView.showsHorizontalScrollIndicator = false
tableView.showsVerticalScrollIndicator = false
tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var row : Int = 0
switch section {
case 0:
row = 1
case 1:
row = 7
case 2:
row = 6
default:
row = 0
}
return row
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.init(red: 247 / 255, green: 247 / 255, blue: 247 / 255, alpha: 1.0)
let titleLabel = UILabel()
titleLabel.text = "联系人方式"
titleLabel.textColor = UIColor.lightGray
titleLabel.sizeToFit()
titleLabel.center.y = 20
titleLabel.frame.origin.x = 20
headerView.addSubview(titleLabel)
switch section {
case 0:
titleLabel.text = "消息标题"
case 1:
titleLabel.text = "基本信息"
case 2:
titleLabel.text = "联系人方式"
default:
titleLabel.text = ""
}
return headerView
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
var view = UIView.init()
switch section {
case 1:
let detailView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 180))
detailView.backgroundColor = UIColor.white
let detailScriptLable = UILabel.init(frame: CGRect.init(x: 15, y: 10, width: 100, height: 20))
detailScriptLable.text = "详尽描述"
detailView.addSubview(detailScriptLable)
let detailDescriptFiled = CustomTextField.init(frame: CGRect.init(x: 10, y: 30, width: screenWidth - 20 , height: 140), placeholder: "字数在150字以内", clear: true, leftView: nil, fontSize: 12)
detailDescriptFiled?.backgroundColor = UIColor.init(red: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1.0)
self.textField = detailDescriptFiled
detailView.addSubview(detailDescriptFiled!)
view = detailView
default:
break
}
return view
}
override func touchesShouldBegin(_ touches: Set<UITouch>, with event: UIEvent?, in view: UIView) -> Bool {
self.endEditing(true)
return true
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
var heightForFooterInSection = 0.0
switch section {
case 1:
heightForFooterInSection = 180
// case 2:
// heightForFooterInSection = 100
default:
heightForFooterInSection = 0.0
}
return CGFloat(heightForFooterInSection)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
if cell == nil {
cell = UITableViewCell.init(style: .default, reuseIdentifier: cellID)
}
cell?.accessoryType = .disclosureIndicator
if indexPath.section == 0 {
cell?.textLabel?.text = "标题"
}else if indexPath.section == 1 {
switch indexPath.row {
case 0:
cell?.textLabel?.text = "所在区域"
case 1:
cell?.textLabel?.text = "行业"
case 2:
cell?.textLabel?.text = "工作性质"
case 3:
cell?.textLabel?.text = "学历"
case 4:
cell?.textLabel?.text = "签证"
case 5:
cell?.textLabel?.text = "经验"
case 6:
cell?.textLabel?.text = "期望工资"
default:
cell?.textLabel?.text = ""
}
}else if indexPath.section == 2 {
switch indexPath.row {
case 0:
cell?.textLabel?.text = "联系人名称"
cell?.detailTextLabel?.text = "asdasds"
case 1:
cell?.textLabel?.text = "联系电话"
case 2:
cell?.textLabel?.text = "微信"
case 3:
cell?.textLabel?.text = "QQ"
case 4:
cell?.textLabel?.text = "邮箱"
default:
cell?.textLabel?.text = ""
}
}
return cell!
}
}
|
apache-2.0
|
97f22d66288132c8e9ae8b5bdc8d98aa
| 34.021978 | 204 | 0.486508 | 5.457192 | false | false | false | false |
SASAbus/SASAbus-ios
|
SASAbus/Util/Watch/WatchConnection.swift
|
1
|
2817
|
//
// WatchConnection.swift
// SASAbus
//
// Created by Alex Lardschneider on 28/09/2017.
// Copyright © 2017 SASA AG. All rights reserved.
//
import Foundation
import WatchConnectivity
class WatchConnection: NSObject, WCSessionDelegate {
var appDelegate: AppDelegate!
var session: WCSession!
public static var standard = WatchConnection()
override init() {
super.init()
}
func connect(delegate: AppDelegate) {
if WCSession.isSupported() {
Log.warning("WatchKit Session is available")
self.appDelegate = delegate
session = WCSession.default()
session.delegate = self
session.activate()
} else {
Log.warning("WatchKit Session is not available")
}
}
}
extension WatchConnection {
func sessionDidBecomeInactive(_ session: WCSession) {
Log.warning("WatchKit Session sessionDidBecomeInactive()")
}
func sessionDidDeactivate(_ session: WCSession) {
Log.warning("WatchKit Session sessionDidDeactivate()")
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
Log.warning("WatchKit Session activationDidCompleteWith()")
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
Log.warning("WatchKit Session received message: \(message)")
guard let type = message["type"] as? String else {
Log.error("WatchKit Session message type is not of type 'String'")
return
}
guard let messageType = WatchMessage(rawValue: type) else {
Log.error("WatchKit Session unknown message type: '\(type)'")
return
}
switch messageType{
case .recentBusStops:
UserRealmHelper.getRecentDepartures(replyHandler: replyHandler)
case .favoriteBusStops:
UserRealmHelper.getFavoriteBusStopsForWatch(replyHandler: replyHandler)
case .calculateDepartures:
let busStopGroup = message["bus_stop_group"] as! Int
DepartureMonitor.calculateForWatch(busStopGroup, replyHandler: replyHandler)
case .setBusStopFavorite:
let busStop = message["bus_stop"] as! Int
let isFavorite = message["is_favorite"] as! Bool
if isFavorite {
UserRealmHelper.addFavoriteBusStop(group: busStop)
} else {
UserRealmHelper.removeFavoriteBusStop(group: busStop)
}
replyHandler([:])
default:
break
}
}
}
|
gpl-3.0
|
d0c2959147d8a982c576e72b459ddb1b
| 29.945055 | 133 | 0.607244 | 5.243948 | false | false | false | false |
DianQK/rx-sample-code
|
Stopwatch/BasicViewModel.swift
|
1
|
2180
|
//
// BasicViewModel.swift
// Stopwatch
//
// Created by DianQK on 12/09/2016.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
//import RxExtensions
struct BasicViewModel: StopwatchViewModelProtocol {
let startAStopStyle: Observable<Style.Button>
let resetALapStyle: Observable<Style.Button>
let displayTime: Observable<String>
let displayElements: Observable<[(title: Observable<String>, displayTime: Observable<String>, color: Observable<UIColor>)]>
private enum State {
case timing, stopped
}
init(input: (startAStopTrigger: Observable<Void>, resetALapTrigger: Observable<Void>)) {
let state = input.startAStopTrigger
.scan(State.stopped) {
switch $0.0 {
case .stopped: return State.timing
case .timing: return State.stopped
}
}
.shareReplay(1)
displayTime = state
.flatMapLatest { state -> Observable<TimeInterval> in
switch state {
case .stopped:
return Observable.empty()
case .timing:
return Observable<Int>.interval(0.01, scheduler: MainScheduler.instance).map { _ in 0.01 }
}
}
.scan(0, accumulator: +)
.startWith(0)
.map(Tool.convertToTimeInfo)
startAStopStyle = state
.map { state in
switch state {
case .stopped:
return Style.Button(title: "Start", titleColor: Tool.Color.green, isEnabled: true, backgroungImage: #imageLiteral(resourceName: "green"))
case .timing:
return Style.Button(title: "Stop", titleColor: Tool.Color.red, isEnabled: true, backgroungImage: #imageLiteral(resourceName: "red"))
}
}
resetALapStyle = Observable.just(Style.Button(title: "", titleColor: UIColor.white, isEnabled: false, backgroungImage: #imageLiteral(resourceName: "gray")))
displayElements = Observable.empty()
}
}
|
mit
|
7e6786f9749815ed3fe7b51ae3799ce6
| 34.145161 | 164 | 0.582836 | 4.706263 | false | false | false | false |
acchou/RxGmail
|
Example/RxGmail/ThreadMessagesViewController.swift
|
1
|
1337
|
//
// ThreadMessagesViewController.swift
// RxGmail
//
// Created by Andy Chou on 3/6/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class ThreadMessagesViewController: UITableViewController {
let disposeBag = DisposeBag()
var threadId: String!
override func viewDidLoad() {
super.viewDidLoad()
let inputs = ThreadMessagesViewModelInputs(threadId: threadId)
let outputs = global.threadMessagesViewModel(inputs)
tableView.dataSource = nil
outputs.messageCells.bindTo(tableView.rx.items(cellIdentifier: "ThreadMessageCell")) { index, message, cell in
cell.textLabel?.text = message.subject
cell.detailTextLabel?.text = message.sender
}
.disposed(by: disposeBag)
tableView.rx
.modelSelected(MessageCell.self)
.subscribe(onNext: {
self.performSegue(withIdentifier: "ShowThreadMessageDetails", sender: $0)
})
.disposed(by: disposeBag)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let messageVC = segue.destination as! MessageViewController
let message = sender as! MessageCell
messageVC.messageId = message.identifier
}
}
|
mit
|
80097262653a6ad158d96a8d03755f23
| 28.043478 | 118 | 0.663922 | 4.929889 | false | false | false | false |
dsonara/DSImageCache
|
DSImageCache/Classes/Core/DSImageCache.swift
|
1
|
894
|
//
// DSImageCache.swift
// DSImageCache
//
// Created by Dipak Sonara on 29/03/17.
// Copyright © 2017 Dipak Sonara. All rights reserved.
import Foundation
import ImageIO
import UIKit
public typealias Image = UIImage
public typealias Color = UIColor
public typealias ImageView = UIImageView
typealias Button = UIButton
public final class DSImageCache<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
/**
A type that has DSImageCache extensions.
*/
public protocol DSImageCacheCompatible {
associatedtype CompatibleType
var ds: CompatibleType { get }
}
public extension DSImageCacheCompatible {
public var ds: DSImageCache<Self> {
get { return DSImageCache(self) }
}
}
extension Image: DSImageCacheCompatible { }
extension ImageView: DSImageCacheCompatible { }
extension Button: DSImageCacheCompatible { }
|
mit
|
2f8e1c6ed275044cf29a37075b07c971
| 20.780488 | 55 | 0.729003 | 4.442786 | false | false | false | false |
juheon0615/GhostHandongSwift
|
HandongAppSwift/RootViewController.swift
|
3
|
3256
|
//
// RootViewController.swift
// HandongAppSwift
//
// Created by csee on 2015. 2. 2..
// Copyright (c) 2015년 GHOST. All rights reserved.
//
import UIKit
class RootViewController: UIViewController, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil)
self.pageViewController!.delegate = self
let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers: NSArray = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers as [AnyObject], direction: .Forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self.modelController
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
// Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
var pageViewRect = self.view.bounds
self.pageViewController!.view.frame = pageViewRect
self.pageViewController!.didMoveToParentViewController(self)
// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var modelController: ModelController {
// Return the model controller object, creating it if necessary.
// In more complex implementations, the model controller may be passed to the view controller.
if _modelController == nil {
_modelController = ModelController()
}
return _modelController!
}
var _modelController: ModelController? = nil
// MARK: - UIPageViewController delegate methods
func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
// Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
let currentViewController = self.pageViewController!.viewControllers[0] as! UIViewController
let viewControllers: NSArray = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers as [AnyObject], direction: .Forward, animated: true, completion: {done in })
self.pageViewController!.doubleSided = false
return .Min
}
}
|
mit
|
6b36aa15449d51e89f30b358eb15bfc6
| 44.194444 | 291 | 0.737554 | 5.698774 | false | false | false | false |
dreamsxin/swift
|
test/Driver/subcommands.swift
|
9
|
1871
|
// Check that each of 'swift', 'swift repl', 'swift run' invoke the REPL.
//
// REQUIRES: swift_interpreter
//
// RUN: %swift_driver_plain -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s
// RUN: %swift_driver_plain run -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s
// RUN: %swift_driver_plain repl -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s
//
// CHECK-SWIFT-INVOKES-REPL: {{.*}}/swift -frontend -repl
// Check that 'swift -', 'swift t.swift', and 'swift /path/to/file' invoke the interpreter
// (for shebang line use). We have to run these since we can't get the driver to
// dump what it is doing and test the argv[1] processing.
//
// RUN: rm -rf %t.dir
// RUN: mkdir -p %t.dir/subpath
// RUN: echo "print(\"exec: \" + #file)" > %t.dir/stdin
// RUN: echo "print(\"exec: \" + #file)" > %t.dir/t.swift
// RUN: echo "print(\"exec: \" + #file)" > %t.dir/subpath/build
// RUN: cd %t.dir && %swift_driver_plain - < %t.dir/stdin -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-STDIN-INVOKES-INTERPRETER %s
// CHECK-SWIFT-STDIN-INVOKES-INTERPRETER: exec: <stdin>
// RUN: cd %t.dir && %swift_driver_plain t.swift -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-SUFFIX-INVOKES-INTERPRETER %s
// CHECK-SWIFT-SUFFIX-INVOKES-INTERPRETER: exec: t.swift
// RUN: cd %t.dir && %swift_driver_plain subpath/build -### 2>&1 | FileCheck -check-prefix=CHECK-SWIFT-PATH-INVOKES-INTERPRETER %s
// CHECK-SWIFT-PATH-INVOKES-INTERPRETER: exec: subpath/build
// Check that 'swift foo' invokes 'swift-foo'.
//
// RUN: rm -rf %t.dir
// RUN: mkdir -p %t.dir
// RUN: echo "#!/bin/sh" > %t.dir/swift-foo
// RUN: echo "echo \"exec: \$0\"" >> %t.dir/swift-foo
// RUN: chmod +x %t.dir/swift-foo
// RUN: env PATH=%t.dir %swift_driver_plain foo | FileCheck -check-prefix=CHECK-SWIFT-SUBCOMMAND %s
// CHECK-SWIFT-SUBCOMMAND: exec: {{.*}}/swift-foo
|
apache-2.0
|
7fce0bc524e6cc90e2b6ba02f55c6bf2
| 49.567568 | 134 | 0.660609 | 2.979299 | false | false | false | false |
insidegui/AssetCatalogTinkerer
|
Asset Catalog Tinkerer/ProgressBar.swift
|
1
|
2199
|
//
// ProgressBar.swift
// Asset Catalog Tinkerer
//
// Created by Guilherme Rambo on 27/03/16.
// Copyright © 2016 Guilherme Rambo. All rights reserved.
//
import Cocoa
open class ProgressBar: NSView {
override public init(frame frameRect: NSRect) {
super.init(frame: frameRect)
commonInit()
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
override open func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
open var tintColor: NSColor? {
didSet {
CATransaction.begin()
CATransaction.setAnimationDuration(0.0)
progressLayer.backgroundColor = tintColor?.cgColor
CATransaction.commit()
}
}
open var progress: Double = 0.0 {
didSet {
let animated = oldValue < progress
DispatchQueue.main.async { self.updateProgressLayer(animated) }
}
}
fileprivate var progressLayer: CALayer!
fileprivate func commonInit() {
guard progressLayer == nil else { return }
wantsLayer = true
layer = CALayer()
progressLayer = CALayer()
progressLayer.backgroundColor = tintColor?.cgColor
progressLayer.frame = NSRect(x: 0.0, y: 0.0, width: 0.0, height: bounds.height)
layer!.addSublayer(progressLayer)
progressLayer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
updateProgressLayer()
}
fileprivate var widthForProgressLayer: CGFloat {
return bounds.width * CGFloat(progress)
}
fileprivate func updateProgressLayer(_ animated: Bool = true) {
CATransaction.begin()
CATransaction.setAnimationDuration(animated ? 0.4 : 0.0)
var frame = progressLayer.frame
frame.size.width = widthForProgressLayer
progressLayer.frame = frame
if progress >= 0.99 {
progressLayer.opacity = 0.0
} else {
progressLayer.opacity = 1.0
}
CATransaction.commit()
}
}
|
bsd-2-clause
|
1f9b9588220026bf137c4ca7a1e5b1d9
| 24.858824 | 87 | 0.584622 | 5.171765 | false | false | false | false |
creatubbles/ctb-api-swift
|
CreatubblesAPIClientUnitTests/Spec/Hashtag/HashtagFetchRequestSpec.swift
|
1
|
1857
|
//
// HashtagFetchRequestSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Quick
import Nimble
@testable import CreatubblesAPIClient
class HashtagFetchRequestSpec: QuickSpec
{
override func spec()
{
let hashtagId = "lego"
describe("Fetch hashtag request")
{
it("Should have a proper method") {
let request = HashtagFetchRequest(hashtagId: hashtagId)
expect(request.method) == RequestMethod.get
}
it("Should have a proper endpoint") {
let request = HashtagFetchRequest(hashtagId: hashtagId)
expect(request.endpoint) == "hashtags/\(hashtagId)"
}
}
}
}
|
mit
|
4157fc261ab2408c7dd65a5adeb7f443
| 36.897959 | 81 | 0.687668 | 4.60794 | false | false | false | false |
ThryvInc/subway-ios
|
SubwayMap/NYCDirectionNameProvider.swift
|
2
|
1441
|
//
// NYCDirectionNameProvider.swift
// SubwayMap
//
// Created by Elliot Schrock on 6/17/18.
// Copyright © 2018 Thryv. All rights reserved.
//
import UIKit
public enum ImageDirection: Int {
case left, right, up, down
}
open class NYCDirectionNameProvider: NSObject {
public static func directionName(for direction: Int, routeId: String) -> String {
var directionName = direction == 0 ? "Uptown" : "Downtown"
if routeId == "7" || routeId == "7X" {
directionName = direction == 0 ? "Manhattan bound" : "Queens bound"
}
if routeId == "L" {
directionName = direction == 0 ? "Manhattan bound" : "Brooklyn bound"
}
if routeId == "G" {
directionName = direction == 0 ? "Queens bound" : "Brooklyn bound"
}
if routeId == "GS" {
directionName = direction == 0 ? "Times Square Bound" : "Grand Central bound"
}
return directionName
}
public static func directionEnum(for direction: Int, routeId: String) -> ImageDirection {
var directionEnum = direction == 0 ? ImageDirection.up : ImageDirection.down
if routeId == "7" || routeId == "7X" {
directionEnum = direction == 0 ? .left : .right
}
if routeId == "L" {
directionEnum = direction == 0 ? .left : .right
}
return directionEnum
}
}
|
mit
|
8b46008a707a88c102f6215669f47712
| 29 | 93 | 0.566667 | 4.044944 | false | false | false | false |
SixFiveSoftware/Swift_Pair_Programming_Resources
|
2014-06-28/AsyncTests/AsyncTests/AppDelegate.swift
|
1
|
7054
|
//
// AppDelegate.swift
// AsyncTests
//
// Created by BJ Miller on 6/28/14.
// Copyright (c) 2014 Six Five Software, LLC. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> 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()
}
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if managedObjectContext != nil {
if managedObjectContext.hasChanges && !managedObjectContext.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if !_managedObjectContext {
let coordinator = self.persistentStoreCoordinator
if coordinator != nil {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if !_managedObjectModel {
let modelURL = NSBundle.mainBundle().URLForResource("AsyncTests", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if !_persistentStoreCoordinator {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("AsyncTests.sqlite")
var error: NSError? = nil
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
/*
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.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil)
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
// #pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
}
|
mit
|
3cbf6659677e00b7fe435bf5ddbb7a26
| 51.251852 | 285 | 0.701446 | 6.166084 | false | false | false | false |
josve05a/wikipedia-ios
|
Wikipedia/Code/WMFLoginViewController.swift
|
2
|
16898
|
import UIKit
class WMFLoginViewController: WMFScrollViewController, UITextFieldDelegate, WMFCaptchaViewControllerDelegate, Themeable {
@IBOutlet fileprivate var usernameField: ThemeableTextField!
@IBOutlet fileprivate var passwordField: ThemeableTextField!
@IBOutlet fileprivate var usernameTitleLabel: UILabel!
@IBOutlet fileprivate var passwordTitleLabel: UILabel!
@IBOutlet fileprivate var passwordAlertLabel: UILabel!
@IBOutlet fileprivate var createAccountButton: WMFAuthLinkLabel!
@IBOutlet fileprivate var forgotPasswordButton: UILabel!
@IBOutlet fileprivate var titleLabel: UILabel!
@IBOutlet fileprivate var captchaContainer: UIView!
@IBOutlet fileprivate var loginButton: WMFAuthButton!
@IBOutlet weak var scrollContainer: UIView!
public var loginSuccessCompletion: (() -> Void)?
public var loginDismissedCompletion: (() -> Void)?
@objc public var funnel: WMFLoginFunnel?
private var startDate: Date? // to calculate time elapsed between login start and login success
fileprivate var theme: Theme = Theme.standard
fileprivate lazy var captchaViewController: WMFCaptchaViewController? = WMFCaptchaViewController.wmf_initialViewControllerFromClassStoryboard()
private let loginInfoFetcher = WMFAuthLoginInfoFetcher()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
startDate = Date()
}
@objc func closeButtonPushed(_ : UIBarButtonItem?) {
dismiss(animated: true, completion: nil)
loginDismissedCompletion?()
}
@IBAction fileprivate func loginButtonTapped(withSender sender: UIButton) {
save()
}
override func accessibilityPerformEscape() -> Bool {
closeButtonPushed(nil)
return true
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:)))
navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
loginButton.setTitle(WMFLocalizedString("main-menu-account-login", value:"Log in", comment:"Button text for logging in. {{Identical|Log in}}"), for: .normal)
createAccountButton.strings = WMFAuthLinkLabelStrings(dollarSignString: WMFLocalizedString("login-no-account", value:"Don't have an account? %1$@", comment:"Text for create account button. %1$@ is the message {{msg-wikimedia|login-account-join-wikipedia}}"), substitutionString: WMFLocalizedString("login-join-wikipedia", value:"Join Wikipedia.", comment:"Join Wikipedia text to be used as part of a create account button"))
createAccountButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(createAccountButtonPushed(_:))))
forgotPasswordButton.text = WMFLocalizedString("login-forgot-password", value:"Forgot your password?", comment:"Button text for loading the password reminder interface")
forgotPasswordButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(forgotPasswordButtonPushed(_:))))
usernameField.placeholder = WMFLocalizedString("field-username-placeholder", value:"enter username", comment:"Placeholder text shown inside username field until user taps on it")
passwordField.placeholder = WMFLocalizedString("field-password-placeholder", value:"enter password", comment:"Placeholder text shown inside password field until user taps on it")
titleLabel.text = WMFLocalizedString("login-title", value:"Log in to your account", comment:"Title for log in interface")
usernameTitleLabel.text = WMFLocalizedString("field-username-title", value:"Username", comment:"Title for username field {{Identical|Username}}")
passwordTitleLabel.text = WMFLocalizedString("field-password-title", value:"Password", comment:"Title for password field {{Identical|Password}}")
view.wmf_configureSubviewsForDynamicType()
captchaViewController?.captchaDelegate = self
wmf_add(childController:captchaViewController, andConstrainToEdgesOfContainerView: captchaContainer)
apply(theme: theme)
}
@IBAction func textFieldDidChange(_ sender: UITextField) {
enableProgressiveButtonIfNecessary()
}
fileprivate func enableProgressiveButtonIfNecessary() {
loginButton.isEnabled = shouldProgressiveButtonBeEnabled()
}
fileprivate func disableProgressiveButton() {
loginButton.isEnabled = false
}
fileprivate func shouldProgressiveButtonBeEnabled() -> Bool {
var shouldEnable = areRequiredFieldsPopulated()
if captchaIsVisible() && shouldEnable {
shouldEnable = hasUserEnteredCaptchaText()
}
return shouldEnable
}
fileprivate func hasUserEnteredCaptchaText() -> Bool {
guard let text = captchaViewController?.solution else {
return false
}
return !(text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)).isEmpty
}
fileprivate func requiredInputFields() -> [UITextField] {
assert(isViewLoaded, "This method is only intended to be called when view is loaded, since they'll all be nil otherwise")
return [usernameField, passwordField]
}
fileprivate func areRequiredFieldsPopulated() -> Bool {
return requiredInputFields().wmf_allFieldsFilled()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Check if captcha is required right away. Things could be configured so captcha is required at all times.
getCaptcha()
updatePasswordFieldReturnKeyType()
enableProgressiveButtonIfNecessary()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
usernameField.becomeFirstResponder()
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField {
case usernameField:
passwordField.becomeFirstResponder()
case passwordField:
if captchaIsVisible() {
captchaViewController?.captchaTextFieldBecomeFirstResponder()
}else{
save()
}
default:
assertionFailure("Unhandled text field")
}
return true
}
@IBAction func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == passwordField {
passwordAlertLabel.isHidden = true
passwordField.textColor = theme.colors.primaryText
passwordField.keyboardAppearance = theme.keyboardAppearance
}
}
fileprivate func save() {
wmf_hideKeyboard()
passwordAlertLabel.isHidden = true
setViewControllerUserInteraction(enabled: false)
disableProgressiveButton()
WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("account-creation-logging-in", value:"Logging in...", comment:"Alert shown after account successfully created and the user is being logged in automatically. {{Identical|Logging in}}"), sticky: true, canBeDismissedByUser: false, dismissPreviousAlerts: true, tapCallBack: nil)
guard let username = usernameField.text, let password = passwordField.text else {
assertionFailure("One or more of the required parameters are nil")
return
}
WMFAuthenticationManager.sharedInstance.login(username: username, password: password, retypePassword: nil, oathToken: nil, captchaID: captchaViewController?.captcha?.captchaID, captchaWord: captchaViewController?.solution) { (loginResult) in
switch loginResult {
case .success(_):
let loggedInMessage = String.localizedStringWithFormat(WMFLocalizedString("main-menu-account-title-logged-in", value:"Logged in as %1$@", comment:"Header text used when account is logged in. %1$@ will be replaced with current username."), self.usernameField.text ?? "")
WMFAlertManager.sharedInstance.showSuccessAlert(loggedInMessage, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil)
self.loginSuccessCompletion?()
self.setViewControllerUserInteraction(enabled: true)
self.dismiss(animated: true)
self.funnel?.logSuccess()
if let start = self.startDate {
LoginFunnel.shared.logSuccess(timeElapsed: fabs(start.timeIntervalSinceNow))
} else {
assertionFailure("startDate is nil; startDate is required to calculate timeElapsed")
}
case .failure(let error):
self.setViewControllerUserInteraction(enabled: true)
// Captcha's appear to be one-time, so always try to get a new one on failure.
self.getCaptcha()
if let error = error as? WMFAccountLoginError {
switch error {
case .temporaryPasswordNeedsChange:
self.showChangeTempPasswordViewController()
return
case .needsOathTokenFor2FA:
self.showTwoFactorViewController()
return
case .statusNotPass:
self.passwordField.text = nil
self.passwordField.becomeFirstResponder()
case .wrongPassword:
self.passwordAlertLabel.text = error.localizedDescription
self.passwordAlertLabel.isHidden = false
self.passwordField.textColor = self.theme.colors.error
self.passwordField.keyboardAppearance = self.theme.keyboardAppearance
self.funnel?.logError(error.localizedDescription)
WMFAlertManager.sharedInstance.dismissAlert()
return
default: break
}
}
self.enableProgressiveButtonIfNecessary()
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
self.funnel?.logError(error.localizedDescription)
default:
break
}
}
}
func showChangeTempPasswordViewController() {
guard let presenter = presentingViewController else {
return
}
dismiss(animated: true, completion: {
let changePasswordVC = WMFChangePasswordViewController.wmf_initialViewControllerFromClassStoryboard()
changePasswordVC?.userName = self.usernameField!.text
changePasswordVC?.apply(theme: self.theme)
let navigationController = WMFThemeableNavigationController(rootViewController: changePasswordVC!, theme: self.theme, style: .sheet)
presenter.present(navigationController, animated: true, completion: nil)
})
}
func showTwoFactorViewController() {
guard
let presenter = presentingViewController,
let twoFactorViewController = WMFTwoFactorPasswordViewController.wmf_initialViewControllerFromClassStoryboard()
else {
assertionFailure("Expected view controller(s) not found")
return
}
dismiss(animated: true, completion: {
twoFactorViewController.userName = self.usernameField!.text
twoFactorViewController.password = self.passwordField!.text
twoFactorViewController.captchaID = self.captchaViewController?.captcha?.captchaID
twoFactorViewController.captchaWord = self.captchaViewController?.solution
twoFactorViewController.apply(theme: self.theme)
let navigationController = WMFThemeableNavigationController(rootViewController: twoFactorViewController, theme: self.theme, style: .sheet)
presenter.present(navigationController, animated: true, completion: nil)
})
}
@objc func forgotPasswordButtonPushed(_ recognizer: UITapGestureRecognizer) {
guard
recognizer.state == .ended,
let presenter = presentingViewController,
let forgotPasswordVC = WMFForgotPasswordViewController.wmf_initialViewControllerFromClassStoryboard()
else {
assertionFailure("Expected view controller(s) not found")
return
}
dismiss(animated: true, completion: {
let navigationController = WMFThemeableNavigationController(rootViewController: forgotPasswordVC, theme: self.theme, style: .sheet)
forgotPasswordVC.apply(theme: self.theme)
presenter.present(navigationController, animated: true, completion: nil)
})
}
@objc func createAccountButtonPushed(_ recognizer: UITapGestureRecognizer) {
guard
recognizer.state == .ended,
let presenter = presentingViewController,
let createAcctVC = WMFAccountCreationViewController.wmf_initialViewControllerFromClassStoryboard()
else {
assertionFailure("Expected view controller(s) not found")
return
}
createAcctVC.apply(theme: theme)
funnel?.logCreateAccountAttempt()
LoginFunnel.shared.logCreateAccountAttempt()
dismiss(animated: true, completion: {
createAcctVC.funnel = CreateAccountFunnel()
createAcctVC.funnel?.logStart(fromLogin: self.funnel?.loginSessionToken)
let navigationController = WMFThemeableNavigationController(rootViewController: createAcctVC, theme: self.theme, style: .sheet)
presenter.present(navigationController, animated: true, completion: nil)
})
}
fileprivate func getCaptcha() {
let captchaFailure: WMFErrorHandler = {error in
DispatchQueue.main.async {
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
self.funnel?.logError(error.localizedDescription)
}
}
let siteURL = MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL()
loginInfoFetcher.fetchLoginInfoForSiteURL(siteURL!, success: { info in
DispatchQueue.main.async {
self.captchaViewController?.captcha = info.captcha
self.updatePasswordFieldReturnKeyType()
self.enableProgressiveButtonIfNecessary()
}
}, failure: captchaFailure)
}
func captchaReloadPushed(_ sender: AnyObject) {
enableProgressiveButtonIfNecessary()
}
func captchaSolutionChanged(_ sender: AnyObject, solutionText: String?) {
enableProgressiveButtonIfNecessary()
}
public func captchaSiteURL() -> URL {
return (MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL())!
}
func captchaKeyboardReturnKeyTapped() {
save()
}
public func captchaHideSubtitle() -> Bool {
return true
}
fileprivate func captchaIsVisible() -> Bool {
return captchaViewController?.captcha != nil
}
fileprivate func updatePasswordFieldReturnKeyType() {
passwordField.returnKeyType = captchaIsVisible() ? .next : .done
// Resign and become first responder so keyboard return key updates right away.
if passwordField.isFirstResponder {
passwordField.resignFirstResponder()
passwordField.becomeFirstResponder()
}
}
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
view.tintColor = theme.colors.link
titleLabel.textColor = theme.colors.primaryText
let labels = [usernameTitleLabel, passwordTitleLabel, passwordAlertLabel]
for label in labels {
label?.textColor = theme.colors.secondaryText
}
usernameField.apply(theme: theme)
passwordField.apply(theme: theme)
titleLabel.textColor = theme.colors.primaryText
forgotPasswordButton.textColor = theme.colors.link
captchaContainer.backgroundColor = theme.colors.baseBackground
createAccountButton.apply(theme: theme)
loginButton.apply(theme: theme)
passwordAlertLabel.textColor = theme.colors.error
scrollContainer.backgroundColor = theme.colors.paperBackground
captchaViewController?.apply(theme: theme)
}
}
|
mit
|
c80567b3c14729be2c8ade573324db4d
| 45.550964 | 432 | 0.673985 | 6.129126 | false | false | false | false |
lanit-tercom-school/grouplock
|
GroupLockiOS/GroupLock/Scenes/Home_Stack/ScanningScene/MetadataOutputObjectsDelegate.swift
|
1
|
1291
|
//
// MetadataOutputObjectsDelegate.swift
// GroupLock
//
// Created by Sergej Jaskiewicz on 15.08.16.
// Copyright © 2016 Lanit-Tercom School. All rights reserved.
//
import AVFoundation
protocol MetadataOutputObjectsDelegateOutput {
func qrCodeCaptured(_ request: Scanning.Keys.Request)
}
class MetadataOutputObjectsDelegate: NSObject, AVCaptureMetadataOutputObjectsDelegate {
weak var output: ScanningInteractorInput?
var layer: AVCaptureVideoPreviewLayer?
func captureOutput(_ captureOutput: AVCaptureOutput!,
didOutputMetadataObjects metadataObjects: [Any]!,
from connection: AVCaptureConnection!) {
guard metadataObjects != nil && !metadataObjects.isEmpty else { return }
guard let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject,
let transformedMetadataObject = layer?.transformedMetadataObject(for: metadataObject)
as? AVMetadataMachineReadableCodeObject,
let key = metadataObject.stringValue,
let corners = transformedMetadataObject.corners as? [CFDictionary] else { return }
output?.qrCodeCaptured(Scanning.Keys.Request(keyScanned: key, qrCodeCorners: corners))
}
}
|
apache-2.0
|
b833a2d1bc2a596e860628e15d3d8b13
| 39.3125 | 99 | 0.707752 | 5.863636 | false | false | false | false |
zhubinchen/MarkLite
|
MarkLite/View/KeyboardBar.swift
|
2
|
12086
|
//
// KeyboardBar.swift
// Markdown
//
// Created by zhubch on 2017/7/11.
// Copyright © 2017年 zhubch. All rights reserved.
//
import UIKit
import Alamofire
import RxSwift
fileprivate var width: CGFloat = {
return isPad ? 50 : 40
}()
protocol ButtonConvertiable {
func makeButton() -> UIButton
}
extension UIImage: ButtonConvertiable {
func makeButton() -> UIButton {
let button = UIButton(type: UIButtonType.system)
button.setImage(self, for: .normal)
button.contentEdgeInsets = isPad ? UIEdgeInsetsMake(15, 15, 15, 15) : UIEdgeInsetsMake(12, 12, 12, 12)
return button
}
}
extension String: ButtonConvertiable {
func makeButton() -> UIButton {
let button = UIButton(type: UIButtonType.system)
button.setTitle(self, for: .normal)
button.titleLabel?.font = UIFont.font(ofSize: isPad ? 18 : 16, bold: true)
return button
}
}
fileprivate let uploadURL = ""
class KeyboardBar: UIView {
let scrollView = UIScrollView()
var endButton: UIButton!
let items: [(ButtonConvertiable,Selector)] = {
var items: [(ButtonConvertiable,Selector)] = [
(#imageLiteral(resourceName: "bar_tab"), #selector(tapTab(_:))),
(#imageLiteral(resourceName: "bar_image"), #selector(tapImage(_:))),
(#imageLiteral(resourceName: "bar_link"), #selector(tapLink)),
(#imageLiteral(resourceName: "bar_header"), #selector(tapHeader)),
(#imageLiteral(resourceName: "bar_bold"), #selector(tapBold)),
(#imageLiteral(resourceName: "bar_italic"), #selector(tapItalic)),
(#imageLiteral(resourceName: "highlight"), #selector(tapHighliht)),
(#imageLiteral(resourceName: "bar_deleteLine"), #selector(tapDeletion)),
(#imageLiteral(resourceName: "bar_quote"), #selector(tapQuote)),
(#imageLiteral(resourceName: "bar_code"), #selector(tapCode)),
(#imageLiteral(resourceName: "bar_olist"), #selector(tapOList)),
(#imageLiteral(resourceName: "bar_ulist"), #selector(tapUList)),
(#imageLiteral(resourceName: "bar_todolist"), #selector(tapTodoList))
]
items.append(contentsOf: Configure.shared.keyboardBarItems.mapFilter(mapFunction: { item -> (ButtonConvertiable,Selector) in
return (item, #selector(tapChar(_:)))
}))
return items
}()
weak var textView: TextView?
weak var menu: MenuView?
var textField: UITextField?
let bag = DisposeBag()
var imagePicker: ImagePicker?
init() {
super.init(frame: CGRect(x: 0, y: 0, w: windowWidth, h: width))
setBackgroundColor(.tableBackground)
items.forEachEnumerated { (index, item) in
let button = item.0.makeButton()
button.addTarget(self, action: item.1, for: .touchUpInside)
button.tintColor = .gray
button.tag = index
button.frame = CGRect(x: CGFloat(index) * width, y: 0, w: width, h: width)
self.scrollView.addSubview(button)
}
scrollView.contentSize = CGSize(width: CGFloat(items.count) * width, height: width)
addSubview(scrollView)
endButton = #imageLiteral(resourceName: "bar_keyboard").makeButton()
endButton.tintColor = .gray
endButton.addTarget(self, action: #selector(hideKeyboard), for: .touchUpInside)
addSubview(endButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
scrollView.frame = CGRect(x: 0, y: 0, w: w - width, h: width)
endButton.frame = CGRect(x: w - width, y: 0, w: width, h: width)
self.menu?.dismiss(sender: self.menu?.superview as? UIControl)
}
@objc func hideKeyboard() {
impactIfAllow()
self.menu?.dismiss(sender: self.menu?.superview as? UIControl)
textView?.resignFirstResponder()
}
@objc func tapChar(_ sender: UIButton) {
let char = sender.currentTitle ?? ""
textView?.insertText(char)
}
@objc func tapTab(_ sender: UIButton) {
self.menu?.dismiss(sender: self.menu?.superview as? UIControl)
let pos = sender.superview!.convert(sender.center, to: sender.window)
let menu = MenuView(items: [/" ",/" ",/"Tab"].map{($0,false)},
postion: CGPoint(x: pos.x - 20, y: pos.y - 150)) { [weak self] (index) in
let texts = [" "," ","\t"]
self?.textView?.insertText(texts[index])
}
menu.show()
self.menu = menu
}
@objc func tapImage(_ sender: UIButton) {
self.menu?.dismiss(sender: self.menu?.superview as? UIControl)
guard let textView = self.textView, let vc = textView.viewController else { return }
let pos = sender.superview!.convert(sender.center, to: sender.window)
let menu = MenuView(items: [/"PickFromPhotos",/"PickFromCamera"].map{($0,false)},
postion: CGPoint(x: pos.x - 20, y: pos.y - 110)) { [weak self] (index) in
if index == 0 {
self?.imagePicker = ImagePicker(viewController: vc){ self?.didPickImage($0) }
self?.imagePicker?.pickFromLibray()
self?.textView?.resignFirstResponder()
} else if index == 1 {
self?.imagePicker = ImagePicker(viewController: vc){ self?.didPickImage($0) }
self?.imagePicker?.pickFromCamera()
self?.textView?.resignFirstResponder()
}
}
menu.show()
self.menu = menu
}
@objc func tapLink() {
self.menu?.dismiss(sender: self.menu?.superview as? UIControl)
textView?.viewController?.showAlert(title: /"InsertHref", message: "", actionTitles: [/"Cancel",/"OK"], textFieldconfigurationHandler: { (textField) in
textField.placeholder = "http://example.com"
textField.font = UIFont.font(ofSize: 13)
textField.setTextColor(.primary)
self.textField = textField
}) { (index) in
if index == 1 {
let link = self.textField?.text ?? ""
self.textView?.insertURL(link)
}
}
}
@objc func tapCode() {
guard let textView = self.textView else { return }
let currentRange = textView.selectedRange
let text = textView.text.substring(with: currentRange)
let isEmpty = text.length == 0
let insertText = isEmpty ? /"EnterCode": text
textView.insertText("`\(insertText)`")
if isEmpty {
textView.selectedRange = NSRange(location:currentRange.location + 1, length: insertText.length)
}
}
@objc func tapTodoList(_ sender: UIButton) {
guard let textView = self.textView else { return }
self.menu?.dismiss(sender: self.menu?.superview as? UIControl)
let pos = sender.superview!.convert(sender.center, to: sender.window)
let menu = MenuView(items: [/"Completed",/"Uncompleted"].map{($0,false)},
postion: CGPoint(x: pos.x - 20, y: pos.y - 110)) { (index) in
let currentRange = textView.selectedRange
let insertText = "- [\(index == 0 ? "x" : " ")] item"
textView.insertText("\n\(insertText)")
textView.selectedRange = NSRange(location:currentRange.location + 7, length: (/"item").length)
}
menu.show()
self.menu = menu
}
@objc func tapUList() {
guard let textView = self.textView else { return }
let currentRange = textView.selectedRange
let insertText = "* item"
textView.insertText("\n\(insertText)")
textView.selectedRange = NSRange(location:currentRange.location + 3, length: (/"item").length)
}
@objc func tapOList() {
guard let textView = self.textView else { return }
let currentRange = textView.selectedRange
let insertText = "1. item"
textView.insertText("\n\(insertText)")
textView.selectedRange = NSRange(location:currentRange.location + 4, length: (/"item").length)
}
@objc func tapHeader(_ sender: UIButton) {
guard let textView = self.textView else { return }
self.menu?.dismiss(sender: self.menu?.superview as? UIControl)
let pos = sender.superview!.convert(sender.center, to: sender.window)
let menu = MenuView(items: [/"Header1",/"Header2",/"Header3",/"Header4"].map{($0,false)},
postion: CGPoint(x: pos.x - 20, y: pos.y - 190)) { (index) in
let currentRange = textView.selectedRange
let insertText = ("#" * (index+1)) + " " + /"Header"
textView.insertText("\n\(insertText)")
textView.selectedRange = NSRange(location:currentRange.location + index + 3, length: (/"Header").length)
}
menu.show()
self.menu = menu
}
@objc func tapDeletion() {
guard let textView = self.textView else { return }
let currentRange = textView.selectedRange
let text = textView.text.substring(with: currentRange)
let isEmpty = text.length == 0
let insertText = isEmpty ? /"Delection": text
textView.insertText("~~\(insertText)~~")
if isEmpty {
textView.selectedRange = NSRange(location:currentRange.location + 2, length: insertText.length)
}
}
@objc func tapQuote() {
guard let textView = self.textView else { return }
let currentRange = textView.selectedRange
let insertText = /"Blockquote"
textView.insertText("\n> \(insertText)\n")
textView.selectedRange = NSRange(location:currentRange.location + 3, length: insertText.length)
}
@objc func tapHighliht() {
guard let textView = self.textView else { return }
let currentRange = textView.selectedRange
let text = textView.text.substring(with: currentRange)
let isEmpty = text.length == 0
let insertText = isEmpty ? /"Highlight": text
textView.insertText("==\(insertText)==")
if isEmpty {
textView.selectedRange = NSRange(location:currentRange.location + 2, length: insertText.length)
}
}
@objc func tapBold() {
guard let textView = self.textView else { return }
let currentRange = textView.selectedRange
let text = textView.text.substring(with: currentRange)
let isEmpty = text.length == 0
let insertText = isEmpty ? /"StrongText": text
textView.insertText("**\(insertText)**")
if isEmpty {
textView.selectedRange = NSRange(location:currentRange.location + 2, length: insertText.length)
}
}
@objc func tapItalic() {
guard let textView = self.textView else { return }
let currentRange = textView.selectedRange
let text = textView.text.substring(with: currentRange)
let isEmpty = text.length == 0
let insertText = isEmpty ? /"EmphasizedText": text
textView.insertText("*\(insertText)*")
if isEmpty {
textView.selectedRange = NSRange(location:currentRange.location + 1, length: insertText.length)
}
}
func didPickImage(_ image: UIImage) {
imagePicker = nil
textView?.insertImage(image)
}
}
//extension KeyboardBar {
//
// override var keyCommands: [UIKeyCommand]? {
// return [
// UIKeyCommand(input: "B", modifierFlags: .command, action: #selector(tapBold), discoverabilityTitle: "Bold"),
// UIKeyCommand(input: "I", modifierFlags: .command, action: #selector(tapItalic), discoverabilityTitle: "Italic"),
// ]
// }
//
// override var canBecomeFirstResponder: Bool {
// return true
// }
//}
|
gpl-3.0
|
28d1a84eb48b5f6a5c4ec04004a13597
| 38.358306 | 159 | 0.599934 | 4.437385 | false | false | false | false |
dshahidehpour/IGListKit
|
Examples/Examples-macOS/IGListKitExamples/ViewControllers/UsersViewController.swift
|
3
|
4598
|
/**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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
import IGListKit
final class UsersViewController: NSViewController {
@IBOutlet weak var tableView: NSTableView!
//MARK: Data
var users = [User]() {
didSet {
computeFilteredUsers()
}
}
var searchTerm = "" {
didSet {
computeFilteredUsers()
}
}
private func computeFilteredUsers() {
guard !searchTerm.characters.isEmpty else {
filteredUsers = users
return
}
filteredUsers = users.filter({ $0.name.localizedCaseInsensitiveContains(self.searchTerm) })
}
fileprivate func delete(user: User) {
guard let index = self.users.index(where: { $0.pk == user.pk }) else { return }
self.users.remove(at: index)
}
//MARK: -
//MARK: Diffing
var filteredUsers = [User]() {
didSet {
// get the difference between the old array of Users and the new array of Users
let diff = IGListDiff(oldValue, filteredUsers, .equality)
// this difference is used here to update the table view, but it can be used
// to update collection views and other similar interface elements
// this code can also be added to an extension of NSTableView ;)
tableView.beginUpdates()
tableView.insertRows(at: diff.inserts, withAnimation: .slideDown)
tableView.removeRows(at: diff.deletes, withAnimation: .slideUp)
tableView.reloadData(forRowIndexes: diff.updates, columnIndexes: .zero)
diff.moves.forEach { move in
self.tableView.moveRow(at: move.from, to: move.to)
}
tableView.endUpdates()
}
}
//MARK: -
private func loadSampleUsers() {
guard let file = Bundle.main.url(forResource: "users", withExtension: "json") else { return }
do {
self.users = try UsersProvider(with: file).users
} catch {
NSAlert(error: error).runModal()
}
}
// MARK: Interface
override func viewDidLoad() {
super.viewDidLoad()
loadSampleUsers()
}
override func viewDidAppear() {
super.viewDidAppear()
view.window?.titleVisibility = .hidden
}
@IBAction func shuffle(_ sender: Any?) {
users = users.shuffled
}
@IBAction func search(_ sender: NSSearchField) {
searchTerm = sender.stringValue
}
@IBAction func delete(_ sender: Any?) {
guard tableView.selectedRowIndexes.count > 0 else { return }
tableView.selectedRowIndexes.forEach({ self.delete(user: self.filteredUsers[$0]) })
}
}
extension UsersViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return filteredUsers.count
}
}
extension UsersViewController: NSTableViewDelegate {
private struct Storyboard {
static let cellIdentifier = "cell"
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let cell = tableView.make(withIdentifier: Storyboard.cellIdentifier, owner: tableView) as? NSTableCellView else {
return nil
}
cell.textField?.stringValue = filteredUsers[row].name
return cell
}
@available(OSX 10.11, *)
func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableRowActionEdge) -> [NSTableViewRowAction] {
let delete = NSTableViewRowAction(style: .destructive, title: "Delete") { action, row in
guard row < self.filteredUsers.count else { return }
self.delete(user: self.filteredUsers[row])
}
return [delete]
}
}
|
bsd-3-clause
|
900b22cbf98dcbcea1c66d3299fd63aa
| 29.653333 | 127 | 0.61679 | 5.019651 | false | false | false | false |
atomkirk/big-splash-tvos
|
BigSplash/PhotoSearchService.swift
|
1
|
3287
|
//
// PhotoSearchService.swift
// Spoken
//
// Created by Adam Kirk on 10/15/15.
// Copyright © 2015 Spoken. All rights reserved.
//
import Foundation
import ATKShared
class PhotoSearchService {
typealias PhotoSearchServiceCompletionBlock = (photos: [Photo]) -> Void
struct Photo {
let size: CGSize
let fullSizeURL: NSURL
let thumbnailURL: NSURL
let color: UIColor
}
private var page: Int = 1
func next(completion: PhotoSearchServiceCompletionBlock) {
Q.background {
let url = NSURL(string: "http://big-splash-cdn.s3-us-west-2.amazonaws.com/\(self.page++).json")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
if let
HTTPResponse = response as? NSHTTPURLResponse,
data = data
where HTTPResponse.statusCode == 200 {
if let json = JSON.fromData(data).json {
var newPhotos = [Photo]()
for photo in json.array! {
if let wv = photo["width"].integer,
let hv = photo["height"].integer,
let thumbURL = photo["urls"]["thumb"].url,
let regularURL = photo["urls"]["regular"].url,
let color = photo["color"].string {
let width = CGFloat(wv)
let height = CGFloat(hv)
let color = UIColor(hexString: color)
newPhotos.append(Photo(size: CGSize(width: width, height: height), fullSizeURL: regularURL, thumbnailURL: thumbURL, color: color))
}
}
Q.main {
completion(photos: newPhotos)
}
}
}
})
task.resume()
// if let path = NSBundle.mainBundle().pathForResource("\(self.page++)", ofType: "json") {
// let data = NSFileManager.defaultManager().contentsAtPath(path)
// var newPhotos = [Photo]()
// if let data = data, json = JSON.fromData(data).json {
// for photo in json.array! {
// if let wv = photo["width"].integer,
// let hv = photo["height"].integer,
// let thumbURL = photo["urls"]["thumb"].url,
// let regularURL = photo["urls"]["regular"].url {
// let width = CGFloat(wv)
// let height = CGFloat(hv)
// newPhotos.append(Photo(size: CGSize(width: width, height: height), fullSizeURL: regularURL, thumbnailURL: thumbURL))
// }
// }
// Q.main {
// completion(photos: newPhotos)
// }
// }
// }
}
}
}
|
cc0-1.0
|
333fe10d63dfc86fd77d399c47143d25
| 41.675325 | 170 | 0.441266 | 5.32577 | false | false | false | false |
Bartlebys/Bartleby
|
Bartleby.xOS/core/extensions/BartlebyDocument+DotBart.swift
|
1
|
7890
|
//
// Documente+AppKitFacilities.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 08/07/2016.
//
//
import Foundation
#if os(OSX)
import AppKit
#else
import UIKit
#endif
#if !USE_EMBEDDED_MODULES
import Alamofire
#endif
extension BartlebyDocument {
#if os(OSX)
//MARK: - APP KIT FACILITIES
public func saveMetadata(handlers: Handlers){
let savePanel = NSSavePanel()
savePanel.canCreateDirectories = true
savePanel.nameFieldStringValue = self.fileURL?.lastPathComponent ?? "metadata"
savePanel.allowedFileTypes=["bart"]
savePanel.begin(completionHandler: { (result) in
syncOnMain{
if result==NSApplication.ModalResponse.OK {
if let url = savePanel.url {
let filePath=url.path
self.exportMetadataTo(filePath, handlers:handlers)
}
}
}
})
}
public func loadMetadata(handlers: Handlers){
let openPanel = NSOpenPanel()
openPanel.canCreateDirectories = false
openPanel.allowedFileTypes=["bart"]
openPanel.begin(completionHandler: { (result) in
syncOnMain{
if result==NSApplication.ModalResponse.OK {
if let url = openPanel.url {
let filePath=url.path
self.importMetadataFrom(filePath,handlers:handlers)
}
}
}
})
}
#endif
/**
Call the export Endpoint
- parameter handlers: the handlers
*/
public func importCollectionsFromCollaborativeServer(_ handlers: Handlers){
self.currentUser.login( sucessHandler: {
let pathURL=self.baseURL.appendingPathComponent("/Export")
let dictionary=["excludeTriggers":"true","observationUID":self.metadata.persistentUID];
let urlRequest=HTTPManager.requestWithToken(inDocumentWithUID:self.UID, withActionName:"Export", forMethod:"GET", and: pathURL)
do {
let r=try URLEncoding().encode(urlRequest,with:dictionary)
request(r).validate().responseJSON(completionHandler: { (response) in
let result=response.result
let httpResponse=response.response
if result.isFailure {
let completionState = Completion.failureStateFromAlamofire(response)
handlers.on(completionState)
} else {
if let statusCode=httpResponse?.statusCode {
if 200...299 ~= statusCode {
var issues=[String]()
if let dictionary=result.value as? [String:Any]{
if let collections=dictionary["collections"] as? [String:Any] {
for (collectionName,collectionDictionary) in collections{
if let proxy=self.collectionByName(collectionName),
let collectionDictionary=collectionDictionary as? [String:Any] {
do{
let jsonData = try JSONSerialization.data(withJSONObject: collectionDictionary, options:[])
// Use dynamics
let collection=try self.dynamics.deserialize(typeName: collectionName, data: jsonData, document: nil)
// We need to cast the dynamic type to ManagedModel & BartlebyCollection (BartlebyCollection alone is not enough)
if let bartlebyCollection = collection as? ManagedModel & BartlebyCollection{
proxy.replaceProxyData(bartlebyCollection.getItems())
}else{
throw DocumentError.collectionProxyTypeError
}
}catch{
issues.append("\(error)")
}
}
}
}
}
if issues.count==0{
handlers.on(Completion.successState())
}else{
handlers.on(Completion.failureState(issues.joined(separator: "\n"), statusCode: StatusOfCompletion.expectation_Failed))
}
} else {
var status = StatusOfCompletion.undefined
if let statusCode=httpResponse?.statusCode{
status = StatusOfCompletion (rawValue:statusCode) ?? StatusOfCompletion.undefined
}
handlers.on(Completion.failureState("\(result)", statusCode:status ))
}
}
}
})
}catch{
handlers.on(Completion.failureStateFromError(error))
}
}) { (context) in
handlers.on(Completion.failureStateFromHTTPContext(context))
}
}
public func exportMetadataTo(_ path:String, handlers: Handlers) {
do{
let data = try self._getSerializedMetadata()
Bartleby.fileManager.writeData(data, path: path, handlers: Handlers(completionHandler: { (dataWritten) in
handlers.on(dataWritten)
}))
}catch{
handlers.on(Completion.failureStateFromError(error))
}
}
/**
Imports the metadata from a given path
- parameter path: the import path
- parameter handlers: the handlers
*/
public func importMetadataFrom(_ path:String,handlers: Handlers) {
let readDataHandler=Handlers { (dataCompletion) in
if let data=dataCompletion.data{
do{
try self._useSerializedMetadata(data)
self.metadata.saveThePassword=false // Do not allow password bypassing on .bart import
self.dotBart=true// turn on the flag (the UI should ask for the password)
let previousUID=self.UID
Bartleby.sharedInstance.forget(previousUID)
// Disconnect from SSE
self._closeSSE()
Bartleby.sharedInstance.declare(self)
self.metadata.currentUser?.referentDocument=self
// Reconnect to SSE
self._connectToSSE()
handlers.on(Completion.successState())
}catch{
handlers.on(Completion.failureStateFromError(error))
}
}else{
handlers.on(dataCompletion)
}
}
Bartleby.fileManager.readData(contentsOfFile:path, handlers: readDataHandler)
}
fileprivate func _getSerializedMetadata() throws -> Data{
let serializedMetadata = try self.metadata.toCryptedData()
return serializedMetadata
}
fileprivate func _useSerializedMetadata(_ data:Data) throws {
self.metadata = try DocumentMetadata.fromCryptedData(data,document: self)
}
}
|
apache-2.0
|
4132e871ac5cd8779cadeda5042f7511
| 36.932692 | 165 | 0.501014 | 6.116279 | false | false | false | false |
delannoyk/SoundcloudSDK
|
sources/SoundcloudSDK/model/Playlist.swift
|
1
|
3871
|
//
// Playlist.swift
// SoundcloudSDK
//
// Created by Kevin DELANNOY on 24/02/15.
// Copyright (c) 2015 Kevin Delannoy. All rights reserved.
//
import Foundation
public struct Playlist {
///Playlist's identifier
public let identifier: Int
///Date of creation
public let createdAt: Date
///Mini user representation of the owner
public let createdBy: User
///Duration
public let duration: TimeInterval
///Streamable via API (This will aggregate the playlists tracks streamable attribute.
///Its value will be false if not all tracks have the same streamable value.)
public let streamable: Bool
///Downloadable (This will aggregate the playlists tracks downloadable attribute.
///Its value will be false if not all tracks have the same downloadable value.)
public let downloadable: Bool
///URL to the SoundCloud.com page
public let permalinkURL: URL?
///External purchase link
public let purchaseURL: URL?
///Release year
public let releaseYear: Int?
///Release month
public let releaseMonth: Int?
///Release day
public let releaseDay: Int?
///Release number
public let releaseNumber: String?
///HTML description
public let description: String?
///Genre
public let genre: String?
///Playlist type
public let type: PlaylistType?
///Track title
public let title: String
///URL to a JPEG image
public let artworkURL: ImageURLs
///Tracks
public let tracks: [Track]
///EAN identifier for the playlist
public let ean: String?
///public/private sharing
public let sharingAccess: SharingAccess
///Identifier of the label user
public let labelIdentifier: Int?
///Label name
public let labelName: String?
///Creative common license
public let license: String?
}
// MARK: Equatable
extension Playlist: Equatable {}
/**
Compares 2 Playlists based on their identifier
- parameter lhs: First playlist
- parameter rhs: Second playlist
- returns: true if playlists are equals, false if they're not
*/
public func ==(lhs: Playlist, rhs: Playlist) -> Bool {
return lhs.identifier == rhs.identifier
}
// MARK: Parsing
extension Playlist {
init?(JSON: JSONObject) {
guard let identifier = JSON["id"].intValue, let user = User(JSON: JSON["user"]), JSON["kind"].stringValue == "playlist" else {
return nil
}
self.identifier = identifier
self.createdAt = JSON["created_at"].dateValue(format: "yyyy/MM/dd HH:mm:ss VVVV") ?? Date()
self.createdBy = user
self.duration = JSON["duration"].doubleValue.map { $0 / 1000 } ?? 0
self.streamable = JSON["streamable"].boolValue ?? false
self.downloadable = JSON["downloadable"].boolValue ?? false
self.permalinkURL = JSON["permalink_url"].urlValue
self.purchaseURL = JSON["purchase_url"].urlValue
self.releaseYear = JSON["release_year"].intValue
self.releaseMonth = JSON["release_month"].intValue
self.releaseDay = JSON["release_day"].intValue
self.releaseNumber = JSON["release"].stringValue
self.description = JSON["description"].stringValue
self.genre = JSON["genre"].stringValue
self.type = PlaylistType(rawValue: JSON["playlist_type"].stringValue ?? "")
self.title = JSON["title"].stringValue ?? ""
self.artworkURL = ImageURLs(baseURL: JSON["artwork_url"].urlValue)
self.tracks = JSON["tracks"].flatMap { Track(JSON: $0) } ?? []
self.ean = JSON["ean"].stringValue
self.sharingAccess = SharingAccess(rawValue: JSON["sharing"].stringValue ?? "") ?? .private
self.labelIdentifier = JSON["label_id"].intValue
self.labelName = JSON["label_name"].stringValue
self.license = JSON["license"].stringValue
}
}
|
mit
|
455c6f6234d6d891d35fe12f0c29233e
| 28.325758 | 134 | 0.663911 | 4.516919 | false | false | false | false |
dfsilva/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Settings/AASettingsWallpapper.swift
|
4
|
2165
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
open class AASettingsWallpapper: AACollectionViewController, UICollectionViewDelegateFlowLayout {
let padding: CGFloat = 8
init() {
super.init(collectionLayout: UICollectionViewFlowLayout())
navigationItem.title = AALocalized("WallpapersTitle")
collectionView.register(AAWallpapperPreviewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.contentInset = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding)
collectionView.backgroundColor = ActorSDK.sharedActor().style.vcBgColor
view.backgroundColor = ActorSDK.sharedActor().style.vcBgColor
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let res = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AAWallpapperPreviewCell
res.bind((indexPath as NSIndexPath).item % 3)
return res
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let w = (collectionView.width - 4 * padding) / 3
let h = w * (UIScreen.main.bounds.height / UIScreen.main.bounds.width)
return CGSize(width: w, height: h)
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return padding
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return padding
}
}
|
agpl-3.0
|
b495fc488adc56c6e61f2ab9bc2e396b
| 41.45098 | 180 | 0.713164 | 5.638021 | false | false | false | false |
yonasstephen/swift-of-airbnb
|
frameworks/airbnb-occupant-filter/airbnb-occupant-filter/AirbnbOccupantFilterController.swift
|
1
|
8332
|
//
// AirbnbOccupantFilterController.swift
// airbnb-occupant-filter
//
// Created by Yonas Stephen on 4/4/17.
// Copyright © 2017 Yonas Stephen. All rights reserved.
//
import UIKit
protocol AirbnbOccupantFilterControllerDelegate {
func occupantFilterController(_ occupantFilterController: AirbnbOccupantFilterController, didSaveAdult adult: Int, children: Int, infant: Int, pet: Bool)
}
class AirbnbOccupantFilterController: UIViewController {
var delegate: AirbnbOccupantFilterControllerDelegate?
var adultCount: Int?
var childrenCount: Int?
var infantCount: Int?
var hasPet: Bool?
var humanCount: Int {
return (adultCount ?? 0) + (childrenCount ?? 0)
}
var maxHumanCount: Int {
return 16 - humanCount
}
lazy var adultCounter: AirbnbCounter = {
let view = AirbnbCounter()
view.translatesAutoresizingMaskIntoConstraints = false
view.fieldID = "adult"
view.delegate = self
view.caption = "Adults"
view.maxCount = self.maxHumanCount
view.minCount = 1
return view
}()
lazy var childrenCounter: AirbnbCounter = {
let view = AirbnbCounter()
view.translatesAutoresizingMaskIntoConstraints = false
view.fieldID = "child"
view.delegate = self
view.caption = "Children"
view.subCaption = "Ages 2 - 12"
view.maxCount = self.maxHumanCount
view.minCount = 0
return view
}()
var infantCounter: AirbnbCounter = {
let view = AirbnbCounter()
view.translatesAutoresizingMaskIntoConstraints = false
view.caption = "Infants"
view.subCaption = "2 & under"
view.maxCount = 5
view.minCount = 0
return view
}()
var petSwitch: AirbnbSwitch = {
let view = AirbnbSwitch()
view.translatesAutoresizingMaskIntoConstraints = false
view.caption = "Pet"
return view
}()
lazy var dismissButton: UIBarButtonItem = {
let btn = UIButton(type: UIButtonType.custom)
btn.setImage(UIImage(named: "Delete", in: Bundle(for: AirbnbOccupantFilter.self), compatibleWith: nil), for: .normal)
btn.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
btn.addTarget(self, action: #selector(AirbnbOccupantFilterController.handleDismiss), for: .touchUpInside)
let barBtn = UIBarButtonItem(customView: btn)
return barBtn
}()
var footerSeparator: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = Theme.SECONDARY_COLOR
return view
}()
lazy var saveButton: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.backgroundColor = Theme.SECONDARY_COLOR
btn.setTitleColor(UIColor.white, for: .normal)
btn.setTitle("Save", for: .normal)
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
btn.addTarget(self, action: #selector(AirbnbOccupantFilterController.handleSave), for: .touchUpInside)
return btn
}()
convenience init(adultCount: Int?, childrenCount: Int?, infantCount: Int?, hasPet: Bool?) {
self.init()
self.adultCount = adultCount
self.childrenCount = childrenCount
self.infantCount = infantCount
self.hasPet = hasPet
adultCounter.count = self.adultCount ?? 1
childrenCounter.count = self.childrenCount ?? 0
infantCounter.count = self.infantCount ?? 0
petSwitch.state = self.hasPet ?? false
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupViews()
}
func setupViews() {
view.backgroundColor = Theme.PRIMARY_COLOR
view.addSubview(adultCounter)
adultCounter.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
adultCounter.heightAnchor.constraint(equalToConstant: 50).isActive = true
adultCounter.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
adultCounter.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
view.addSubview(childrenCounter)
childrenCounter.topAnchor.constraint(equalTo: adultCounter.bottomAnchor, constant: 50).isActive = true
childrenCounter.heightAnchor.constraint(equalToConstant: 50).isActive = true
childrenCounter.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
childrenCounter.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
view.addSubview(infantCounter)
infantCounter.topAnchor.constraint(equalTo: childrenCounter.bottomAnchor, constant: 50).isActive = true
infantCounter.heightAnchor.constraint(equalToConstant: 50).isActive = true
infantCounter.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
infantCounter.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
view.addSubview(petSwitch)
petSwitch.topAnchor.constraint(equalTo: infantCounter.bottomAnchor, constant: 50).isActive = true
petSwitch.heightAnchor.constraint(equalToConstant: 50).isActive = true
petSwitch.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
petSwitch.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
setupFooterView()
}
func setupFooterView() {
view.addSubview(saveButton)
saveButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10).isActive = true
saveButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
saveButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -30).isActive = true
saveButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
view.addSubview(footerSeparator)
footerSeparator.bottomAnchor.constraint(equalTo: saveButton.topAnchor, constant: -10).isActive = true
footerSeparator.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
footerSeparator.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
footerSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true
}
func setupNavigationBar() {
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = UIColor.clear
self.navigationItem.setLeftBarButton(dismissButton, animated: true)
}
@objc func handleDismiss() {
self.navigationController?.dismiss(animated: true, completion: nil)
}
@objc func handleSave() {
if let del = delegate {
adultCount = adultCounter.count
childrenCount = childrenCounter.count
infantCount = infantCounter.count
hasPet = petSwitch.state
del.occupantFilterController(self, didSaveAdult: adultCount ?? 1, children: childrenCount ?? 0, infant: infantCount ?? 0, pet: hasPet ?? false)
dismiss(animated: true, completion: nil)
}
}
}
extension AirbnbOccupantFilterController: AirbnbCounterDelegate {
func counter(_ counter: AirbnbCounter, didUpdate count: Int) {
if counter.fieldID == adultCounter.fieldID {
adultCount = count
updateHumanMaxCount()
} else if counter.fieldID == childrenCounter.fieldID {
childrenCount = count
updateHumanMaxCount()
}
}
func updateHumanMaxCount() {
adultCounter.maxCount = maxHumanCount + (adultCount ?? 0)
childrenCounter.maxCount = maxHumanCount + (childrenCount ?? 0)
}
}
|
mit
|
711db0b225f3cf853cc58e9e56d14a43
| 37.215596 | 157 | 0.668827 | 5.0006 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/CartLineEstimatedCost.swift
|
1
|
6404
|
//
// CartLineEstimatedCost.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// The estimated cost of the merchandise line that the buyer will pay at
/// checkout.
open class CartLineEstimatedCostQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CartLineEstimatedCost
/// The amount of the merchandise line.
@discardableResult
open func amount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartLineEstimatedCostQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "amount", aliasSuffix: alias, subfields: subquery)
return self
}
/// The compare at amount of the merchandise line.
@discardableResult
open func compareAtAmount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartLineEstimatedCostQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "compareAtAmount", aliasSuffix: alias, subfields: subquery)
return self
}
/// The estimated cost of the merchandise line before discounts.
@discardableResult
open func subtotalAmount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartLineEstimatedCostQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "subtotalAmount", aliasSuffix: alias, subfields: subquery)
return self
}
/// The estimated total cost of the merchandise line.
@discardableResult
open func totalAmount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartLineEstimatedCostQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "totalAmount", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// The estimated cost of the merchandise line that the buyer will pay at
/// checkout.
open class CartLineEstimatedCost: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CartLineEstimatedCostQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "amount":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLineEstimatedCost.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
case "compareAtAmount":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLineEstimatedCost.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
case "subtotalAmount":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLineEstimatedCost.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
case "totalAmount":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLineEstimatedCost.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
default:
throw SchemaViolationError(type: CartLineEstimatedCost.self, field: fieldName, value: fieldValue)
}
}
/// The amount of the merchandise line.
open var amount: Storefront.MoneyV2 {
return internalGetAmount()
}
func internalGetAmount(alias: String? = nil) -> Storefront.MoneyV2 {
return field(field: "amount", aliasSuffix: alias) as! Storefront.MoneyV2
}
/// The compare at amount of the merchandise line.
open var compareAtAmount: Storefront.MoneyV2? {
return internalGetCompareAtAmount()
}
func internalGetCompareAtAmount(alias: String? = nil) -> Storefront.MoneyV2? {
return field(field: "compareAtAmount", aliasSuffix: alias) as! Storefront.MoneyV2?
}
/// The estimated cost of the merchandise line before discounts.
open var subtotalAmount: Storefront.MoneyV2 {
return internalGetSubtotalAmount()
}
func internalGetSubtotalAmount(alias: String? = nil) -> Storefront.MoneyV2 {
return field(field: "subtotalAmount", aliasSuffix: alias) as! Storefront.MoneyV2
}
/// The estimated total cost of the merchandise line.
open var totalAmount: Storefront.MoneyV2 {
return internalGetTotalAmount()
}
func internalGetTotalAmount(alias: String? = nil) -> Storefront.MoneyV2 {
return field(field: "totalAmount", aliasSuffix: alias) as! Storefront.MoneyV2
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "amount":
response.append(internalGetAmount())
response.append(contentsOf: internalGetAmount().childResponseObjectMap())
case "compareAtAmount":
if let value = internalGetCompareAtAmount() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "subtotalAmount":
response.append(internalGetSubtotalAmount())
response.append(contentsOf: internalGetSubtotalAmount().childResponseObjectMap())
case "totalAmount":
response.append(internalGetTotalAmount())
response.append(contentsOf: internalGetTotalAmount().childResponseObjectMap())
default:
break
}
}
return response
}
}
}
|
mit
|
2d2c3f67b2df177c9266127cbbd633aa
| 34.776536 | 118 | 0.728763 | 3.955528 | false | false | false | false |
mwolicki/swift-game
|
Space Battle/Rx.swift
|
1
|
2677
|
//
// Created by Marcin Wolicki on 15/03/2016.
// Copyright (c) 2016 Marcin Wolicki. All rights reserved.
//
import Foundation
class HandlerWrapper<T>{
typealias Handler = T -> ()
private let _handler : Handler
init (handler:Handler){
_handler = handler
}
func invoke(arg : T){
_handler(arg)
}
}
class Observable<T> {
init(){
_onDispose = {}
}
private let _onDispose:Dispose
init(onDispose:Dispose){
_onDispose = onDispose
}
typealias Handler = T -> ()
typealias Dispose = () -> ()
private var subscribers = [HandlerWrapper<T>]()
func subscribe(fun: Handler) -> Dispose{
let wrapper = HandlerWrapper(handler: fun)
subscribers.append(wrapper);
return {
self.subscribers = self.subscribers.filter({$0 !== wrapper})
if self.subscribers.count == 0 {
self._onDispose()}
}
}
func set(el: T) {
for s in subscribers {
s.invoke(el)
}
}
}
extension Observable {
func map<R>(mapper: (T -> R)) -> Observable<R> {
var disposer:Dispose = {}
let o = Observable<R>(onDispose: {disposer()})
disposer = self.subscribe({ o.set(mapper($0)) })
return o
}
func iterOnce(fun: (T -> ())) {
self.subscribe({ fun($0) })()
}
func map2<T2, R>(mapper: ((T, T2) -> R), o2: Observable<T2>) -> Observable<R> {
var v1: T? = nil
var v2: T2? = nil
var disposer:Dispose = {}
let o = Observable<R>(onDispose: {disposer()})
let performNext = {
if case .Some(let _v1) = v1 {
if case .Some(let _v2) = v2 {
let val = mapper(_v1, _v2)
o.set(val)
}
}
}
let disposer1 = self.subscribe({ v1 = $0; performNext() })
let disposer2 = o2.subscribe({ v2 = $0; performNext() })
disposer = {disposer1(); disposer2()}
return o
}
func filter(predictor: (T -> Bool)) -> Observable<T> {
var disposer:Dispose = {}
let o = Observable<T>(onDispose: {disposer()})
disposer = self.subscribe({
if predictor($0) {
o.set($0)
}
})
return o
}
func merge(o2: Observable<T>) -> Observable<T> {
var disposer:Dispose = {}
let o = Observable<T>(onDispose: {disposer()})
let disposer1 = self.subscribe({ o.set($0) })
let disposer2 = o2.subscribe({ o.set($0) })
disposer = {disposer1(); disposer2()}
return o
}
}
|
mit
|
1524a1c5bbb9813e588a37b854ece744
| 24.254717 | 83 | 0.503549 | 3.87971 | false | false | false | false |
mparrish91/gifRecipes
|
framework/Model/MediaEmbed.swift
|
1
|
962
|
//
// MediaEmbed.swift
// reddift
//
// Created by sonson on 2015/04/21.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
/**
Media represents the content which is embeded a link.
*/
public struct MediaEmbed {
/// Height of content.
let height: Int
/// Width of content.
let width: Int
/// Information of content.
let content: String
/// Is content scrolled?
let scrolling: Bool
/**
Update each property with JSON object.
- parameter json: JSON object which is included "t2" JSON.
*/
public init (json: JSONDictionary) {
height = json["height"] as? Int ?? 0
width = json["width"] as? Int ?? 0
let tempContent = json["content"] as? String ?? ""
content = tempContent.unescapeHTML
scrolling = json["scrolling"] as? Bool ?? false
}
var string: String {
get {
return "{content=\(content)\nsize=\(width)x\(height)}\n"
}
}
}
|
mit
|
14d2216b737a0fb878c5b34f6136e05c
| 21.857143 | 68 | 0.610417 | 3.779528 | false | false | false | false |
narner/AudioKit
|
Examples/iOS/AnalogSynthX/AnalogSynthX/SMSegmentView/SMAlphaImageSegment.swift
|
1
|
3172
|
//
// SMAlphaImageSegment.swift
// SMSegmentViewController
//
// Created by mlaskowski on 01/10/15.
// Copyright © 2016 si.ma. All rights reserved.
//
import Foundation
import UIKit
open class SMAlphaImageSegment: SMBasicSegment {
// UI Elements
override open var frame: CGRect {
didSet {
self.resetContentFrame()
}
}
open var margin: CGFloat = 5.0 {
didSet {
self.resetContentFrame()
}
}
var vertical = false
open var animationDuration: TimeInterval = 0.5
open var selectedAlpha: CGFloat = 1.0
open var unselectedAlpha: CGFloat = 0.3
open var pressedAlpha: CGFloat = 0.65
internal(set) var imageView: UIImageView = UIImageView()
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(margin: CGFloat,
selectedAlpha: CGFloat,
unselectedAlpha: CGFloat,
pressedAlpha: CGFloat,
image: UIImage?) {
self.margin = margin
self.selectedAlpha = selectedAlpha
self.unselectedAlpha = unselectedAlpha
self.pressedAlpha = pressedAlpha
self.imageView.image = image
self.imageView.alpha = unselectedAlpha
super.init(frame: CGRect.zero)
self.setupUIElements()
}
override open func orientationChangedTo(_ mode: SegmentOrganiseMode) {
self.vertical = mode == .segmentOrganiseVertical
//resetContentFrame(vertical)
}
func setupUIElements() {
self.imageView.contentMode = UIViewContentMode.scaleAspectFit
self.addSubview(self.imageView)
}
// MARK: Update Frame
func resetContentFrame() {
let margin = self.vertical ? (self.margin * 1.5) : self.margin
let imageViewFrame = CGRect(x: margin,
y: margin,
width: self.frame.size.width - margin * 2,
height: self.frame.size.height - margin * 2)
self.imageView.frame = imageViewFrame
}
// MARK: Selections
override func setSelected(_ selected: Bool, inView view: SMBasicSegmentView) {
super.setSelected(selected, inView: view)
if selected {
self.startAnimationToAlpha(self.selectedAlpha)
} else {
self.startAnimationToAlpha(self.unselectedAlpha)
}
}
func startAnimationToAlpha(_ alpha: CGFloat) {
UIView.animate(withDuration: self.animationDuration,
delay: 0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 0.1,
options: .beginFromCurrentState,
animations: { () -> Void in
self.imageView.alpha = alpha
}, completion: nil)
}
// MARK: Handle touch
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if self.isSelected == false {
self.startAnimationToAlpha(self.pressedAlpha)
}
}
}
|
mit
|
a60a8d5def3192e77054288d6bd2428d
| 28.635514 | 84 | 0.596026 | 4.870968 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
Swift/redundant-connection.swift
|
2
|
1114
|
/**
* https://leetcode.com/problems/redundant-connection/
*
*
*/
// Date: Fri Jun 25 16:16:27 PDT 2021
class Solution {
func findRedundantConnection(_ edges: [[Int]]) -> [Int] {
let n = edges.count
var parent: [Int : Int] = [:]
for index in 1 ... n {
parent[index] = index
}
func find(_ x: Int) -> Int {
var x = x
while let p = parent[x], p != x {
x = p
}
return x
}
func union(_ x: Int, _ y: Int) {
let px = find(x)
let py = find(y)
for index in 1 ... n {
if parent[index, default: index] == py {
parent[index] = px
}
}
}
var result = [Int]()
for edge in edges {
let a = edge[0]
let b = edge[1]
if parent[b] != nil, parent[b] == parent[a] {
result = edge
continue
}
union(a, b)
}
return result
}
}
|
mit
|
a88229ad2d2c8df6f1a8c7f6d27c93f7
| 23.23913 | 61 | 0.376122 | 4.156716 | false | false | false | false |
lando2319/ParseLoginExample
|
pleDir/SignInVC.swift
|
1
|
1981
|
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import UIKit
import Parse
class SignInVC: UIViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var errorMessageLabel: UILabel!
@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBAction func passwordResetButton(sender: AnyObject) {
self.performSegueWithIdentifier("passwordResetSegue", sender: self)
}
@IBAction func signUp(sender: AnyObject) {
performSegueWithIdentifier("signUpSegue", sender: self)
}
@IBAction func signIn(sender: AnyObject) {
PFUser.logInWithUsernameInBackground(userNameField.text, password:passwordField.text) {
(user: PFUser?, error: NSError?) -> Void in
if user != nil {
// Do stuff after successful login.
println("you're in")
self.performSegueWithIdentifier("goHomeFromSignIn", sender: self)
} else {
self.errorMessageLabel.text = error!.userInfo?["error"] as? String
// The login failed. Check error to see why.
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.hidden = true
activityIndicator.hidesWhenStopped = true
let backButton = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: navigationController, action: nil)
navigationItem.leftBarButtonItem = backButton
self.title = "Title HERE"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
2351874483f6a7d4430d49f559ce0a4d
| 36.377358 | 129 | 0.667845 | 5.213158 | false | false | false | false |
lkzhao/YetAnotherAnimationLibrary
|
Sources/YetAnotherAnimationLibrary/Solvers/DecaySolver.swift
|
1
|
2089
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct DecaySolver<Value: VectorConvertible>: RK4Solver {
public typealias Vector = Value.Vector
public let damping: Double
public let threshold: Double
public var current: AnimationProperty<Value>!
public var velocity: AnimationProperty<Value>!
public init(damping: Double,
threshold: Double) {
self.damping = damping
self.threshold = threshold
}
public func acceleration(current: Vector, velocity: Vector) -> Vector {
return -damping * velocity
}
public func updateWith(newCurrent: Vector, newVelocity: Vector) -> Bool {
if newVelocity.distance(between: .zero) < threshold {
current.vector = newCurrent
velocity.vector = .zero
return true
} else {
current.vector = newCurrent
velocity.vector = newVelocity
return false
}
}
}
|
mit
|
04330fba9a0b990a82801ff357353f01
| 37.685185 | 80 | 0.701771 | 4.726244 | false | false | false | false |
SusanDoggie/Doggie
|
Sources/DoggieCore/Swift/Policy.swift
|
1
|
1636
|
//
// Policy.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
infix operator =~: ComparisonPrecedence
@_transparent
public func =~ <T: Equatable>(a: T, b: T) -> Bool {
return a == b
}
extension Optional {
@_transparent
public static func =~(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
return rhs ~= lhs
}
}
extension RangeExpression {
@_transparent
public static func =~(lhs: Bound, rhs: Self) -> Bool {
return rhs ~= lhs
}
}
|
mit
|
1c78a886a1e48259b8b0e39fe60591d2
| 33.808511 | 83 | 0.70599 | 4.238342 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
WordPress/Classes/ViewRelated/Notifications/Views/NoteBlockHeaderTableViewCell.swift
|
2
|
2168
|
import Foundation
import WordPressShared.WPStyleGuide
class NoteBlockHeaderTableViewCell: NoteBlockTableViewCell {
// MARK: - Public Properties
var headerTitle: String? {
set {
headerTitleLabel.text = newValue
}
get {
return headerTitleLabel.text
}
}
var attributedHeaderTitle: NSAttributedString? {
set {
headerTitleLabel.attributedText = newValue
}
get {
return headerTitleLabel.attributedText
}
}
var headerDetails: String? {
set {
headerDetailsLabel.text = newValue
}
get {
return headerDetailsLabel.text
}
}
// MARK: - Public Methods
func downloadGravatarWithURL(_ url: URL?) {
if url == gravatarURL {
return
}
let placeholderImage = Style.gravatarPlaceholderImage
let gravatar = url.flatMap { Gravatar($0) }
gravatarImageView.downloadGravatar(gravatar, placeholder: placeholderImage, animate: true)
gravatarURL = url
}
// MARK: - View Methods
override func awakeFromNib() {
super.awakeFromNib()
accessoryType = .disclosureIndicator
backgroundColor = Style.blockBackgroundColor
headerTitleLabel.font = Style.headerTitleBoldFont
headerTitleLabel.textColor = Style.headerTitleColor
headerDetailsLabel.font = Style.headerDetailsRegularFont
headerDetailsLabel.textColor = Style.headerDetailsColor
gravatarImageView.image = Style.gravatarPlaceholderImage
}
// MARK: - Overriden Methods
override func refreshSeparators() {
separatorsView.bottomVisible = true
separatorsView.bottomInsets = UIEdgeInsets.zero
}
// MARK: - Private Alias
fileprivate typealias Style = WPStyleGuide.Notifications
// MARK: - Private
fileprivate var gravatarURL: URL?
// MARK: - IBOutlets
@IBOutlet fileprivate weak var gravatarImageView: UIImageView!
@IBOutlet fileprivate weak var headerTitleLabel: UILabel!
@IBOutlet fileprivate weak var headerDetailsLabel: UILabel!
}
|
gpl-2.0
|
12a857ac8eaf15a05173a62efbee3966
| 26.794872 | 98 | 0.65452 | 5.516539 | false | false | false | false |
grantmagdanz/InupiaqKeyboard
|
Keyboard/Shapes.swift
|
2
|
13936
|
//
// Shapes.swift
// TastyImitationKeyboard
//
// Created by Alexei Baboulevitch on 10/5/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
// TODO: these shapes were traced and as such are erratic and inaccurate; should redo as SVG or PDF
///////////////////
// SHAPE OBJECTS //
///////////////////
class BackspaceShape: Shape {
override func drawCall(color: UIColor) {
drawBackspace(self.bounds, color: color)
}
}
class ShiftShape: Shape {
var withLock: Bool = false {
didSet {
self.overflowCanvas.setNeedsDisplay()
}
}
override func drawCall(color: UIColor) {
drawShift(self.bounds, color: color, withRect: self.withLock)
}
}
class GlobeShape: Shape {
override func drawCall(color: UIColor) {
drawGlobe(self.bounds, color: color)
}
}
class Shape: UIView {
var color: UIColor? {
didSet {
if self.color != nil {
self.overflowCanvas.setNeedsDisplay()
}
}
}
// in case shapes draw out of bounds, we still want them to show
var overflowCanvas: OverflowCanvas!
convenience init() {
self.init(frame: CGRectZero)
}
override required init(frame: CGRect) {
super.init(frame: frame)
self.opaque = false
self.clipsToBounds = false
self.overflowCanvas = OverflowCanvas(shape: self)
self.addSubview(self.overflowCanvas)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var oldBounds: CGRect?
override func layoutSubviews() {
if self.bounds.width == 0 || self.bounds.height == 0 {
return
}
if oldBounds != nil && CGRectEqualToRect(self.bounds, oldBounds!) {
return
}
oldBounds = self.bounds
super.layoutSubviews()
let overflowCanvasSizeRatio = CGFloat(1.25)
let overflowCanvasSize = CGSizeMake(self.bounds.width * overflowCanvasSizeRatio, self.bounds.height * overflowCanvasSizeRatio)
self.overflowCanvas.frame = CGRectMake(
CGFloat((self.bounds.width - overflowCanvasSize.width) / 2.0),
CGFloat((self.bounds.height - overflowCanvasSize.height) / 2.0),
overflowCanvasSize.width,
overflowCanvasSize.height)
self.overflowCanvas.setNeedsDisplay()
}
func drawCall(color: UIColor) { /* override me! */ }
class OverflowCanvas: UIView {
unowned var shape: Shape
init(shape: Shape) {
self.shape = shape
super.init(frame: CGRectZero)
self.opaque = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
CGContextSaveGState(ctx)
let xOffset = (self.bounds.width - self.shape.bounds.width) / CGFloat(2)
let yOffset = (self.bounds.height - self.shape.bounds.height) / CGFloat(2)
CGContextTranslateCTM(ctx, xOffset, yOffset)
self.shape.drawCall(shape.color != nil ? shape.color! : UIColor.blackColor())
CGContextRestoreGState(ctx)
}
}
}
/////////////////////
// SHAPE FUNCTIONS //
/////////////////////
func getFactors(fromSize: CGSize, toRect: CGRect) -> (xScalingFactor: CGFloat, yScalingFactor: CGFloat, lineWidthScalingFactor: CGFloat, fillIsHorizontal: Bool, offset: CGFloat) {
let xSize = { () -> CGFloat in
let scaledSize = (fromSize.width / CGFloat(2))
if scaledSize > toRect.width {
return (toRect.width / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
let ySize = { () -> CGFloat in
let scaledSize = (fromSize.height / CGFloat(2))
if scaledSize > toRect.height {
return (toRect.height / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
let actualSize = min(xSize, ySize)
return (actualSize, actualSize, actualSize, false, 0)
}
func centerShape(fromSize: CGSize, toRect: CGRect) {
let xOffset = (toRect.width - fromSize.width) / CGFloat(2)
let yOffset = (toRect.height - fromSize.height) / CGFloat(2)
let ctx = UIGraphicsGetCurrentContext()
CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, xOffset, yOffset)
}
func endCenter() {
let ctx = UIGraphicsGetCurrentContext()
CGContextRestoreGState(ctx)
}
func drawBackspace(bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSizeMake(44, 32), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSizeMake(44 * xScalingFactor, 32 * yScalingFactor), toRect: bounds)
//// Color Declarations
let color = color
let color2 = UIColor.grayColor() // TODO:
//// Bezier Drawing
let
bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(16 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(44 * xScalingFactor, 26 * yScalingFactor), controlPoint1: CGPointMake(38 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(44 * xScalingFactor, 6 * yScalingFactor), controlPoint1: CGPointMake(44 * xScalingFactor, 22 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 6 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(36 * xScalingFactor, 0 * yScalingFactor), controlPoint1: CGPointMake(44 * xScalingFactor, 6 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 0 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(16 * xScalingFactor, 0 * yScalingFactor), controlPoint1: CGPointMake(32 * xScalingFactor, 0 * yScalingFactor), controlPoint2: CGPointMake(16 * xScalingFactor, 0 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(0 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(16 * xScalingFactor, 32 * yScalingFactor))
bezierPath.closePath()
color.setFill()
bezierPath.fill()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(20 * xScalingFactor, 10 * yScalingFactor))
bezier2Path.addLineToPoint(CGPointMake(34 * xScalingFactor, 22 * yScalingFactor))
bezier2Path.addLineToPoint(CGPointMake(20 * xScalingFactor, 10 * yScalingFactor))
bezier2Path.closePath()
UIColor.grayColor().setFill()
bezier2Path.fill()
color2.setStroke()
bezier2Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.moveToPoint(CGPointMake(20 * xScalingFactor, 22 * yScalingFactor))
bezier3Path.addLineToPoint(CGPointMake(34 * xScalingFactor, 10 * yScalingFactor))
bezier3Path.addLineToPoint(CGPointMake(20 * xScalingFactor, 22 * yScalingFactor))
bezier3Path.closePath()
UIColor.redColor().setFill()
bezier3Path.fill()
color2.setStroke()
bezier3Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier3Path.stroke()
endCenter()
}
func drawShift(bounds: CGRect, color: UIColor, withRect: Bool) {
let factors = getFactors(CGSizeMake(38, (withRect ? 34 + 4 : 32)), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
centerShape(CGSizeMake(38 * xScalingFactor, (withRect ? 34 + 4 : 32) * yScalingFactor), toRect: bounds)
//// Color Declarations
let color2 = color
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(28 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(19 * xScalingFactor, 0 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(0 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(0 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(10 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(10 * xScalingFactor, 28 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(14 * xScalingFactor, 32 * yScalingFactor), controlPoint1: CGPointMake(10 * xScalingFactor, 28 * yScalingFactor), controlPoint2: CGPointMake(10 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(24 * xScalingFactor, 32 * yScalingFactor), controlPoint1: CGPointMake(16 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(24 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(28 * xScalingFactor, 28 * yScalingFactor), controlPoint1: CGPointMake(24 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(28 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(28 * xScalingFactor, 18 * yScalingFactor), controlPoint1: CGPointMake(28 * xScalingFactor, 26 * yScalingFactor), controlPoint2: CGPointMake(28 * xScalingFactor, 18 * yScalingFactor))
bezierPath.closePath()
color2.setFill()
bezierPath.fill()
if withRect {
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRectMake(10 * xScalingFactor, 34 * yScalingFactor, 18 * xScalingFactor, 4 * yScalingFactor))
color2.setFill()
rectanglePath.fill()
}
endCenter()
}
func drawGlobe(bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSizeMake(41, 40), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSizeMake(41 * xScalingFactor, 40 * yScalingFactor), toRect: bounds)
//// Color Declarations
let color = color
//// Oval Drawing
let ovalPath = UIBezierPath(ovalInRect: CGRectMake(0 * xScalingFactor, 0 * yScalingFactor, 40 * xScalingFactor, 40 * yScalingFactor))
color.setStroke()
ovalPath.lineWidth = 1 * lineWidthScalingFactor
ovalPath.stroke()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(20 * xScalingFactor, -0 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(20 * xScalingFactor, 40 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(20 * xScalingFactor, -0 * yScalingFactor))
bezierPath.closePath()
color.setStroke()
bezierPath.lineWidth = 1 * lineWidthScalingFactor
bezierPath.stroke()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(0.5 * xScalingFactor, 19.5 * yScalingFactor))
bezier2Path.addLineToPoint(CGPointMake(39.5 * xScalingFactor, 19.5 * yScalingFactor))
bezier2Path.addLineToPoint(CGPointMake(0.5 * xScalingFactor, 19.5 * yScalingFactor))
bezier2Path.closePath()
color.setStroke()
bezier2Path.lineWidth = 1 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.moveToPoint(CGPointMake(21.63 * xScalingFactor, 0.42 * yScalingFactor))
bezier3Path.addCurveToPoint(CGPointMake(21.63 * xScalingFactor, 39.6 * yScalingFactor), controlPoint1: CGPointMake(21.63 * xScalingFactor, 0.42 * yScalingFactor), controlPoint2: CGPointMake(41 * xScalingFactor, 19 * yScalingFactor))
bezier3Path.lineCapStyle = CGLineCap.Round;
color.setStroke()
bezier3Path.lineWidth = 1 * lineWidthScalingFactor
bezier3Path.stroke()
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.moveToPoint(CGPointMake(17.76 * xScalingFactor, 0.74 * yScalingFactor))
bezier4Path.addCurveToPoint(CGPointMake(18.72 * xScalingFactor, 39.6 * yScalingFactor), controlPoint1: CGPointMake(17.76 * xScalingFactor, 0.74 * yScalingFactor), controlPoint2: CGPointMake(-2.5 * xScalingFactor, 19.04 * yScalingFactor))
bezier4Path.lineCapStyle = CGLineCap.Round;
color.setStroke()
bezier4Path.lineWidth = 1 * lineWidthScalingFactor
bezier4Path.stroke()
//// Bezier 5 Drawing
let bezier5Path = UIBezierPath()
bezier5Path.moveToPoint(CGPointMake(6 * xScalingFactor, 7 * yScalingFactor))
bezier5Path.addCurveToPoint(CGPointMake(34 * xScalingFactor, 7 * yScalingFactor), controlPoint1: CGPointMake(6 * xScalingFactor, 7 * yScalingFactor), controlPoint2: CGPointMake(19 * xScalingFactor, 21 * yScalingFactor))
bezier5Path.lineCapStyle = CGLineCap.Round;
color.setStroke()
bezier5Path.lineWidth = 1 * lineWidthScalingFactor
bezier5Path.stroke()
//// Bezier 6 Drawing
let bezier6Path = UIBezierPath()
bezier6Path.moveToPoint(CGPointMake(6 * xScalingFactor, 33 * yScalingFactor))
bezier6Path.addCurveToPoint(CGPointMake(34 * xScalingFactor, 33 * yScalingFactor), controlPoint1: CGPointMake(6 * xScalingFactor, 33 * yScalingFactor), controlPoint2: CGPointMake(19 * xScalingFactor, 22 * yScalingFactor))
bezier6Path.lineCapStyle = CGLineCap.Round;
color.setStroke()
bezier6Path.lineWidth = 1 * lineWidthScalingFactor
bezier6Path.stroke()
endCenter()
}
|
bsd-3-clause
|
9abc00dddf353a70bf6e29c2676cda30
| 38.367232 | 241 | 0.683266 | 4.364547 | false | false | false | false |
knutigro/AppReviews
|
AppReviews/ReviewCellView.swift
|
1
|
1738
|
//
// ReviewCellView.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-04-12.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import AppKit
import EDStarRating
class ReviewCellView: NSTableCellView {
@IBOutlet weak var starRating: EDStarRating?
private var kvoContext = 0
deinit {
removeObserver(self, forKeyPath: "objectValue", context: &kvoContext)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addObserver(self, forKeyPath: "objectValue", options: .New, context: &kvoContext)
}
override func awakeFromNib() {
super.awakeFromNib()
if let starRating = starRating {
starRating.starImage = NSImage(named: "star")
starRating.starHighlightedImage = NSImage(named: "star-highlighted")
starRating.maxRating = 5
starRating.delegate = self
starRating.horizontalMargin = 5
starRating.displayMode = UInt(EDStarRatingDisplayAccurate)
starRating.rating = 3.5
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &kvoContext {
if let starRating = starRating, objectValue = objectValue as? NSManagedObject {
starRating.bind("rating", toObject: objectValue, withKeyPath: "rating", options: nil)
}
}
else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
}
// MARK: EDStarRatingProtocol
extension ReviewCellView: EDStarRatingProtocol {
}
|
gpl-3.0
|
2e79e0b0b05194445f9990ee08f869f0
| 28.982759 | 156 | 0.635213 | 4.895775 | false | false | false | false |
bradhowes/SynthInC
|
SwiftMIDI/Note.swift
|
1
|
3426
|
// Note.swift
// SynthInC
//
// Created by Brad Howes
// Copyright (c) 2016 Brad Howes. All rights reserved.
import AVFoundation
/**
Generate a textual representation of a MIDI note. For instance, MIDI note 60 is "C4" and 73 is "C#5"
- parameter note: the MIDI note to convert
- returns: the note textual representation
*/
public func noteText(_ note: Int) -> String {
let notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
let octave = (note / 12) - 1
let index = note % 12
return "\(notes[index])\(octave)"
}
// Define some common durations. For reasons lost to me, a quarter note is defined as 480, so a 32nd note would be 60.
// Once we move to the AVFoundation level though, we deal with MusicTimeStamp values which are just Doubles.
// Duration.quarter == 480
// Duration.quarter == MusicTimeStamp(1.0)
public typealias Duration = Int
/// Additional functions for Duration values.
public extension Duration {
/// Calculate a dotted note duration
var dotted: Duration { return self + self / 2 }
/// Obtain a scaled note duration, where 1.0 is a 1/4 note (why?)
var scaled: MusicTimeStamp { return MusicTimeStamp(self) / MusicTimeStamp(480.0) }
/// Obtain a grace note duration
var grace: Duration { return -abs(self / 2) }
static let thirtysecond = 60
static let sixteenth = thirtysecond * 2 // 120
static let eighth = sixteenth * 2 // 240
static let quarter = eighth * 2 // 480
static let half = quarter * 2 // 960
static let whole = half * 2 // 1920
}
/// Enumeration of all of the notes in the "In C" score. The assigned integers are the MIDI note values.
public enum NoteValue : Int {
case re = 0
case G3 = 55
case C4 = 60
case C4s = 61
case D4 = 62
case D4s = 63
case E4 = 64
case F4 = 65
case F4s = 66
case G4 = 67
case G4s = 68
case A4 = 69
case A4s = 70
case B4 = 71
case C5 = 72
case C5s = 73
case D5 = 74
case D5s = 75
case E5 = 76
case F5 = 77
case F5s = 78
case G5 = 79
case G5s = 80
case A5 = 81
case A5s = 82
case B5 = 83
case C6 = 84
}
/**
A note has a pitch and a duration (sustain). Notes make up a `Phrase`.
*/
public struct Note {
let note: NoteValue
let isGraceNote: Bool
let duration: MusicTimeStamp
/**
Initialize new Note instance
- parameter note: the pitch of the note (a value of zero (0) indicates a rest)
- parameter duration: how long the note plays (120 is a sixteenth note)
*/
public init(_ note: NoteValue, _ duration: Duration) {
self.note = note
self.isGraceNote = duration < 0
self.duration = abs(duration.scaled)
}
/**
Obtain the time when this note starts playing
- parameter clock: the current clock time
- parameter slop: random variation to apply to the time
- returns: start time
*/
public func getStartTime(clock: MusicTimeStamp, slop: MusicTimeStamp) -> MusicTimeStamp {
return clock + (isGraceNote ? -duration : slop)
}
/**
Obtain the time when this note stops playing
- parameter clock: the current clock time
- returns: end time
*/
public func getEndTime(clock: MusicTimeStamp) -> MusicTimeStamp {
return isGraceNote ? clock : clock + duration
}
}
|
mit
|
5519994f7aafb152e4068890c9fa4293
| 27.55 | 118 | 0.6223 | 3.858108 | false | false | false | false |
ahumeijun/GeekWeather
|
GeekWeatherTests/CommandLineParserTest.swift
|
1
|
9981
|
//
// CommandLineParserTest.swift
// GeekWeather
//
// Created by 梅俊 on 15/12/16.
// Copyright © 2015年 RangerStudio. All rights reserved.
//
import XCTest
@testable import GeekWeather
class CommandLineParserTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
func testCommandOptionEqula() {
let commandOption1 = CommandOption()
commandOption1.option = "m"
commandOption1.argument = "hello"
let commandOption2 = CommandOption()
commandOption2.option = "m"
commandOption2.argument = "hello"
let commandOption3 = CommandOption()
commandOption3.option = "m"
commandOption3.argument = "world"
let commandOption4 = CommandOption()
commandOption4.option = "n"
commandOption4.argument = "hello"
let commandOption5 = CommandOption()
commandOption5.option = "n"
commandOption5.argument = "world"
let commandOption6 = CommandOption()
commandOption6.option = "n"
commandOption6.argument = "world"
let commandOption7 = CommandOption()
commandOption7.option = "n"
let commandOption8 = CommandOption()
commandOption8.argument = "world"
let commandOption9 = CommandOption()
XCTAssertTrue(commandOption1.isEqual(commandOption2))
XCTAssertFalse(commandOption1.isEqual(commandOption3))
XCTAssertFalse(commandOption3.isEqual(commandOption4))
XCTAssertFalse(commandOption4.isEqual(commandOption5))
XCTAssertTrue(commandOption5.isEqual(commandOption6))
XCTAssertFalse(commandOption6.isEqual(commandOption7))
XCTAssertFalse(commandOption6.isEqual(commandOption8))
XCTAssertFalse(commandOption6.isEqual(commandOption9))
XCTAssertFalse(commandOption7.isEqual(commandOption8))
XCTAssertFalse(commandOption7.isEqual(commandOption9))
XCTAssertFalse(commandOption8.isEqual(commandOption9))
}
func testCommandLineEqual() {
//command option
let commandOption0 = CommandOption()
commandOption0.option = "m"
commandOption0.argument = "hello"
let commandOption1 = CommandOption()
commandOption1.option = "m"
commandOption1.argument = "hello"
let commandOption2 = CommandOption()
commandOption2.option = "m"
commandOption2.argument = "world"
let commandOption3 = CommandOption()
commandOption3.option = "n"
commandOption3.argument = "hello"
let commandOption4 = CommandOption()
commandOption4.option = "n"
commandOption4.argument = "world"
//command line
let commandLine0 = CommandLine()
commandLine0.command = "svn"
commandLine0.appendArgument("commit")
commandLine0.appendOption(commandOption0)
let commandLine1 = CommandLine()
commandLine1.command = "svn"
commandLine1.appendArgument("commit")
commandLine1.appendOption(commandOption0)
let commandLine2 = CommandLine()
commandLine2.command = "svn"
commandLine2.appendArgument("commit")
commandLine2.appendOption(commandOption1)
let commandLine3 = CommandLine()
commandLine3.command = "svn"
commandLine3.appendArgument("commit")
commandLine3.appendOption(commandOption2)
let commandLine4 = CommandLine()
commandLine4.command = "git"
commandLine4.appendArgument("commit")
commandLine4.appendOption(commandOption2)
let commandLine5 = CommandLine()
commandLine5.command = "svn"
commandLine5.appendArgument("log")
commandLine5.appendOption(commandOption2)
let commandLine6 = CommandLine()
commandLine6.command = "git"
commandLine6.appendArgument("log")
commandLine6.appendOption(commandOption3)
let commandLine7 = CommandLine()
commandLine7.command = "svn"
commandLine7.appendArgument("commit")
commandLine7.appendOption(commandOption0)
commandLine7.appendOption(commandOption3);
let commandLine8 = CommandLine()
commandLine8.command = "svn"
commandLine8.appendArgument("commit")
commandLine8.appendOption(commandOption1)
commandLine8.appendOption(commandOption3)
let commandLine9 = CommandLine()
commandLine9.command = "svn"
commandLine9.appendArgument("commit")
commandLine9.appendOption(commandOption2)
commandLine9.appendOption(commandOption4)
let commandLine10 = CommandLine()
commandLine10.command = "svn"
commandLine10.appendArgument("commit")
commandLine10.appendOption(commandOption0)
commandLine10.appendOption(commandOption4)
let commandLine11 = CommandLine()
commandLine11.command = "svn"
commandLine11.appendArgument("commit")
commandLine11.appendOption(commandOption4)
commandLine11.appendOption(commandOption0)
let commandLine12 = CommandLine()
commandLine12.command = "svn"
commandLine12.appendArgument("commit")
commandLine12.appendOption(commandOption3)
commandLine12.appendOption(commandOption1)
XCTAssertTrue(commandLine0.isEqual(commandLine1))
XCTAssertTrue(commandLine1.isEqual(commandLine2))
XCTAssertFalse(commandLine2.isEqual(commandLine3))
XCTAssertFalse(commandLine3.isEqual(commandLine4))
XCTAssertFalse(commandLine4.isEqual(commandLine5))
XCTAssertFalse(commandLine5.isEqual(commandLine6))
XCTAssertFalse(commandLine6.isEqual(commandLine2))
XCTAssertFalse(commandLine0.isEqual(commandLine7))
XCTAssertTrue(commandLine7.isEqual(commandLine8))
XCTAssertFalse(commandLine7.isEqual(commandLine9))
XCTAssertFalse(commandLine7.isEqual(commandLine10))
XCTAssertFalse(commandLine8.isEqual(commandLine9))
XCTAssertFalse(commandLine8.isEqual(commandLine10))
XCTAssertFalse(commandLine9.isEqual(commandLine10))
XCTAssertTrue(commandLine10.isEqual(commandLine11))
XCTAssertTrue(commandLine7.isEqual(commandLine12))
XCTAssertTrue(commandLine12.isEqual(commandLine8))
}
func testParse() {
let commandLine1 : CommandLine = try! CommandLineParser.shareParser.parse("svn commit -m helloworld")!
let commandLine2 : CommandLine = try! CommandLineParser.shareParser.parse("svn commit -m helloworld")!
let commandLine3 : CommandLine = try! CommandLineParser.shareParser.parse("svn commit -m helloworld")!
let commandLine4 : CommandLine = try! CommandLineParser.shareParser.parse("svn commit -m helloworld")!
let commandLine5 : CommandLine = try! CommandLineParser.shareParser.parse("svn commit -m helloworld")!
let commandLine6 : CommandLine = try! CommandLineParser.shareParser.parse("svn -m helloworld commit")!
let commandLine7 : CommandLine = try! CommandLineParser.shareParser.parse("svn commit dir -m hello -n world")!
let commandLine8 : CommandLine = try! CommandLineParser.shareParser.parse("svn commit dir -n world -m hello")!
let commandLine9 : CommandLine = try! CommandLineParser.shareParser.parse("svn commit -m hello dir -n world")!
let commandLine0 : CommandLine = try! CommandLineParser.shareParser.parse("svn -m hello commit dir -n world")!
let commandLine10 : CommandLine = try! CommandLineParser.shareParser.parse("svn cat -vct")!
let commandLine11 : CommandLine = try! CommandLineParser.shareParser.parse("svn -vct cat")!
let commandLine12 : CommandLine = try! CommandLineParser.shareParser.parse("svn cat -v -c -t")!
let commandLine13 : CommandLine = try! CommandLineParser.shareParser.parse("svn cat -vc -t")!
let commandLine14 : CommandLine = try! CommandLineParser.shareParser.parse("svn cat -v -ct")!
let commandLine15 : CommandLine = try! CommandLineParser.shareParser.parse("svn cat -ctv")!
XCTAssertTrue(commandLine1.isEqual(commandLine2))
XCTAssertTrue(commandLine2.isEqual(commandLine3))
XCTAssertTrue(commandLine3.isEqual(commandLine4))
XCTAssertTrue(commandLine4.isEqual(commandLine5))
XCTAssertTrue(commandLine5.isEqual(commandLine6))
XCTAssertTrue(commandLine7.isEqual(commandLine8))
XCTAssertTrue(commandLine7.isEqual(commandLine9))
XCTAssertTrue(commandLine8.isEqual(commandLine9))
XCTAssertTrue(commandLine9.isEqual(commandLine0))
XCTAssertTrue(commandLine10.isEqual(commandLine11))
XCTAssertTrue(commandLine11.isEqual(commandLine12))
XCTAssertTrue(commandLine12.isEqual(commandLine13))
XCTAssertTrue(commandLine13.isEqual(commandLine14))
XCTAssertTrue(commandLine14.isEqual(commandLine15))
}
}
|
apache-2.0
|
5a4138969e412a7d90c47abb57fe84fc
| 39.544715 | 118 | 0.670142 | 4.862994 | false | true | false | false |
sschiau/swift
|
stdlib/public/core/Optional.swift
|
15
|
26698
|
//===----------------------------------------------------------------------===//
//
// 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 that represents either a wrapped value or `nil`, the absence of a
/// value.
///
/// You use the `Optional` type whenever you use optional values, even if you
/// never type the word `Optional`. Swift's type system usually shows the
/// wrapped type's name with a trailing question mark (`?`) instead of showing
/// the full type name. For example, if a variable has the type `Int?`, that's
/// just another way of writing `Optional<Int>`. The shortened form is
/// preferred for ease of reading and writing code.
///
/// The types of `shortForm` and `longForm` in the following code sample are
/// the same:
///
/// let shortForm: Int? = Int("42")
/// let longForm: Optional<Int> = Int("42")
///
/// The `Optional` type is an enumeration with two cases. `Optional.none` is
/// equivalent to the `nil` literal. `Optional.some(Wrapped)` stores a wrapped
/// value. For example:
///
/// let number: Int? = Optional.some(42)
/// let noNumber: Int? = Optional.none
/// print(noNumber == nil)
/// // Prints "true"
///
/// You must unwrap the value of an `Optional` instance before you can use it
/// in many contexts. Because Swift provides several ways to safely unwrap
/// optional values, you can choose the one that helps you write clear,
/// concise code.
///
/// The following examples use this dictionary of image names and file paths:
///
/// let imagePaths = ["star": "/glyphs/star.png",
/// "portrait": "/images/content/portrait.jpg",
/// "spacer": "/images/shared/spacer.gif"]
///
/// Getting a dictionary's value using a key returns an optional value, so
/// `imagePaths["star"]` has type `Optional<String>` or, written in the
/// preferred manner, `String?`.
///
/// Optional Binding
/// ----------------
///
/// To conditionally bind the wrapped value of an `Optional` instance to a new
/// variable, use one of the optional binding control structures, including
/// `if let`, `guard let`, and `switch`.
///
/// if let starPath = imagePaths["star"] {
/// print("The star image is at '\(starPath)'")
/// } else {
/// print("Couldn't find the star image")
/// }
/// // Prints "The star image is at '/glyphs/star.png'"
///
/// Optional Chaining
/// -----------------
///
/// To safely access the properties and methods of a wrapped instance, use the
/// postfix optional chaining operator (postfix `?`). The following example uses
/// optional chaining to access the `hasSuffix(_:)` method on a `String?`
/// instance.
///
/// if imagePaths["star"]?.hasSuffix(".png") == true {
/// print("The star image is in PNG format")
/// }
/// // Prints "The star image is in PNG format"
///
/// Using the Nil-Coalescing Operator
/// ---------------------------------
///
/// Use the nil-coalescing operator (`??`) to supply a default value in case
/// the `Optional` instance is `nil`. Here a default path is supplied for an
/// image that is missing from `imagePaths`.
///
/// let defaultImagePath = "/images/default.png"
/// let heartPath = imagePaths["heart"] ?? defaultImagePath
/// print(heartPath)
/// // Prints "/images/default.png"
///
/// The `??` operator also works with another `Optional` instance on the
/// right-hand side. As a result, you can chain multiple `??` operators
/// together.
///
/// let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath
/// print(shapePath)
/// // Prints "/images/default.png"
///
/// Unconditional Unwrapping
/// ------------------------
///
/// When you're certain that an instance of `Optional` contains a value, you
/// can unconditionally unwrap the value by using the forced
/// unwrap operator (postfix `!`). For example, the result of the failable `Int`
/// initializer is unconditionally unwrapped in the example below.
///
/// let number = Int("42")!
/// print(number)
/// // Prints "42"
///
/// You can also perform unconditional optional chaining by using the postfix
/// `!` operator.
///
/// let isPNG = imagePaths["star"]!.hasSuffix(".png")
/// print(isPNG)
/// // Prints "true"
///
/// Unconditionally unwrapping a `nil` instance with `!` triggers a runtime
/// error.
@frozen
public enum Optional<Wrapped>: ExpressibleByNilLiteral {
// The compiler has special knowledge of Optional<Wrapped>, including the fact
// that it is an `enum` with cases named `none` and `some`.
/// The absence of a value.
///
/// In code, the absence of a value is typically written using the `nil`
/// literal rather than the explicit `.none` enumeration case.
case none
/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
/// Creates an instance that stores the given value.
@_transparent
public init(_ some: Wrapped) { self = .some(some) }
/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `map` method with a closure that returns a non-optional value.
/// This example performs an arithmetic operation on an
/// optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let possibleSquare = possibleNumber.map { $0 * $0 }
/// print(possibleSquare)
/// // Prints "Optional(1764)"
///
/// let noNumber: Int? = nil
/// let noSquare = noNumber.map { $0 * $0 }
/// print(noSquare)
/// // Prints "nil"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable
public func map<U>(
_ transform: (Wrapped) throws -> U
) rethrows -> U? {
switch self {
case .some(let y):
return .some(try transform(y))
case .none:
return .none
}
}
/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `flatMap` method with a closure that returns an optional value.
/// This example performs an arithmetic operation with an optional result on
/// an optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in
/// let (result, overflowed) = x.multipliedReportingOverflow(by: x)
/// return overflowed ? nil : result
/// }
/// print(nonOverflowingSquare)
/// // Prints "Optional(1764)"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable
public func flatMap<U>(
_ transform: (Wrapped) throws -> U?
) rethrows -> U? {
switch self {
case .some(let y):
return try transform(y)
case .none:
return .none
}
}
/// Creates an instance initialized with `nil`.
///
/// Do not call this initializer directly. It is used by the compiler when you
/// initialize an `Optional` instance with a `nil` literal. For example:
///
/// var i: Index? = nil
///
/// In this example, the assignment to the `i` variable calls this
/// initializer behind the scenes.
@_transparent
public init(nilLiteral: ()) {
self = .none
}
/// The wrapped value of this instance, unwrapped without checking whether
/// the instance is `nil`.
///
/// The `unsafelyUnwrapped` property provides the same value as the forced
/// unwrap operator (postfix `!`). However, in optimized builds (`-O`), no
/// check is performed to ensure that the current instance actually has a
/// value. Accessing this property in the case of a `nil` value is a serious
/// programming error and could lead to undefined behavior or a runtime
/// error.
///
/// In debug builds (`-Onone`), the `unsafelyUnwrapped` property has the same
/// behavior as using the postfix `!` operator and triggers a runtime error
/// if the instance is `nil`.
///
/// The `unsafelyUnwrapped` property is recommended over calling the
/// `unsafeBitCast(_:)` function because the property is more restrictive
/// and because accessing the property still performs checking in debug
/// builds.
///
/// - Warning: This property trades safety for performance. Use
/// `unsafelyUnwrapped` only when you are confident that this instance
/// will never be equal to `nil` and only after you've tried using the
/// postfix `!` operator.
@inlinable
public var unsafelyUnwrapped: Wrapped {
@inline(__always)
get {
if let x = self {
return x
}
_debugPreconditionFailure("unsafelyUnwrapped of nil optional")
}
}
/// - Returns: `unsafelyUnwrapped`.
///
/// This version is for internal stdlib use; it avoids any checking
/// overhead for users, even in Debug builds.
@inlinable
internal var _unsafelyUnwrappedUnchecked: Wrapped {
@inline(__always)
get {
if let x = self {
return x
}
_internalInvariantFailure("_unsafelyUnwrappedUnchecked of nil optional")
}
}
}
extension Optional: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
switch self {
case .some(let value):
var result = "Optional("
debugPrint(value, terminator: "", to: &result)
result += ")"
return result
case .none:
return "nil"
}
}
}
extension Optional: CustomReflectable {
public var customMirror: Mirror {
switch self {
case .some(let value):
return Mirror(
self,
children: [ "some": value ],
displayStyle: .optional)
case .none:
return Mirror(self, children: [:], displayStyle: .optional)
}
}
}
@_transparent
public // COMPILER_INTRINSIC
func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer,
_filenameLength: Builtin.Word,
_filenameIsASCII: Builtin.Int1,
_line: Builtin.Word,
_isImplicitUnwrap: Builtin.Int1) {
// Cannot use _preconditionFailure as the file and line info would not be
// printed.
if Bool(_isImplicitUnwrap) {
_preconditionFailure(
"Unexpectedly found nil while implicitly unwrapping an Optional value",
file: StaticString(_start: _filenameStart,
utf8CodeUnitCount: _filenameLength,
isASCII: _filenameIsASCII),
line: UInt(_line))
} else {
_preconditionFailure(
"Unexpectedly found nil while unwrapping an Optional value",
file: StaticString(_start: _filenameStart,
utf8CodeUnitCount: _filenameLength,
isASCII: _filenameIsASCII),
line: UInt(_line))
}
}
extension Optional: Equatable where Wrapped: Equatable {
/// Returns a Boolean value indicating whether two optional instances are
/// equal.
///
/// Use this equal-to operator (`==`) to compare any two optional instances of
/// a type that conforms to the `Equatable` protocol. The comparison returns
/// `true` if both arguments are `nil` or if the two arguments wrap values
/// that are equal. Conversely, the comparison returns `false` if only one of
/// the arguments is `nil` or if the two arguments wrap values that are not
/// equal.
///
/// let group1 = [1, 2, 3, 4, 5]
/// let group2 = [1, 3, 5, 7, 9]
/// if group1.first == group2.first {
/// print("The two groups start the same.")
/// }
/// // Prints "The two groups start the same."
///
/// You can also use this operator to compare a non-optional value to an
/// optional that wraps the same type. The non-optional value is wrapped as an
/// optional before the comparison is made. In the following example, the
/// `numberToMatch` constant is wrapped as an optional before comparing to the
/// optional `numberFromString`:
///
/// let numberToFind: Int = 23
/// let numberFromString: Int? = Int("23") // Optional(23)
/// if numberToFind == numberFromString {
/// print("It's a match!")
/// }
/// // Prints "It's a match!"
///
/// An instance that is expressed as a literal can also be used with this
/// operator. In the next example, an integer literal is compared with the
/// optional integer `numberFromString`. The literal `23` is inferred as an
/// `Int` instance and then wrapped as an optional before the comparison is
/// performed.
///
/// if 23 == numberFromString {
/// print("It's a match!")
/// }
/// // Prints "It's a match!"
///
/// - Parameters:
/// - lhs: An optional value to compare.
/// - rhs: Another optional value to compare.
@inlinable
public static func ==(lhs: Wrapped?, rhs: Wrapped?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l == r
case (nil, nil):
return true
default:
return false
}
}
}
extension Optional: Hashable where Wrapped: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
switch self {
case .none:
hasher.combine(0 as UInt8)
case .some(let wrapped):
hasher.combine(1 as UInt8)
hasher.combine(wrapped)
}
}
}
// Enable pattern matching against the nil literal, even if the element type
// isn't equatable.
@frozen
public struct _OptionalNilComparisonType: ExpressibleByNilLiteral {
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
}
}
extension Optional {
/// Returns a Boolean value indicating whether an argument matches `nil`.
///
/// You can use the pattern-matching operator (`~=`) to test whether an
/// optional instance is `nil` even when the wrapped value's type does not
/// conform to the `Equatable` protocol. The pattern-matching operator is used
/// internally in `case` statements for pattern matching.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type, and then uses a `switch`
/// statement to determine whether the stream is `nil` or has a configured
/// value. When evaluating the `nil` case of the `switch` statement, this
/// operator is called behind the scenes.
///
/// var stream: DataStream? = nil
/// switch stream {
/// case nil:
/// print("No data stream is configured.")
/// case let x?:
/// print("The data stream has \(x.availableBytes) bytes available.")
/// }
/// // Prints "No data stream is configured."
///
/// - Note: To test whether an instance is `nil` in an `if` statement, use the
/// equal-to operator (`==`) instead of the pattern-matching operator. The
/// pattern-matching operator is primarily intended to enable `case`
/// statement pattern matching.
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to match against `nil`.
@_transparent
public static func ~=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return false
case .none:
return true
}
}
// Enable equality comparisons against the nil literal, even if the
// element type isn't equatable
/// Returns a Boolean value indicating whether the left-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if stream == nil {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
@_transparent
public static func ==(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some:
return false
case .none:
return true
}
}
/// Returns a Boolean value indicating whether the left-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if stream != nil {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
@_transparent
public static func !=(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some:
return true
case .none:
return false
}
}
/// Returns a Boolean value indicating whether the right-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if nil == stream {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
@_transparent
public static func ==(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return false
case .none:
return true
}
}
/// Returns a Boolean value indicating whether the right-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if nil != stream {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
@_transparent
public static func !=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return true
case .none:
return false
}
}
}
/// Performs a nil-coalescing operation, returning the wrapped value of an
/// `Optional` instance or a default value.
///
/// A nil-coalescing operation unwraps the left-hand side if it has a value, or
/// it returns the right-hand side as a default. The result of this operation
/// will have the non-optional type of the left-hand side's `Wrapped` type.
///
/// This operator uses short-circuit evaluation: `optional` is checked first,
/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:
///
/// func getDefault() -> Int {
/// print("Calculating default...")
/// return 42
/// }
///
/// let goodNumber = Int("100") ?? getDefault()
/// // goodNumber == 100
///
/// let notSoGoodNumber = Int("invalid-input") ?? getDefault()
/// // Prints "Calculating default..."
/// // notSoGoodNumber == 42
///
/// In this example, `goodNumber` is assigned a value of `100` because
/// `Int("100")` succeeded in returning a non-`nil` result. When
/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns
/// `nil`, and so the `getDefault()` method is called to supply a default
/// value.
///
/// - Parameters:
/// - optional: An optional value.
/// - defaultValue: A value to use as a default. `defaultValue` is the same
/// type as the `Wrapped` type of `optional`.
@_transparent
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T)
rethrows -> T {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
/// Performs a nil-coalescing operation, returning the wrapped value of an
/// `Optional` instance or a default `Optional` value.
///
/// A nil-coalescing operation unwraps the left-hand side if it has a value, or
/// returns the right-hand side as a default. The result of this operation
/// will be the same type as its arguments.
///
/// This operator uses short-circuit evaluation: `optional` is checked first,
/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:
///
/// let goodNumber = Int("100") ?? Int("42")
/// print(goodNumber)
/// // Prints "Optional(100)"
///
/// let notSoGoodNumber = Int("invalid-input") ?? Int("42")
/// print(notSoGoodNumber)
/// // Prints "Optional(42)"
///
/// In this example, `goodNumber` is assigned a value of `100` because
/// `Int("100")` succeeds in returning a non-`nil` result. When
/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns
/// `nil`, and so `Int("42")` is called to supply a default value.
///
/// Because the result of this nil-coalescing operation is itself an optional
/// value, you can chain default values by using `??` multiple times. The
/// first optional value that isn't `nil` stops the chain and becomes the
/// result of the whole expression. The next example tries to find the correct
/// text for a greeting in two separate dictionaries before falling back to a
/// static default.
///
/// let greeting = userPrefs[greetingKey] ??
/// defaults[greetingKey] ?? "Greetings!"
///
/// If `userPrefs[greetingKey]` has a value, that value is assigned to
/// `greeting`. If not, any value in `defaults[greetingKey]` will succeed, and
/// if not that, `greeting` will be set to the non-optional default value,
/// `"Greetings!"`.
///
/// - Parameters:
/// - optional: An optional value.
/// - defaultValue: A value to use as a default. `defaultValue` and
/// `optional` have the same type.
@_transparent
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?)
rethrows -> T? {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
//===----------------------------------------------------------------------===//
// Bridging
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
extension Optional: _ObjectiveCBridgeable {
// The object that represents `none` for an Optional of this type.
internal static var _nilSentinel: AnyObject {
@_silgen_name("_swift_Foundation_getOptionalNilSentinelObject")
get
}
public func _bridgeToObjectiveC() -> AnyObject {
// Bridge a wrapped value by unwrapping.
if let value = self {
return _bridgeAnythingToObjectiveC(value)
}
// Bridge nil using a sentinel.
return type(of: self)._nilSentinel
}
public static func _forceBridgeFromObjectiveC(
_ source: AnyObject,
result: inout Optional<Wrapped>?
) {
// Map the nil sentinel back to .none.
// NB that the signature of _forceBridgeFromObjectiveC adds another level
// of optionality, so we need to wrap the immediate result of the conversion
// in `.some`.
if source === _nilSentinel {
result = .some(.none)
return
}
// Otherwise, force-bridge the underlying value.
let unwrappedResult = source as! Wrapped
result = .some(.some(unwrappedResult))
}
public static func _conditionallyBridgeFromObjectiveC(
_ source: AnyObject,
result: inout Optional<Wrapped>?
) -> Bool {
// Map the nil sentinel back to .none.
// NB that the signature of _forceBridgeFromObjectiveC adds another level
// of optionality, so we need to wrap the immediate result of the conversion
// in `.some` to indicate success of the bridging operation, with a nil
// result.
if source === _nilSentinel {
result = .some(.none)
return true
}
// Otherwise, try to bridge the underlying value.
if let unwrappedResult = source as? Wrapped {
result = .some(.some(unwrappedResult))
return true
} else {
result = .none
return false
}
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> Optional<Wrapped> {
if let nonnullSource = source {
// Map the nil sentinel back to none.
if nonnullSource === _nilSentinel {
return .none
} else {
return .some(nonnullSource as! Wrapped)
}
} else {
// If we unexpectedly got nil, just map it to `none` too.
return .none
}
}
}
#endif
|
apache-2.0
|
e3c65b639c405ca22d210933becb53a9
| 34.597333 | 82 | 0.628549 | 4.308909 | false | false | false | false |
zapdroid/RXWeather
|
Pods/Alamofire/Source/SessionManager.swift
|
1
|
38090
|
//
// SessionManager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
open class SessionManager {
// MARK: - Helper Types
/// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
/// associated values.
///
/// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with
/// streaming information.
/// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
/// error.
public enum MultipartFormDataEncodingResult {
case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?)
case failure(Error)
}
// MARK: - Properties
/// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use
/// directly for any ad hoc requests.
open static let `default`: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
/// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
open static let defaultHTTPHeaders: HTTPHeaders = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joined(separator: ", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`
let userAgent: String = {
if let info = Bundle.main.infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(macOS)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion: String = {
guard
let afInfo = Bundle(for: SessionManager.self).infoDictionary,
let build = afInfo["CFBundleShortVersionString"]
else { return "Unknown" }
return "Alamofire/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent,
]
}()
/// Default memory threshold used when encoding `MultipartFormData` in bytes.
open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000
/// The underlying session.
open let session: URLSession
/// The session delegate handling all the task and session delegate callbacks.
open let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
open var startRequestsImmediately: Bool = true
/// The request adapter called each time a new request is created.
open var adapter: RequestAdapter?
/// The request retrier called each time a request encounters an error to determine whether to retry the request.
open var retrier: RequestRetrier? {
get { return delegate.retrier }
set { delegate.retrier = newValue }
}
/// The background completion handler closure provided by the UIApplicationDelegate
/// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
/// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
/// will automatically call the handler.
///
/// If you need to handle your own events before the handler is called, then you need to override the
/// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
///
/// `nil` by default.
open var backgroundCompletionHandler: (() -> Void)?
let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString)
// MARK: - Lifecycle
/// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter configuration: The configuration used to construct the managed session.
/// `URLSessionConfiguration.default` by default.
/// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
/// default.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance.
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil) {
self.delegate = delegate
session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter session: The URL session.
/// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise.
public init?(
session: URLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil) {
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionManager = self
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] _ in
guard let strongSelf = self else { return }
DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Data Request
/// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding`
/// and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `DataRequest`.
@discardableResult
open func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest {
var originalRequest: URLRequest?
do {
originalRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)
return request(encodedURLRequest)
} catch {
return request(originalRequest, failedWith: error)
}
}
/// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `DataRequest`.
open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
var originalRequest: URLRequest?
do {
originalRequest = try urlRequest.asURLRequest()
let originalTask = DataRequest.Requestable(urlRequest: originalRequest!)
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
let request = DataRequest(session: session, requestTask: .data(originalTask, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return request(originalRequest, failedWith: error)
}
}
// MARK: Private - Request Implementation
private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest {
var requestTask: Request.RequestTask = .data(nil, nil)
if let urlRequest = urlRequest {
let originalTask = DataRequest.Requestable(urlRequest: urlRequest)
requestTask = .data(originalTask, nil)
}
let underlyingError = error.underlyingAdaptError ?? error
let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError)
if let retrier = retrier, error is AdaptError {
allowRetrier(retrier, toRetry: request, with: underlyingError)
} else {
if startRequestsImmediately { request.resume() }
}
return request
}
// MARK: - Download Request
// MARK: URL Request
/// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`,
/// `headers` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest {
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return download(encodedURLRequest, to: destination)
} catch {
return download(nil, to: destination, failedWith: error)
}
}
/// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save
/// them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ urlRequest: URLRequestConvertible,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return download(.request(urlRequest), to: destination)
} catch {
return download(nil, to: destination, failedWith: error)
}
}
// MARK: Resume Data
/// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve
/// the contents of the original request and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken
/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the
/// data is written incorrectly and will always fail to resume the download. For more information about the bug and
/// possible workarounds, please refer to the following Stack Overflow post:
///
/// - http://stackoverflow.com/a/39347461/1342462
///
/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for
/// additional information.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
resumingWith resumeData: Data,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest {
return download(.resumeData(resumeData), to: destination)
}
// MARK: Private - Download Implementation
private func download(
_ downloadable: DownloadRequest.Downloadable,
to destination: DownloadRequest.DownloadFileDestination?)
-> DownloadRequest {
do {
let task = try downloadable.task(session: session, adapter: adapter, queue: queue)
let download = DownloadRequest(session: session, requestTask: .download(downloadable, task))
download.downloadDelegate.destination = destination
delegate[task] = download
if startRequestsImmediately { download.resume() }
return download
} catch {
return download(downloadable, to: destination, failedWith: error)
}
}
private func download(
_ downloadable: DownloadRequest.Downloadable?,
to destination: DownloadRequest.DownloadFileDestination?,
failedWith error: Error)
-> DownloadRequest {
var downloadTask: Request.RequestTask = .download(nil, nil)
if let downloadable = downloadable {
downloadTask = .download(downloadable, nil)
}
let underlyingError = error.underlyingAdaptError ?? error
let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError)
download.downloadDelegate.destination = destination
if let retrier = retrier, error is AdaptError {
allowRetrier(retrier, toRetry: download, with: underlyingError)
} else {
if startRequestsImmediately { download.resume() }
}
return download
}
// MARK: - Upload Request
// MARK: File
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ fileURL: URL,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest {
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(fileURL, with: urlRequest)
} catch {
return upload(nil, failedWith: error)
}
}
/// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.file(fileURL, urlRequest))
} catch {
return upload(nil, failedWith: error)
}
}
// MARK: Data
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ data: Data,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest {
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(data, with: urlRequest)
} catch {
return upload(nil, failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.data(data, urlRequest))
} catch {
return upload(nil, failedWith: error)
}
}
// MARK: InputStream
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest {
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(stream, with: urlRequest)
} catch {
return upload(nil, failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.stream(stream, urlRequest))
} catch {
return upload(nil, failedWith: error)
}
}
// MARK: MultipartFormData
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `url`, `method` and `headers`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) {
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
with: urlRequest,
encodingCompletion: encodingCompletion
)
} catch {
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `urlRequest`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter urlRequest: The URL request.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
with urlRequest: URLRequestConvertible,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) {
DispatchQueue.global(qos: .utility).async {
let formData = MultipartFormData()
multipartFormData(formData)
var tempFileURL: URL?
do {
var urlRequestWithContentType = try urlRequest.asURLRequest()
urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
let isBackgroundSession = self.session.configuration.identifier != nil
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
let data = try formData.encode()
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(data, with: urlRequestWithContentType),
streamingFromDisk: false,
streamFileURL: nil
)
DispatchQueue.main.async { encodingCompletion?(encodingResult) }
} else {
let fileManager = FileManager.default
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
tempFileURL = fileURL
var directoryError: Error?
// Create directory inside serial queue to ensure two threads don't do this in parallel
self.queue.sync {
do {
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
directoryError = error
}
}
if let directoryError = directoryError { throw directoryError }
try formData.writeEncodedData(to: fileURL)
let upload = self.upload(fileURL, with: urlRequestWithContentType)
// Cleanup the temp file once the upload is complete
upload.delegate.queue.addOperation {
do {
try FileManager.default.removeItem(at: fileURL)
} catch {
// No-op
}
}
DispatchQueue.main.async {
let encodingResult = MultipartFormDataEncodingResult.success(
request: upload,
streamingFromDisk: true,
streamFileURL: fileURL
)
encodingCompletion?(encodingResult)
}
}
} catch {
// Cleanup the temp file in the event that the multipart form data encoding failed
if let tempFileURL = tempFileURL {
do {
try FileManager.default.removeItem(at: tempFileURL)
} catch {
// No-op
}
}
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
}
// MARK: Private - Upload Implementation
private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest {
do {
let task = try uploadable.task(session: session, adapter: adapter, queue: queue)
let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task))
if case let .stream(inputStream, _) = uploadable {
upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream }
}
delegate[task] = upload
if startRequestsImmediately { upload.resume() }
return upload
} catch {
return upload(uploadable, failedWith: error)
}
}
private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest {
var uploadTask: Request.RequestTask = .upload(nil, nil)
if let uploadable = uploadable {
uploadTask = .upload(uploadable, nil)
}
let underlyingError = error.underlyingAdaptError ?? error
let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError)
if let retrier = retrier, error is AdaptError {
allowRetrier(retrier, toRetry: upload, with: underlyingError)
} else {
if startRequestsImmediately { upload.resume() }
}
return upload
}
#if !os(watchOS)
// MARK: - Stream Request
// MARK: Hostname and Port
/// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter hostName: The hostname of the server to connect to.
/// - parameter port: The port of the server to connect to.
///
/// - returns: The created `StreamRequest`.
@discardableResult
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open func stream(withHostName hostName: String, port: Int) -> StreamRequest {
return stream(.stream(hostName: hostName, port: port))
}
// MARK: NetService
/// Creates a `StreamRequest` for bidirectional streaming using the `netService`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter netService: The net service used to identify the endpoint.
///
/// - returns: The created `StreamRequest`.
@discardableResult
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open func stream(with netService: NetService) -> StreamRequest {
return stream(.netService(netService))
}
// MARK: Private - Stream Implementation
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest {
do {
let task = try streamable.task(session: session, adapter: adapter, queue: queue)
let request = StreamRequest(session: session, requestTask: .stream(streamable, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return stream(failedWith: error)
}
}
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
private func stream(failedWith error: Error) -> StreamRequest {
let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error)
if startRequestsImmediately { stream.resume() }
return stream
}
#endif
// MARK: - Internal - Retry Request
func retry(_ request: Request) -> Bool {
guard let originalTask = request.originalTask else { return false }
do {
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
request.delegate.task = task // resets all task delegate data
request.retryCount += 1
request.startTime = CFAbsoluteTimeGetCurrent()
request.endTime = nil
task.resume()
return true
} catch {
request.delegate.error = error.underlyingAdaptError ?? error
return false
}
}
private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) {
DispatchQueue.utility.async { [weak self] in
guard let strongSelf = self else { return }
retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in
guard let strongSelf = self else { return }
guard shouldRetry else {
if strongSelf.startRequestsImmediately { request.resume() }
return
}
DispatchQueue.utility.after(timeDelay) {
guard let strongSelf = self else { return }
let retrySucceeded = strongSelf.retry(request)
if retrySucceeded, let task = request.task {
strongSelf.delegate[task] = request
} else {
if strongSelf.startRequestsImmediately { request.resume() }
}
}
}
}
}
}
|
mit
|
c7f971966c1788e783b4c77bb19980ed
| 42.382688 | 129 | 0.622027 | 5.446875 | false | false | false | false |
che1404/RGViperChat
|
vipergenTemplate/che1404/swift/Presenter/VIPERPresenterSpec.swift
|
1
|
1164
|
//
// Created by AUTHOR
// Copyright (c) YEAR AUTHOR. All rights reserved.
//
import Quick
import Nimble
import Cuckoo
@testable import ProjectName
class VIPERPresenterSpec: QuickSpec {
var presenter: VIPERPresenter!
var mockView: MockVIPERViewProtocol!
var mockWireframe: MockVIPERWireframeProtocol!
var mockInteractor: MockVIPERInteractorInputProtocol!
override func spec() {
beforeEach {
self.mockInteractor = MockVIPERInteractorInputProtocol()
self.mockView = MockVIPERViewProtocol()
self.mockWireframe = MockVIPERWireframeProtocol()
self.presenter = VIPERPresenter()
self.presenter.view = self.mockView
self.presenter.wireframe = self.mockWireframe
self.presenter.interactor = self.mockInteractor
}
it("Todo") {
}
afterEach {
self.mockInteractor = nil
self.mockView = nil
self.mockWireframe = nil
self.presenter.view = nil
self.presenter.wireframe = nil
self.presenter.interactor = nil
self.presenter = nil
}
}
}
|
mit
|
d2f4f4a6d73b42a395fe1488c3647998
| 26.714286 | 68 | 0.63488 | 5.082969 | false | false | false | false |
Jnosh/swift
|
test/IDE/coloring.swift
|
1
|
23505
|
// RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s
// RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s
// XFAIL: broken_std_regex
#line 17 "abc.swift"
// CHECK: <kw>#line</kw> <int>17</int> <str>"abc.swift"</str>
@available(iOS 8.0, OSX 10.10, *)
// CHECK: <attr-builtin>@available</attr-builtin>(<kw>iOS</kw> <float>8.0</float>, <kw>OSX</kw> <float>10.10</float>, *)
func foo() {
// CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> <float>10.10</float>, <kw>iOS</kw> <float>8.01</float>, *) {<kw>let</kw> <kw>_</kw> = <str>"iOS"</str>}
if #available (OSX 10.10, iOS 8.01, *) {let _ = "iOS"}
}
enum List<T> {
case Nil
// rdar://21927124
// CHECK: <attr-builtin>indirect</attr-builtin> <kw>case</kw> Cons(T, List)
indirect case Cons(T, List)
}
// CHECK: <kw>struct</kw> S {
struct S {
// CHECK: <kw>var</kw> x : <type>Int</type>
var x : Int
// CHECK: <kw>var</kw> y : <type>Int</type>.<type>Int</type>
var y : Int.Int
// CHECK: <kw>var</kw> a, b : <type>Int</type>
var a, b : Int
}
enum EnumWithDerivedEquatableConformance : Int {
// CHECK-LABEL: <kw>enum</kw> EnumWithDerivedEquatableConformance : {{(<type>)}}Int{{(</type>)?}} {
case CaseA
// CHECK-NEXT: <kw>case</kw> CaseA
case CaseB, CaseC
// CHECK-NEXT: <kw>case</kw> CaseB, CaseC
case CaseD = 30, CaseE
// CHECK-NEXT: <kw>case</kw> CaseD = <int>30</int>, CaseE
}
// CHECK-NEXT: }
// CHECK: <kw>class</kw> MyCls {
class MyCls {
// CHECK: <kw>var</kw> www : <type>Int</type>
var www : Int
// CHECK: <kw>func</kw> foo(x: <type>Int</type>) {}
func foo(x: Int) {}
// CHECK: <kw>var</kw> aaa : <type>Int</type> {
var aaa : Int {
// CHECK: <kw>get</kw> {}
get {}
// CHECK: <kw>set</kw> {}
set {}
}
// CHECK: <kw>var</kw> bbb : <type>Int</type> {
var bbb : Int {
// CHECK: <kw>set</kw> {
set {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
}
// CHECK: <kw>subscript</kw> (i : <type>Int</type>, j : <type>Int</type>) -> <type>Int</type> {
subscript (i : Int, j : Int) -> Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> i + j
return i + j
}
// CHECK: <kw>set</kw>(v) {
set(v) {
// CHECK: v + i - j
v + i - j
}
}
// CHECK: <kw>func</kw> multi(<kw>_</kw> name: <type>Int</type>, otherpart x: <type>Int</type>) {}
func multi(_ name: Int, otherpart x: Int) {}
}
// CHECK-LABEL: <kw>class</kw> Attributes {
class Attributes {
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v0: <type>Int</type>
@IBOutlet var v0: Int
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-id>@IBOutlet</attr-id> <kw>var</kw> {{(<attr-builtin>)?}}v1{{(</attr-builtin>)?}}: <type>String</type>
@IBOutlet @IBOutlet var v1: String
// CHECK: <attr-builtin>@objc</attr-builtin> <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v2{{(</attr-builtin>)?}}: <type>String</type>
@objc @IBOutlet var v2: String
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-builtin>@objc</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v3{{(</attr-builtin>)?}}: <type>String</type>
@IBOutlet @objc var v3: String
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f1() {}
@available(*, unavailable) func f1() {}
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@IBAction</attr-builtin> <kw>func</kw> f2() {}
@available(*, unavailable) @IBAction func f2() {}
// CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f3() {}
@IBAction @available(*, unavailable) func f3() {}
// CHECK: <attr-builtin>mutating</attr-builtin> <kw>func</kw> func_mutating_1() {}
mutating func func_mutating_1() {}
// CHECK: <attr-builtin>nonmutating</attr-builtin> <kw>func</kw> func_mutating_2() {}
nonmutating func func_mutating_2() {}
}
func stringLikeLiterals() {
// CHECK: <kw>var</kw> us1: <type>UnicodeScalar</type> = <str>"a"</str>
var us1: UnicodeScalar = "a"
// CHECK: <kw>var</kw> us2: <type>UnicodeScalar</type> = <str>"ы"</str>
var us2: UnicodeScalar = "ы"
// CHECK: <kw>var</kw> ch1: <type>Character</type> = <str>"a"</str>
var ch1: Character = "a"
// CHECK: <kw>var</kw> ch2: <type>Character</type> = <str>"あ"</str>
var ch2: Character = "あ"
// CHECK: <kw>var</kw> s1 = <str>"abc абвгд あいうえお"</str>
var s1 = "abc абвгд あいうえお"
}
// CHECK: <kw>var</kw> globComp : <type>Int</type>
var globComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> <int>0</int>
return 0
}
}
// CHECK: <comment-block>/* foo is the best */</comment-block>
/* foo is the best */
// CHECK: <kw>func</kw> foo(n: <type>Float</type>) -> <type>Int</type> {
func foo(n: Float) -> Int {
// CHECK: <kw>var</kw> fnComp : <type>Int</type>
var fnComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> a: <type>Int</type>
// CHECK: <kw>return</kw> <int>0</int>
var a: Int
return 0
}
}
// CHECK: <kw>var</kw> q = {{(<type>)?}}MyCls{{(</type>)?}}()
var q = MyCls()
// CHECK: <kw>var</kw> ee = <str>"yoo"</str>;
var ee = "yoo";
// CHECK: <kw>return</kw> <int>100009</int>
return 100009
}
///- returns: single-line, no space
// CHECK: ///- <doc-comment-field>returns</doc-comment-field>: single-line, no space
/// - returns: single-line, 1 space
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 1 space
/// - returns: single-line, 2 spaces
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 2 spaces
/// - returns: single-line, more spaces
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, more spaces
// CHECK: <kw>protocol</kw> Prot {
protocol Prot {
// CHECK: <kw>typealias</kw> Blarg
typealias Blarg
// CHECK: <kw>func</kw> protMeth(x: <type>Int</type>)
func protMeth(x: Int)
// CHECK: <kw>var</kw> protocolProperty1: <type>Int</type> { <kw>get</kw> }
var protocolProperty1: Int { get }
// CHECK: <kw>var</kw> protocolProperty2: <type>Int</type> { <kw>get</kw> <kw>set</kw> }
var protocolProperty2: Int { get set }
}
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-* : FunnyPrecedence{{$}}
infix operator *-* : FunnyPrecedence
// CHECK: <kw>precedencegroup</kw> FunnyPrecedence
// CHECK-NEXT: <kw>associativity</kw>: left{{$}}
// CHECK-NEXT: <kw>higherThan</kw>: MultiplicationPrecedence
precedencegroup FunnyPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}
// CHECK: <kw>func</kw> *-*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-+* : FunnyPrecedence
infix operator *-+* : FunnyPrecedence
// CHECK: <kw>func</kw> *-+*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-+*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *--*{{$}}
infix operator *--*
// CHECK: <kw>func</kw> *--*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *--*(l: Int, r: Int) -> Int { return l }
// CHECK: <kw>protocol</kw> Prot2 : <type>Prot</type> {}
protocol Prot2 : Prot {}
// CHECK: <kw>class</kw> SubCls : <type>MyCls</type>, <type>Prot</type> {}
class SubCls : MyCls, Prot {}
// CHECK: <kw>func</kw> genFn<T : <type>Prot</type> <kw>where</kw> <type>T</type>.<type>Blarg</type> : <type>Prot2</type>>(<kw>_</kw>: <type>T</type>) -> <type>Int</type> {}{{$}}
func genFn<T : Prot where T.Blarg : Prot2>(_: T) -> Int {}
func f(x: Int) -> Int {
// CHECK: <comment-line>// string interpolation is the best</comment-line>
// string interpolation is the best
// CHECK: <str>"This is string </str>\<anchor>(</anchor>genFn({(a:<type>Int</type> -> <type>Int</type>) <kw>in</kw> a})<anchor>)</anchor><str> interpolation"</str>
"This is string \(genFn({(a:Int -> Int) in a})) interpolation"
// CHECK: <str>"This is unterminated</str>
"This is unterminated
// CHECK: <str>"This in unterminated with ignored \( "interpolation" ) in it</str>
"This in unterminated with ignored \( "interpolation" ) in it
// CHECK: <str>"This is terminated with \( invalid interpolation" + "in it"</str>
"This is terminated with \( invalid interpolation" + "in it"
// CHECK: <str>"""
// CHECK-NEXT: This is a multiline string.
// CHECK-NEXT: """</str>
"""
This is a multiline string.
"""
// CHECK: <str>"""
// CHECK-NEXT: This is a multiline</str>\<anchor>(</anchor> <str>"interpolated"</str> <anchor>)</anchor><str>string
// CHECK-NEXT: </str>\<anchor>(</anchor>
// CHECK-NEXT: <str>"inner"</str>
// CHECK-NEXT: <anchor>)</anchor><str>
// CHECK-NEXT: """</str>
"""
This is a multiline\( "interpolated" )string
\(
"inner"
)
"""
}
// CHECK: <kw>func</kw> bar(x: <type>Int</type>) -> (<type>Int</type>, <type>Float</type>) {
func bar(x: Int) -> (Int, Float) {
// CHECK: foo({{(<type>)?}}Float{{(</type>)?}}())
foo(Float())
}
class GenC<T1,T2> {}
func test() {
// CHECK: {{(<type>)?}}GenC{{(</type>)?}}<<type>Int</type>, <type>Float</type>>()
var x = GenC<Int, Float>()
}
// CHECK: <kw>typealias</kw> MyInt = <type>Int</type>
typealias MyInt = Int
func test2(x: Int) {
// CHECK: <str>"</str>\<anchor>(</anchor>x<anchor>)</anchor><str>"</str>
"\(x)"
}
// CHECK: <kw>class</kw> Observers {
class Observers {
// CHECK: <kw>var</kw> p1 : <type>Int</type> {
var p1 : Int {
// CHECK: <kw>willSet</kw>(newValue) {}
willSet(newValue) {}
// CHECK: <kw>didSet</kw> {}
didSet {}
}
// CHECK: <kw>var</kw> p2 : <type>Int</type> {
var p2 : Int {
// CHECK: <kw>didSet</kw> {}
didSet {}
// CHECK: <kw>willSet</kw> {}
willSet {}
}
}
// CHECK: <kw>func</kw> test3(o: <type>AnyObject</type>) {
func test3(o: AnyObject) {
// CHECK: <kw>let</kw> x = o <kw>as</kw>! <type>MyCls</type>
let x = o as! MyCls
}
// CHECK: <kw>func</kw> test4(<kw>inout</kw> a: <type>Int</type>) {{{$}}
func test4(inout a: Int) {
// CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> >= <float>10.10</float>, <kw>iOS</kw> >= <float>8.01</float>) {<kw>let</kw> OSX = <str>"iOS"</str>}}{{$}}
if #available (OSX >= 10.10, iOS >= 8.01) {let OSX = "iOS"}}
// CHECK: <kw>func</kw> test4b(a: <kw>inout</kw> <type>Int</type>) {{{$}}
func test4b(a: inout Int) {
}
// CHECK: <kw>class</kw> MySubClass : <type>MyCls</type> {
class MySubClass : MyCls {
// CHECK: <attr-builtin>override</attr-builtin> <kw>func</kw> foo(x: <type>Int</type>) {}
override func foo(x: Int) {}
// CHECK: <attr-builtin>convenience</attr-builtin> <kw>init</kw>(a: <type>Int</type>) {}
convenience init(a: Int) {}
}
// CHECK: <kw>var</kw> g1 = { (x: <type>Int</type>) -> <type>Int</type> <kw>in</kw> <kw>return</kw> <int>0</int> }
var g1 = { (x: Int) -> Int in return 0 }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> ~~ {
infix operator ~~ {}
// CHECK: <attr-builtin>prefix</attr-builtin> <kw>operator</kw> *~~ {
prefix operator *~~ {}
// CHECK: <attr-builtin>postfix</attr-builtin> <kw>operator</kw> ~~* {
postfix operator ~~* {}
func test_defer() {
defer {
// CHECK: <kw>let</kw> x : <type>Int</type> = <int>0</int>
let x : Int = 0
}
}
// FIXME: blah.
// FIXME: blah blah
// Something something, FIXME: blah
// CHECK: <comment-line>// <comment-marker>FIXME: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// <comment-marker>FIXME: blah blah</comment-marker></comment-line>
// CHECK: <comment-line>// Something something, <comment-marker>FIXME: blah</comment-marker></comment-line>
/* FIXME: blah*/
// CHECK: <comment-block>/* <comment-marker>FIXME: blah*/</comment-marker></comment-block>
/*
* FIXME: blah
* Blah, blah.
*/
// CHECK: <comment-block>/*
// CHECK: * <comment-marker>FIXME: blah</comment-marker>
// CHECK: * Blah, blah.
// CHECK: */</comment-block>
// TODO: blah.
// TTODO: blah.
// MARK: blah.
// CHECK: <comment-line>// <comment-marker>TODO: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// T<comment-marker>TODO: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// <comment-marker>MARK: blah.</comment-marker></comment-line>
// CHECK: <kw>func</kw> test5() -> <type>Int</type> {
func test5() -> Int {
// CHECK: <comment-line>// <comment-marker>TODO: something, something.</comment-marker></comment-line>
// TODO: something, something.
// CHECK: <kw>return</kw> <int>0</int>
return 0
}
func test6<T : Prot>(x: T) {}
// CHECK: <kw>func</kw> test6<T : <type>Prot</type>>(x: <type>T</type>) {}{{$}}
// http://whatever.com?ee=2&yy=1 and radar://123456
/* http://whatever.com FIXME: see in http://whatever.com/fixme
http://whatever.com */
// CHECK: <comment-line>// <comment-url>http://whatever.com?ee=2&yy=1</comment-url> and <comment-url>radar://123456</comment-url></comment-line>
// CHECK: <comment-block>/* <comment-url>http://whatever.com</comment-url> <comment-marker>FIXME: see in <comment-url>http://whatever.com/fixme</comment-url></comment-marker>
// CHECK: <comment-url>http://whatever.com</comment-url> */</comment-block>
// CHECK: <comment-line>// <comment-url>http://whatever.com/what-ever</comment-url></comment-line>
// http://whatever.com/what-ever
// CHECK: <kw>func</kw> <placeholder><#test1#></placeholder> () {}
func <#test1#> () {}
/// Brief.
///
/// Simple case.
///
/// - parameter x: A number
/// - parameter y: Another number
/// - PaRamEteR z-hyphen-q: Another number
/// - parameter : A strange number...
/// - parameternope1: Another number
/// - parameter nope2
/// - parameter: nope3
/// -parameter nope4: Another number
/// * parameter nope5: Another number
/// - parameter nope6: Another number
/// - Parameters: nope7
/// - seealso: yes
/// - seealso: yes
/// - seealso:
/// -seealso: nope
/// - seealso : nope
/// - seealso nope
/// - returns: `x + y`
func foo(x: Int, y: Int) -> Int { return x + y }
// CHECK: <doc-comment-line>/// Brief.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// Simple case.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> x: A number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> y: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>PaRamEteR</doc-comment-field> z-hyphen-q: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> : A strange number...
// CHECK: </doc-comment-line><doc-comment-line>/// - parameternope1: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope2
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter: nope3
// CHECK: </doc-comment-line><doc-comment-line>/// -parameter nope4: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// * parameter nope5: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope6: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - Parameters: nope7
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>:
// CHECK: </doc-comment-line><doc-comment-line>/// -seealso: nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso : nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso nope
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y`
// CHECK: </doc-comment-line><kw>func</kw> foo(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y }
/// Brief.
///
/// Simple case.
///
/// - Parameters:
/// - x: A number
/// - y: Another number
///
///- note: NOTE1
///
/// - NOTE: NOTE2
/// - note: Not a Note field (not at top level)
/// - returns: `x + y`
func bar(x: Int, y: Int) -> Int { return x + y }
// CHECK: <doc-comment-line>/// Brief.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// Simple case.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>Parameters</doc-comment-field>:
// CHECK: </doc-comment-line><doc-comment-line>/// - x: A number
// CHECK: </doc-comment-line><doc-comment-line>/// - y: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y`
// CHECK: </doc-comment-line><kw>func</kw> bar(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y }
/**
Does pretty much nothing.
Not a parameter list: improper indentation.
- Parameters: sdfadsf
- WARNING: - WARNING: Should only have one field
- $$$: Not a field.
Empty field, OK:
*/
func baz() {}
// CHECK: <doc-comment-block>/**
// CHECK: Does pretty much nothing.
// CHECK: Not a parameter list: improper indentation.
// CHECK: - Parameters: sdfadsf
// CHECK: - <doc-comment-field>WARNING</doc-comment-field>: - WARNING: Should only have one field
// CHECK: - $$$: Not a field.
// CHECK: Empty field, OK:
// CHECK: */</doc-comment-block>
// CHECK: <kw>func</kw> baz() {}
/***/
func emptyDocBlockComment() {}
// CHECK: <doc-comment-block>/***/</doc-comment-block>
// CHECK: <kw>func</kw> emptyDocBlockComment() {}
/**
*/
func emptyDocBlockComment2() {}
// CHECK: <doc-comment-block>/**
// CHECK: */
// CHECK: <kw>func</kw> emptyDocBlockComment2() {}
/** */
func emptyDocBlockComment3() {}
// CHECK: <doc-comment-block>/** */
// CHECK: <kw>func</kw> emptyDocBlockComment3() {}
/**/
func malformedBlockComment(f : () throws -> ()) rethrows {}
// CHECK: <doc-comment-block>/**/</doc-comment-block>
// CHECK: <kw>func</kw> malformedBlockComment(f : () <kw>throws</kw> -> ()) <attr-builtin>rethrows</attr-builtin> {}
//: playground doc comment line
func playgroundCommentLine(f : () throws -> ()) rethrows {}
// CHECK: <comment-line>//: playground doc comment line</comment-line>
/*:
playground doc comment multi-line
*/
func playgroundCommentMultiLine(f : () throws -> ()) rethrows {}
// CHECK: <comment-block>/*:
// CHECK: playground doc comment multi-line
// CHECK: */</comment-block>
/// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings)
// CHECK: <doc-comment-line>/// [strict weak ordering](<comment-url>http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings</comment-url>
func funcTakingFor(for internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingFor(for internalName: <type>Int</type>) {}
func funcTakingIn(in internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingIn(in internalName: <type>Int</type>) {}
_ = 123
// CHECK: <int>123</int>
_ = -123
// CHECK: <int>-123</int>
_ = -1
// CHECK: <int>-1</int>
_ = -0x123
// CHECK: <int>-0x123</int>
_ = -3.1e-5
// CHECK: <float>-3.1e-5</float>
/** aaa
- returns: something
*/
// CHECK: - <doc-comment-field>returns</doc-comment-field>: something
let filename = #file
// CHECK: <kw>let</kw> filename = <kw>#file</kw>
let line = #line
// CHECK: <kw>let</kw> line = <kw>#line</kw>
let column = #column
// CHECK: <kw>let</kw> column = <kw>#column</kw>
let function = #function
// CHECK: <kw>let</kw> function = <kw>#function</kw>
let image = #imageLiteral(resourceName: "cloud.png")
// CHECK: <kw>let</kw> image = <object-literal>#imageLiteral(resourceName: "cloud.png")</object-literal>
let file = #fileLiteral(resourceName: "cloud.png")
// CHECK: <kw>let</kw> file = <object-literal>#fileLiteral(resourceName: "cloud.png")</object-literal>
let black = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
// CHECK: <kw>let</kw> black = <object-literal>#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)</object-literal>
let rgb = [#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1),
#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1),
#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)]
// CHECK: <kw>let</kw> rgb = [<object-literal>#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)</object-literal>,
// CHECK: <object-literal>#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1)</object-literal>,
// CHECK: <object-literal>#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)</object-literal>]
"--\"\(x) --"
// CHECK: <str>"--\"</str>\<anchor>(</anchor>x<anchor>)</anchor><str> --"</str>
func keywordAsLabel1(in: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel1(in: <type>Int</type>) {}
func keywordAsLabel2(for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel2(for: <type>Int</type>) {}
func keywordAsLabel3(if: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel3(if: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel4(_: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel4(<kw>_</kw>: <type>Int</type>) {}
func keywordAsLabel5(_: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel5(<kw>_</kw>: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel6(if let: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel6(if <kw>let</kw>: <type>Int</type>) {}
func foo1() {
// CHECK: <kw>func</kw> foo1() {
keywordAsLabel1(in: 1)
// CHECK: keywordAsLabel1(in: <int>1</int>)
keywordAsLabel2(for: 1)
// CHECK: keywordAsLabel2(for: <int>1</int>)
keywordAsLabel3(if: 1, for: 2)
// CHECK: keywordAsLabel3(if: <int>1</int>, for: <int>2</int>)
keywordAsLabel5(1, for: 2)
// CHECK: keywordAsLabel5(<int>1</int>, for: <int>2</int>)
_ = (if: 0, for: 2)
// CHECK: <kw>_</kw> = (if: <int>0</int>, for: <int>2</int>)
_ = (_: 0, _: 2)
// CHECK: <kw>_</kw> = (<kw>_</kw>: <int>0</int>, <kw>_</kw>: <int>2</int>)
}
func foo2(O1 : Int?, O2: Int?, O3: Int?) {
guard let _ = O1, var _ = O2, let _ = O3 else { }
// CHECK: <kw>guard</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 <kw>else</kw> { }
if let _ = O1, var _ = O2, let _ = O3 {}
// CHECK: <kw>if</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 {}
}
func keywordInCaseAndLocalArgLabel(_ for: Int, for in: Int, class _: Int) {
// CHECK: <kw>func</kw> keywordInCaseAndLocalArgLabel(<kw>_</kw> for: <type>Int</type>, for in: <type>Int</type>, class <kw>_</kw>: <type>Int</type>) {
switch(`for`, `in`) {
case (let x, let y):
// CHECK: <kw>case</kw> (<kw>let</kw> x, <kw>let</kw> y):
print(x, y)
}
}
// Keep this as the last test
/**
Trailing off ...
func unterminatedBlockComment() {}
// CHECK: <comment-line>// Keep this as the last test</comment-line>
// CHECK: <doc-comment-block>/**
// CHECK: Trailing off ...
// CHECK: func unterminatedBlockComment() {}
// CHECK: </doc-comment-block>
|
apache-2.0
|
f058ce520f6ccbae83523e01b4aecb73
| 36.193344 | 178 | 0.605778 | 2.905298 | false | false | false | false |
ustwo/US2MapperKit
|
US2MapperKit/Shared Test Cases/Classes/Internal/_TestObjectSix.swift
|
1
|
1745
|
import Foundation
class _TestObjectSix {
var optionalCompoundString : String?
var non_optionalCompoundString : String
required init(_non_optionalCompoundString : String) {
non_optionalCompoundString = _non_optionalCompoundString
}
convenience init?(_ dictionary: Dictionary<String, AnyObject>) {
let dynamicTypeString = "\(self.dynamicType)"
let className = dynamicTypeString.componentsSeparatedByString(".").last
if let valuesDict = US2Mapper.mapValues(from: dictionary, forType: className!, employing: US2Instantiator.sharedInstance, defaultsEnabled : true) {
let temp_non_optionalCompoundString : String = typeCast(valuesDict["non_optionalCompoundString"])!
self.init(_non_optionalCompoundString : temp_non_optionalCompoundString)
if let unwrapped_optionalCompoundString : Any = valuesDict["optionalCompoundString"] {
optionalCompoundString = typeCast(unwrapped_optionalCompoundString)
}
} else {
self.init(_non_optionalCompoundString : String())
return nil
}
}
func updateWithDictionary(dictionary: Dictionary<String, AnyObject>) {
let dynamicTypeString = "\(self.dynamicType)"
let className = dynamicTypeString.componentsSeparatedByString(".").last
if let valuesDict = US2Mapper.mapValues(from: dictionary, forType: className!, employing: US2Instantiator.sharedInstance, defaultsEnabled : false) {
if let unwrapped_optionalCompoundString : Any = valuesDict["optionalCompoundString"] {
optionalCompoundString = typeCast(unwrapped_optionalCompoundString)
}
if let unwrapped_non_optionalCompoundString : Any = valuesDict["non_optionalCompoundString"] {
non_optionalCompoundString = typeCast(unwrapped_non_optionalCompoundString)!
}
}
}
}
|
mit
|
6b3495b9597025c57b202baa10a0829a
| 32.576923 | 150 | 0.765043 | 4.164678 | false | false | false | false |
zhaosjason/jetline_bling
|
JetBlueIphone/JetBlueApp/JetBlueApp/JetBlueApp/DraggableViewBackground.swift
|
1
|
4831
|
//
// DraggableViewBackground.swift
// TinderSwipeCardsSwift
//
// Created by Gao Chao on 4/30/15.
// Modified by Cameron Averill on 11/8/15
// This is the view for the cards on the swipe
import Foundation
import UIKit
class DraggableViewBackground: UIView, DraggableViewDelegate {
var exampleCardLabels: [String]!
var allCards: [DraggableView]!
let MAX_BUFFER_SIZE = 2
let CARD_HEIGHT: CGFloat = 386
let CARD_WIDTH: CGFloat = 290
var cardsLoadedIndex: Int!
var loadedCards: [DraggableView]!
var menuButton: UIButton!
var messageButton: UIButton!
var checkButton: UIButton!
var xButton: UIButton!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
super.layoutSubviews()
self.setupView()
exampleCardLabels = ["first", "second", "third", "fourth", "last"]
allCards = []
loadedCards = []
cardsLoadedIndex = 0
self.loadCards()
}
func setupView() -> Void {
self.backgroundColor = UIColor(red: 0.92, green: 0.93, blue: 0.95, alpha: 1)
xButton = UIButton(frame: CGRectMake((self.frame.size.width - CARD_WIDTH)/2 + 35, self.frame.size.height/2 + CARD_HEIGHT/2 + 10, 59, 59))
xButton.setImage(UIImage(named: "xButton"), forState: UIControlState.Normal)
xButton.addTarget(self, action: "swipeLeft", forControlEvents: UIControlEvents.TouchUpInside)
checkButton = UIButton(frame: CGRectMake(self.frame.size.width/2 + CARD_WIDTH/2 - 85, self.frame.size.height/2 + CARD_HEIGHT/2 + 10, 59, 59))
checkButton.setImage(UIImage(named: "checkButton"), forState: UIControlState.Normal)
checkButton.addTarget(self, action: "swipeRight", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(xButton)
self.addSubview(checkButton)
}
func createDraggableViewWithDataAtIndex(index: NSInteger) -> DraggableView {
var draggableView = DraggableView(frame: CGRectMake((self.frame.size.width - CARD_WIDTH)/2, (self.frame.size.height - CARD_HEIGHT)/2, CARD_WIDTH, CARD_HEIGHT))
draggableView.information.text = exampleCardLabels[index]
draggableView.delegate = self
return draggableView
}
func loadCards() -> Void {
if exampleCardLabels.count > 0 {
let numLoadedCardsCap = exampleCardLabels.count > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : exampleCardLabels.count
for var i = 0; i < exampleCardLabels.count; i++ {
var newCard: DraggableView = self.createDraggableViewWithDataAtIndex(i)
allCards.append(newCard)
if i < numLoadedCardsCap {
loadedCards.append(newCard)
}
}
for var i = 0; i < loadedCards.count; i++ {
if i > 0 {
self.insertSubview(loadedCards[i], belowSubview: loadedCards[i - 1])
} else {
self.addSubview(loadedCards[i])
}
cardsLoadedIndex = cardsLoadedIndex + 1
}
}
}
func cardSwipedLeft(card: UIView) -> Void {
loadedCards.removeAtIndex(0)
if cardsLoadedIndex < allCards.count {
loadedCards.append(allCards[cardsLoadedIndex])
cardsLoadedIndex = cardsLoadedIndex + 1
self.insertSubview(loadedCards[MAX_BUFFER_SIZE - 1], belowSubview: loadedCards[MAX_BUFFER_SIZE - 2])
}
}
func cardSwipedRight(card: UIView) -> Void {
loadedCards.removeAtIndex(0)
if cardsLoadedIndex < allCards.count {
loadedCards.append(allCards[cardsLoadedIndex])
cardsLoadedIndex = cardsLoadedIndex + 1
self.insertSubview(loadedCards[MAX_BUFFER_SIZE - 1], belowSubview: loadedCards[MAX_BUFFER_SIZE - 2])
}
}
func swipeRight() -> Void {
if loadedCards.count <= 0 {
return
}
var dragView: DraggableView = loadedCards[0]
dragView.overlayView.setMode(GGOverlayViewMode.GGOverlayViewModeRight)
UIView.animateWithDuration(0.2, animations: {
() -> Void in
dragView.overlayView.alpha = 1
})
dragView.rightClickAction()
}
func swipeLeft() -> Void {
if loadedCards.count <= 0 {
return
}
var dragView: DraggableView = loadedCards[0]
dragView.overlayView.setMode(GGOverlayViewMode.GGOverlayViewModeLeft)
UIView.animateWithDuration(0.2, animations: {
() -> Void in
dragView.overlayView.alpha = 1
})
dragView.leftClickAction()
}
}
|
gpl-3.0
|
ae94eb09c2130ecc371b7bd668947437
| 35.885496 | 167 | 0.613745 | 4.690291 | false | false | false | false |
Brightify/Cuckoo
|
Source/DefaultValueRegistry.swift
|
5
|
4203
|
//
// DefaultValueRegistry.swift
// Cuckoo
//
// Created by Tadeáš Kříž on 20/09/16.
// Copyright © 2016 Brightify. All rights reserved.
//
public class DefaultValueRegistry {
private static let defaultRegisteredTypes: [ObjectIdentifier: Any] = [
ObjectIdentifier(Void.self): Void(),
ObjectIdentifier(Int.self): Int(),
ObjectIdentifier(Int8.self): Int8(),
ObjectIdentifier(Int16.self): Int16(),
ObjectIdentifier(Int32.self): Int32(),
ObjectIdentifier(Int64.self): Int64(),
ObjectIdentifier(UInt.self): UInt(),
ObjectIdentifier(UInt8.self): UInt8(),
ObjectIdentifier(UInt16.self): UInt16(),
ObjectIdentifier(UInt32.self): UInt32(),
ObjectIdentifier(UInt64.self): UInt64(),
ObjectIdentifier(String.self): String(),
ObjectIdentifier(Bool.self): Bool(),
ObjectIdentifier(Double.self): Double(),
ObjectIdentifier(Float.self): Float()
]
private static var registeredTypes = defaultRegisteredTypes
public static func register<T>(value: T, forType type: T.Type) {
registeredTypes[ObjectIdentifier(type)] = value
}
public static func defaultValue<T>(for type: Set<T>.Type) -> Set<T> {
return defaultValueOrNil(for: type) ?? []
}
public static func defaultValue<T>(for type: Array<T>.Type) -> Array<T> {
return defaultValueOrNil(for: type) ?? []
}
public static func defaultValue<K, V>(for type: Dictionary<K, V>.Type) -> Dictionary<K, V> {
return defaultValueOrNil(for: type) ?? [:]
}
public static func defaultValue<T>(for type: Optional<T>.Type) -> Optional<T> {
return defaultValueOrNil(for: type) ?? nil
}
public static func defaultValue<T>(for type: T.Type) -> T {
if let registeredDefault = defaultValueOrNil(for: type) {
return registeredDefault
}
fatalError("Type \(T.self) does not have default return value registered.")
}
public static func reset() {
registeredTypes = defaultRegisteredTypes
}
private static func defaultValueOrNil<T>(for type: T.Type) -> T? {
return registeredTypes[ObjectIdentifier(type)] as? T
}
// Overloads for tuples.
public static func defaultValue<P1, P2>(for type: (P1, P2).Type) -> (P1, P2) {
if let registeredDefault = defaultValueOrNil(for: type) {
return registeredDefault
} else {
return (defaultValue(for: P1.self), defaultValue(for: P2.self))
}
}
public static func defaultValue<P1, P2, P3>(for type: (P1, P2, P3).Type) -> (P1, P2, P3) {
if let registeredDefault = defaultValueOrNil(for: type) {
return registeredDefault
} else {
return (defaultValue(for: P1.self), defaultValue(for: P2.self), defaultValue(for: P3.self))
}
}
public static func defaultValue<P1, P2, P3, P4>(for type: (P1, P2, P3, P4).Type) -> (P1, P2, P3, P4) {
if let registeredDefault = defaultValueOrNil(for: type) {
return registeredDefault
} else {
return (defaultValue(for: P1.self), defaultValue(for: P2.self), defaultValue(for: P3.self), defaultValue(for: P4.self))
}
}
public static func defaultValue<P1, P2, P3, P4, P5>(for type: (P1, P2, P3, P4, P5).Type) -> (P1, P2, P3, P4, P5) {
if let registeredDefault = defaultValueOrNil(for: type) {
return registeredDefault
} else {
return (defaultValue(for: P1.self), defaultValue(for: P2.self), defaultValue(for: P3.self), defaultValue(for: P4.self), defaultValue(for: P5.self))
}
}
public static func defaultValue<P1, P2, P3, P4, P5, P6>(for type: (P1, P2, P3, P4, P5, P6).Type) -> (P1, P2, P3, P4, P5, P6) {
if let registeredDefault = defaultValueOrNil(for: type) {
return registeredDefault
} else {
return (defaultValue(for: P1.self), defaultValue(for: P2.self), defaultValue(for: P3.self), defaultValue(for: P4.self), defaultValue(for: P5.self), defaultValue(for: P6.self))
}
}
}
|
mit
|
f646c9135c3beb39975d5fe469e70bc1
| 38.224299 | 187 | 0.616154 | 3.794756 | false | false | false | false |
mirego/taylor-ios
|
Taylor/UI/UIControl+Actions.swift
|
1
|
2844
|
// Copyright (c) 2016, Mirego
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// - Neither the name of the Mirego nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import UIKit
private class ActionTrampoline<T>: NSObject {
private let action: (T) -> Void
init(action: @escaping (T) -> Void) {
self.action = action
}
@objc func exectuteControlAction(sender: UIControl) {
action(sender as! T)
}
}
private var UIControlActionAssociatedObjectKeys: [UInt: UnsafeMutablePointer<Int8>] = [:]
public protocol UIControlActionFunctionProtocol {}
extension UIControl: UIControlActionFunctionProtocol {}
public extension UIControlActionFunctionProtocol where Self: UIControl {
func addAction(events: UIControl.Event, _ action: @escaping (Self) -> Void) {
let trampoline = ActionTrampoline(action: action)
addTarget(trampoline, action: #selector(trampoline.exectuteControlAction(sender:)), for: events)
objc_setAssociatedObject(self, actionKey(forEvents: events), trampoline, .OBJC_ASSOCIATION_RETAIN)
}
private func actionKey(forEvents events: UIControl.Event) -> UnsafeMutablePointer<Int8> {
if let key = UIControlActionAssociatedObjectKeys[events.rawValue] {
return key
} else {
let key = UnsafeMutablePointer<Int8>.allocate(capacity: 1)
UIControlActionAssociatedObjectKeys[events.rawValue] = key
return key
}
}
}
|
bsd-3-clause
|
3a2d52b79b36d4dc7abf31eaa153f010
| 44.142857 | 106 | 0.738748 | 4.724252 | false | false | false | false |
insidegui/AppleEvents
|
Dependencies/swift-protobuf/Sources/SwiftProtobuf/Message.swift
|
1
|
8313
|
// Sources/SwiftProtobuf/Message.swift - Message support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
/// The protocol which all generated protobuf messages implement.
/// `Message` is the protocol type you should use whenever
/// you need an argument or variable which holds "some message".
///
/// Generated messages also implement `Hashable`, and thus `Equatable`.
/// However, the protocol conformance is declared on a different protocol.
/// This allows you to use `Message` as a type directly:
///
/// func consume(message: Message) { ... }
///
/// Instead of needing to use it as a type constraint on a generic declaration:
///
/// func consume<M: Message>(message: M) { ... }
///
/// If you need to convince the compiler that your message is `Hashable` so
/// you can insert it into a `Set` or use it as a `Dictionary` key, use
/// a generic declaration with a type constraint:
///
/// func insertIntoSet<M: Message & Hashable>(message: M) {
/// mySet.insert(message)
/// }
///
/// The actual functionality is implemented either in the generated code or in
/// default implementations of the below methods and properties.
public protocol Message: CustomDebugStringConvertible {
/// Creates a new message with all of its fields initialized to their default
/// values.
init()
// Metadata
// Basic facts about this class and the proto message it was generated from
// Used by various encoders and decoders
/// The fully-scoped name of the message from the original .proto file,
/// including any relevant package name.
static var protoMessageName: String { get }
/// True if all required fields (if any) on this message and any nested
/// messages (recursively) have values set; otherwise, false.
var isInitialized: Bool { get }
/// Some formats include enough information to transport fields that were
/// not known at generation time. When encountered, they are stored here.
var unknownFields: UnknownStorage { get set }
//
// General serialization/deserialization machinery
//
/// Decode all of the fields from the given decoder.
///
/// This is a simple loop that repeatedly gets the next field number
/// from `decoder.nextFieldNumber()` and then uses the number returned
/// and the type information from the original .proto file to decide
/// what type of data should be decoded for that field. The corresponding
/// method on the decoder is then called to get the field value.
///
/// This is the core method used by the deserialization machinery. It is
/// `public` to enable users to implement their own encoding formats by
/// conforming to `Decoder`; it should not be called otherwise.
///
/// Note that this is not specific to binary encodng; formats that use
/// textual identifiers translate those to field numbers and also go
/// through this to decode messages.
///
/// - Parameters:
/// - decoder: a `Decoder`; the `Message` will call the method
/// corresponding to the type of this field.
/// - Throws: an error on failure or type mismatch. The type of error
/// thrown depends on which decoder is used.
mutating func decodeMessage<D: Decoder>(decoder: inout D) throws
/// Traverses the fields of the message, calling the appropriate methods
/// of the passed `Visitor` object.
///
/// This is used internally by:
///
/// * Protobuf binary serialization
/// * JSON serialization (with some twists to account for specialty JSON)
/// * Protobuf Text serialization
/// * `hashValue` computation
///
/// Conceptually, serializers create visitor objects that are
/// then passed recursively to every message and field via generated
/// `traverse` methods. The details get a little involved due to
/// the need to allow particular messages to override particular
/// behaviors for specific encodings, but the general idea is quite simple.
func traverse<V: Visitor>(visitor: inout V) throws
// Standard utility properties and methods.
// Most of these are simple wrappers on top of the visitor machinery.
// They are implemented in the protocol, not in the generated structs,
// so can be overridden in user code by defining custom extensions to
// the generated struct.
/// The hash value generated from this message's contents, for conformance
/// with the `Hashable` protocol.
var hashValue: Int { get }
/// Helper to compare `Message`s when not having a specific type to use
/// normal `Equatable`. `Equatable` is provided with specific generated
/// types.
func isEqualTo(message: Message) -> Bool
}
public extension Message {
/// Generated proto2 messages that contain required fields, nested messages
/// that contain required fields, and/or extensions will provide their own
/// implementation of this property that tests that all required fields are
/// set. Users of the generated code SHOULD NOT override this property.
var isInitialized: Bool {
// The generated code will include a specialization as needed.
return true
}
/// A hash based on the message's full contents.
var hashValue: Int {
var visitor = HashVisitor()
try? traverse(visitor: &visitor)
return visitor.hashValue
}
/// A description generated by recursively visiting all fields in the message,
/// including messages.
var debugDescription: String {
// TODO Ideally there would be something like serializeText() that can
// take a prefix so we could do something like:
// [class name](
// [text format]
// )
let className = String(reflecting: type(of: self))
let header = "\(className):\n"
return header + textFormatString()
}
/// Creates an instance of the message type on which this method is called,
/// executes the given block passing the message in as its sole `inout`
/// argument, and then returns the message.
///
/// This method acts essentially as a "builder" in that the initialization of
/// the message is captured within the block, allowing the returned value to
/// be set in an immutable variable. For example,
///
/// let msg = MyMessage.with { $0.myField = "foo" }
/// msg.myOtherField = 5 // error: msg is immutable
///
/// - Parameter populator: A block or function that populates the new message,
/// which is passed into the block as an `inout` argument.
/// - Returns: The message after execution of the block.
public static func with(
_ populator: (inout Self) throws -> ()
) rethrows -> Self {
var message = Self()
try populator(&message)
return message
}
}
/// Implementation base for all messages; not intended for client use.
///
/// In general, use `SwiftProtobuf.Message` instead when you need a variable or
/// argument that can hold any type of message. Occasionally, you can use
/// `SwiftProtobuf.Message & Equatable` or `SwiftProtobuf.Message & Hashable` as
/// generic constraints if you need to write generic code that can be applied to
/// multiple message types that uses equality tests, puts messages in a `Set`,
/// or uses them as `Dictionary` keys.
public protocol _MessageImplementationBase: Message, Hashable {
// Legacy function; no longer used, but left to maintain source compatibility.
func _protobuf_generated_isEqualTo(other: Self) -> Bool
}
public extension _MessageImplementationBase {
public func isEqualTo(message: Message) -> Bool {
guard let other = message as? Self else {
return false
}
return self == other
}
// Legacy default implementation that is used by old generated code, current
// versions of the plugin/generator provide this directly, but this is here
// just to avoid breaking source compatibility.
public static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs._protobuf_generated_isEqualTo(other: rhs)
}
// Legacy function that is generated by old versions of the plugin/generator,
// defaulted to keep things simple without changing the api surface.
public func _protobuf_generated_isEqualTo(other: Self) -> Bool {
return self == other
}
}
|
bsd-2-clause
|
7caf249144fbfb7bc1c1d6a6416712b8
| 40.153465 | 80 | 0.708769 | 4.570093 | false | false | false | false |
cliffpanos/True-Pass-iOS
|
iOSApp/CheckInWatchKitApp Extension/Detail Controllers/ComplicationController.swift
|
1
|
3637
|
//
// ComplicationController.swift
// TruePassWatchKitApp Extension
//
// Created by Cliff Panos on 4/15/17.
// Copyright © 2017 Clifford Panos. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
//Timeline can go backwards but not forwards
handler([.backward])
}
func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil)
}
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil) //The timelineEndDate should be NOW since True Pass does not look into the future
}
func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
let publicPrivacyBehavior = CLKComplicationPrivacyBehavior.showOnLockScreen
handler(publicPrivacyBehavior)
}
// MARK: - Timeline Population
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
// Get the complication data from the extension delegate.
//let myDelegate = WC.ext
//var data : Dictionary = myDelegate.myComplicationData[complication]!
var entry : CLKComplicationTimelineEntry?
let now = Date()
// Create the template and timeline entry.
if complication.family == .modularSmall {
//let longText = data[ComplicationTextData]
//let shortText = data[ComplicationShortTextData]
//let textTemplate = CLKComplicationTemplateModularSmallSimpleText()
//textTemplate.textProvider = CLKSimpleTextProvider(text: longText, shortText: shortText)
let imageTemplate = CLKComplicationTemplateModularSmallSimpleImage()
imageTemplate.imageProvider = CLKImageProvider(onePieceImage: #imageLiteral(resourceName: "clearIcon"))
imageTemplate.tintColor = UIColor.TrueColors.lightBlue
// Create the entry.
entry = CLKComplicationTimelineEntry(date: now, complicationTemplate: imageTemplate)
} else {
// ...configure entries for other complication families.
}
// Call the handler with the current timeline entry
handler(entry)
}
func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries after to the given date
handler(nil)
}
// MARK: - Placeholder Templates
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
handler(nil)
}
}
|
apache-2.0
|
9b8765c18f0372369060754836a33f52
| 38.521739 | 169 | 0.676018 | 5.9509 | false | false | false | false |
ltcarbonell/deckstravaganza
|
Deckstravaganza/GCHelper.swift
|
1
|
7973
|
import GameKit
/// Custom delegate used to provide information to the application implementing GCHelper.
public protocol GCHelperDelegate {
/// Method called when a match has been initiated.
func matchStarted()
/// Method called when the device received data about the match from another device in the match.
func match(_ match: GKMatch, didReceiveData: Data, fromPlayer: String)
/// Method called when the match has ended.
func matchEnded()
}
/// A GCHelper instance represents a wrapper around a GameKit match.
open class GCHelper: NSObject, GKMatchmakerViewControllerDelegate, GKGameCenterControllerDelegate, GKMatchDelegate, GKLocalPlayerListener {
/// The match object provided by GameKit.
open var match: GKMatch!
fileprivate var delegate: GCHelperDelegate?
fileprivate var invite: GKInvite!
fileprivate var invitedPlayer: GKPlayer!
fileprivate var playersDict = [String:AnyObject]()
fileprivate var presentingViewController: UIViewController!
fileprivate var authenticated = false
fileprivate var matchStarted = false
/// The shared instance of GCHelper, allowing you to access the same instance across all uses of the library.
open class var sharedInstance: GCHelper {
struct Static {
static let instance = GCHelper()
}
return Static.instance
}
override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(GCHelper.authenticationChanged), name: NSNotification.Name(rawValue: GKPlayerAuthenticationDidChangeNotificationName), object: nil)
}
// MARK: Internal functions
internal func authenticationChanged() {
if GKLocalPlayer.localPlayer().isAuthenticated && !authenticated {
print("Authentication changed: player authenticated")
authenticated = true
} else {
print("Authentication changed: player not authenticated")
authenticated = false
}
}
fileprivate func lookupPlayers() {
let playerIDs = match.players.map { $0.playerID! }
GKPlayer.loadPlayers(forIdentifiers: playerIDs) { (players, error) -> Void in
if error != nil {
print("Error retrieving player info: \(error!.localizedDescription)")
self.matchStarted = false
self.delegate?.matchEnded()
} else {
guard let players = players else {
print("Error retrieving players; returned nil")
return
}
for player in players {
print("Found player: \(player.alias)")
self.playersDict[player.playerID!] = player
}
self.matchStarted = true
GKMatchmaker.shared().finishMatchmaking(for: self.match)
self.delegate?.matchStarted()
}
}
}
// MARK: User functions
/// Authenticates the user with their Game Center account if possible
open func authenticateLocalUser() {
print("Authenticating local user...")
if GKLocalPlayer.localPlayer().isAuthenticated == false {
GKLocalPlayer.localPlayer().authenticateHandler = { (view, error) in
if error == nil {
self.authenticated = true
} else {
print("\(error?.localizedDescription)")
}
}
} else {
print("Already authenticated")
}
}
/**
Attempts to pair up the user with other users who are also looking for a match.
:param: minPlayers The minimum number of players required to create a match.
:param: maxPlayers The maximum number of players allowed to create a match.
:param: viewController The view controller to present required GameKit view controllers from.
:param: delegate The delegate receiving data from GCHelper.
*/
open func findMatchWithMinPlayers(_ minPlayers: Int, maxPlayers: Int, viewController: UIViewController, delegate theDelegate: GCHelperDelegate) {
matchStarted = false
match = nil
presentingViewController = viewController
delegate = theDelegate
presentingViewController.dismiss(animated: false, completion: nil)
let request = GKMatchRequest()
request.minPlayers = minPlayers
request.maxPlayers = maxPlayers
let mmvc = GKMatchmakerViewController(matchRequest: request)!
mmvc.matchmakerDelegate = self
presentingViewController.present(mmvc, animated: true, completion: nil)
}
/**
Presents the game center view controller provided by GameKit.
:param: viewController The view controller to present GameKit's view controller from.
:param: viewState The state in which to present the new view controller.
*/
open func showGameCenter(_ viewController: UIViewController, viewState: GKGameCenterViewControllerState) {
presentingViewController = viewController
let gcvc = GKGameCenterViewController()
gcvc.viewState = viewState
gcvc.gameCenterDelegate = self
presentingViewController.present(gcvc, animated: true, completion: nil)
}
// MARK: GKGameCenterControllerDelegate
open func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
presentingViewController.dismiss(animated: true, completion: nil)
}
// MARK: GKMatchmakerViewControllerDelegate
open func matchmakerViewControllerWasCancelled(_ viewController: GKMatchmakerViewController) {
presentingViewController.dismiss(animated: true, completion: nil)
}
open func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFailWithError error: Error) {
presentingViewController.dismiss(animated: true, completion: nil)
print("Error finding match: \(error.localizedDescription)")
}
open func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFind theMatch: GKMatch) {
presentingViewController.dismiss(animated: true, completion: nil)
match = theMatch
match.delegate = self
if !matchStarted && match.expectedPlayerCount == 0 {
print("Ready to start match!")
self.lookupPlayers()
}
}
// MARK: GKMatchDelegate
open func match(_ theMatch: GKMatch, didReceive data: Data, fromPlayer playerID: String) {
if match != theMatch {
return
}
delegate?.match(theMatch, didReceiveData: data, fromPlayer: playerID)
}
open func match(_ theMatch: GKMatch, player playerID: String, didChange state: GKPlayerConnectionState) {
if match != theMatch {
return
}
switch state {
case .stateConnected where !matchStarted && theMatch.expectedPlayerCount == 0:
lookupPlayers()
case .stateDisconnected:
matchStarted = false
delegate?.matchEnded()
match = nil
default:
break
}
}
open func match(_ theMatch: GKMatch, didFailWithError error: Error?) {
if match != theMatch {
return
}
print("Match failed with error: \(error?.localizedDescription)")
matchStarted = false
delegate?.matchEnded()
}
// MARK: GKLocalPlayerListener
open func player(_ player: GKPlayer, didAccept inviteToAccept: GKInvite) {
let mmvc = GKMatchmakerViewController(invite: inviteToAccept)!
mmvc.matchmakerDelegate = self
presentingViewController.present(mmvc, animated: true, completion: nil)
}
}
|
mit
|
e34681b003859d3dab60e0a0b6a3d226
| 36.78673 | 204 | 0.64292 | 5.506215 | false | false | false | false |
shengrong1987/AutoCompleteSearchBar
|
AutoCompleteSearchBar/AutoCompleteSearchBar.swift
|
1
|
9655
|
//
// AutoCompleteSearchBar.swift
// MadeInChina
//
// Created by sheng rong on 9/15/15.
// Copyright © 2015 MICN. All rights reserved.
//
import Foundation
import UIKit
public protocol AutoCompleteSearchBarDelegate{
//return the results in array of string
func autoCompleteSeachBarResults(searchBar: AutoCompleteSearchBar, withInputText:String) -> [String]
//when one of the result was clicked, return the selected result content
func autoCompleteSearchBarOnSelect(selectedText : String )
}
@objc public class AutoCompleteSearchBar: UISearchBar, UITableViewDataSource, UITableViewDelegate {
static public let HEIGHT_FOR_CELL = 30
static public let RESULT_FONT_SIZE = CGFloat(12.0)
static public let SEARCH_TEXT_OFFSET_X = CGFloat(30)
static public let RESULT_FONT_NAME = "Helvetica"
//compact mode switch
public var compact : Bool = true
//max autocomplete container width
public var maxWidthAutoComplete : CGFloat?
//max autocomplete container height
public var maxHeightAutoComplete : CGFloat?
//max number of result shown in table view
public var maxResultNumber : Int?
public var autoCompleteDelegate : AutoCompleteSearchBarDelegate?
private var autoComplteResult : [String]?
private var resultTableView : UITableView?
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
maxWidthAutoComplete = bounds.width
maxResultNumber = 5
setup()
}
public init(frame: CGRect, maxWidthForAutoCompleteContainer:CGFloat, maxHeightForAutoCompleteContainer: CGFloat) {
self.maxHeightAutoComplete = maxHeightForAutoCompleteContainer
self.maxWidthAutoComplete = maxWidthForAutoCompleteContainer
super.init(frame: frame)
setup()
}
public init(frame: CGRect, maxWidthForAutoCompleteContainer:CGFloat, maxResultNumber: Int){
self.maxResultNumber = maxResultNumber
self.maxWidthAutoComplete = maxWidthForAutoCompleteContainer
super.init(frame: frame)
}
convenience public override init(frame: CGRect) {
self.init(frame:frame, maxWidthForAutoCompleteContainer:frame.width, maxResultNumber : 5)
}
deinit{
resultTableView?.delegate = nil
resultTableView?.dataSource = nil
resultTableView = nil
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override public func awakeFromNib() {
super.awakeFromNib()
maxWidthAutoComplete = bounds.width
maxResultNumber = 5
setup()
}
private func setup(){
//initialize data
autoComplteResult = []
var tableHeight : CGFloat?
if maxHeightAutoComplete == nil {
tableHeight = CGFloat(maxResultNumber! * AutoCompleteSearchBar.HEIGHT_FOR_CELL)
}else{
tableHeight = maxHeightAutoComplete
}
//searchBar setting
self.searchTextPositionAdjustment = UIOffsetMake(0, 0)
// find my viewcontroller container
let viewForViewController : UIViewController? = self.firstAvailableViewController()
if viewForViewController == nil{
return
}
//convert my coordinate point to the one within viewcontroller
let globalPoint = self.convertPoint(frame.origin, toView: viewForViewController?.view)
//create and config autoComplete
resultTableView = UITableView(frame: CGRectMake(0, globalPoint.y + frame.height, maxWidthAutoComplete!, tableHeight!))
viewForViewController!.view.addSubview(resultTableView!)
resultTableView?.separatorStyle = .None
resultTableView?.rowHeight = CGFloat(AutoCompleteSearchBar.HEIGHT_FOR_CELL)
resultTableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "autoCompleteResultCell")
resultTableView?.layer.cornerRadius = 2
resultTableView?.layer.borderWidth = 1
resultTableView?.layer.borderColor = UIColor.clearColor().CGColor
resultTableView!.delegate = self
resultTableView!.dataSource = self
resultTableView?.hidden = true
//notification for search text change
NSNotificationCenter.defaultCenter().addObserver(self, selector: "searchTextChange:", name: UITextFieldTextDidChangeNotification, object: nil)
}
func searchTextChange(sender:NSNotificationCenter){
if self.text == ""{
resultTableView?.hidden = true
return
}
autoComplteResult = (self.autoCompleteDelegate?.autoCompleteSeachBarResults(self, withInputText: self.text!))!
guard let results = autoComplteResult
where results.count > 0 else{
return
}
resultTableView?.reloadData()
resultTableView?.hidden = false
updateLayout()
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("autoCompleteResultCell", forIndexPath: indexPath)
if cell == nil{
cell = UITableViewCell(style: .Default, reuseIdentifier: "autoCompleteResultCell")
}
cell?.textLabel?.font = UIFont(name: AutoCompleteSearchBar.RESULT_FONT_NAME, size: AutoCompleteSearchBar.RESULT_FONT_SIZE)
cell?.textLabel!.text = autoComplteResult![indexPath.row]
cell?.textLabel?.backgroundColor = UIColor.clearColor()
let selectedView: UIView = UIView(frame: (cell?.bounds)!)
selectedView.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1.0)
cell?.selectedBackgroundView = selectedView
return cell!
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return autoComplteResult!.count
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedText = autoComplteResult![indexPath.row]
self.text = selectedText
autoComplteResult = []
resultTableView?.hidden = true
self.autoCompleteDelegate?.autoCompleteSearchBarOnSelect(selectedText)
}
//update table frame
private func updateLayout(){
let sortedResults = autoComplteResult!.sort(sortedByStringSize)
let longestString = sortedResults.last
let tableWidth : CGFloat
let tableOffset : CGFloat
if compact{
//calculate table width by using the longest string in results plus cell inset within tableview * 2
let insetX = resultTableView?.separatorInset.left
tableWidth = UIFont(name: AutoCompleteSearchBar.RESULT_FONT_NAME, size: AutoCompleteSearchBar.RESULT_FONT_SIZE)!.sizeOfString(longestString!, constrainedToWidth: Double(self.maxWidthAutoComplete!)).width + insetX! * 2
tableOffset = AutoCompleteSearchBar.SEARCH_TEXT_OFFSET_X
}else{
tableWidth = maxWidthAutoComplete!
tableOffset = 0
}
//calculate table height by using number of result,or maxresult shown, or maxHeight
var numberShown = autoComplteResult?.count
if autoComplteResult?.count > maxResultNumber{
numberShown = maxResultNumber
}
var tableHeight : CGFloat
if maxHeightAutoComplete == nil{
tableHeight = CGFloat(numberShown! * AutoCompleteSearchBar.HEIGHT_FOR_CELL)
}else{
tableHeight = maxHeightAutoComplete!
}
//update frame
self.resultTableView?.frame = CGRectMake(tableOffset, (resultTableView?.frame.origin.y)!, tableWidth, tableHeight)
}
func sortedByStringSize(s1: String, s2:String) -> Bool{
let size1 : CGSize = UIFont(name: AutoCompleteSearchBar.RESULT_FONT_NAME, size:AutoCompleteSearchBar.RESULT_FONT_SIZE)!.sizeOfString(s1, constrainedToWidth: Double(self.maxWidthAutoComplete!))
let size2 : CGSize = UIFont(name: AutoCompleteSearchBar.RESULT_FONT_NAME, size:AutoCompleteSearchBar.RESULT_FONT_SIZE)!.sizeOfString(s2, constrainedToWidth: Double(self.maxWidthAutoComplete!))
return size1.width < size2.width
}
}
private extension UIResponder {
// Thanks to Phil M
// http://stackoverflow.com/questions/1340434/get-to-uiviewcontroller-from-uiview-on-iphone
func firstAvailableViewController() -> UIViewController? {
// convenience function for casting and to "mask" the recursive function
return self.traverseResponderChainForFirstViewController() as! UIViewController?
}
func traverseResponderChainForFirstViewController() -> AnyObject? {
if let nextResponder = self.nextResponder() {
if nextResponder.isKindOfClass(UIViewController) {
return nextResponder
} else if (nextResponder.isKindOfClass(UIView)) {
return nextResponder.traverseResponderChainForFirstViewController()
} else {
return nil
}
}
return nil
}
}
extension UIFont{
func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
return NSString(string: string).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
options: [.UsesLineFragmentOrigin, .UsesFontLeading],
attributes: [NSFontAttributeName: self],
context: nil).size
}
}
|
mit
|
819deca5263e94e38a958e1ae1d19a63
| 39.911017 | 229 | 0.68179 | 5.249592 | false | false | false | false |
prolificinteractive/IQKeyboardManager
|
IQKeybordManagerSwift/IQKeyboardManager.swift
|
1
|
61322
|
//
// IQKeyboardManager.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-14 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
import UIKit
/**
@author Iftekhar Qurashi
@related [email protected]
@class IQKeyboardManager
@abstract Keyboard TextField/TextView Manager. A generic version of KeyboardManagement. https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
*/
/* @const kIQDoneButtonToolbarTag Default tag for toolbar with Done button -1002. */
let kIQDoneButtonToolbarTag : Int = -1002
/* @const kIQPreviousNextButtonToolbarTag Default tag for toolbar with Previous/Next buttons -1005. */
let kIQPreviousNextButtonToolbarTag : Int = -1005
class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate {
/******************UIKeyboard handling*************************/
/** @abstract enable/disable the keyboard manager. Default is YES(Enabled when class loads in `+(void)load` method. */
var enable: Bool = false {
didSet {
//If not enable, enable it.
if enable == true && oldValue == false {
//If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard.
if _kbShowNotification != nil {
keyboardWillShow(_kbShowNotification)
}
_IQShowLog("enabled")
} else if enable == false && oldValue == true { //If not disable, desable it.
keyboardWillHide(nil)
_IQShowLog("disabled")
}
}
}
/** @abstract To set keyboard distance from textField. can't be less than zero. Default is 10.0. */
var keyboardDistanceFromTextField: CGFloat {
set {
_privateKeyboardDistanceFromTextField = max(0, newValue)
_IQShowLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)")
}
get {
return _privateKeyboardDistanceFromTextField
}
}
/** @abstract Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES. */
var preventShowingBottomBlankSpace = true
/******************IQToolbar handling*************************/
/** @abstract Automatic add the IQToolbar functionality. Default is YES. */
var enableAutoToolbar: Bool = true {
didSet {
enableAutoToolbar ?addToolbarIfRequired():removeToolbarIfRequired()
var enableToolbar = enableAutoToolbar ? "Yes" : "NO"
_IQShowLog("enableAutoToolbar: \(enableToolbar)")
}
}
/** @abstract AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews. */
var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.BySubviews
/** @abstract If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO. */
var shouldToolbarUsesTextFieldTintColor = false
/** @abstract If YES, then it add the textField's placeholder text on IQToolbar. Default is YES. */
var shouldShowTextFieldPlaceholder = true
/** @abstract placeholder Font. Default is nil. */
var placeholderFont: UIFont?
/******************UITextView handling*************************/
/** @abstract Adjust textView's frame when it is too big in height. Default is NO. */
var canAdjustTextView = false
/*********UIKeyboard appearance overriding********************/
/** @abstract override the keyboardAppearance for all textField/textView. Default is NO. */
var overrideKeyboardAppearance = false
/** @abstract if overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property. */
var keyboardAppearance = UIKeyboardAppearance.Default
/*********UITextField/UITextView Resign handling**************/
/** @abstract Resigns Keyboard on touching outside of UITextField/View. Default is NO. Enabling/disable gesture */
var shouldResignOnTouchOutside: Bool = false {
didSet {
_tapGesture.enabled = shouldResignOnTouchOutside
let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
_IQShowLog("shouldResignOnTouchOutside: \(shouldResign)")
}
}
/*******************UISound handling*************************/
/** @abstract If YES, then it plays inputClick sound on next/previous/done click. */
var shouldPlayInputClicks = false
/****************UIAnimation handling***********************/
/** @abstract If YES, then uses keyboard default animation curve style to move view, otherwise uses UIViewAnimationOptionCurveEaseInOut animation style. Default is YES.
@discussion Sometimes strange animations may be produced if uses default curve style animation in iOS 7 and changing the textFields very frequently. */
var shouldAdoptDefaultKeyboardAnimation = true
//Private variables
/*******************************************/
/** To save UITextField/UITextView object voa textField/textView notifications. */
private weak var _textFieldView: UIView?
/** used with canAdjustTextView boolean. */
private var _textFieldViewIntialFrame = CGRectZero
/** To save rootViewController.view.frame. */
private var _topViewBeginRect = CGRectZero
/** used with canAdjustTextView to detect a textFieldView frame is changes or not. (Bug ID: #92)*/
private var _isTextFieldViewFrameChanged = false
/** To save rootViewController */
private weak var _rootViewController: UIViewController?
/*******************************************/
/** Variable to save lastScrollView that was scrolled. */
private weak var _lastScrollView: UIScrollView?
/** LastScrollView's initial contentOffset. */
private var _startingContentOffset = CGPointZero
/** LastScrollView's initial contentInsets. */
private var _startingContentInsets = UIEdgeInsetsZero
/*******************************************/
/** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
private var _kbShowNotification: NSNotification?
/** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
private var _isKeyboardShowing = false
/** To save keyboard size. */
private var _kbSize = CGSizeZero
/** To save keyboard animation duration. */
private var _animationDuration = 0.25
/** To mimic the keyboard animation */
private var _animationCurve = UIViewAnimationOptions.CurveEaseOut
/*******************************************/
/** TapGesture to resign keyboard on view's touch. */
private var _tapGesture: UITapGestureRecognizer!
/*******************************************/
/** To use with keyboardDistanceFromTextField. */
private var _privateKeyboardDistanceFromTextField: CGFloat = 10.0
/*******************************************/
/* Singleton Object Initialization. */
override init() {
super.init()
// Registering for keyboard notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHide:", name: UIKeyboardDidHideNotification, object: nil)
// Registering for textField notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextFieldTextDidBeginEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextFieldTextDidEndEditingNotification, object: nil)
// Registering for textView notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextViewTextDidBeginEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextViewTextDidEndEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidChange:", name: UITextViewTextDidChangeNotification, object: nil)
// Registering for orientation changes notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeStatusBarOrientation:", name: UIApplicationWillChangeStatusBarOrientationNotification, object: nil)
//Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
_tapGesture = UITapGestureRecognizer(target: self, action: "tapRecognized:")
_tapGesture.delegate = self
_tapGesture.enabled = shouldResignOnTouchOutside
}
/** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */
override class func load() {
super.load()
//Enabling IQKeyboardManager.
IQKeyboardManager.sharedManager().enable = true
}
deinit {
// Disable the keyboard manager.
enable = false
//Removing notification observers on dealloc.
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/* Automatically called first time from the `+(void)load` method. */
class func sharedManager() -> IQKeyboardManager {
struct Static {
//Singleton instance. Initializing keyboard manger.
static let kbManager = IQKeyboardManager()
}
/** @return Returns the default singleton instance. */
return Static.kbManager
}
/** Getting keyWindow. */
private func keyWindow() -> UIWindow? {
if _textFieldView?.window != nil {
return _textFieldView?.window
} else {
struct Static {
/** @abstract Save keyWindow object for reuse.
@discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */
static var keyWindow : UIWindow?
}
/* (Bug ID: #23, #25, #73) */
let originalKeyWindow = UIApplication.sharedApplication().keyWindow
//If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
if originalKeyWindow != nil && (Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) {
Static.keyWindow = originalKeyWindow
}
//Return KeyWindow
return Static.keyWindow
}
}
/* Helper function to manipulate RootViewController's frame with animation. */
private func setRootViewFrame(var frame: CGRect) {
// Getting topMost ViewController.
var controller = _textFieldView?.topMostController()
if controller == nil {
controller = keyWindow()?.topMostController()
}
if let unwrappedController = controller {
//frame size needs to be adjusted on iOS8 due to orientation structure changes.
if IQ_IS_IOS8_OR_GREATER == true {
frame.size = unwrappedController.view.size
}
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
// Setting it's new frame
unwrappedController.view.frame = frame
self._IQShowLog("Set \(controller?._IQDescription()) frame to : \(frame)")
}) { (animated:Bool) -> Void in}
} else { // If can't get rootViewController then printing warning to user.
_IQShowLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager")
}
}
/* Adjusting RootViewController's frame according to device orientation. */
private func adjustFrame() {
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
if _textFieldView == nil {
return
}
_IQShowLog("****** \(__FUNCTION__) %@ started ******")
// Boolean to know keyboard is showing/hiding
_isKeyboardShowing = true
// Getting KeyWindow object.
let optionalWindow = keyWindow()
// Getting RootViewController. (Bug ID: #1, #4)
var optionalRootController = _textFieldView?.topMostController()
if optionalRootController == nil {
optionalRootController = keyWindow()?.topMostController()
}
// Converting Rectangle according to window bounds.
let optionalTextFieldViewRect = _textFieldView?.superview?.convertRect(_textFieldView!.frame, toView: optionalWindow)
if optionalRootController == nil || optionalWindow == nil || optionalTextFieldViewRect == nil {
return
}
let rootController = optionalRootController!
let window = optionalWindow!
let textFieldView = _textFieldView!
let textFieldViewRect = optionalTextFieldViewRect!
//If it's iOS8 then we should do calculations according to portrait orientations. // (Bug ID: #64, #66)
let interfaceOrientation = (IQ_IS_IOS8_OR_GREATER) ? UIInterfaceOrientation.Portrait : rootController.interfaceOrientation
// Getting RootViewRect.
var rootViewRect = rootController.view.frame
//Getting statusBarFrame
let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
var move : CGFloat = 0.0
// Move positive = textField is hidden.
// Move negative = textField is showing.
// Calculating move position. Common for both normal and special cases.
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft:
move = min(textFieldViewRect.x - (statusBarFrame.width+5), textFieldViewRect.right - (window.width-_kbSize.width))
case UIInterfaceOrientation.LandscapeRight:
move = min(window.width - textFieldViewRect.right - (statusBarFrame.width+5), _kbSize.width - textFieldViewRect.x)
case UIInterfaceOrientation.Portrait:
move = min(textFieldViewRect.y - (statusBarFrame.height+5), textFieldViewRect.bottom - (window.height-_kbSize.height))
case UIInterfaceOrientation.PortraitUpsideDown:
move = min(window.height - textFieldViewRect.bottom - (statusBarFrame.height+5), _kbSize.height - textFieldViewRect.y)
default:
break
}
_IQShowLog("Need to move: \(move)")
// Getting it's superScrollView. // (Enhancement ID: #21, #24)
let superScrollView = textFieldView.superScrollView()
//If there was a lastScrollView. // (Bug ID: #34)
if let lastScrollView = _lastScrollView {
//If we can't find current superScrollView, then setting lastScrollView to it's original form.
if superScrollView == nil {
_IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
lastScrollView.contentInset = _startingContentInsets
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
_startingContentInsets = UIEdgeInsetsZero
_startingContentOffset = CGPointZero
_lastScrollView = nil
} else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
_IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
lastScrollView.contentInset = _startingContentInsets
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
_lastScrollView = superScrollView
_startingContentInsets = superScrollView!.contentInset
_startingContentOffset = superScrollView!.contentOffset
_IQShowLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
//Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
} else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
_lastScrollView = unwrappedSuperScrollView
_startingContentInsets = unwrappedSuperScrollView.contentInset
_startingContentOffset = unwrappedSuperScrollView.contentOffset
_IQShowLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
// Special case for ScrollView.
// If we found lastScrollView then setting it's contentOffset to show textField.
if let lastScrollView = _lastScrollView {
//Saving
var lastView = textFieldView
var superScrollView = _lastScrollView
while let scrollView = superScrollView {
//Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
if move > 0 ? move > -scrollView.contentOffset.y : scrollView.contentOffset.y>0 {
//Getting lastViewRect.
if let lastViewRect = lastView.superview?.convertRect(lastView.frame, toView: scrollView) {
//Calculating the expected Y offset from move and scrollView's contentOffset.
var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move)
//Rearranging the expected Y offset according to the view.
shouldOffsetY = min(shouldOffsetY, lastViewRect.y /*-5*/) //-5 is for good UI.//Commenting -5 Bug ID #69
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
self._IQShowLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset")
self._IQShowLog("Remaining Move: \(move)")
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, shouldOffsetY)
}) { (animated:Bool) -> Void in }
}
// Getting next lastView & superScrollView.
lastView = scrollView
superScrollView = lastView.superScrollView()
} else {
break
}
}
if let lastScrollViewRect = lastScrollView.superview?.convertRect(lastScrollView.frame, toView: window) {
//Updating contentInset
var bottom : CGFloat = 0.0
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft:
bottom = _kbSize.width-(window.width - lastScrollViewRect.right)
case UIInterfaceOrientation.LandscapeRight:
bottom = _kbSize.width - lastScrollViewRect.x
case UIInterfaceOrientation.Portrait:
bottom = _kbSize.height-(window.height - lastScrollViewRect.bottom)
case UIInterfaceOrientation.PortraitUpsideDown:
bottom = _kbSize.height - lastScrollViewRect.y
default:
break
}
// Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
var movedInsets = lastScrollView.contentInset
movedInsets.bottom = max(_startingContentInsets.bottom, bottom)
_IQShowLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)")
lastScrollView.contentInset = movedInsets
_IQShowLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)")
}
}
//Going ahead. No else if.
//Special case for UITextView(Readjusting the move variable when textView hight is too big to fit on screen).
//If we have permission to adjust the textView, then let's do it on behalf of user. (Enhancement ID: #15)
//Added _isTextFieldViewFrameChanged. (Bug ID: #92)
if canAdjustTextView == true && textFieldView is UITextView == true && _isTextFieldViewFrameChanged == false {
var textViewHeight = textFieldView.height
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight:
textViewHeight = min(textViewHeight, (window.width-_kbSize.width-(statusBarFrame.width+5)))
case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown:
textViewHeight = min(textViewHeight, (window.height-_kbSize.height-(statusBarFrame.height+5)))
default:
break
}
UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve|UIViewAnimationOptions.BeginFromCurrentState), animations: { () -> Void in
self._IQShowLog("\(textFieldView._IQDescription()) Old Frame : \(textFieldView.frame)")
textFieldView.height = textViewHeight
self._isTextFieldViewFrameChanged = true
self._IQShowLog("\(textFieldView._IQDescription()) New Frame : \(textFieldView.frame)")
}, completion: { (finished) -> Void in })
}
// Special case for iPad modalPresentationStyle.
if rootController.modalPresentationStyle == UIModalPresentationStyle.FormSheet || rootController.modalPresentationStyle == UIModalPresentationStyle.PageSheet {
_IQShowLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)")
// Positive or zero.
if move >= 0 {
// We should only manipulate y.
rootViewRect.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
var minimumY: CGFloat = 0
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight:
minimumY = window.width-rootViewRect.height-statusBarFrame.width-(_kbSize.width-keyboardDistanceFromTextField)
case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown:
minimumY = (window.height-rootViewRect.height-statusBarFrame.height)/2-(_kbSize.height-keyboardDistanceFromTextField)
default:
break
}
rootViewRect.y = max(rootViewRect.y, minimumY)
}
_IQShowLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
} else { // Negative
// Calculating disturbed distance. Pull Request #3
let disturbDistance = rootViewRect.y - _topViewBeginRect.y
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
// We should only manipulate y.
rootViewRect.y -= max(move, disturbDistance)
_IQShowLog("Moving Downward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
}
}
} else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case)
// Positive or zero.
if move >= 0 {
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft: rootViewRect.x -= move
case UIInterfaceOrientation.LandscapeRight: rootViewRect.x += move
case UIInterfaceOrientation.Portrait: rootViewRect.y -= move
case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.y += move
default :
break
}
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft:
rootViewRect.x = max(rootViewRect.x, min(0, -_kbSize.width+keyboardDistanceFromTextField))
case UIInterfaceOrientation.LandscapeRight:
rootViewRect.x = min(rootViewRect.x, +_kbSize.width-keyboardDistanceFromTextField)
case UIInterfaceOrientation.Portrait:
rootViewRect.y = max(rootViewRect.y, min(0, -_kbSize.height+keyboardDistanceFromTextField))
case UIInterfaceOrientation.PortraitUpsideDown:
rootViewRect.y = min(rootViewRect.y, +_kbSize.height-keyboardDistanceFromTextField)
default:
break
}
}
_IQShowLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
} else { // Negative
var disturbDistance : CGFloat = 0
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft:
disturbDistance = rootViewRect.x - _topViewBeginRect.x
case UIInterfaceOrientation.LandscapeRight:
disturbDistance = _topViewBeginRect.x - rootViewRect.x
case UIInterfaceOrientation.Portrait:
disturbDistance = rootViewRect.y - _topViewBeginRect.y
case UIInterfaceOrientation.PortraitUpsideDown:
disturbDistance = _topViewBeginRect.y - rootViewRect.y
default :
break
}
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft: rootViewRect.x -= max(move, disturbDistance)
case UIInterfaceOrientation.LandscapeRight: rootViewRect.x += max(move, disturbDistance)
case UIInterfaceOrientation.Portrait: rootViewRect.y -= max(move, disturbDistance)
case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.y += max(move, disturbDistance)
default :
break
}
_IQShowLog("Moving Downward")
// Setting adjusted rootViewRect
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
}
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/* UIKeyboardWillShowNotification. */
func keyboardWillShow(notification : NSNotification?) -> Void {
_kbShowNotification = notification
if enable == false {
return
}
_IQShowLog("****** \(__FUNCTION__) started ******")
//Due to orientation callback we need to resave it's original frame. // (Bug ID: #46)
//Added _isTextFieldViewFrameChanged check. Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed. (Bug ID: #92)
if _isTextFieldViewFrameChanged == false {
if let textFieldView = _textFieldView {
_textFieldViewIntialFrame = textFieldView.frame
_IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)")
}
}
// (Bug ID: #5)
if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == true {
// keyboard is not showing(At the beginning only). We should save rootViewRect.
var rootController = _textFieldView?.topMostController()
if rootController == nil {
rootController = keyWindow()?.topMostController()
}
if let unwrappedRootController = rootController {
_topViewBeginRect = unwrappedRootController.view.frame
_IQShowLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRectZero
}
}
let oldKBSize = _kbSize
if let info = notification?.userInfo {
if shouldAdoptDefaultKeyboardAnimation {
// Getting keyboard animation.
if let curve = info[UIKeyboardAnimationCurveUserInfoKey]?.unsignedLongValue {
/* If you are running below Xcode 6.1 then please add `-DIQ_IS_XCODE_BELOW_6_1` flag in 'other swift flag' to fix compiler errors.
http://stackoverflow.com/questions/24369272/swift-ios-deployment-target-command-line-flag */
#if IQ_IS_XCODE_BELOW_6_1
_animationCurve = UIViewAnimationOptions.fromRaw(curve)!
#else
_animationCurve = UIViewAnimationOptions(rawValue: curve)
#endif
}
} else {
_animationCurve = UIViewAnimationOptions.CurveEaseOut
}
// Getting keyboard animation duration
if let duration = info[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue {
//Saving animation duration
if duration != 0.0 {
_animationDuration = duration
}
}
// Getting UIKeyboardSize.
if let rect = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue() {
_kbSize = rect.size
_IQShowLog("UIKeyboard Size : \(_kbSize)")
}
}
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostController()
}
if let topController = topMostController {
//If it's iOS8 then we should do calculations according to portrait orientations. // (Bug ID: #64, #66)
let interfaceOrientation = (IQ_IS_IOS8_OR_GREATER) ? UIInterfaceOrientation.Portrait : topController.interfaceOrientation
// Adding Keyboard distance from textField.
switch interfaceOrientation {
case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight:
_kbSize.width += keyboardDistanceFromTextField
case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown:
_kbSize.height += keyboardDistanceFromTextField
default :
break
}
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if CGSizeEqualToSize(_kbSize, oldKBSize) == false {
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _textFieldView?.viewController() is UITableViewController == false && _textFieldView?.isAlertViewTextField() == false {
adjustFrame()
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
func keyboardWillHide(notification : NSNotification?) -> Void {
//If it's not a fake notification generated by [self setEnable:NO].
if notification != nil {
_kbShowNotification = nil
}
//If not enabled then do nothing.
if enable == false {
return
}
_IQShowLog("****** \(__FUNCTION__) started ******")
//Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56)
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
// if (_textFieldView == nil) return
// Boolean to know keyboard is showing/hiding
_isKeyboardShowing = false
let info : [NSObject : AnyObject]? = notification?.userInfo
// Getting keyboard animation duration
if let duration = info?[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue {
if duration != 0 {
// Setitng keyboard animation duration
_animationDuration = duration
}
}
//Restoring the contentOffset of the lastScrollView
if let lastScrollView = _lastScrollView {
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.contentOffset = self._startingContentOffset
self._IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)")
// TODO: restore scrollView state
// This is temporary solution. Have to implement the save and restore scrollView state
var superScrollView = self._lastScrollView?.superScrollView()
while let scrollView = superScrollView {
let contentSize = CGSizeMake(max(scrollView.contentSize.width, scrollView.width), max(scrollView.contentSize.height, scrollView.height))
let minimumY = contentSize.height-scrollView.height
if minimumY < scrollView.contentOffset.y {
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, minimumY)
self._IQShowLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)")
}
superScrollView = superScrollView?.superScrollView()
}
}) { (finished) -> Void in }
}
// Setting rootViewController frame to it's original position. // (Bug ID: #18)
if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == false {
if let rootViewController = _rootViewController {
if IQ_IS_IOS8_OR_GREATER == true {
_topViewBeginRect.size = rootViewController.view.size
}
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
self._IQShowLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)")
// Setting it's new frame
rootViewController.view.frame = self._topViewBeginRect
}) { (finished) -> Void in }
_rootViewController = nil
}
}
//Reset all values
_lastScrollView = nil
_kbSize = CGSizeZero
_startingContentInsets = UIEdgeInsetsZero
_startingContentOffset = CGPointZero
// topViewBeginRect = CGRectZero //Commented due to #82
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
func keyboardDidHide(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
_topViewBeginRect = CGRectZero
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
func textFieldViewDidBeginEditing(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
// Getting object
_textFieldView = notification.object as? UIView
if overrideKeyboardAppearance == true {
if _textFieldView is UITextField == true {
(_textFieldView as UITextField).keyboardAppearance = keyboardAppearance
} else if _textFieldView is UITextView == true {
(_textFieldView as UITextView).keyboardAppearance = keyboardAppearance
}
}
// Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed.
//Added _isTextFieldViewFrameChanged check. (Bug ID: #92)
if _isTextFieldViewFrameChanged == false {
if let textFieldView = _textFieldView {
_textFieldViewIntialFrame = textFieldView.frame
_IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)")
}
}
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if enableAutoToolbar == true {
_IQShowLog("adding UIToolbars if required")
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if _textFieldView is UITextView == true && _textFieldView?.inputAccessoryView == nil {
UIView.animateWithDuration(0.00001, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
self.addToolbarIfRequired()
}, completion: { (finished) -> Void in
if let textFieldRetain = self._textFieldView {
textFieldRetain.resignFirstResponder()
textFieldRetain.becomeFirstResponder()
}
})
} else {
addToolbarIfRequired()
}
}
if enable == false {
_IQShowLog("****** \(__FUNCTION__) ended ******")
return
}
_textFieldView?.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14)
if _isKeyboardShowing == false { // (Bug ID: #5)
// keyboard is not showing(At the beginning only). We should save rootViewRect.
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let rootViewController = _rootViewController {
_topViewBeginRect = rootViewController.view.frame
_IQShowLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)")
}
}
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37, #74, #76)
//See notes:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _textFieldView?.viewController()? is UITableViewController == false && _textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
func textFieldViewDidEndEditing(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
_textFieldView?.window?.removeGestureRecognizer(_tapGesture) // (Enhancement ID: #14)
// We check if there's a change in original frame or not.
if _isTextFieldViewFrameChanged == true {
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
self._isTextFieldViewFrameChanged = false
self._IQShowLog("Restoring \(self._textFieldView?._IQDescription()) frame to : \(self._textFieldViewIntialFrame)")
self._textFieldView?.frame = self._textFieldViewIntialFrame
}, completion: { (finished) -> Void in })
}
//Setting object to nil
_textFieldView = nil
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/* UITextViewTextDidChangeNotificationBug, fix for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string */
func textFieldViewDidChange(notification:NSNotification) { // (Bug ID: #18)
let textView = notification.object as UITextView
let line = textView .caretRectForPosition(textView.selectedTextRange?.start)
let overflow = CGRectGetMaxY(line) - (textView.contentOffset.y + CGRectGetHeight(textView.bounds) - textView.contentInset.bottom - textView.contentInset.top)
//Added overflow conditions (Bug ID: 95)
if overflow > 0.0 && overflow < CGFloat(FLT_MAX) {
// We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
// Scroll caret to visible area
var offset = textView.contentOffset
offset.y += overflow + 7 // leave 7 pixels margin
// Cannot animate with setContentOffset:animated: or caret will not appear
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in
textView.contentOffset = offset
}, completion: { (finished) -> Void in })
}
}
/** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
func willChangeStatusBarOrientation(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
//If textFieldViewInitialRect is saved then restore it.(UITextView case @canAdjustTextView)
if _isTextFieldViewFrameChanged == true {
if let textFieldView = _textFieldView {
//Due to orientation callback we need to set it's original position.
UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve|UIViewAnimationOptions.BeginFromCurrentState), animations: { () -> Void in
textFieldView.frame = self._textFieldViewIntialFrame
self._IQShowLog("Restoring \(textFieldView._IQDescription()) frame to : \(self._textFieldViewIntialFrame)")
self._isTextFieldViewFrameChanged = false
}, completion: { (finished) -> Void in })
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/** Resigning on tap gesture. */
func tapRecognized(gesture: UITapGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Ended {
gesture.view?.endEditing(true)
}
}
/** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
/** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
// Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
return (touch.view is UIControl || touch.view is UINavigationBar) ? false : true
}
/** Resigning textField. */
func resignFirstResponder() {
if let textFieldRetain = _textFieldView {
//Resigning first responder
let isResignFirstResponder = textFieldRetain.resignFirstResponder()
// If it refuses then becoming it as first responder again. (Bug ID: #96)
if isResignFirstResponder == false {
//If it refuses to resign then becoming it first responder again for getting notifications callback.
textFieldRetain.becomeFirstResponder()
_IQShowLog("Refuses to resign first responder: \(_textFieldView?._IQDescription())")
}
}
}
/** Get all UITextField/UITextView siblings of textFieldView. */
func responderViews()-> NSArray? {
var tableView : UIView? = _textFieldView?.superTableView()
if tableView == nil {
tableView = tableView?.superCollectionView()
}
//If there is a tableView in view's hierarchy, then fetching all it's subview that responds.
if let unwrappedTableView = tableView { // (Enhancement ID: #22)
return unwrappedTableView.deepResponderViews()
} else { //Otherwise fetching all the siblings
if let textFields = _textFieldView?.responderSiblings() {
//Sorting textFields according to behaviour
switch toolbarManageBehaviour {
//If autoToolbar behaviour is bySubviews, then returning it.
case IQAutoToolbarManageBehaviour.BySubviews: return textFields
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.ByTag: return textFields.sortedArrayByTag()
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.ByPosition: return textFields.sortedArrayByPosition()
}
} else {
return nil
}
}
}
/** previousAction. */
func previousAction (segmentedControl : AnyObject?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.currentDevice().playInputClick()
}
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
if textFields.containsObject(textFieldRetain) == true {
//Getting index of current textField.
let index = textFields.indexOfObject(textFieldRetain)
//If it is not first textField. then it's previous object becomeFirstResponder.
if index > 0 {
let nextTextField = textFields[index-1] as UIView
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
_IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
}
}
}
}
}
/** nextAction. */
func nextAction (segmentedControl : AnyObject?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.currentDevice().playInputClick()
}
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
if textFields.containsObject(textFieldRetain) == true {
//Getting index of current textField.
let index = textFields.indexOfObject(textFieldRetain)
//If it is not last textField. then it's next object becomeFirstResponder.
if index < textFields.count-1 {
let nextTextField = textFields[index+1] as UIView
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
_IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
}
}
}
}
}
/** doneAction. Resigning current textField. */
func doneAction (barButton : IQBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.currentDevice().playInputClick()
}
//Resign textFieldView.
resignFirstResponder()
}
/** Add toolbar if it is required to add on textFields and it's siblings. */
private func addToolbarIfRequired() {
// Getting all the sibling textFields.
if let siblings = responderViews() {
// If only one object is found, then adding only Done button.
if siblings.count == 1 {
let textField = siblings.firstObject as UIView
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
if textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == kIQPreviousNextButtonToolbarTag {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
textField.inputAccessoryView?.tag = kIQDoneButtonToolbarTag // (Bug ID: #78)
//Setting toolbar tintColor. // (Enhancement ID: #30)
if shouldToolbarUsesTextFieldTintColor == true {
textField.inputAccessoryView?.tintColor = textField.tintColor
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true && placeholderFont != nil {
(textField.inputAccessoryView as IQToolbar).titleFont = placeholderFont
}
}
} else if siblings.count != 0 {
// If more than 1 textField is found. then adding previous/next/done buttons on it.
for textField in siblings as [UIView] {
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Done toolbar).
if textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == kIQDoneButtonToolbarTag {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: "previousAction:", nextAction: "nextAction:", doneAction: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
textField.inputAccessoryView?.tag = kIQPreviousNextButtonToolbarTag // (Bug ID: #78)
//Setting toolbar tintColor // (Enhancement ID: #30)
if shouldToolbarUsesTextFieldTintColor == true {
textField.inputAccessoryView?.tintColor = textField.tintColor
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true && placeholderFont != nil {
(textField.inputAccessoryView as IQToolbar).titleFont = placeholderFont
}
}
//If the toolbar is added by IQKeyboardManager then automatically enabling/disabling the previous/next button.
if textField.inputAccessoryView?.tag == kIQPreviousNextButtonToolbarTag {
//In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
// If firstTextField, then previous should not be enabled.
if siblings[0] as UIView == textField {
textField.setEnablePrevious(false, isNextEnabled: true)
} else if siblings.lastObject as UIView == textField { // If lastTextField then next should not be enaled.
textField.setEnablePrevious(true, isNextEnabled: false)
} else {
textField.setEnablePrevious(true, isNextEnabled: true)
}
}
}
}
}
}
/** Remove any toolbar if it is IQToolbar. */
private func removeToolbarIfRequired() { // (Bug ID: #18)
// Getting all the sibling textFields.
if let siblings = responderViews() {
for view in siblings as [UIView] {
let toolbar = view.inputAccessoryView
if toolbar is IQToolbar == true && (toolbar?.tag == kIQDoneButtonToolbarTag || toolbar?.tag == kIQPreviousNextButtonToolbarTag) {
if view is UITextField == true {
let textField = view as UITextField
textField.inputAccessoryView = nil
} else if view is UITextView == true {
let textView = view as UITextView
textView.inputAccessoryView = nil
}
}
}
}
}
private func _IQShowLog(logString: String) {
let showLog = true
if showLog == true {
println("IQKeyboardManager: " + logString)
}
}
}
|
mit
|
e62343e8a7e576a72ff7311892a90506
| 47.399369 | 365 | 0.593718 | 6.59873 | false | false | false | false |
creatubbles/ctb-api-swift
|
CreatubblesAPIClient/Sources/Requests/User/FetchTrendingUsersResponseHandler.swift
|
1
|
2311
|
//
// FetchTrendingUsersResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import ObjectMapper
class FetchTrendingUsersResponseHandler: ResponseHandler {
fileprivate let completion: UsersClosure?
init(completion: UsersClosure?) {
self.completion = completion
}
override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) {
if let response = response,
let mappers = Mapper<UserMapper>().mapArray(JSONObject: response["data"]) {
let metadata = MappingUtils.metadataFromResponse(response)
let pageInfo = MappingUtils.pagingInfoFromResponse(response)
let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata)
let users = mappers.map({ User(mapper: $0, dataMapper: dataMapper, metadata: metadata) })
executeOnMainQueue { self.completion?(users, pageInfo, ErrorTransformer.errorFromResponse(response, error: error)) }
} else {
executeOnMainQueue { self.completion?(nil, nil, ErrorTransformer.errorFromResponse(response, error: error)) }
}
}
}
|
mit
|
065b0654921a0010ba2f7774da3dc1be
| 45.22 | 128 | 0.720467 | 4.774793 | false | false | false | false |
byu-oit-appdev/ios-byuSuite
|
byuSuite/Apps/Vending/model/VendingClient.swift
|
1
|
4140
|
//
// VendingClient.swift
// byuSuite
//
// Created by Alex Boswell on 1/3/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
private let BASE_URL = "https://api.byu.edu:443/domains/vending/v1/vending.ashx"
private let MACHINES_SERVICE = "machines"
private let INVENTORY_SERVICE = "inventory"
private let MERCHANDISE_SERVICE = "merchandise"
class VendingClient: ByuClient2 {
static func getAllMicrowaves(callback: @escaping ([VendingMachine]?, ByuError?) -> Void) {
makeVendingRequestWithService(service: MACHINES_SERVICE, action: "listAllMicrowaves") { (response) in
if response.succeeded {
do {
callback(try parseMachines(response: response), nil)
} catch {
callback(nil, InvalidModelError.byuError)
}
} else {
callback(nil, response.error)
}
}
}
static func getAllMachines(callback: @escaping ([VendingMachine]?, ByuError?) -> Void) {
makeVendingRequestWithService(service: MACHINES_SERVICE, action: "listAllMachines") { (response) in
if response.succeeded {
do {
callback(try parseMachines(response: response), nil)
} catch {
callback(nil, InvalidModelError.byuError)
}
} else {
callback(nil, response.error)
}
}
}
static func getAllItemsInMachine(machineId: Int, callback: @escaping ([VendingItem]?, ByuError?) -> Void) {
makeVendingRequestWithService(service: INVENTORY_SERVICE, action: "getAllLocation", extraQueryParams: ["loc": "\(machineId)"]) { (response) in
if response.succeeded,
let data = response.getDataJson() as? [String: Any],
let itemData = data["items"] as? [[String: Any]] {
callback((itemData.map { VendingItem(dict: $0) }).sorted(), nil)
} else {
callback(nil, response.error)
}
}
}
static func getAllCategories(callback: @escaping ([VendingCategory]?, ByuError?) -> Void) {
makeVendingRequestWithService(service: MERCHANDISE_SERVICE, action: "listCategories") { (response) in
if response.succeeded, let data = response.getDataJson() as? [[String: Any]] {
do {
callback((try data.map { try VendingCategory(dict: $0) }).sorted(), nil)
} catch {
callback(nil, InvalidModelError.byuError)
}
} else {
callback(nil, response.error)
}
}
}
static func getAllProductsInCategory(categoryId: Int, callback: @escaping ([VendingProduct]?, ByuError?) -> Void) {
makeVendingRequestWithService(service: MERCHANDISE_SERVICE, action: "getProducts", extraQueryParams: ["cat": "\(categoryId)"]) { (response) in
if response.succeeded, let data = response.getDataJson() as? [[String: Any]] {
do {
callback((try data.map { try VendingProduct(dict: $0) }).sorted(), nil)
} catch {
callback(nil, InvalidModelError.byuError)
}
} else {
callback(nil, response.error)
}
}
}
static func getAllMachinesContainingProduct(productId: Int, callback: @escaping ([VendingMachine]?, ByuError?) -> Void) {
makeVendingRequestWithService(service: INVENTORY_SERVICE, action: "findMachinesWithStock", extraQueryParams: ["product": "\(productId)"]) { (response) in
if response.succeeded {
do {
callback(try parseMachines(response: response), nil)
} catch {
callback(nil, InvalidModelError.byuError)
}
} else {
callback(nil, response.error)
}
}
}
//MARK: Custom methods
static func parseMachines(response: ByuResponse2) throws -> [VendingMachine]? {
guard let data = response.getDataJson() as? [[String: Any]] else { return nil }
return (try data.map { try VendingMachine(dict: $0) }).sorted()
}
static func makeVendingRequestWithService(service: String, action: String, extraQueryParams: [String: String]? = nil, callback: @escaping (ByuResponse2) -> Void) {
var queryParams = [String:String]()
if let extraQueryParams = extraQueryParams {
queryParams = extraQueryParams
}
queryParams["format"] = "json"
queryParams["service"] = service
queryParams["action"] = action
let request = ByuRequest2(requestMethod: .GET, url: super.url(base: BASE_URL, queryParams: queryParams))
ByuRequestManager.instance.makeRequest(request, callback: callback)
}
}
|
apache-2.0
|
116e1907341bcb5f49bbc3379a9ff2c7
| 34.681034 | 164 | 0.694612 | 3.457811 | false | false | false | false |
SwifterSwift/SwifterSwift
|
Sources/SwifterSwift/SwiftStdlib/SignedIntegerExtensions.swift
|
1
|
2690
|
// SignedIntegerExtensions.swift - Copyright 2020 SwifterSwift
//
// SignedIntegerExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/15/17.
// Copyright © 2017 SwifterSwift
//
#if canImport(Foundation)
import Foundation
#endif
// MARK: - Properties
public extension SignedInteger {
/// SwifterSwift: Absolute value of integer number.
var abs: Self {
return Swift.abs(self)
}
/// SwifterSwift: Check if integer is positive.
var isPositive: Bool {
return self > 0
}
/// SwifterSwift: Check if integer is negative.
var isNegative: Bool {
return self < 0
}
/// SwifterSwift: Check if integer is even.
var isEven: Bool {
return (self % 2) == 0
}
/// SwifterSwift: Check if integer is odd.
var isOdd: Bool {
return (self % 2) != 0
}
/// SwifterSwift: String of format (XXh XXm) from seconds Int.
var timeString: String {
guard self > 0 else {
return "0 sec"
}
if self < 60 {
return "\(self) sec"
}
if self < 3600 {
return "\(self / 60) min"
}
let hours = self / 3600
let mins = (self % 3600) / 60
if hours != 0, mins == 0 {
return "\(hours)h"
}
return "\(hours)h \(mins)m"
}
}
// MARK: - Methods
public extension SignedInteger {
/// SwifterSwift: Greatest common divisor of integer value and n.
///
/// - Parameter number: integer value to find gcd with.
/// - Returns: greatest common divisor of self and n.
func gcd(of number: Self) -> Self {
return number == 0 ? self : number.gcd(of: self % number)
}
/// SwifterSwift: Least common multiple of integer and n.
///
/// - Parameter number: integer value to find lcm with.
/// - Returns: least common multiple of self and n.
func lcm(of number: Self) -> Self {
return (self * number).abs / gcd(of: number)
}
#if canImport(Foundation)
/// SwifterSwift: Ordinal representation of an integer.
///
/// print((12).ordinalString()) // prints "12th"
///
/// - Parameter locale: locale, default is .current.
/// - Returns: string ordinal representation of number in specified locale language. E.g. input 92, output in "en": "92nd".
@available(macOS 10.11, *)
func ordinalString(locale: Locale = .current) -> String? {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .ordinal
guard let number = self as? NSNumber else { return nil }
return formatter.string(from: number)
}
#endif
}
|
mit
|
1aa4412debb7384fda5d18945c7d9d2c
| 26.438776 | 127 | 0.588323 | 4.22135 | false | false | false | false |
think-dev/MadridBUS
|
Carthage/Checkouts/BRYXBanner/Example/BRYXBanner/ViewController.swift
|
1
|
2477
|
//
// ViewController.swift
// BRYXBanner
//
// Created by Harlan Haskins on 07/27/2015.
// Copyright (c) 2015 Harlan Haskins. All rights reserved.
//
import UIKit
import BRYXBanner
struct BannerColors {
static let red = UIColor(red:198.0/255.0, green:26.00/255.0, blue:27.0/255.0, alpha:1.000)
static let green = UIColor(red:48.00/255.0, green:174.0/255.0, blue:51.5/255.0, alpha:1.000)
static let yellow = UIColor(red:255.0/255.0, green:204.0/255.0, blue:51.0/255.0, alpha:1.000)
static let blue = UIColor(red:31.0/255.0, green:136.0/255.0, blue:255.0/255.0, alpha:1.000)
}
class ViewController: UIViewController {
@IBOutlet weak var imageSwitch: UISwitch!
@IBOutlet weak var positionSegmentedControl: UISegmentedControl!
@IBOutlet weak var springinessSegmentedControl: UISegmentedControl!
@IBOutlet weak var titleField: UITextField!
@IBOutlet weak var subtitleField: UITextField!
@IBOutlet weak var colorSegmentedControl: UISegmentedControl!
@IBOutlet weak var inViewSwitch: UISwitch!
@IBAction func showButtonTapped(_ sender: UIButton) {
let color = currentColor()
let image = imageSwitch.isOn ? UIImage(named: "Icon") : nil
let title = titleField.text?.validated
let subtitle = subtitleField.text?.validated
let banner = Banner(title: title, subtitle: subtitle, image: image, backgroundColor: color)
banner.springiness = currentSpringiness()
banner.position = currentPosition()
if inViewSwitch.isOn {
banner.show(view, duration: 3.0)
} else {
banner.show(duration: 3.0)
}
}
func currentPosition() -> BannerPosition {
switch positionSegmentedControl.selectedSegmentIndex {
case 0: return .top
default: return .bottom
}
}
func currentSpringiness() -> BannerSpringiness {
switch springinessSegmentedControl.selectedSegmentIndex {
case 0: return .none
case 1: return .slight
default: return .heavy
}
}
func currentColor() -> UIColor {
switch colorSegmentedControl.selectedSegmentIndex {
case 0: return BannerColors.red
case 1: return BannerColors.green
case 2: return BannerColors.yellow
default: return BannerColors.blue
}
}
}
extension String {
var validated: String? {
if self.isEmpty { return nil }
return self
}
}
|
mit
|
259b83cd919da705c4c5154899a9897c
| 32.026667 | 99 | 0.660476 | 4.087459 | false | false | false | false |
taybenlor/Saliva
|
Saliva/Saliva.swift
|
1
|
3853
|
//
// Saliva.swift
// Saliva
//
// Saliva allows you to bind parts of your UI together so
// that they will update in unison. It's lightweight and flexible.
// Saliva works by using a timer that's synchronised to the
// display framerate. There's very little overhead, but because
// your code could potentially run every frame - make it snappy.
//
// The simplest usage is bind(from: yourSource, to: yourSink).
// You can make each whatever you like. For example:
//
// bind(from: { self.model.coordinate }, to: { self.view.center = $0 })
//
// If the type of the binding (in the above case probably CGPoint) is equatable
// then Saliva will only call the binding if the value changes.
//
// If you explicitly want Saliva to bind every frame call bindEveryFrame
// or if you want to explicitly bind only new values call bindNewValues
//
//
// Using a timer that runs every frame to create bindings like this
// can seem pretty messy. However since Swift has only some support
// for KVO and since KVO based systems can have a lot of overhead, this
// is a neat way to get simple bindings that are performant.
//
// Created by Ben Taylor on 11/12/2014.
// Copyright (c) 2014 Ben Taylor. All rights reserved.
//
import UIKit
public class BindingCollection: NSObject {
var bindings: [Binding] = []
var _displayLink: CADisplayLink?
var displayLink: CADisplayLink {
if let displayLink = _displayLink {
return displayLink
}
_displayLink = CADisplayLink(target: self, selector: "handleDisplayLinkTick")
_displayLink?.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
return _displayLink!
}
deinit {
displayLink.invalidate()
}
// Public
func addBinding(binding: Binding) {
bindings.append(binding)
updatePausedState()
}
func removeBinding(binding: Binding) {
bindings = bindings.filter { $0 !== binding }
updatePausedState()
}
public func handleDisplayLinkTick() {
for binding in bindings {
binding.apply()
}
}
// Private
internal func updatePausedState() {
if bindings.count > 0 {
displayLink.paused = false
} else {
displayLink.paused = true
}
}
}
public class Binding {
func apply() {}
}
public class SimpleBinding<T>: Binding {
let fromFunc: () -> T
let toFunc: (T) -> ()
init(from: () -> T, to: (T) -> ()) {
fromFunc = from
toFunc = to
}
// Passes the information from fromFunc to toFunc
override func apply() {
toFunc(fromFunc())
}
}
public class DifferenceBinding<T: Equatable>: SimpleBinding<T> {
var lastValue: T? = nil
override init(from: () -> T, to: (T) -> ()) {
super.init(from: from, to: to)
}
override func apply() {
let newValue = fromFunc()
if let lastValue = lastValue {
if newValue != lastValue {
toFunc(newValue)
}
} else {
toFunc(newValue)
}
lastValue = newValue
}
}
// Shared state and helper functions
// Not super keen on the shared state
// but it does allow for a nicer API
public let sharedBindingCollection = BindingCollection()
public func bind<T>(from fromFunc: () -> T, to toFunc: (T) -> ()) -> Binding {
return bindEveryFrame(from: fromFunc, to: toFunc)
}
public func bind<T: Equatable>(from fromFunc: () -> T, to toFunc: (T) -> ()) -> Binding {
return bindNewValues(from: fromFunc, to: toFunc)
}
public func bindEveryFrame<T>(from fromFunc: () -> T, to toFunc: (T) -> ()) -> SimpleBinding<T> {
let binding = SimpleBinding(from: fromFunc, to: toFunc)
sharedBindingCollection.addBinding(binding)
return binding
}
public func bindNewValues<T: Equatable>(from fromFunc: () -> T, to toFunc: (T) -> ()) -> DifferenceBinding<T> {
let binding = DifferenceBinding(from: fromFunc, to: toFunc)
sharedBindingCollection.addBinding(binding)
return binding
}
public func unbind(binding: Binding) {
sharedBindingCollection.removeBinding(binding)
}
|
bsd-3-clause
|
25538618617c2b2562b72a82989fe1dc
| 24.523179 | 111 | 0.692707 | 3.434046 | false | false | false | false |
ben-ng/swift
|
validation-test/compiler_crashers_fixed/01266-getselftypeforcontainer.swift
|
1
|
601
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct c {
func e() {
}
let c = a
protocol a {
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
}
protocol a : a {
d<f : e, g: e where g.h == f.h> {
}
protocol e {
}
func a<
|
apache-2.0
|
23c54cb5c84fc93b2375418065cbf0d5
| 22.115385 | 79 | 0.667221 | 3.035354 | false | false | false | false |
AlphaJian/LarsonApp
|
LarsonApp/LarsonApp/View/MKButton/MKBlueButton.swift
|
2
|
454
|
//
// MKBlueButton.swift
// JoeApp
//
// Created by Jian Zhang on 3/14/16.
// Copyright © 2016 PwC. All rights reserved.
//
import UIKit
class MKBlueButton: MKButton {
override func awakeFromNib() {
self.layer.cornerRadius = 2
self.layer.shadowOpacity = 0.3
self.layer.shadowRadius = 2.0
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 2, height: 2)
}
}
|
apache-2.0
|
c5b8a7d95d1b5036f90f346999b13f73
| 20.571429 | 61 | 0.637969 | 3.511628 | false | false | false | false |
muhlenXi/SwiftEx
|
projects/TodoList/TodoList/ViewController.swift
|
1
|
4720
|
//
// ViewController.swift
// TodoList
//
// Created by 席银军 on 2017/8/20.
// Copyright © 2017年 muhlenXi. All rights reserved.
//
import UIKit
var todos: [TodoModel] = []
var selectedTodo: TodoModel?
var resultTodo: [TodoModel] = []
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var searchController = UISearchController(searchResultsController: nil)
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
todos = [TodoModel(id: UUID().uuidString, image: "play_selected", title: "1、Have fun with friends.", date: Date()), TodoModel(id: UUID().uuidString, image: "shopping_selected", title: "2、Go shopping.", date: Date()), TodoModel(id: UUID().uuidString, image: "call_selected", title: "3、Call to brother.", date: Date()), TodoModel(id: UUID().uuidString, image: "travel_selected", title: "4、Travel To Tibet.", date: Date()), TodoModel(id: UUID().uuidString, image: "eat_selected", title: "5、Eat lunch.", date: Date())]
tableView.tableFooterView = UIView()
// Set search controller
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
// Hide the search bar
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Event responnse
func doneAction() {
tableView.setEditing(false, animated: true)
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(ViewController.editAction(_:)))
}
@IBAction func editAction(_ sender: Any) {
tableView.setEditing(true, animated: true)
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(ViewController.doneAction))
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EditTodo" {
if let indexPath = tableView.indexPathForSelectedRow {
selectedTodo = todos[indexPath.row]
}
}
}
}
// MARK: - Date extension
extension Date {
func normalString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.dateFormat = "yyyy-MM-dd"
let string = dateFormatter.string(from: self)
return string
}
}
// MARK: - UITableViewDataSource & UITableViewDelegate
extension ViewController: UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive {
return resultTodo.count
} else {
return todos.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TodoCell", for: indexPath) as! TodoTableViewCell
let todo: TodoModel
if searchController.isActive {
todo = resultTodo[indexPath.row]
} else {
todo = todos[indexPath.row]
}
cell.thumbnail.image = UIImage(named: todo.image)
cell.todoTitle.text = todo.title
cell.todoDate.text = todo.date.normalString()
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80.0
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
todos.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let todo = todos.remove(at: sourceIndexPath.row)
todos.insert(todo, at: destinationIndexPath.row)
}
}
extension ViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
resultTodo = todos.filter{ $0.title.range(of: searchController.searchBar.text!) != nil}
tableView.reloadData()
}
}
|
mit
|
89cdbaab21b2caa8a4168a4137778439
| 32.578571 | 522 | 0.649649 | 4.964097 | false | false | false | false |
nodes-ios/model-generator
|
model-generator/Generators/EncodableCodeGenerator.swift
|
1
|
2104
|
//
// EncodableCodeGenerator.swift
// model-generator
//
// Created by Dominik Hádl on 19/01/16.
// Copyright © 2016 Nodes. All rights reserved.
//
import Foundation
struct EncodableCodeGenerator {
static func encodableCode(withModel model: Model, useNativeDictionaries: Bool) -> String {
var indent = Indentation(level: 1)
// Create the function signature
var code = indent.string() + (model.accessLevel == .Public ? "public " : "")
code += "func encodableRepresentation() -> NSCoding {\n"
// Increase indent level
indent = indent.nextLevel()
// Create the dictionary
code += indent.string()
code += (useNativeDictionaries ? "var dict = [String: AnyObject]()\n" : "let dict = NSMutableDictionary()\n")
// Get longest property key for alignment spaces
let maxPropertyLength = model.longestPropertyKeyLength()
// Generate encodable code for each property
for property in model.properties {
let keyCharactersCount = property.key?.count ?? property.name.unescaped.count
code += indent.string()
if useNativeDictionaries {
code += "dict[\"\(property.key ?? property.name.unescaped)\"]"
code += String.repeated(character: " ", count: maxPropertyLength - keyCharactersCount)
code += " = \(property.name.escaped)"
code += property.isPrimitiveType ? "" : "\(property.isOptional ? "?" : "").encodableRepresentation()"
} else {
code += "(dict, \"\(property.key ?? property.name.unescaped)\")"
code += String.repeated(character: " ", count: maxPropertyLength - keyCharactersCount)
code += " <== \(property.name.escaped)"
}
code += "\n"
}
// Return the dictionary
code += indent.string() + "return dict\n"
// Decrease the indent level
indent = indent.previousLevel()
// Close the function
code += indent.string() + "}"
return code
}
}
|
mit
|
a92d0c5b377165b1e64c482c69aef807
| 34.627119 | 117 | 0.588011 | 4.888372 | false | false | false | false |
GoodMorningCody/EverybodySwift
|
WeeklyToDo/WeeklyToDo/Task.swift
|
1
|
2176
|
//
// Task.swift
// WeeklyToDo
//
// Created by Cody on 2015. 1. 26..
// Copyright (c) 2015년 TIEKLE. All rights reserved.
//
import Foundation
import CoreData
class Task: NSManagedObject {
@NSManaged var repeat: NSNumber
@NSManaged var todo: String
@NSManaged var done: NSNumber
@NSManaged var doneDate: NSDate?
@NSManaged var creationDate: NSDate?
@NSManaged var weekend : Weekend
func didCreataionWhenPresent() -> Bool {
if repeat.boolValue==true {
return false
}
if creationDate==nil {
return false
}
var component = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond, fromDate: NSDate())
component.hour = 0
component.minute = 0
component.second = 0
//let present = component.date
let present = NSCalendar.currentCalendar().dateFromComponents(component)
if present?.timeIntervalSince1970 > creationDate?.timeIntervalSince1970 {
return true
}
return false
}
func didDoneWhenPresent() -> Bool {
if done.boolValue==false {
return false
}
var componentPresent = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: weekend.date!)
var componentCurrent = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: NSDate())
let present = NSCalendar.currentCalendar().dateFromComponents(componentPresent)
let current = NSCalendar.currentCalendar().dateFromComponents(componentCurrent)
if present?.timeIntervalSince1970 < current?.timeIntervalSince1970 && repeat.boolValue==true {
return true
}
return false
}
}
|
mit
|
42473de4276ee5c42e62a90011b9da95
| 34.064516 | 290 | 0.667893 | 5.617571 | false | false | false | false |
mobilabsolutions/jenkins-ios
|
JenkinsiOS/Controller/JobViewController.swift
|
1
|
18072
|
//
// JobViewController.swift
// JenkinsiOS
//
// Created by Robert on 29.09.16.
// Copyright © 2016 MobiLab Solutions. All rights reserved.
//
import Crashlytics
import UIKit
class JobViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
@IBOutlet var buildButton: BigButton!
var account: Account?
var job: Job?
var viewWillAppearCalled = false
private var showAllBuilds = false
private var reloadTimer: Timer?
// MARK: - Actions
@objc func triggerBuild() {
guard let job = job
else { return }
if job.parameters.isEmpty {
triggerBuildWithoutParameters()
} else {
prepareForBuildWithParameters()
}
}
// MARK: - Viewcontroller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
let filteringHeaderViewNib = UINib(nibName: "FilteringHeaderTableViewCell", bundle: .main)
tableView.register(filteringHeaderViewNib, forCellReuseIdentifier: Constants.Identifiers.buildsFilteringCell)
tableView.backgroundColor = Constants.UI.backgroundColor
view.backgroundColor = Constants.UI.backgroundColor
tableView.separatorStyle = .none
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: view.frame.height - buildButton.frame.minY, right: 0)
buildButton.addTarget(self, action: #selector(triggerBuild), for: .touchUpInside)
performRequest()
setupReload()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupUI()
viewWillAppearCalled = true
if reloadTimer?.isValid != true {
setupReload()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
reloadTimer?.invalidate()
}
private func setupReload() {
reloadTimer = Timer.scheduledTimer(timeInterval: Constants.Defaults.defaultReloadInterval, target: self,
selector: #selector(performRequest), userInfo: nil, repeats: true)
}
// MARK: - UITableViewDataSource and Delegate
private enum JobSection: Int {
case overview = 0
case specialBuild = 1
case otherBuilds = 2
}
func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let section = JobSection(rawValue: indexPath.section)
else { return UITableViewCell() }
switch section {
case .overview:
return cellForOverView(indexPath: indexPath)
case .specialBuild:
return cellForSpecialBuild(indexPath: indexPath)
case .otherBuilds:
return cellForOtherBuilds(indexPath: indexPath)
}
}
private func cellForOverView(indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
return cellForSimpleHeader(title: job?.name ?? "JOB", indexPath: indexPath)
}
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.jobOverViewCell, for: indexPath) as! JobOverviewTableViewCell
cell.job = job
return cell
}
private func cellForSpecialBuild(indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
return cellForSimpleHeader(title: "LAST BUILD", indexPath: indexPath)
}
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.specialBuildCell, for: indexPath) as! SpecialBuildTableViewCell
cell.build = job?.lastBuild
cell.delegate = self
return cell
}
private func cellForOtherBuilds(indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
return cellForSelectableBuildsHeader(indexPath: indexPath)
}
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.buildCell, for: indexPath) as! BuildTableViewCell
if let builds = job?.builds, indexPath.row - 1 < builds.count {
cell.build = builds[indexPath.row - 1]
}
return cell
}
private func cellForSimpleHeader(title: String, indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.titleCell, for: indexPath)
cell.textLabel?.text = title
return cell
}
private func cellForSelectableBuildsHeader(indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.buildsFilteringCell, for: indexPath) as! FilteringHeaderTableViewCell
cell.delegate = self
cell.title = "OTHER BUILDS"
cell.canDeselectAllOptions = true
cell.options = ["SHOW ALL (\(job?.builds.count ?? 0))"]
cell.select(where: { _ in showAllBuilds })
return cell
}
func numberOfSections(in _: UITableView) -> Int {
guard let _ = job
else { return 0 }
return 3
}
func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let job = job, let section = JobSection(rawValue: section)
else { return 0 }
switch section {
case .overview:
return 2
case .specialBuild:
return 2
case .otherBuilds:
return 1 + (showAllBuilds ? job.builds.count : 0)
}
}
func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let section = JobSection(rawValue: indexPath.section)
else { return }
switch (section, indexPath.row) {
case (.overview, _):
return
case (.specialBuild, 0):
return
case (.specialBuild, _):
performSegue(withIdentifier: Constants.Identifiers.showBuildSegue, sender: job?.lastBuild)
case (.otherBuilds, 0):
return
case (.otherBuilds, _):
performSegue(withIdentifier: Constants.Identifiers.showBuildSegue, sender: job?.builds[indexPath.row - 1])
}
}
func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let section = JobSection(rawValue: indexPath.section)
else { return 0 }
switch section {
case .overview:
return indexPath.row == 0 ? 36 : 180
case .specialBuild:
return indexPath.row == 0 ? 36 : 129
case .otherBuilds:
return indexPath.row == 0 ? 67 : 74
}
}
// MARK: - Building
private func prepareForBuildWithParameters() {
performSegue(withIdentifier: Constants.Identifiers.showParametersSegue, sender: nil)
}
private func triggerBuildWithoutParameters() {
let alert = alertWithImage(image: UIImage(named: "ic-rocket"), title: "Start Build",
message: "Do you want to trigger a build?", height: 64)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Start", style: .default, handler: { [weak self] _ in
self?.buildWithoutParameters()
}))
present(alert, animated: true, completion: nil)
}
private func buildWithoutParameters() {
guard let job = job, let account = account
else { return }
if account.password == nil || account.username == nil {
displayInputTokenError(for: job, with: account)
} else {
let modalViewController = presentModalInformationViewController()
performBuild(job: job, account: account, token: nil, parameters: nil) { result, error in
DispatchQueue.main.async { [unowned self] in
self.completionForBuild()(modalViewController, result, error)
}
}
}
}
private func displayInputTokenError(for job: Job, with account: Account) {
var tokenTextField: UITextField!
let useAction = UIAlertAction(title: "Use", style: .default, handler: { [weak self] _ in
self?.performBuild(job: job, account: account, token: tokenTextField.text, parameters: nil) {
self?.completionForBuild()(self?.createModalInformationViewController(), $0, $1)
}
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
displayError(title: "Please Input a token",
message: "To start a build without username or password, a token is required",
textFieldConfigurations: [{ textField in
textField.placeholder = "Token"
tokenTextField = textField
}], actions: [useAction, cancelAction])
}
private func presentModalInformationViewController() -> ModalInformationViewController? {
guard let modal = createModalInformationViewController()
else { return nil }
present(modal, animated: true, completion: nil)
return modal
}
private func createModalInformationViewController() -> ModalInformationViewController? {
guard isViewLoaded, view.window != nil
else { return nil }
let modalViewController = ModalInformationViewController.withLoadingIndicator(title: "Loading...")
modalViewController.dismissOnTap = false
return modalViewController
}
private func completionForBuild() -> (ModalInformationViewController?, JobListQuietingDown?, Error?) -> Void {
return { [weak self]
modalViewController, quietingDown, error in
if let error = error {
if self?.presentedViewController == modalViewController {
modalViewController?.dismiss(animated: true, completion: {
self?.displayError(error: error)
})
} else {
self?.displayError(error: error)
}
} else {
func showQuietingDownModal() {
if quietingDown?.quietingDown == true {
self?.displayError(title: "Quieting Down", message: "The server is currently quieting down.\nThe build was added to the queue.",
textFieldConfigurations: [], actions: [UIAlertAction(title: "OK", style: .default)])
}
}
if self?.presentedViewController == modalViewController {
modalViewController?.dismiss(animated: true, completion: showQuietingDownModal)
} else {
showQuietingDownModal()
}
}
}
}
private func displayError(error: Error) {
displayNetworkError(error: error, onReturnWithTextFields: { returnData in
self.account?.username = returnData["username"]!
self.account?.password = returnData["password"]!
self.triggerBuild()
})
}
fileprivate func performBuild(job: Job, account: Account, token: String?, parameters: [ParameterValue]?, completion: @escaping (JobListQuietingDown?, Error?) -> Void) {
do {
try NetworkManager.manager.performBuild(account: account, job: job, token: token, parameters: parameters, completion: completion)
LoggingManager.loggingManager.logTriggeredBuild(withParameters: parameters?.map { $0.parameter.type } ?? [])
} catch {
completion(nil, error)
}
}
// MARK: - Refreshing
func updateData(completion: @escaping (Error?) -> Void) {
if let account = account, let job = job {
let userRequest = UserRequest.userRequestForJob(account: account, requestUrl: job.url)
_ = NetworkManager.manager.completeJobInformation(userRequest: userRequest, job: job, completion: { _, error in
completion(error)
})
}
}
@objc func openUrl() {
guard let job = self.job
else { return }
UIApplication.shared.open(job.url, options: [:], completionHandler: nil)
}
@objc func favorite() {
if let account = account, job != nil {
job?.toggleFavorite(account: account)
let imageName = !job!.isFavorite ? "fav" : "fav-fill"
navigationItem.rightBarButtonItem?.image = UIImage(named: imageName)
}
}
@objc func performRequest() {
updateData { error in
DispatchQueue.main.async {
guard error == nil
else {
if let error = error {
self.displayNetworkError(error: error, onReturnWithTextFields: { returnData in
self.updateAccount(data: returnData)
self.performRequest()
})
}
return
}
LoggingManager.loggingManager.log(contentView: .job)
if self.viewWillAppearCalled {
self.updateUI()
}
}
}
}
private func setupUI() {
let imageName = (job == nil || !job!.isFavorite) ? "fav" : "fav-fill"
let favoriteBarButtonItem = UIBarButtonItem(image: UIImage(named: imageName), style: .plain, target: self, action: #selector(favorite))
navigationItem.rightBarButtonItem = favoriteBarButtonItem
title = "Jobs"
updateUI()
}
func updateUI() {
tableView.reloadData()
navigationItem.rightBarButtonItem?.isEnabled = job?.isFullVersion ?? false
buildButton.isEnabled = job?.isFullVersion ?? false
}
// MARK: - ViewController Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? ParametersContainerViewController, segue.identifier == Constants.Identifiers.showParametersSegue {
dest.parameters = job?.parameters ?? []
dest.parametersDelegate = self
} else if let dest = segue.destination as? BuildViewController, segue.identifier == Constants.Identifiers.showBuildSegue, let build = sender as? Build {
dest.account = account
dest.build = build
} else if let dest = segue.destination as? ArtifactsTableViewController, segue.identifier == Constants.Identifiers.showArtifactsSegue,
let build = sender as? Build {
dest.account = account
dest.build = build
} else if let dest = segue.destination as? TestResultsTableViewController, segue.identifier == Constants.Identifiers.showTestResultsSegue,
let build = sender as? Build {
dest.account = account
dest.build = build
} else if let dest = segue.destination as? ConsoleOutputViewController, segue.identifier == Constants.Identifiers.showConsoleOutputSegue,
let build = sender as? Build, let account = self.account {
dest.request = NetworkManager.manager.getConsoleOutputUserRequest(build: build, account: account)
} else if let dest = segue.destination as? ChangesTableViewController, segue.identifier == Constants.Identifiers.showChangesSegue, let build = sender as? Build, let account = self.account {
dest.account = account
dest.build = build
}
}
}
extension JobViewController: ParametersViewControllerDelegate {
func completeBuildIdsForRunParameter(parameter: Parameter, completion: @escaping (Parameter) -> Void) {
guard let account = self.account, let projectName = parameter.additionalData as? String
else { return }
let baseUrl = account.baseUrl.appendingPathComponent("job").appendingPathComponent(projectName)
let userRequest = UserRequest.userRequestForJobBuildIds(account: account, requestUrl: baseUrl)
_ = NetworkManager.manager.getJobBuildIds(userRequest: userRequest) { buildIds, _ in
guard let ids = buildIds
else { completion(parameter); return }
parameter.additionalData = ids.builds.map { "\(projectName)#\($0.id)" } as AnyObject
completion(parameter)
}
}
func build(parameters: [ParameterValue], completion: @escaping (JobListQuietingDown?, Error?) -> Void) {
guard let job = job, let account = account
else { completion(nil, BuildError.notEnoughDataError); return }
performBuild(job: job, account: account, token: nil, parameters: parameters, completion: completion)
}
func updateAccount(data: [String: String?]) {
account?.username = data["username"]!
account?.password = data["password"]!
}
}
extension JobViewController: BuildsInformationOpeningDelegate {
func showLogs(build: Build) {
performSegue(withIdentifier: Constants.Identifiers.showConsoleOutputSegue, sender: build)
}
func showArtifacts(build: Build) {
performSegue(withIdentifier: Constants.Identifiers.showArtifactsSegue, sender: build)
}
func showTestResults(build: Build) {
performSegue(withIdentifier: Constants.Identifiers.showTestResultsSegue, sender: build)
}
func showChanges(build: Build) {
performSegue(withIdentifier: Constants.Identifiers.showChangesSegue, sender: build)
}
}
extension JobViewController: FilteringHeaderTableViewCellDelegate {
func didSelect(selected _: CustomStringConvertible, cell _: FilteringHeaderTableViewCell) {
if !showAllBuilds {
showAllBuilds = true
tableView.reloadSections([JobSection.otherBuilds.rawValue], with: .automatic)
}
}
func didDeselectAll() {
if showAllBuilds {
showAllBuilds = false
tableView.reloadSections([JobSection.otherBuilds.rawValue], with: .automatic)
}
}
}
|
mit
|
f871e4a9a9d68f0f5f50012d7c0ee20a
| 37.286017 | 197 | 0.630347 | 5.110577 | false | false | false | false |
PureSwift/BlueZ
|
Sources/BluetoothLinux/DeviceCommand.swift
|
2
|
1448
|
//
// DeviceCommand.swift
// BluetoothLinux
//
// Created by Alsey Coleman Miller on 3/2/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if os(Linux)
import Glibc
#elseif os(OSX) || os(iOS)
import Darwin.C
#endif
import Foundation
import Bluetooth
public extension HostController {
func deviceCommand<T: HCICommand>(_ command: T) throws {
try HCISendCommand(internalSocket, command: command)
}
func deviceCommand<T: HCICommandParameter>(_ commandParameter: T) throws {
let command = T.command
let parameterData = commandParameter.data
try HCISendCommand(internalSocket, command: command, parameterData: parameterData)
}
}
// MARK: - Internal HCI Function
internal func HCISendCommand <T: HCICommand> (_ deviceDescriptor: CInt,
command: T,
parameterData: Data = Data()) throws {
let packetType = HCIPacketType.Command.rawValue
let header = HCICommandHeader(command: command, parameterLength: UInt8(parameterData.count))
/// data sent to host controller interface
var data = [UInt8]([packetType]) + [UInt8](header.data) + [UInt8](parameterData)
// write to device descriptor socket
guard write(deviceDescriptor, &data, data.count) >= 0 // should we check if all data was written?
else { throw POSIXError.errorno }
}
|
mit
|
45590a9475fdbc6afc59b96a6af57093
| 27.372549 | 101 | 0.648238 | 4.293769 | false | false | false | false |
zoeyzhong520/InformationTechnology
|
InformationTechnology/InformationTechnology/Classes/Recommend推荐/Science科技/Controller/CellDetailViewController.swift
|
1
|
2468
|
//
// CellDetailViewController.swift
// InformationTechnology
//
// Created by qianfeng on 16/11/4.
// Copyright © 2016年 zzj. All rights reserved.
//
import UIKit
import Alamofire
class CellDetailViewController: UIViewController,navigationBarProtocol {
//创建视图
private var detailView:CellDetailView?
//定义数据刷新页码
private var currentPage = 1
//cell数据接口
var urlString:String?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
//下载cell详情页面的数据
downloadData()
//创建视图
configUI()
}
func leftBtnClick() {
navigationController?.popViewControllerAnimated(true)
}
func configUI() {
addTitle("推荐")
self.navigationController?.navigationBar.tintColor = UIColor(red: 209/255.0, green: 49/255.0, blue: 92/255.0, alpha: 1.0)
//添加button
//addButton(nil, imageName: "userdetails_back_unselected_night", position: .left, selector: #selector(leftBtnClick))
automaticallyAdjustsScrollViewInsets = false
detailView = CellDetailView(frame: CGRectZero)
view.addSubview(detailView!)
//约束
detailView?.snp_makeConstraints(closure: { (make) in
make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(64, 0, 0, 0))
})
}
//下载cell详情页面的数据
func downloadData() {
let aurlLimitList = String(format: urlString!, currentPage)
let downloader = KTCDownloader()
downloader.delegate = self
downloader.postWithUrl(aurlLimitList)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK:KTCDownloader的代理方法
extension CellDetailViewController:KTCDownloaderProtocol {
//下载失败
func downloader(downloader: KTCDownloader, didFailWithError error: NSError) {
print(error)
}
//下载成功
func downloader(downloader: KTCDownloader, didFinishWithData data: NSData?) {
if let tmpData = data {
let model = CellDetailModel.parseData(tmpData)
//json解析
self.detailView?.model = model
}
}
}
|
mit
|
2dfed568035adc3a623e79e920554ea1
| 22.47 | 129 | 0.617384 | 4.849174 | false | false | false | false |
danieleggert/SimpleKeyValueStore
|
SimpleKeyValueStore/SimpleKeyValueStore.swift
|
1
|
4065
|
//
// SimpleKeyValueStore.swift
// SimpleKeyValueStore
//
// Created by Daniel Eggert on 12/08/2015.
// Copyright © 2015 Daniel Eggert. All rights reserved.
//
import Foundation
/// Generic key-value-store
public protocol KeyValueStore : class, SequenceType {
typealias Key = String
typealias Value = NSData
subscript (key: Key) -> Value? { get set }
typealias Generator : KeyValueStoreGeneratorType
func generate() -> Self.Generator
}
extension KeyValueStore {
public func deleteDataForKey(key: Key) {
self[key] = nil
}
}
public func dbmKeyValueStoreAtURL(URL: NSURL) throws -> DBMKeyValueStore {
return try DBMKeyValueStore(URL: URL)
}
public protocol KeyValueStoreGeneratorType : GeneratorType {
typealias Element = String
}
public final class DBMKeyValueStore : KeyValueStore {
public enum Error : ErrorType {
case UnableToOpen(Int32)
}
private let database: UnsafeMutablePointer<DBM>
init(URL: NSURL) throws {
database = dbm_open(URL.fileSystemRepresentation, O_RDWR |
O_CREAT, 0x1b0)
if database == UnsafeMutablePointer<DBM>(nilLiteral: ()) {
throw Error.UnableToOpen(dbm_error(database))
}
}
deinit {
dbm_close(database)
}
public subscript (key: String) -> NSData? {
get {
return dataForKey(key)
}
set {
setData(newValue, forKey: key)
}
}
private func setData(data: NSData?, forKey key: String) {
if let data = data {
return key.withDatum { keyAsDatum in
return data.withDatum { dataAsDatum in
dbm_store(database, keyAsDatum, dataAsDatum, DBM_REPLACE)
fsync(dbm_dirfno(database))
}
}
} else {
return key.withDatum { keyAsDatum in
dbm_delete(database, keyAsDatum)
fsync(dbm_dirfno(database))
}
}
}
private func dataForKey(key: String) -> NSData? {
return key.withDatum { keyAsDatum -> NSData? in
let d = dbm_fetch(database, keyAsDatum)
if d.dptr == UnsafeMutablePointer<Void>(nilLiteral: ()) {
return nil
} else {
return NSData(dbmDatum: d)
}
}
}
public typealias Generator = DBMKeyValueStoreGenerator
public func generate() -> DBMKeyValueStoreGenerator {
return DBMKeyValueStoreGenerator(store: self)
}
}
public struct DBMKeyValueStoreGenerator : KeyValueStoreGeneratorType {
private let store: DBMKeyValueStore
private var didGetFirst = false
private init(store: DBMKeyValueStore) {
self.store = store
}
public mutating func next() -> String? {
if !didGetFirst {
didGetFirst = true
return dbm_firstkey(store.database).toString()
} else {
return dbm_nextkey(store.database).toString()
}
}
}
extension String {
private func withDatum<R>(@noescape block: (datum) -> R) -> R {
let buffer = nulTerminatedUTF8
return buffer.withUnsafeBufferPointer { ubp -> R in
let ump = UnsafeMutablePointer<Void>(ubp.baseAddress)
let d = datum(dptr: ump, dsize: buffer.count - 1)
return block(d)
}
}
}
extension datum {
private func toString() -> String? {
if let data = NSData(dbmDatum: self) {
return NSString(data: data, encoding: NSUTF8StringEncoding) as String?
}
return nil
}
}
extension NSData {
private convenience init?(dbmDatum d: datum) {
guard d.dptr != UnsafeMutablePointer<Void>(nilLiteral: ()) else { return nil }
self.init(bytes: d.dptr, length: d.dsize)
}
private func withDatum<R>(@noescape block: (datum) -> R) -> R {
let ump = UnsafeMutablePointer<Void>(bytes)
let d = datum(dptr: ump, dsize: length)
return block(d)
}
}
|
mit
|
aaa2856a668dd3e843c06efcc75970e7
| 26.646259 | 86 | 0.597195 | 4.300529 | false | false | false | false |
DRybochkin/Spika.swift
|
Spika/Models/CSMessageModel.swift
|
1
|
2612
|
//
// CSMessageModel.swift
// Prototype
//
// Created by Dmitry Rybochkin on 25.02.17.
// Copyright (c) 2015 Clover Studio. All rights reserved.
//
import Foundation
import UIKit
import JSONModel
class CSMessageModel: CSModel {
var id: String!
var userID: String!
var roomID: String!
var user: CSUserModel!
var messageType: KAppMessageType!
var type: NSNumber! {
didSet {
messageType = KAppMessageType(rawValue: type.intValue)!
}
}
var message: String!
var created: Date!
var file: CSFileModel!
var localID: String!
var location: CSLocationModel!
var seenBy: [CSSeenByModel]!
var deleted: Date!
var messageStatus: KAppMessageStatus = KAppMessageStatus.Received
var status: NSNumber! {
didSet {
messageStatus = KAppMessageStatus(rawValue: status.intValue)!
}
}
static func createMessage(user: CSUserModel!, message: String!, type: KAppMessageType!, file: CSFileModel!, location: CSLocationModel!) -> CSMessageModel {
let messageForReturn = CSMessageModel()
messageForReturn.user = user
messageForReturn.userID = user.userID
messageForReturn.roomID = user.roomID
messageForReturn.type = NSNumber(value: type.rawValue)
messageForReturn.status = NSNumber(value: KAppMessageStatus.Sent.rawValue)
messageForReturn.message = message
messageForReturn.localID = messageForReturn.generateLocalIDwithLength(32)
messageForReturn.created = Date()
if (file != nil) {
messageForReturn.file = file
}
if (location != nil) {
messageForReturn.location = location
}
return messageForReturn
}
func updateMessage(withData data: CSMessageModel) {
self.seenBy = data.seenBy
self.deleted = data.deleted
}
func generateLocalIDwithLength(_ length: Int) -> String {
var AB: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"
var randomString: String = ""
for _ in 0..<length {
let randomIndex = Int(arc4random_uniform(UInt32(AB.characters.count)))
let char = AB[AB.index(AB.startIndex, offsetBy: randomIndex)]
randomString.append(char)
}
return randomString
}
override class func keyMapper() -> JSONKeyMapper! {
return JSONKeyMapper(modelToJSONDictionary: ["id":"_id"])
}
override class func classForCollectionProperty(propertyName: String!) -> Swift.AnyClass! {
return CSSeenByModel.self
}
}
|
mit
|
3704ae78eece7fd3781ebd11ffdfdb77
| 31.65 | 159 | 0.658116 | 4.472603 | false | false | false | false |
yaslab/ZipArchive.swift
|
Sources/ZipModel/FileTime.swift
|
1
|
2802
|
//
// DateTime.swift
// ZipArchive
//
// Created by Yasuhiro Hatta on 2017/06/18.
// Copyright © 2017 yaslab. All rights reserved.
//
import struct Foundation.Date
import struct Foundation.DateComponents
import struct Foundation.Calendar
import struct Foundation.TimeZone
public struct FileTime {
public var year: Int
public var month: Int
public var day: Int
public var hour: Int
public var minute: Int
public var second: Int
public init(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int) {
self.year = year
self.month = month
self.day = day
self.hour = hour
self.minute = minute
self.second = second
}
}
extension FileTime {
public init(date: UInt16, time: UInt16) {
let date = Int(date)
let time = Int(time)
year = ((date & 0b1111111000000000) >> 9) + 1980
month = ((date & 0b0000000111100000) >> 5)
day = ( date & 0b0000000000011111)
hour = ((time & 0b1111100000000000) >> 11)
minute = ((time & 0b0000011111100000) >> 5)
second = ( time & 0b0000000000011111) * 2
}
public var zipDate: UInt16 {
var date = 0
var y = 0
if year > 1980 {
y = year - 1980
}
date += y << 9
date += month << 5
date += day
return UInt16(date)
}
public var zipTime: UInt16 {
var time = 0
time += hour << 11
time += minute << 5
time += second / 2
return UInt16(time)
}
}
extension FileTime {
public var dateComponents: DateComponents {
var comps = DateComponents()
comps.year = year
comps.month = month
comps.day = day
comps.hour = hour
comps.minute = minute
comps.second = second
return comps
}
public func date(with timeZone: TimeZone) -> Date? {
var comps = self.dateComponents
comps.timeZone = timeZone
let calendar = Calendar(identifier: .gregorian)
return calendar.date(from: comps)
}
}
extension FileTime {
public init(date: Date, timeZone: TimeZone = .current) {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
let comps = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
year = comps.year!
month = comps.month!
day = comps.day!
hour = comps.hour!
minute = comps.minute!
second = comps.second!
}
public static func now(with timeZone: TimeZone = .current) -> FileTime {
return FileTime(date: Date(), timeZone: timeZone)
}
}
|
mit
|
0cd52378a57104806cc4de80e41fd8c1
| 23.356522 | 103 | 0.561228 | 4.131268 | false | false | false | false |
ruikong/actor-platform
|
actor-apps/app-ios/Actor/Controllers/Conversation/ConversationViewController.swift
|
15
|
32495
|
//
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
import MobileCoreServices
class ConversationViewController: ConversationBaseViewController {
// MARK: -
// MARK: Private vars
private let BubbleTextIdentifier = "BubbleTextIdentifier"
private let BubbleMediaIdentifier = "BubbleMediaIdentifier"
private let BubbleDocumentIdentifier = "BubbleDocumentIdentifier"
private let BubbleServiceIdentifier = "BubbleServiceIdentifier"
private let BubbleBannerIdentifier = "BubbleBannerIdentifier"
private let titleView: UILabel = UILabel();
private let subtitleView: UILabel = UILabel();
private let navigationView: UIView = UIView();
private let avatarView = BarAvatarView(frameSize: 36, type: .Rounded)
private let backgroundView: UIView = UIView()
private var layoutCache: LayoutCache!
// private let heightCache = HeightCache()
//
// // MARK: -
// MARK: Public vars
let binder: Binder = Binder();
var unreadMessageId: jlong = 0
// MARK: -
// MARK: Constructors
override init(peer: AMPeer) {
super.init(peer: peer);
// Messages
self.collectionView.registerClass(AABubbleTextCell.self, forCellWithReuseIdentifier: BubbleTextIdentifier)
self.collectionView.registerClass(AABubbleMediaCell.self, forCellWithReuseIdentifier: BubbleMediaIdentifier)
self.collectionView.registerClass(AABubbleDocumentCell.self, forCellWithReuseIdentifier: BubbleDocumentIdentifier)
self.collectionView.registerClass(AABubbleServiceCell.self, forCellWithReuseIdentifier: BubbleServiceIdentifier)
self.collectionView.backgroundColor = UIColor.clearColor()
self.collectionView.alwaysBounceVertical = true
backgroundView.clipsToBounds = true
backgroundView.backgroundColor = UIColor(
patternImage:UIImage(named: "bg_foggy_birds")!.tintBgImage(MainAppTheme.bubbles.chatBgTint))
view.insertSubview(backgroundView, atIndex: 0)
// Text Input
self.textInputbar.backgroundColor = MainAppTheme.chat.chatField
self.textInputbar.autoHideRightButton = false;
self.textView.placeholder = NSLocalizedString("ChatPlaceholder",comment: "Placeholder")
self.rightButton.setTitle(NSLocalizedString("ChatSend", comment: "Send"), forState: UIControlState.Normal)
self.rightButton.setTitleColor(MainAppTheme.chat.sendEnabled, forState: UIControlState.Normal)
self.rightButton.setTitleColor(MainAppTheme.chat.sendDisabled, forState: UIControlState.Disabled)
self.keyboardPanningEnabled = true;
self.textView.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
self.leftButton.setImage(UIImage(named: "conv_attach")!
.tintImage(MainAppTheme.chat.attachColor)
.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal),
forState: UIControlState.Normal)
// Navigation Title
navigationView.frame = CGRectMake(0, 0, 190, 44);
navigationView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
titleView.frame = CGRectMake(0, 4, 190, 20)
titleView.font = UIFont(name: "HelveticaNeue-Medium", size: 17)!
titleView.adjustsFontSizeToFitWidth = false;
titleView.textColor = Resources.PrimaryLightText
titleView.textAlignment = NSTextAlignment.Center;
titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
titleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
subtitleView.frame = CGRectMake(0, 22, 190, 20);
subtitleView.font = UIFont.systemFontOfSize(13);
subtitleView.adjustsFontSizeToFitWidth=false;
subtitleView.textColor = Resources.SecondaryLightText
subtitleView.textAlignment = NSTextAlignment.Center;
subtitleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
subtitleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
navigationView.addSubview(titleView);
navigationView.addSubview(subtitleView);
self.navigationItem.titleView = navigationView;
// Navigation Avatar
avatarView.frame = CGRectMake(0, 0, 36, 36)
var avatarTapGesture = UITapGestureRecognizer(target: self, action: "onAvatarTap");
avatarTapGesture.numberOfTapsRequired = 1
avatarTapGesture.numberOfTouchesRequired = 1
avatarView.addGestureRecognizer(avatarTapGesture)
var barItem = UIBarButtonItem(customView: avatarView)
self.navigationItem.rightBarButtonItem = barItem
// self.singleTapGesture.cancelsTouchesInView = true
// var longPressGesture = AALongPressGestureRecognizer(target: self, action: Selector("longPress:"))
// self.collectionView.addGestureRecognizer(longPressGesture)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
textView.text = MSG.loadDraftWithPeer(peer)
// Installing bindings
if (UInt(peer.getPeerType().ordinal()) == AMPeerType.PRIVATE.rawValue) {
let user = MSG.getUserWithUid(peer.getPeerId())
var nameModel = user.getNameModel();
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(user.getAvatarModel(), closure: { (value: AMAvatar?) -> () in
self.avatarView.bind(user.getNameModel().get(), id: user.getId(), avatar: value)
})
binder.bind(MSG.getTypingWithUid(peer.getPeerId())!, valueModel2: user.getPresenceModel()!, closure:{ (typing:JavaLangBoolean?, presence:AMUserPresence?) -> () in
if (typing != nil && typing!.booleanValue()) {
self.subtitleView.text = MSG.getFormatter().formatTyping();
self.subtitleView.textColor = Resources.PrimaryLightText
} else {
var stateText = MSG.getFormatter().formatPresence(presence, withSex: user.getSex())
self.subtitleView.text = stateText;
var state = UInt(presence!.getState().ordinal())
if (state == AMUserPresence_State.ONLINE.rawValue) {
self.subtitleView.textColor = Resources.PrimaryLightText
} else {
self.subtitleView.textColor = Resources.SecondaryLightText
}
}
})
} else if (UInt(peer.getPeerType().ordinal()) == AMPeerType.GROUP.rawValue) {
let group = MSG.getGroupWithGid(peer.getPeerId())
var nameModel = group.getNameModel()
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(group.getAvatarModel(), closure: { (value: AMAvatar?) -> () in
self.avatarView.bind(group.getNameModel().get(), id: group.getId(), avatar: value)
})
binder.bind(MSG.getGroupTypingWithGid(group.getId())!, valueModel2: group.getMembersModel(), valueModel3: group.getPresenceModel(), closure: { (typingValue:IOSIntArray?, members:JavaUtilHashSet?, onlineCount:JavaLangInteger?) -> () in
// if (!group.isMemberModel().get().booleanValue()) {
// self.subtitleView.text = NSLocalizedString("ChatNoGroupAccess", comment: "You is not member")
// self.textInputbar.hidden = true
// return
// } else {
// self.textInputbar.hidden = false
// }
if (typingValue != nil && typingValue!.length() > 0) {
self.subtitleView.textColor = Resources.PrimaryLightText
if (typingValue!.length() == 1) {
var uid = typingValue!.intAtIndex(0);
var user = MSG.getUserWithUid(uid)
self.subtitleView.text = MSG.getFormatter().formatTypingWithName(user.getNameModel().get())
} else {
self.subtitleView.text = MSG.getFormatter().formatTypingWithCount(typingValue!.length());
}
} else {
var membersString = MSG.getFormatter().formatGroupMembers(members!.size())
if (onlineCount == nil || onlineCount!.integerValue == 0) {
self.subtitleView.textColor = Resources.SecondaryLightText
self.subtitleView.text = membersString;
} else {
membersString = membersString + ", ";
var onlineString = MSG.getFormatter().formatGroupOnline(onlineCount!.intValue());
var attributedString = NSMutableAttributedString(string: (membersString + onlineString))
attributedString.addAttribute(NSForegroundColorAttributeName, value: Resources.PrimaryLightText, range: NSMakeRange(membersString.size(), onlineString.size()))
self.subtitleView.attributedText = attributedString
}
}
})
}
MSG.onConversationOpenWithPeer(peer)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
backgroundView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
}
override func viewDidLoad() {
super.viewDidLoad()
// unreadMessageId = MSG.loadLastReadState(peer)
navigationItem.backBarButtonItem = UIBarButtonItem(title: NSLocalizedString("NavigationBack",comment: "Back button"), style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
MSG.onConversationOpenWithPeer(peer)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if count(navigationController!.viewControllers) > 2 {
if let firstController = navigationController!.viewControllers[0] as? UIViewController,
let currentController: AnyObject = navigationController!.viewControllers[count(navigationController!.viewControllers) - 1] as? ConversationViewController {
navigationController!.setViewControllers([firstController, currentController], animated: false)
}
}
}
override func setUnread(rid: jlong) {
self.unreadMessageId = rid
}
// override func afterLoaded() {
// NSLog("afterLoaded")
// var sortState = MSG.loadLastReadState(peer)
//
// if (sortState == 0) {
// NSLog("lastReadMessage == 0")
// return
// }
//
// if (getCount() == 0) {
// NSLog("getCount() == 0")
// return
// }
//
// var index = -1
// unreadMessageId = 0
// for var i = getCount() - 1; i >= 0; --i {
// var item = objectAtIndex(i) as! AMMessage
// if (item.getSortDate() > sortState && item.getSenderId() != MSG.myUid()) {
// index = i
// unreadMessageId = item.getRid()
// break
// }
// }
//
// if (index < 0) {
// NSLog("Not found")
// } else {
// NSLog("Founded @\(index)")
// // self.tableView.reloadData()
// // self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: Int(index), inSection: 0), atScrollPosition: UITableViewScrollPosition.Middle, animated: false)
// }
// }
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated);
MSG.saveDraftWithPeer(peer, withDraft: textView.text);
}
// MARK: -
// MARK: Methods
func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Began {
let point = gesture.locationInView(self.collectionView)
let indexPath = self.collectionView.indexPathForItemAtPoint(point)
if indexPath != nil {
if let cell = collectionView.cellForItemAtIndexPath(indexPath!) as? AABubbleCell {
if cell.bubble.superview != nil {
var bubbleFrame = cell.bubble.frame
bubbleFrame = collectionView.convertRect(bubbleFrame, fromView: cell.bubble.superview)
if CGRectContainsPoint(bubbleFrame, point) {
// cell.becomeFirstResponder()
var menuController = UIMenuController.sharedMenuController()
menuController.setTargetRect(bubbleFrame, inView:collectionView)
menuController.menuItems = [UIMenuItem(title: "Copy", action: "copy")]
menuController.setMenuVisible(true, animated: true)
}
}
}
}
}
}
override func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
// if (touch.view == self.tableView) {
// return true
// }
if (touch.view is UITableViewCell) {
return true
}
if (touch.view.superview is UITableViewCell) {
return true
}
// if (touch.view.superview?.superview is UITableViewCell) {
// return true
// }
// if([touch.view isKindOfClass:[UITableViewCell class]]) {
// return NO;
// }
// // UITableViewCellContentView => UITableViewCell
// if([touch.view.superview isKindOfClass:[UITableViewCell class]]) {
// return NO;
// }
// // UITableViewCellContentView => UITableViewCellScrollView => UITableViewCell
// if([touch.view.superview.superview isKindOfClass:[UITableViewCell class]]) {
// return NO;
// }
// if (touch.view is UITableViewCellContentView && gestureRecognizer == self.singleTapGesture) {
// return true
// }
// if (touch.view.superview is AABubbleCell && gestureRecognizer == self.singleTapGesture) {
// return false
// }
return false
}
// func tap(gesture: UITapGestureRecognizer) {
// if gesture.state == UIGestureRecognizerState.Ended {
// let point = gesture.locationInView(tableView)
// let indexPath = tableView.indexPathForRowAtPoint(point)
// if indexPath != nil {
// if let cell = tableView.cellForRowAtIndexPath(indexPath!) as? AABubbleCell {
//
//
// } else if let content = item.getContent() as? AMDocumentContent {
// if let documentCell = cell as? AABubbleDocumentCell {
// var frame = documentCell.bubble.frame
// frame = tableView.convertRect(frame, fromView: cell.bubble.superview)
// if CGRectContainsPoint(frame, point) {
// if let fileSource = content.getSource() as? AMFileRemoteSource {
// MSG.requestStateWithFileId(fileSource.getFileReference().getFileId(), withCallback: CocoaDownloadCallback(
// notDownloaded: { () -> () in
// MSG.startDownloadingWithReference(fileSource.getFileReference())
// }, onDownloading: { (progress) -> () in
// MSG.cancelDownloadingWithFileId(fileSource.getFileReference().getFileId())
// }, onDownloaded: { (reference) -> () in
// var controller = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: CocoaFiles.pathFromDescriptor(reference))!)
// controller.delegate = self
// controller.presentPreviewAnimated(true)
// }))
// } else if let fileSource = content.getSource() as? AMFileLocalSource {
// MSG.requestUploadStateWithRid(item.getRid(), withCallback: CocoaUploadCallback(
// notUploaded: { () -> () in
// MSG.resumeUploadWithRid(item.getRid())
// }, onUploading: { (progress) -> () in
// MSG.pauseUploadWithRid(item.getRid())
// }, onUploadedClosure: { () -> () in
// var controller = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: CocoaFiles.pathFromDescriptor(fileSource.getFileDescriptor()))!)
// controller.delegate = self
// controller.presentPreviewAnimated(true)
// }))
// }
// }
// }
// } else if let content = item.getContent() as? AMBannerContent {
// if let bannerCell = cell as? AABubbleAdCell {
// var frame = bannerCell.contentView.frame
// frame = tableView.convertRect(frame, fromView: cell.contentView.superview)
// if CGRectContainsPoint(frame, point) {
// UIApplication.sharedApplication().openURL(NSURL(string: content.getAdUrl())!)
// }
// }
// }
// }
// }
// }
// }
func onAvatarTap() {
let id = Int(peer.getPeerId())
var controller: AAViewController
if (UInt(peer.getPeerType().ordinal()) == AMPeerType.PRIVATE.rawValue) {
controller = UserViewController(uid: id)
} else if (UInt(peer.getPeerType().ordinal()) == AMPeerType.GROUP.rawValue) {
controller = GroupViewController(gid: id)
} else {
return
}
if (isIPad) {
var navigation = AANavigationController()
navigation.viewControllers = [controller]
var popover = UIPopoverController(contentViewController: navigation)
controller.popover = popover
popover.presentPopoverFromBarButtonItem(navigationItem.rightBarButtonItem!,
permittedArrowDirections: UIPopoverArrowDirection.Up,
animated: true)
} else {
navigateNext(controller, removeCurrent: false)
}
}
func onBubbleAvatarTap(view: UIView, uid: jint) {
var controller = UserViewController(uid: Int(uid))
if (isIPad) {
var navigation = AANavigationController()
navigation.viewControllers = [controller]
var popover = UIPopoverController(contentViewController: navigation)
controller.popover = popover
popover.presentPopoverFromRect(view.bounds, inView: view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
} else {
navigateNext(controller, removeCurrent: false)
}
}
override func textWillUpdate() {
super.textWillUpdate();
MSG.onTypingWithPeer(peer);
}
override func didPressRightButton(sender: AnyObject!) {
MSG.trackTextSendWithPeer(peer)
MSG.sendMessageWithPeer(peer, withText: textView.text)
super.didPressRightButton(sender);
}
override func didPressLeftButton(sender: AnyObject!) {
super.didPressLeftButton(sender)
var hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
var buttons = hasCamera ? ["PhotoCamera", "PhotoLibrary", "SendDocument"] : ["PhotoLibrary", "SendDocument"]
var tapBlock = { (index: Int) -> () in
if index == 0 || (hasCamera && index == 1) {
var pickerController = AAImagePickerController()
pickerController.sourceType = (hasCamera && index == 0) ?
UIImagePickerControllerSourceType.Camera : UIImagePickerControllerSourceType.PhotoLibrary
pickerController.mediaTypes = [kUTTypeImage]
pickerController.view.backgroundColor = MainAppTheme.list.bgColor
pickerController.navigationBar.tintColor = MainAppTheme.navigation.barColor
pickerController.delegate = self
pickerController.navigationBar.tintColor = MainAppTheme.navigation.titleColor
pickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: MainAppTheme.navigation.titleColor]
self.presentViewController(pickerController, animated: true, completion: nil)
} else if index >= 0 {
var documentPicker = UIDocumentMenuViewController(documentTypes: UTTAll, inMode: UIDocumentPickerMode.Import)
documentPicker.view.backgroundColor = UIColor.clearColor()
documentPicker.delegate = self
self.presentViewController(documentPicker, animated: true, completion: nil)
}
}
if (isIPad) {
showActionSheet(buttons, cancelButton: "AlertCancel", destructButton: nil, sourceView: self.leftButton, sourceRect: self.leftButton.bounds, tapClosure: tapBlock)
} else {
showActionSheetFast(buttons, cancelButton: "AlertCancel", tapClosure: tapBlock)
}
}
override func buildCell(collectionView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UICollectionViewCell {
var message = (item as! AMMessage);
var cell: AABubbleCell
if (message.getContent() is AMTextContent) {
cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleTextIdentifier, forIndexPath: indexPath) as! AABubbleTextCell
} else if (message.getContent() is AMPhotoContent) {
cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleMediaIdentifier, forIndexPath: indexPath) as! AABubbleMediaCell
} else if (message.getContent() is AMDocumentContent) {
cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleDocumentIdentifier, forIndexPath: indexPath) as! AABubbleDocumentCell
} else if (message.getContent() is AMServiceContent){
cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleServiceIdentifier, forIndexPath: indexPath) as! AABubbleServiceCell
} else {
cell = collectionView.dequeueReusableCellWithReuseIdentifier(BubbleTextIdentifier, forIndexPath: indexPath) as! AABubbleTextCell
}
cell.setConfig(peer, controller: self)
return cell
}
override func bindCell(collectionView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UICollectionViewCell) {
var message = item as! AMMessage
var bubbleCell = (cell as! AABubbleCell)
var setting = buildCellSetting(indexPath.row)
bubbleCell.performBind(message, setting: setting, layoutCache: layoutCache)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(6, 0, 100, 0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, idForItemAtIndexPath indexPath: NSIndexPath) -> Int64 {
var message = objectAtIndexPath(indexPath) as! AMMessage
return Int64(message.getRid())
}
override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, gravityForItemAtIndexPath indexPath: NSIndexPath) -> MessageGravity {
return MessageGravity.Center
}
override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var message = objectAtIndexPath(indexPath) as! AMMessage;
var setting = buildCellSetting(indexPath.row)
let group = peer.getPeerType().ordinal() == jint(AMPeerType.GROUP.rawValue)
var height = MessagesLayouting.measureHeight(message, group: group, setting: setting, layoutCache: layoutCache)
return CGSizeMake(self.view.bounds.width, height)
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!) -> Bool {
// return true
return false
}
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
// var cell = collectionView.cellForItemAtIndexPath(indexPath) as! AABubbleCell
// UIMenuController.sharedMenuController().setTargetRect(cell.bubble.bounds, inView: cell.bubble)
// return true
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!) {
}
override func onItemsAdded(indexes: [Int]) {
var toUpdate = [Int]()
for ind in indexes {
if !indexes.contains(ind + 1) {
if ind + 1 < getCount() {
toUpdate.append(ind + 1)
}
}
if !indexes.contains(ind - 1) {
if ind > 0 {
toUpdate.append(ind - 1)
}
}
}
updateRows(toUpdate)
}
override func needFullReload(item: AnyObject?, cell: UICollectionViewCell) -> Bool {
var message = (item as! AMMessage);
if cell is AABubbleTextCell {
if (message.getContent() is AMPhotoContent) {
return true
}
}
return false
}
func buildCellSetting(index: Int) -> CellSetting {
// return CellSetting(showDate: false, clenchTop: false, clenchBottom: false, showNewMessages: false)
var current = objectAtIndex(index) as! AMMessage
var next: AMMessage! = index > 0 ? objectAtIndex(index - 1) as! AMMessage : nil
var prev: AMMessage! = index + 1 < getCount() ? objectAtIndex(index + 1) as! AMMessage : nil
var isShowDate = true
var isShowDateNext = true
var isShowNewMessages = (unreadMessageId == current.getRid())
var clenchTop = false
var clenchBottom = false
if (prev != nil) {
isShowDate = !areSameDate(current, prev: prev)
if !isShowDate {
clenchTop = useCompact(current, next: prev)
}
}
if (next != nil) {
if areSameDate(next, prev: current) {
clenchBottom = useCompact(current, next: next)
}
}
return CellSetting(showDate: isShowDate, clenchTop: clenchTop, clenchBottom: clenchBottom, showNewMessages: isShowNewMessages)
}
func useCompact(source: AMMessage, next: AMMessage) -> Bool {
if (source.getContent() is AMServiceContent) {
if (next.getContent() is AMServiceContent) {
return true
}
} else {
if (next.getContent() is AMServiceContent) {
return false
}
if (source.getSenderId() == next.getSenderId()) {
return true
}
}
return false
}
func areSameDate(source:AMMessage, prev: AMMessage) -> Bool {
let calendar = NSCalendar.currentCalendar()
var currentDate = NSDate(timeIntervalSince1970: Double(source.getDate())/1000.0)
var currentDateComp = calendar.components(.CalendarUnitDay | .CalendarUnitYear | .CalendarUnitMonth, fromDate: currentDate)
var nextDate = NSDate(timeIntervalSince1970: Double(prev.getDate())/1000.0)
var nextDateComp = calendar.components(.CalendarUnitDay | .CalendarUnitYear | .CalendarUnitMonth, fromDate: nextDate)
return (currentDateComp.year == nextDateComp.year && currentDateComp.month == nextDateComp.month && currentDateComp.day == nextDateComp.day)
}
override func displayListForController() -> AMBindedDisplayList {
var res = MSG.getMessagesGlobalListWithPeer(peer)
if (res.getBackgroundProcessor() == nil) {
res.setBackgroundProcessor(BubbleBackgroundProcessor())
}
layoutCache = (res.getBackgroundProcessor() as! BubbleBackgroundProcessor).layoutCache
return res
}
}
// MARK: -
// MARK: UIDocumentPicker Delegate
extension ConversationViewController: UIDocumentPickerDelegate {
func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
var path = url.path!;
var fileName = url.lastPathComponent
var range = path.rangeOfString("/tmp", options: NSStringCompareOptions.allZeros, range: nil, locale: nil)
var descriptor = path.substringFromIndex(range!.startIndex)
NSLog("Picked file: \(descriptor)")
MSG.trackDocumentSendWithPeer(peer)
MSG.sendDocumentWithPeer(peer, withName: fileName, withMime: "application/octet-stream", withDescriptor: descriptor)
}
}
// MARK: -
// MARK: UIImagePickerController Delegate
extension ConversationViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
MainAppTheme.navigation.applyStatusBar()
picker.dismissViewControllerAnimated(true, completion: nil)
MSG.trackPhotoSendWithPeer(peer)
MSG.sendUIImage(image, peer: peer)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
MainAppTheme.navigation.applyStatusBar()
picker.dismissViewControllerAnimated(true, completion: nil)
MSG.sendUIImage(info[UIImagePickerControllerOriginalImage] as! UIImage, peer: peer)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
MainAppTheme.navigation.applyStatusBar()
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
extension ConversationViewController: UIDocumentMenuDelegate {
func documentMenu(documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
self.presentViewController(documentPicker, animated: true, completion: nil)
}
}
|
mit
|
740d27ed05926b5ade916573d72f0b93
| 46.508772 | 246 | 0.620403 | 5.650322 | false | false | false | false |
wu890608/wu89
|
wu89/wu89/Classes/Tools/NetworkingTool.swift
|
1
|
776
|
//
// NetworkingTool.swift
// Neworking
//
// Created by wu on 2017/6/17.
// Copyright © 2017年 wu. All rights reserved.
//
import Foundation
import Alamofire
enum MethodType {
case GET
case POST
}
class NetworkTools {
class func requestData(type:MethodType,URLString:String,parameters:[String:NSString]? = nil,finish:@escaping (_ result:AnyObject)->()) {
let method = type == .GET ? HTTPMethod.get :HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
guard let result = response.result.value else{
print(response.result.error as Any)
return
}
finish(result as AnyObject)
}
}
}
|
mit
|
69221f35e34cb513c5b83af4ab70c331
| 23.935484 | 140 | 0.620957 | 4.367232 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/ViewRelated/Blog/Blogging Reminders/BloggingRemindersPushPromptViewController.swift
|
1
|
9861
|
import UIKit
class BloggingRemindersPushPromptViewController: UIViewController {
// MARK: - Subviews
private let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = Metrics.stackSpacing
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .equalSpacing
return stackView
}()
private let imageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: Images.bellImageName))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.tintColor = .systemYellow
return imageView
}()
private let titleLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.font = WPStyleGuide.serifFontForTextStyle(.title1, fontWeight: .semibold)
label.numberOfLines = 2
label.textAlignment = .center
label.text = TextContent.title
return label
}()
private let promptLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.font = .preferredFont(forTextStyle: .body)
label.text = TextContent.prompt
label.numberOfLines = 4
label.textAlignment = .center
label.textColor = .secondaryLabel
return label
}()
private let hintLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.font = .preferredFont(forTextStyle: .body)
label.text = TextContent.hint
label.numberOfLines = 4
label.textAlignment = .center
label.textColor = .secondaryLabel
return label
}()
private lazy var turnOnNotificationsButton: UIButton = {
let button = FancyButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.isPrimary = true
button.setTitle(TextContent.turnOnButtonTitle, for: .normal)
button.addTarget(self, action: #selector(turnOnButtonTapped), for: .touchUpInside)
button.titleLabel?.adjustsFontSizeToFitWidth = true
return button
}()
private lazy var dismissButton: UIButton = {
let button = UIButton(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(.gridicon(.cross), for: .normal)
button.tintColor = .secondaryLabel
button.addTarget(self, action: #selector(dismissTapped), for: .touchUpInside)
return button
}()
// MARK: - Properties
/// Indicates whether push notifications have been disabled or not.
///
private var pushNotificationsAuthorized: UNAuthorizationStatus = .notDetermined {
didSet {
navigateIfNecessary()
}
}
/// Analytics tracker
///
private let tracker: BloggingRemindersTracker
/// The closure that will be called once push notifications have been authorized.
///
private let onAuthorized: () -> ()
// MARK: - Initializers
init(
tracker: BloggingRemindersTracker,
onAuthorized: @escaping () -> ()) {
self.tracker = tracker
self.onAuthorized = onAuthorized
super.init(nibName: nil, bundle: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationBecameActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
required init?(coder: NSCoder) {
// This VC is designed to be initialized programmatically.
fatalError("Use init(tracker:) instead")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .basicBackground
view.addSubview(dismissButton)
configureStackView()
view.addSubview(turnOnNotificationsButton)
configureConstraints()
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewDidAppear(_ animated: Bool) {
tracker.screenShown(.enableNotifications)
super.viewDidAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// If a parent VC is being dismissed, and this is the last view shown in its navigation controller, we'll assume
// the flow was completed.
if isBeingDismissedDirectlyOrByAncestor() && navigationController?.viewControllers.last == self {
tracker.flowDismissed(source: .enableNotifications)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
calculatePreferredContentSize()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
hintLabel.isHidden = traitCollection.preferredContentSizeCategory.isAccessibilityCategory
}
private func calculatePreferredContentSize() {
let size = CGSize(width: view.bounds.width, height: UIView.layoutFittingCompressedSize.height)
preferredContentSize = view.systemLayoutSizeFitting(size)
}
@objc
private func applicationBecameActive() {
refreshPushAuthorizationStatus()
}
// MARK: - View Configuration
private func configureStackView() {
view.addSubview(stackView)
stackView.addArrangedSubviews([
imageView,
titleLabel,
promptLabel,
hintLabel
])
}
private func configureConstraints() {
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Metrics.edgeMargins.left),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.edgeMargins.right),
stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: Metrics.edgeMargins.top),
turnOnNotificationsButton.topAnchor.constraint(greaterThanOrEqualTo: stackView.bottomAnchor, constant: Metrics.edgeMargins.bottom),
turnOnNotificationsButton.heightAnchor.constraint(greaterThanOrEqualToConstant: Metrics.turnOnButtonHeight),
turnOnNotificationsButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Metrics.edgeMargins.left),
turnOnNotificationsButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.edgeMargins.right),
turnOnNotificationsButton.bottomAnchor.constraint(equalTo: view.safeBottomAnchor, constant: -Metrics.edgeMargins.bottom),
dismissButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.dismissButtonMargin),
dismissButton.topAnchor.constraint(equalTo: view.topAnchor, constant: Metrics.dismissButtonMargin)
])
}
// MARK: - Actions
@objc private func turnOnButtonTapped() {
tracker.buttonPressed(button: .notificationSettings, screen: .enableNotifications)
if let targetURL = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(targetURL)
} else {
assertionFailure("Couldn't unwrap Settings URL")
}
}
private func refreshPushAuthorizationStatus() {
PushNotificationsManager.shared.loadAuthorizationStatus { status in
self.pushNotificationsAuthorized = status
}
}
func navigateIfNecessary() {
// If push has been authorized, continue the flow
if pushNotificationsAuthorized == .authorized {
onAuthorized()
}
}
}
// MARK: - BloggingRemindersActions
extension BloggingRemindersPushPromptViewController: BloggingRemindersActions {
@objc private func dismissTapped() {
dismiss(from: .dismiss, screen: .enableNotifications, tracker: tracker)
}
}
// MARK: - DrawerPresentable
extension BloggingRemindersPushPromptViewController: DrawerPresentable {
var collapsedHeight: DrawerHeight {
return .maxHeight
}
}
extension BloggingRemindersPushPromptViewController: ChildDrawerPositionable {
var preferredDrawerPosition: DrawerPosition {
return .expanded
}
}
// MARK: - Constants
private enum TextContent {
static let title = NSLocalizedString("Turn on push notifications", comment: "Title of the screen in the Blogging Reminders flow which prompts users to enable push notifications.")
static let prompt = NSLocalizedString("To use blogging reminders, you'll need to turn on push notifications.",
comment: "Prompt telling users that they need to enable push notifications on their device to use the blogging reminders feature.")
static let hint = NSLocalizedString("Go to Settings → Notifications → WordPress, and toggle Allow Notifications.",
comment: "Instruction telling the user how to enable notifications in their device's system Settings app. The section names here should match those in Settings.")
static let turnOnButtonTitle = NSLocalizedString("Turn on notifications", comment: "Title for a button which takes the user to the WordPress app's settings in the system Settings app.")
}
private enum Images {
static let bellImageName = "reminders-bell"
}
private enum Metrics {
static let dismissButtonMargin: CGFloat = 20.0
static let edgeMargins = UIEdgeInsets(top: 80, left: 28, bottom: 80, right: 28)
static let stackSpacing: CGFloat = 20.0
static let turnOnButtonHeight: CGFloat = 44.0
}
|
gpl-2.0
|
66b3599736c0121befdb372191c9839d
| 35.507407 | 214 | 0.692909 | 5.629355 | false | false | false | false |
nextcloud/ios
|
iOSClient/Extensions/UIImage+Extensions.swift
|
1
|
9501
|
//
// UIColor+fixedOrientation.swift
// Nextcloud
//
// Created by Marino Faggiana on 27/11/2019.
// Copyright © 2019 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
import UIKit
import Accelerate
extension UIImage {
@objc func resizeImage(size: CGSize, isAspectRation: Bool = true) -> UIImage? {
let originRatio = self.size.width / self.size.height
let newRatio = size.width / size.height
var newSize = size
if isAspectRation {
if originRatio < newRatio {
newSize.height = size.height
newSize.width = size.height * originRatio
} else {
newSize.width = size.width
newSize.height = size.width / originRatio
}
}
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = newImage {
return image
}
return self
}
func fixedOrientation() -> UIImage? {
guard imageOrientation != UIImage.Orientation.up else {
// This is default orientation, don't need to do anything
return self.copy() as? UIImage
}
guard let cgImage = self.cgImage else {
// CGImage is not available
return nil
}
guard let colorSpace = cgImage.colorSpace, let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
return nil // Not able to create CGContext
}
var transform: CGAffineTransform = CGAffineTransform.identity
switch imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: CGFloat.pi)
case .left, .leftMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: CGFloat.pi / 2.0)
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: CGFloat.pi / -2.0)
case .up, .upMirrored:
break
@unknown default:
break
}
// Flip image one more time if needed to, this is to prevent flipped image
switch imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .up, .down, .left, .right:
break
@unknown default:
break
}
ctx.concatenate(transform)
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
default:
ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
break
}
guard let newCGImage = ctx.makeImage() else { return nil }
return UIImage(cgImage: newCGImage, scale: 1, orientation: .up)
}
@objc func image(color: UIColor, size: CGFloat) -> UIImage {
let size = CGSize(width: size, height: size)
UIGraphicsBeginImageContextWithOptions(size, false, self.scale)
color.setFill()
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(origin: .zero, size: size)
guard let cgImage = self.cgImage else { return self }
context?.clip(to: rect, mask: cgImage)
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return newImage
}
func isEqualToImage(image: UIImage?) -> Bool {
if image == nil { return false }
let data1: NSData = self.pngData()! as NSData
let data2: NSData = image!.pngData()! as NSData
return data1.isEqual(data2)
}
class func imageWithView(_ view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0)
defer { UIGraphicsEndImageContext() }
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
}
func image(alpha: CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: .zero, blendMode: .normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// Downsamles a image using ImageIO. Has better memory perfomance than redrawing using UIKit
///
/// - [Source](https://swiftsenpai.com/development/reduce-uiimage-memory-footprint/)
/// - [Original Source, WWDC18](https://developer.apple.com/videos/play/wwdc2018/416/?time=1352)
/// - Parameters:
/// - imageURL: The URL path of the image
/// - pointSize: The target point size
/// - scale: The point to pixel scale (Pixeld per point)
/// - Returns: The downsampled image, if successful
static func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat = UIScreen.main.scale) -> UIImage? {
// Create an CGImageSource that represent an image
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else { return nil }
// Calculate the desired dimension
let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
// Perform downsampling
let downsampleOptions = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels
] as CFDictionary
guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { return nil }
// Return the downsampled image as UIImage
return UIImage(cgImage: downsampledImage)
}
// Source:
// https://stackoverflow.com/questions/27092354/rotating-uiimage-in-swift/47402811#47402811
func rotate(radians: Float) -> UIImage? {
var newSize = CGRect(origin: CGPoint.zero, size: self.size).applying(CGAffineTransform(rotationAngle: CGFloat(radians))).size
// Trim off the extremely small float value to prevent core graphics from rounding it up
newSize.width = floor(newSize.width)
newSize.height = floor(newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, true, self.scale)
let context = UIGraphicsGetCurrentContext()!
// Move origin to middle
context.translateBy(x: newSize.width / 2, y: newSize.height / 2)
// Rotate around middle
context.rotate(by: CGFloat(radians))
// Draw the image at its center
self.draw(in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
func colorizeFolder(metadata: tableMetadata, tableDirectory: tableDirectory? = nil) -> UIImage {
let serverUrl = metadata.serverUrl + "/" + metadata.fileName
var image = self
if let tableDirectory = tableDirectory {
if let hex = tableDirectory.colorFolder, let color = UIColor(hex: hex) {
image = self.withTintColor(color, renderingMode: .alwaysOriginal)
}
} else if let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, serverUrl)), let hex = tableDirectory.colorFolder, let color = UIColor(hex: hex) {
image = self.withTintColor(color, renderingMode: .alwaysOriginal)
}
return image
}
}
|
gpl-3.0
|
3457c0d7bd57e714c294d1fee710b5a8
| 40.125541 | 274 | 0.652211 | 4.675197 | false | false | false | false |
kArTeL/News-YC---iPhone
|
HN/CustomViews/TextField/HNTextField.swift
|
5
|
959
|
//
// HNTextField.swift
// HN
//
// Created by Ben Gordon on 9/30/14.
// Copyright (c) 2014 bennyguitar. All rights reserved.
//
import UIKit
class HNTextField: UITextField {
var placeholderColor: UIColor? = UIColor(white: 1.0, alpha: 0.35)
override func drawPlaceholderInRect(rect: CGRect) {
if (placeholderColor != nil) {
var placeholderRect = CGRectMake(rect.origin.x, (rect.size.height - font.lineHeight)/2, rect.size.width, font.lineHeight);
var p = NSString(string: placeholder!)
var attr = [NSForegroundColorAttributeName:placeholderColor!, NSFontAttributeName:UIFont(name: "HelveticaNeue-Thin", size: 14.0)!]
p.drawInRect(placeholderRect, withAttributes: attr)
}
}
override func drawRect(rect: CGRect) {
addSubview(UIView.separatorWithWidth(Float(rect.size.width), origin: CGPointMake(0, CGFloat(height()) - 1), color: placeholderColor!))
}
}
|
mit
|
04d52119ee203a526cbc211c6459297c
| 35.884615 | 142 | 0.671533 | 4.080851 | false | false | false | false |
stripe/stripe-ios
|
StripeApplePay/StripeApplePay/Source/PaymentsCore/API/Models/PaymentIntent.swift
|
1
|
6134
|
//
// PaymentIntent.swift
// StripeApplePay
//
// Created by David Estes on 6/29/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
extension StripeAPI {
@_spi(STP) public struct PaymentIntent: UnknownFieldsDecodable {
// TODO: (MOBILESDK-468) Add modern bindings for more PaymentIntent fields
/// The Stripe ID of the PaymentIntent.
@_spi(STP) public let id: String
/// The client secret used to fetch this PaymentIntent
@_spi(STP) public let clientSecret: String
/// Amount intended to be collected by this PaymentIntent.
@_spi(STP) public let amount: Int
/// If status is `.canceled`, when the PaymentIntent was canceled.
@_spi(STP) public let canceledAt: Date?
/// Capture method of this PaymentIntent
@_spi(STP) public let captureMethod: CaptureMethod
/// Confirmation method of this PaymentIntent
@_spi(STP) public let confirmationMethod: ConfirmationMethod
/// When the PaymentIntent was created.
@_spi(STP) public let created: Date
/// The currency associated with the PaymentIntent.
@_spi(STP) public let currency: String
/// The `description` field of the PaymentIntent.
/// An arbitrary string attached to the object. Often useful for displaying to users.
@_spi(STP) public let stripeDescription: String?
/// Whether or not this PaymentIntent was created in livemode.
@_spi(STP) public let livemode: Bool
/// Email address that the receipt for the resulting payment will be sent to.
@_spi(STP) public let receiptEmail: String?
/// The Stripe ID of the Source used in this PaymentIntent.
@_spi(STP) public let sourceId: String?
/// The Stripe ID of the PaymentMethod used in this PaymentIntent.
@_spi(STP) public let paymentMethodId: String?
/// Status of the PaymentIntent
@_spi(STP) public let status: Status
/// Shipping information for this PaymentIntent.
@_spi(STP) public let shipping: ShippingDetails?
/// Status types for a PaymentIntent
@frozen @_spi(STP) public enum Status: String, SafeEnumCodable {
/// Unknown status
case unknown
/// This PaymentIntent requires a PaymentMethod or Source
case requiresPaymentMethod = "requires_payment_method"
/// This PaymentIntent requires a Source
/// Deprecated: Use STPPaymentIntentStatusRequiresPaymentMethod instead.
@available(
*,
deprecated,
message: "Use STPPaymentIntentStatus.requiresPaymentMethod instead",
renamed: "STPPaymentIntentStatus.requiresPaymentMethod"
)
case requiresSource = "requires_source"
/// This PaymentIntent needs to be confirmed
case requiresConfirmation = "requires_confirmation"
/// The selected PaymentMethod or Source requires additional authentication steps.
/// Additional actions found via `next_action`
case requiresAction = "requires_action"
/// The selected Source requires additional authentication steps.
/// Additional actions found via `next_source_action`
/// Deprecated: Use STPPaymentIntentStatusRequiresAction instead.
@available(
*,
deprecated,
message: "Use STPPaymentIntentStatus.requiresAction instead",
renamed: "STPPaymentIntentStatus.requiresAction"
)
case requiresSourceAction = "requires_source_action"
/// Stripe is processing this PaymentIntent
case processing
/// The payment has succeeded
case succeeded
/// Indicates the payment must be captured, for STPPaymentIntentCaptureMethodManual
case requiresCapture = "requires_capture"
/// This PaymentIntent was canceled and cannot be changed.
case canceled
case unparsable
// TODO: This is @frozen because of a bug in the Xcode 12.2 Swift compiler.
// Remove @frozen after Xcode 12.2 support has been dropped.
}
@frozen @_spi(STP) public enum ConfirmationMethod: String, SafeEnumCodable {
/// Unknown confirmation method
case unknown
/// Confirmed via publishable key
case manual
/// Confirmed via secret key
case automatic
case unparsable
// TODO: This is @frozen because of a bug in the Xcode 12.2 Swift compiler.
// Remove @frozen after Xcode 12.2 support has been dropped.
}
@frozen @_spi(STP) public enum CaptureMethod: String, SafeEnumCodable {
/// Unknown capture method
case unknown
/// The PaymentIntent will be automatically captured
case automatic
/// The PaymentIntent must be manually captured once it has the status
/// `.requiresCapture`
case manual
case unparsable
// TODO: This is @frozen because of a bug in the Xcode 12.2 Swift compiler.
// Remove @frozen after Xcode 12.2 support has been dropped.
}
@_spi(STP) public var _allResponseFieldsStorage: NonEncodableParameters?
}
}
extension StripeAPI.PaymentIntent {
/// Helper function for extracting PaymentIntent id from the Client Secret.
/// This avoids having to pass around both the id and the secret.
/// - Parameter clientSecret: The `client_secret` from the PaymentIntent
internal static func id(fromClientSecret clientSecret: String) -> String? {
// see parseClientSecret from stripe-js-v3
let components = clientSecret.components(separatedBy: "_secret_")
if components.count >= 2 && components[0].hasPrefix("pi_") {
return components[0]
} else {
return nil
}
}
}
|
mit
|
71f7da3aa6048ca3439dcca235b383cb
| 40.161074 | 95 | 0.629545 | 5.49552 | false | false | false | false |
devinross/curry
|
Examples/Examples/ColorsViewController.swift
|
1
|
2383
|
//
// ColorsViewController.swift
// Created by Devin Ross on 9/12/16.
//
/*
curry || https://github.com/devinross/curry
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
class ColorsViewController: UIViewController {
override func loadView() {
super.loadView()
self.view.backgroundColor = UIColor.white
let scrollView = UIScrollView(frame: self.view.bounds)
self.view.addSubview(scrollView)
let pad = CGFloat(20.0)
let width = (self.view.width - (pad*4.0)) / 3.0
let middleX = pad*2 + width
let rightX = pad*3 + width*2
let colors = [[UIColor(red: 0, green: 121/255.0, blue: 210/255.0, alpha: 1),]]
var middle = CGRect(x: middleX, y: pad, width: width, height: width)
var left = CGRect(x:pad, y: pad, width: width, height: width)
var right = CGRect(x:rightX, y: pad, width: width, height: width)
for array in colors {
let block1 = UIView(frame: left, backgroundColor: array.first!)
scrollView.addSubview(block1)
let block2 = UIView(frame: middle, backgroundColor: array[1])
scrollView.addSubview(block2)
let block3 = UIView(frame: right, backgroundColor: array.last!)
scrollView.addSubview(block3)
left.origin.y = block1.maxY + pad
middle.origin.y = block1.maxY + pad;
right.origin.y = block1.maxY + pad;
}
scrollView.contentHeight = right.origin.y
}
}
|
mit
|
456a8dca2a8e8a0fdcee408db5ca3f85
| 26.390805 | 80 | 0.72052 | 3.706065 | false | false | false | false |
LuckyChen73/CW_WEIBO_SWIFT
|
WeiBo/WeiBo/Classes/View(视图)/Compose(发布)/WBComposePicCell.swift
|
1
|
2836
|
//
// WBComposePicCell.swift
// WeiBo
//
// Created by chenWei on 2017/4/12.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
//协议
protocol WBComposePicCellDelegate: NSObjectProtocol {
//添加或替换图片
func addOrReplacePicture(cell: WBComposePicCell)
//删除图片
func deletePicture(cell: WBComposePicCell)
}
class WBComposePicCell: UICollectionViewCell {
// 代理属性
weak var delegate: WBComposePicCellDelegate?
/// 添加或替换图片的按钮
lazy var addOrReplaceButton: UIButton = UIButton(title: nil, target: self, selector: #selector(addOrReplacePicture), events: UIControlEvents.touchUpInside, bgImage: "compose_pic_add")
/// 删除图片的按钮
lazy var deleteButton: UIButton = UIButton(title: nil, target: self, selector: #selector(deletePicture), events: UIControlEvents.touchUpInside, bgImage: "compose_photo_close")
var image: UIImage? {
didSet{
if let image = image { // 有值就给 cell的按钮设置图片
addOrReplaceButton.setBackgroundImage(image, for: .normal)
addOrReplaceButton.setBackgroundImage(image, for: .highlighted)
} else {
addOrReplaceButton.setBackgroundImage(UIImage(named: "compose_pic_add"), for: .normal)
addOrReplaceButton.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), for: .highlighted)
}
//如果image有值, 删除按钮就显示
deleteButton.isHidden = image == nil
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI 搭建
extension WBComposePicCell {
func setupUI() {
self.contentView.addSubview(addOrReplaceButton)
self.contentView.addSubview(deleteButton)
addOrReplaceButton.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(10)
make.right.equalTo(self).offset(-10)
make.top.equalTo(self).offset(10)
make.bottom.equalTo(self).offset(-10)
}
deleteButton.snp.makeConstraints { (make) in
make.left.equalTo(self.snp.right).offset(-23)
make.top.equalTo(self)
}
}
}
// MARK: - 点击事件的处理
extension WBComposePicCell {
/// 添加或更换图片
@objc fileprivate func addOrReplacePicture() {
delegate?.addOrReplacePicture(cell: self)
}
/// 删除图片
@objc fileprivate func deletePicture() {
delegate?.deletePicture(cell: self)
}
}
|
mit
|
882278ca314bde126c0ee14783356973
| 23.117117 | 187 | 0.617109 | 4.222397 | false | false | false | false |
huangboju/QMUI.swift
|
QMUI.swift/QMUIKit/UIKitExtensions/UITabBarItem+QMUI.swift
|
1
|
2143
|
//
// UITabBarItem+QMUI.swift
// QMUI.swift
//
// Created by xnxin on 2017/7/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import Foundation
extension UITabBarItem {
private struct AssociatedKeys {
static var kDoubleTapBlock = "kDoubleTapBlock"
}
typealias Qmui_doubleTapClosureType = (_ tabBarItem: UITabBarItem, _ index: Int) -> Void?
/**
* 双击 tabBarItem 时的回调,默认为 nil。
* @arg tabBarItem 被双击的 UITabBarItem
* @arg index 被双击的 UITabBarItem 的序号
*/
var qmui_doubleTapClosure: Qmui_doubleTapClosureType? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.kDoubleTapBlock) as? Qmui_doubleTapClosureType
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.kDoubleTapBlock, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
/**
* 获取一个UITabBarItem内的按钮,里面包含imageView、label等子View
*/
func qmui_barButton() -> UIControl? {
return value(forKey: "view") as? UIControl
}
/**
* 获取一个UITabBarItem内显示图标的UIImageView,如果找不到则返回nil
* @warning 需要对nil的返回值做保护
*/
func qmui_imageView() -> UIImageView? {
guard let barButton = qmui_barButton() else {
return nil
}
var result: UIImageView?
barButton.subviews.forEach {
// iOS10及以后,imageView都是用UITabBarSwappableImageView实现的,所以遇到这个class就直接拿
if String(describing: type(of: $0)).isEqual("UITabBarSwappableImageView") {
result = $0 as? UIImageView
}
if IOS_VERSION < 10 {
// iOS10以前,选中的item的高亮是用UITabBarSelectionIndicatorView实现的,所以要屏蔽掉
if $0 is UIImageView && String(describing: type(of: $0)).isEqual("UITabBarSelectionIndicatorView") {
result = $0 as? UIImageView
}
}
}
return result
}
}
|
mit
|
4d420f75bda146eee06f6b36cd6cbf56
| 27.597015 | 119 | 0.611169 | 4.156182 | false | false | false | false |
aktowns/swen
|
Sources/Swen/Util/Colour.swift
|
1
|
2565
|
//
// Colour.swift created on 28/12/15
// Swen project
//
// Copyright 2015 Ashley Towns <[email protected]>
//
// 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.
//
public struct Colour {
static let DEFAULT_ALPHA: UInt8 = 120
public var r: UInt8
public var g: UInt8
public var b: UInt8
public var a: UInt8
public init(r: UInt8, g: UInt8, b: UInt8, a: UInt8) {
self.r = r
self.g = g
self.b = b
self.a = a
}
public init(r: UInt8, g: UInt8, b: UInt8) {
self.init(r: r, g: g, b: b, a: Colour.DEFAULT_ALPHA)
}
public init(hex: UInt32) {
self.init(r: UInt8(hex >> 24 & 255),
g: UInt8(hex >> 16 & 255),
b: UInt8(hex >> 8 & 255),
a: UInt8(hex & 255))
}
public init(rgba: (UInt8, UInt8, UInt8, UInt8)) {
self.init(r: rgba.0, g: rgba.1, b: rgba.2, a: rgba.3)
}
public init(rgb: (UInt8, UInt8, UInt8)) {
self.init(r: rgb.0, g: rgb.1, b: rgb.2, a: Colour.DEFAULT_ALPHA)
}
public func alpha(a: UInt8) -> Colour {
return Colour(rgba: (self.r, self.g, self.b, a))
}
public var hex: UInt32 {
return (UInt32(self.r) << 24 | UInt32(self.g) << 16 | UInt32(self.b) << 8 | UInt32(self.a))
}
public static var black: Colour {
return Colour(hex: 0x000000FF)
}
public static var white: Colour {
return Colour(hex: 0xFFFFFFFF)
}
public static var red: Colour {
return Colour(hex: 0xFF0000FF)
}
public static var green: Colour {
return Colour(hex: 0x00FF00FF)
}
public static var blue: Colour {
return Colour(hex: 0x0000FFFF)
}
public static var lightRed: Colour {
return Colour(hex: 0xff9999FF)
}
public static var lightGreen: Colour {
return Colour(hex: 0xccffccFF)
}
public static var lightBlue: Colour {
return Colour(hex: 0x66ccffFF)
}
public static var yellow: Colour {
return Colour(hex: 0xFFFF00FF)
}
public static var orange: Colour {
return Colour(hex: 0xff9900FF)
}
public static var purple: Colour {
return Colour(hex: 0x660066FF)
}
}
|
apache-2.0
|
3d1ce4441a49f73a229bd7785fc091ce
| 23.428571 | 95 | 0.640546 | 3.151106 | false | false | false | false |
ResearchSuite/ResearchSuiteAppFramework-iOS
|
Example/ResearchSuiteAppFramework/OhmageState.swift
|
1
|
1148
|
//
// OhmageState.swift
// ResearchSuiteAppFramework
//
// Created by James Kizer on 3/25/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import ReSwift
import ResearchSuiteAppFramework
final public class OhmageOMHSSDKState: RSAFBaseState {
let sessionToken: String?
let email: String?
let password: String?
public required init() {
self.sessionToken = nil
self.email = nil
self.password = nil
super.init()
}
public init(sessionToken: String?, email: String?, password: String?) {
self.sessionToken = sessionToken
self.email = email
self.password = password
super.init()
}
public static func newState(
fromState: OhmageOMHSSDKState,
sessionToken: (String?)? = nil,
email: (String?)? = nil,
password: (String?)? = nil
) -> OhmageOMHSSDKState {
return OhmageOMHSSDKState(
sessionToken: sessionToken ?? fromState.sessionToken,
email: email ?? fromState.email,
password: password ?? fromState.password
)
}
}
|
apache-2.0
|
dd9856a53ff4917d2db69b889d8619ab
| 23.934783 | 75 | 0.613775 | 4.428571 | false | false | false | false |
Jnosh/swift
|
test/SILGen/super.swift
|
5
|
4956
|
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
import resilient_class
public class Parent {
public final var finalProperty: String {
return "Parent.finalProperty"
}
public var property: String {
return "Parent.property"
}
public final class var finalClassProperty: String {
return "Parent.finalProperty"
}
public class var classProperty: String {
return "Parent.property"
}
public func methodOnlyInParent() {}
public final func finalMethodOnlyInParent() {}
public func method() {}
public final class func finalClassMethodOnlyInParent() {}
public class func classMethod() {}
}
public class Child : Parent {
// CHECK-LABEL: sil @_T05super5ChildC8propertySSfg : $@convention(method) (@guaranteed Child) -> @owned String {
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T05super6ParentC8propertySSfg : $@convention(method) (@guaranteed Parent) -> @owned String
// CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]])
// CHECK: destroy_value [[CASTED_SELF_COPY]]
// CHECK: return [[RESULT]]
public override var property: String {
return super.property
}
// CHECK-LABEL: sil @_T05super5ChildC13otherPropertySSfg : $@convention(method) (@guaranteed Child) -> @owned String {
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[COPIED_SELF:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[COPIED_SELF]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T05super6ParentC13finalPropertySSfg
// CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]])
// CHECK: destroy_value [[CASTED_SELF_COPY]]
// CHECK: return [[RESULT]]
public var otherProperty: String {
return super.finalProperty
}
}
public class Grandchild : Child {
// CHECK-LABEL: sil @_T05super10GrandchildC06onlyInB0yyF
public func onlyInGrandchild() {
// CHECK: function_ref @_T05super6ParentC012methodOnlyInB0yyF : $@convention(method) (@guaranteed Parent) -> ()
super.methodOnlyInParent()
// CHECK: function_ref @_T05super6ParentC017finalMethodOnlyInB0yyF
super.finalMethodOnlyInParent()
}
// CHECK-LABEL: sil @_T05super10GrandchildC6methodyyF
public override func method() {
// CHECK: function_ref @_T05super6ParentC6methodyyF : $@convention(method) (@guaranteed Parent) -> ()
super.method()
}
}
public class GreatGrandchild : Grandchild {
// CHECK-LABEL: sil @_T05super15GreatGrandchildC6methodyyF
public override func method() {
// CHECK: function_ref @_T05super10GrandchildC6methodyyF : $@convention(method) (@guaranteed Grandchild) -> ()
super.method()
}
}
public class ChildToResilientParent : ResilientOutsideParent {
public override func method() {
super.method()
}
public override class func classMethod() {
super.classMethod()
}
}
public class ChildToFixedParent : OutsideParent {
public override func method() {
super.method()
}
public override class func classMethod() {
super.classMethod()
}
}
public extension ResilientOutsideChild {
public func callSuperMethod() {
super.method()
}
public class func callSuperClassMethod() {
super.classMethod()
}
}
public class GenericBase<T> {
public func method() {}
}
public class GenericDerived<T> : GenericBase<T> {
public override func method() {
// CHECK-LABEL: sil private @_T05super14GenericDerivedC6methodyyFyycfU_ : $@convention(thin) <T> (@owned GenericDerived<T>) -> ()
// CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
// CHECK: return
{
super.method()
}()
// CHECK-LABEL: sil private @_T05super14GenericDerivedC6methodyyF13localFunctionL_yylF : $@convention(thin) <T> (@owned GenericDerived<T>) -> ()
// CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
// CHECK: return
func localFunction() {
super.method()
}
localFunction()
// CHECK-LABEL: sil private @_T05super14GenericDerivedC6methodyyF15genericFunctionL_yqd__r__lF : $@convention(thin) <T><U> (@in U, @owned GenericDerived<T>) -> ()
// CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
// CHECK: return
func genericFunction<U>(_: U) {
super.method()
}
genericFunction(0)
}
}
|
apache-2.0
|
56bb8321c879e7ea6bce876ce65f4486
| 33.416667 | 166 | 0.662228 | 3.760243 | false | false | false | false |
functionaldude/XLPagerTabStrip
|
Example/Example/ChildControllers/TableChildExampleViewController.swift
|
1
|
3305
|
// TableChildExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import XLPagerTabStrip
class TableChildExampleViewController: UITableViewController, IndicatorInfoProvider {
let cellIdentifier = "postCell"
var blackTheme = false
var itemInfo = IndicatorInfo(title: "View")
init(style: UITableViewStyle, itemInfo: IndicatorInfo) {
self.itemInfo = itemInfo
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "PostCell", bundle: Bundle.main), forCellReuseIdentifier: cellIdentifier)
tableView.estimatedRowHeight = 60.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.allowsSelection = false
if blackTheme {
tableView.backgroundColor = UIColor(red: 15/255.0, green: 16/255.0, blue: 16/255.0, alpha: 1.0)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataProvider.sharedInstance.postsData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PostCell,
let data = DataProvider.sharedInstance.postsData.object(at: indexPath.row) as? NSDictionary else { return PostCell() }
cell.configureWithData(data)
if blackTheme {
cell.changeStylToBlack()
}
return cell
}
// MARK: - IndicatorInfoProvider
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return itemInfo
}
}
|
mit
|
6ace92d9ab8d27085b0594351dcfa79c
| 37.430233 | 130 | 0.715885 | 4.962462 | false | false | false | false |
Ryan-Vanderhoef/Antlers
|
AppIdea/Frameworks/Bond/Bond/Bond+Arrays.swift
|
1
|
15248
|
//
// Bond+Arrays.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: - Vector Dynamic
// MARK: Array Bond
public class ArrayBond<T>: Bond<Array<T>> {
public var willInsertListener: ((DynamicArray<T>, [Int]) -> Void)?
public var didInsertListener: ((DynamicArray<T>, [Int]) -> Void)?
public var willRemoveListener: ((DynamicArray<T>, [Int]) -> Void)?
public var didRemoveListener: ((DynamicArray<T>, [Int]) -> Void)?
public var willUpdateListener: ((DynamicArray<T>, [Int]) -> Void)?
public var didUpdateListener: ((DynamicArray<T>, [Int]) -> Void)?
override public init() {
super.init()
}
override public func bind(dynamic: Dynamic<Array<T>>) {
bind(dynamic, fire: true, strongly: true)
}
override public func bind(dynamic: Dynamic<Array<T>>, fire: Bool) {
bind(dynamic, fire: fire, strongly: true)
}
override public func bind(dynamic: Dynamic<Array<T>>, fire: Bool, strongly: Bool) {
super.bind(dynamic, fire: fire, strongly: strongly)
}
}
// MARK: Dynamic array
public class DynamicArray<T>: Dynamic<Array<T>>, SequenceType {
public typealias Element = T
public typealias Generator = DynamicArrayGenerator<T>
public override init(_ v: Array<T>) {
super.init(v)
}
public override func bindTo(bond: Bond<Array<T>>) {
bond.bind(self, fire: true, strongly: true)
}
public override func bindTo(bond: Bond<Array<T>>, fire: Bool) {
bond.bind(self, fire: fire, strongly: true)
}
public override func bindTo(bond: Bond<Array<T>>, fire: Bool, strongly: Bool) {
bond.bind(self, fire: fire, strongly: strongly)
}
public var count: Int {
return value.count
}
public var capacity: Int {
return value.capacity
}
public var isEmpty: Bool {
return value.isEmpty
}
public var first: T? {
return value.first
}
public var last: T? {
return value.last
}
public func append(newElement: T) {
dispatchWillInsert([value.count])
value.append(newElement)
dispatchDidInsert([value.count-1])
}
public func append(array: Array<T>) {
if array.count > 0 {
let count = value.count
dispatchWillInsert(Array(count..<value.count))
value += array
dispatchDidInsert(Array(count..<value.count))
}
}
public func removeLast() -> T {
if self.count > 0 {
dispatchWillRemove([value.count-1])
let last = value.removeLast()
dispatchDidRemove([value.count])
return last
}
fatalError("Cannot remveLast() as there are no elements in the array!")
}
public func insert(newElement: T, atIndex i: Int) {
dispatchWillInsert([i])
value.insert(newElement, atIndex: i)
dispatchDidInsert([i])
}
public func splice(array: Array<T>, atIndex i: Int) {
if array.count > 0 {
dispatchWillInsert(Array(i..<i+array.count))
value.splice(array, atIndex: i)
dispatchDidInsert(Array(i..<i+array.count))
}
}
public func removeAtIndex(index: Int) -> T {
dispatchWillRemove([index])
let object = value.removeAtIndex(index)
dispatchDidRemove([index])
return object
}
public func removeAll(keepCapacity: Bool) {
let count = value.count
dispatchWillRemove(Array<Int>(0..<count))
value.removeAll(keepCapacity: keepCapacity)
dispatchDidRemove(Array<Int>(0..<count))
}
public subscript(index: Int) -> T {
get {
return value[index]
}
set(newObject) {
if index == value.count {
dispatchWillInsert([index])
value[index] = newObject
dispatchDidInsert([index])
} else {
dispatchWillUpdate([index])
value[index] = newObject
dispatchDidUpdate([index])
}
}
}
public func generate() -> DynamicArrayGenerator<T> {
return DynamicArrayGenerator<T>(array: self)
}
private func dispatchWillInsert(indices: [Int]) {
for bondBox in bonds {
if let arrayBond = bondBox.bond as? ArrayBond {
arrayBond.willInsertListener?(self, indices)
}
}
}
private func dispatchDidInsert(indices: [Int]) {
for bondBox in bonds {
if let arrayBond = bondBox.bond as? ArrayBond {
arrayBond.didInsertListener?(self, indices)
}
}
}
private func dispatchWillRemove(indices: [Int]) {
for bondBox in bonds {
if let arrayBond = bondBox.bond as? ArrayBond {
arrayBond.willRemoveListener?(self, indices)
}
}
}
private func dispatchDidRemove(indices: [Int]) {
for bondBox in bonds {
if let arrayBond = bondBox.bond as? ArrayBond {
arrayBond.didRemoveListener?(self, indices)
}
}
}
private func dispatchWillUpdate(indices: [Int]) {
for bondBox in bonds {
if let arrayBond = bondBox.bond as? ArrayBond {
arrayBond.willUpdateListener?(self, indices)
}
}
}
private func dispatchDidUpdate(indices: [Int]) {
for bondBox in bonds {
if let arrayBond = bondBox.bond as? ArrayBond {
arrayBond.didUpdateListener?(self, indices)
}
}
}
}
public struct DynamicArrayGenerator<T>: GeneratorType {
private var index = -1
private let array: DynamicArray<T>
init(array: DynamicArray<T>) {
self.array = array
}
typealias Element = T
public mutating func next() -> T? {
index++
return index < array.count ? array[index] : nil
}
}
// MARK: Dynamic Array Map Proxy
private class DynamicArrayMapProxy<T, U>: DynamicArray<U> {
private unowned var sourceArray: DynamicArray<T>
private var mapf: (T, Int) -> U
private let bond: ArrayBond<T>
private init(sourceArray: DynamicArray<T>, mapf: (T, Int) -> U) {
self.sourceArray = sourceArray
self.mapf = mapf
self.bond = ArrayBond<T>()
self.bond.bind(sourceArray, fire: false)
super.init([])
bond.willInsertListener = { [unowned self] array, i in
self.dispatchWillInsert(i)
}
bond.didInsertListener = { [unowned self] array, i in
self.dispatchDidInsert(i)
}
bond.willRemoveListener = { [unowned self] array, i in
self.dispatchWillRemove(i)
}
bond.didRemoveListener = { [unowned self] array, i in
self.dispatchDidRemove(i)
}
bond.willUpdateListener = { [unowned self] array, i in
self.dispatchWillUpdate(i)
}
bond.didUpdateListener = { [unowned self] array, i in
self.dispatchDidUpdate(i)
}
}
override var count: Int {
return sourceArray.count
}
override var capacity: Int {
return sourceArray.capacity
}
override var isEmpty: Bool {
return sourceArray.isEmpty
}
override var first: U? {
if let first = sourceArray.first {
return mapf(first, 0)
} else {
return nil
}
}
override var last: U? {
if let last = sourceArray.last {
return mapf(last, sourceArray.count - 1)
} else {
return nil
}
}
override func append(newElement: U) {
fatalError("Modifying proxy array is not supported!")
}
override func append(array: Array<U>) {
fatalError("Modifying proxy array is not supported!")
}
override func removeLast() -> U {
fatalError("Modifying proxy array is not supported!")
}
override func insert(newElement: U, atIndex i: Int) {
fatalError("Modifying proxy array is not supported!")
}
override func splice(array: Array<U>, atIndex i: Int) {
fatalError("Modifying proxy array is not supported!")
}
override func removeAtIndex(index: Int) -> U {
fatalError("Modifying proxy array is not supported!")
}
override func removeAll(keepCapacity: Bool) {
fatalError("Modifying proxy array is not supported!")
}
override subscript(index: Int) -> U {
get {
return mapf(sourceArray[index], index)
}
set(newObject) {
fatalError("Modifying proxy array is not supported!")
}
}
}
func indexOfFirstEqualOrLargerThan(x: Int, array: [Int]) -> Int {
var idx: Int = -1
for (index, element) in enumerate(array) {
if element < x {
idx = index
} else {
break
}
}
return idx + 1
}
// MARK: Dynamic Array Filter Proxy
private class DynamicArrayFilterProxy<T>: DynamicArray<T> {
private unowned var sourceArray: DynamicArray<T>
private var pointers: [Int] = []
private var filterf: T -> Bool
private let bond: ArrayBond<T>
private init(sourceArray: DynamicArray<T>, filterf: T -> Bool) {
self.sourceArray = sourceArray
self.filterf = filterf
self.bond = ArrayBond<T>()
self.bond.bind(sourceArray, fire: false)
super.init([])
for (index, element) in enumerate(sourceArray) {
if filterf(element) {
pointers.append(index)
}
}
bond.didInsertListener = { [unowned self] array, indices in
var insertedIndices: [Int] = []
var pointers = self.pointers
for idx in indices {
for (index, element) in enumerate(pointers) {
if element >= idx {
pointers[index] = element + 1
}
}
let element = array[idx]
if filterf(element) {
let position = indexOfFirstEqualOrLargerThan(idx, pointers)
pointers.insert(idx, atIndex: position)
insertedIndices.append(position)
}
}
if insertedIndices.count > 0 {
self.dispatchWillInsert(insertedIndices)
}
self.pointers = pointers
if insertedIndices.count > 0 {
self.dispatchDidInsert(insertedIndices)
}
}
bond.willRemoveListener = { [unowned self] array, indices in
var removedIndices: [Int] = []
var pointers = self.pointers
for idx in reverse(indices) {
if let idx = find(pointers, idx) {
pointers.removeAtIndex(idx)
removedIndices.append(idx)
}
for (index, element) in enumerate(pointers) {
if element >= idx {
pointers[index] = element - 1
}
}
}
if removedIndices.count > 0 {
self.dispatchWillRemove(reverse(removedIndices))
}
self.pointers = pointers
if removedIndices.count > 0 {
self.dispatchDidRemove(reverse(removedIndices))
}
}
bond.didUpdateListener = { [unowned self] array, indices in
let idx = indices[0]
let element = array[idx]
var insertedIndices: [Int] = []
var removedIndices: [Int] = []
var updatedIndices: [Int] = []
var pointers = self.pointers
if let idx = find(pointers, idx) {
if filterf(element) {
// update
updatedIndices.append(idx)
} else {
// remove
pointers.removeAtIndex(idx)
removedIndices.append(idx)
}
} else {
if filterf(element) {
let position = indexOfFirstEqualOrLargerThan(idx, pointers)
pointers.insert(idx, atIndex: position)
insertedIndices.append(position)
} else {
// nothing
}
}
if insertedIndices.count > 0 {
self.dispatchWillInsert(insertedIndices)
}
if removedIndices.count > 0 {
self.dispatchWillRemove(removedIndices)
}
if updatedIndices.count > 0 {
self.dispatchWillUpdate(updatedIndices)
}
self.pointers = pointers
if updatedIndices.count > 0 {
self.dispatchDidUpdate(updatedIndices)
}
if removedIndices.count > 0 {
self.dispatchDidRemove(removedIndices)
}
if insertedIndices.count > 0 {
self.dispatchDidInsert(insertedIndices)
}
}
}
private override var count: Int {
return pointers.count
}
private override var capacity: Int {
return pointers.capacity
}
private override var isEmpty: Bool {
return pointers.isEmpty
}
private override var first: T? {
if let first = pointers.first {
return sourceArray[first]
} else {
return nil
}
}
private override var last: T? {
if let last = pointers.last {
return sourceArray[last]
} else {
return nil
}
}
override private func append(newElement: T) {
fatalError("Modifying proxy array is not supported!")
}
private override func append(array: Array<T>) {
fatalError("Modifying proxy array is not supported!")
}
override private func removeLast() -> T {
fatalError("Modifying proxy array is not supported!")
}
override private func insert(newElement: T, atIndex i: Int) {
fatalError("Modifying proxy array is not supported!")
}
private override func splice(array: Array<T>, atIndex i: Int) {
fatalError("Modifying proxy array is not supported!")
}
override private func removeAtIndex(index: Int) -> T {
fatalError("Modifying proxy array is not supported!")
}
override private func removeAll(keepCapacity: Bool) {
fatalError("Modifying proxy array is not supported!")
}
override private subscript(index: Int) -> T {
get {
return sourceArray[pointers[index]]
}
set {
fatalError("Modifying proxy array is not supported!")
}
}
}
// MARK: Dynamic Array additions
public extension DynamicArray
{
public func map<U>(f: (T, Int) -> U) -> DynamicArray<U> {
return _map(self, f)
}
public func map<U>(f: T -> U) -> DynamicArray<U> {
let mapf = { (o: T, i: Int) -> U in f(o) }
return _map(self, mapf)
}
public func filter(f: T -> Bool) -> DynamicArray<T> {
return _filter(self, f)
}
}
// MARK: Map
private func _map<T, U>(dynamicArray: DynamicArray<T>, f: (T, Int) -> U) -> DynamicArrayMapProxy<T, U> {
return DynamicArrayMapProxy(sourceArray: dynamicArray, mapf: f)
}
// MARK: Filter
private func _filter<T>(dynamicArray: DynamicArray<T>, f: T -> Bool) -> DynamicArray<T> {
return DynamicArrayFilterProxy(sourceArray: dynamicArray, filterf: f)
}
|
mit
|
061e16e90bd480eadb589d60147872e8
| 24.583893 | 104 | 0.62946 | 4.03493 | false | false | false | false |
hsoi/RxSwift
|
RxCocoa/Common/DelegateProxyType.swift
|
2
|
9601
|
//
// DelegateProxyType.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
/**
`DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with
views that can have only one delegate/datasource registered.
`Proxies` store information about observers, subscriptions and delegates
for specific views.
Type implementing `DelegateProxyType` should never be initialized directly.
To fetch initialized instance of type implementing `DelegateProxyType`, `proxyForObject` method
should be used.
This is more or less how it works.
+-------------------------------------------+
| |
| UIView subclass (UIScrollView) |
| |
+-----------+-------------------------------+
|
| Delegate
|
|
+-----------v-------------------------------+
| |
| Delegate proxy : DelegateProxyType +-----+----> Observable<T1>
| , UIScrollViewDelegate | |
+-----------+-------------------------------+ +----> Observable<T2>
| |
| +----> Observable<T3>
| |
| forwards events |
| to custom delegate |
| v
+-----------v-------------------------------+
| |
| Custom delegate (UIScrollViewDelegate) |
| |
+-------------------------------------------+
Since RxCocoa needs to automagically create those Proxys
..and because views that have delegates can be hierarchical
UITableView : UIScrollView : UIView
.. and corresponding delegates are also hierarchical
UITableViewDelegate : UIScrollViewDelegate : NSObject
.. and sometimes there can be only one proxy/delegate registered,
every view has a corresponding delegate virtual factory method.
In case of UITableView / UIScrollView, there is
extensions UIScrollView {
public func rx_createDelegateProxy() -> RxScrollViewDelegateProxy {
return RxScrollViewDelegateProxy(view: self)
}
....
and override in UITableView
extension UITableView {
public override func rx_createDelegateProxy() -> RxScrollViewDelegateProxy {
....
*/
public protocol DelegateProxyType : AnyObject {
/**
Creates new proxy for target object.
*/
static func createProxyForObject(object: AnyObject) -> AnyObject
/**
Returns assigned proxy for object.
- parameter object: Object that can have assigned delegate proxy.
- returns: Assigned delegate proxy or `nil` if no delegate proxy is assigned.
*/
static func assignedProxyFor(object: AnyObject) -> AnyObject?
/**
Assigns proxy to object.
- parameter object: Object that can have assigned delegate proxy.
- parameter proxy: Delegate proxy object to assign to `object`.
*/
static func assignProxy(proxy: AnyObject, toObject object: AnyObject)
/**
Returns designated delegate property for object.
Objects can have multiple delegate properties.
Each delegate property needs to have it's own type implementing `DelegateProxyType`.
- parameter object: Object that has delegate property.
- returns: Value of delegate property.
*/
static func currentDelegateFor(object: AnyObject) -> AnyObject?
/**
Sets designated delegate property for object.
Objects can have multiple delegate properties.
Each delegate property needs to have it's own type implementing `DelegateProxyType`.
- parameter toObject: Object that has delegate property.
- parameter delegate: Delegate value.
*/
static func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject)
/**
Returns reference of normal delegate that receives all forwarded messages
through `self`.
- returns: Value of reference if set or nil.
*/
func forwardToDelegate() -> AnyObject?
/**
Sets reference of normal delegate that receives all forwarded messages
through `self`.
- parameter forwardToDelegate: Reference of delegate that receives all messages through `self`.
- parameter retainDelegate: Should `self` retain `forwardToDelegate`.
*/
func setForwardToDelegate(forwardToDelegate: AnyObject?, retainDelegate: Bool)
}
/**
Returns existing proxy for object or installs new instance of delegate proxy.
- parameter object: Target object on which to install delegate proxy.
- returns: Installed instance of delegate proxy.
extension UISearchBar {
public var rx_delegate: DelegateProxy {
return proxyForObject(RxSearchBarDelegateProxy.self, self)
}
public var rx_text: ControlProperty<String> {
let source: Observable<String> = self.rx_delegate.observe("searchBar:textDidChange:")
...
}
}
*/
public func proxyForObject<P: DelegateProxyType>(type: P.Type, _ object: AnyObject) -> P {
MainScheduler.ensureExecutingOnScheduler()
let maybeProxy = P.assignedProxyFor(object) as? P
let proxy: P
if maybeProxy == nil {
proxy = P.createProxyForObject(object) as! P
P.assignProxy(proxy, toObject: object)
assert(P.assignedProxyFor(object) === proxy)
}
else {
proxy = maybeProxy!
}
let currentDelegate: AnyObject? = P.currentDelegateFor(object)
if currentDelegate !== proxy {
proxy.setForwardToDelegate(currentDelegate, retainDelegate: false)
P.setCurrentDelegate(proxy, toObject: object)
assert(P.currentDelegateFor(object) === proxy)
assert(proxy.forwardToDelegate() === currentDelegate)
}
return proxy
}
@available(*, deprecated=2.0.0, message="Please use version that takes type as first argument.")
public func proxyForObject<P: DelegateProxyType>(object: AnyObject) -> P {
return proxyForObject(P.self, object)
}
func installDelegate<P: DelegateProxyType>(proxy: P, delegate: AnyObject, retainDelegate: Bool, onProxyForObject object: AnyObject) -> Disposable {
weak var weakDelegate: AnyObject? = delegate
assert(proxy.forwardToDelegate() === nil, "There is already a set delegate \(proxy.forwardToDelegate())")
proxy.setForwardToDelegate(delegate, retainDelegate: retainDelegate)
// refresh properties after delegate is set
// some views like UITableView cache `respondsToSelector`
P.setCurrentDelegate(nil, toObject: object)
P.setCurrentDelegate(proxy, toObject: object)
assert(proxy.forwardToDelegate() === delegate, "Setting of delegate failed")
return AnonymousDisposable {
MainScheduler.ensureExecutingOnScheduler()
let delegate: AnyObject? = weakDelegate
assert(delegate == nil || proxy.forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(proxy.forwardToDelegate()), and it should have been \(proxy)")
proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate)
}
}
extension ObservableType {
func subscribeProxyDataSourceForObject<P: DelegateProxyType>(object: AnyObject, dataSource: AnyObject, retainDataSource: Bool, binding: (P, Event<E>) -> Void)
-> Disposable {
let proxy = proxyForObject(P.self, object)
let disposable = installDelegate(proxy, delegate: dataSource, retainDelegate: retainDataSource, onProxyForObject: object)
let subscription = self.asObservable()
// source can't ever end, otherwise it will release the subscriber
.concat(Observable.never())
.subscribe { [weak object] (event: Event<E>) in
MainScheduler.ensureExecutingOnScheduler()
if let object = object {
assert(proxy === P.currentDelegateFor(object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(P.currentDelegateFor(object))")
}
binding(proxy, event)
switch event {
case .Error(let error):
bindingErrorToInterface(error)
disposable.dispose()
case .Completed:
disposable.dispose()
default:
break
}
}
return StableCompositeDisposable.create(subscription, disposable)
}
}
|
mit
|
8e1f448e8efafc3398166aebc067a4e7
| 36.354086 | 196 | 0.570729 | 6.099111 | false | false | false | false |
qq456cvb/DeepLearningKitForiOS
|
iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/DeepNetwork+SetupNetworkFromDict.swift
|
1
|
5286
|
//
// DeepNetwork+SetupNetworkFromDict.swift
// MemkiteMetal
//
// Created by Amund Tveit on 10/12/15.
// Copyright © 2015 memkite. All rights reserved.
//
import Foundation
import Metal
public extension DeepNetwork {
func setupNetworkFromDict(_ deepNetworkAsDict: Dictionary<String, Any>, inputimage: MTLBuffer, inputshape: [Float], caching_mode:Bool) {
let start = Date()
print(" ==> setupNetworkFromDict()")
// Add input image
var layer_number = 0
layer_data_caches.append(Dictionary<String, MTLBuffer>()) // for input
pool_type_caches.append(Dictionary<String,String>())
blob_cache.append(Dictionary<String,([Float],[Float])>())
namedDataLayers.append(("input", inputimage))
layer_number += 1
// Add remaining network
var previousBuffer:MTLBuffer = inputimage
var previousShape:[Float] = inputshape
self.deepNetworkAsDict = deepNetworkAsDict
// create new command buffer for next layer
var currentCommandBuffer: MTLCommandBuffer = metalCommandQueue.makeCommandBufferWithUnretainedReferences()
var t = Date()
for layer in deepNetworkAsDict["layer"] as! [NSDictionary] {
if let type = layer["type"] as? String {
let layer_string = layer["name"] as! String
layer_data_caches.append(Dictionary<String, MTLBuffer>())
pool_type_caches.append(Dictionary<String,String>())
blob_cache.append(Dictionary<String,([Float],[Float])>())
if type == "ReLU" {
self.gpuCommandLayers.append(currentCommandBuffer)
//(previousBuffer, currentCommandBuffer) = createRectifierLayer(previousBuffer)
(previousBuffer, currentCommandBuffer) = createRectifierLayer(layer, inputBuffer:previousBuffer, metalCommandQueue:metalCommandQueue, metalDefaultLibrary:metalDefaultLibrary, metalDevice:metalDevice)
self.namedDataLayers.append((layer["name"]! as! String, previousBuffer))
} else if type == "Pooling" {
self.gpuCommandLayers.append(currentCommandBuffer)
// (previousBuffer, currentCommandBuffer, previousShape) = createPoolingLayer(layer, inputBuffer: previousBuffer, inputShape: previousShape)
(previousBuffer, currentCommandBuffer, previousShape) = createPoolingLayerCached(layer: layer, inputBuffer: previousBuffer, inputShape: previousShape, metalCommandQueue: metalCommandQueue, metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice, pool_type_caches: &pool_type_caches, layer_data_caches: &layer_data_caches, layer_number: layer_number, layer_string: layer_string, caching_mode: caching_mode)
self.namedDataLayers.append((layer["name"]! as! String, previousBuffer))
} else if type == "Convolution" {
self.gpuCommandLayers.append(currentCommandBuffer)
// (previousBuffer, currentCommandBuffer, previousShape) = createConvolutionLayer(layer, inputBuffer: previousBuffer, inputShape: previousShape)
(previousBuffer, currentCommandBuffer, previousShape) = createConvolutionLayerCached(layer, inputBuffer: previousBuffer, inputShape: previousShape, metalCommandQueue: metalCommandQueue, metalDefaultLibrary:metalDefaultLibrary, metalDevice:metalDevice, layer_data_caches: &layer_data_caches, blob_cache: &blob_cache, layer_number: layer_number, layer_string: layer_string, caching_mode: caching_mode)
self.namedDataLayers.append((layer["name"]! as! String, previousBuffer))
} else if type == "InnerProduct" {
self.gpuCommandLayers.append(currentCommandBuffer)
// (previousBuffer, currentCommandBuffer, previousShape) = createConvolutionLayer(layer, inputBuffer: previousBuffer, inputShape: previousShape)
(previousBuffer, currentCommandBuffer, previousShape) = createFullyConnectedLayerCached(layer, inputBuffer: previousBuffer, inputShape: previousShape, metalCommandQueue: metalCommandQueue, metalDefaultLibrary:metalDefaultLibrary, metalDevice:metalDevice, layer_data_caches: &layer_data_caches, blob_cache: &blob_cache, layer_number: layer_number, layer_string: layer_string, caching_mode: caching_mode)
self.namedDataLayers.append((layer["name"]! as! String, previousBuffer))
}
let name = layer["name"] as! String
print("\(name): \(Date().timeIntervalSince(t))")
t = Date()
layer_number += 1
}
}
self.gpuCommandLayers.append(currentCommandBuffer)
print("bar")
print("AFTER LAYER DATA CHACES = \(layer_data_caches[0])")
print("POOL TYPE CACHES = \(pool_type_caches)")
print("Time to set up network: \(Date().timeIntervalSince(start))")
}
}
|
apache-2.0
|
ff7ef0eb2aa1dd5c3b4377729489166c
| 57.076923 | 436 | 0.638789 | 5.071977 | false | false | false | false |
mercadopago/sdk-ios
|
MercadoPagoSDKExamples/MercadoPagoSDKExamples/CardViewController.swift
|
1
|
14780
|
//
// CardViewController.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 28/1/15.
// Copyright (c) 2015 com.mercadopago. All rights reserved.
//
import UIKit
import MercadoPagoSDK
class CardViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, KeyboardDelegate {
var publicKey : String?
@IBOutlet weak var tableView : UITableView!
var cardNumberCell : MPCardNumberTableViewCell!
var expirationDateCell : MPExpirationDateTableViewCell!
var cardholderNameCell : MPCardholderNameTableViewCell!
var userIdCell : MPUserIdTableViewCell!
var securityCodeCell : SimpleSecurityCodeTableViewCell!
var paymentMethod : PaymentMethod!
var hasError : Bool = false
var loadingView : UILoadingView!
var identificationType : IdentificationType?
var identificationTypes : [IdentificationType]?
var callback : ((token : Token?) -> Void)?
var isKeyboardVisible : Bool?
var inputsCells : NSMutableArray!
init(merchantPublicKey: String, paymentMethod: PaymentMethod, callback: (token: Token?) -> Void) {
super.init(nibName: "CardViewController", bundle: nil)
self.publicKey = merchantPublicKey
self.paymentMethod = paymentMethod
self.callback = callback
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init() {
super.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized)
self.view.addSubview(self.loadingView)
self.title = "Datos de tu tarjeta".localized
self.navigationItem.backBarButtonItem?.title = "Atrás"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Continuar".localized, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CardViewController.submitForm))
let mercadoPago = MercadoPago(publicKey: self.publicKey!)
mercadoPago.getIdentificationTypes({(identificationTypes: [IdentificationType]?) -> Void in
self.identificationTypes = identificationTypes
self.prepareTableView()
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
}, failure: { (error: NSError?) -> Void in
self.prepareTableView()
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
self.userIdCell.hidden = true
}
)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CardViewController.willShowKeyboard(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CardViewController.willHideKeyboard(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func willHideKeyboard(notification: NSNotification) {
// resize content insets.
let contentInsets = UIEdgeInsetsMake(64, 0.0, 0.0, 0)
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = contentInsets
}
func willShowKeyboard(notification: NSNotification) {
let s:NSValue? = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)
let keyboardBounds :CGRect = s!.CGRectValue()
// resize content insets.
let contentInsets = UIEdgeInsetsMake(64, 0.0, keyboardBounds.size.height, 0)
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = contentInsets
}
@IBAction func submitForm() {
self.view.addSubview(self.loadingView)
let cardToken = CardToken(cardNumber: self.cardNumberCell.getCardNumber(), expirationMonth: self.expirationDateCell.getExpirationMonth(), expirationYear: self.expirationDateCell.getExpirationYear(), securityCode: self.securityCodeCell.getSecurityCode(), cardholderName: self.cardholderNameCell.getCardholderName(), docType: self.userIdCell.getUserIdType(), docNumber: self.userIdCell.getUserIdValue())
if validateForm(cardToken) {
createToken(cardToken)
} else {
self.loadingView.removeFromSuperview()
self.hasError = true
self.tableView.reloadData()
}
}
func getIndexForObject(object: AnyObject) -> Int {
var i = 0
for arr in self.inputsCells {
if let input = object as? UITextField {
if let arrTextField = (arr as! NSArray)[0] as? UITextField {
if input == arrTextField {
return i
}
}
}
i = i + 1
}
return -1
}
func scrollToRow(indexPath: NSIndexPath) {
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
}
func focusAndScrollForIndex(index: Int) {
var i = 0
for arr in self.inputsCells {
if i == index {
if let textField = (arr as! NSArray)[0] as? UITextField {
if let cell = (arr as! NSArray)[1] as? ErrorTableViewCell {
if !textField.isFirstResponder() {
textField.becomeFirstResponder()
}
let indexPath = self.tableView.indexPathForCell(cell)
if indexPath != nil {
scrollToRow(indexPath!)
}
}
}
}
i = i + 1
}
}
func prev(object: AnyObject?) {
if object != nil {
let index = getIndexForObject(object!)
if index >= 1 {
focusAndScrollForIndex(index-1)
}
}
}
func next(object: AnyObject?) {
if object != nil {
let index = getIndexForObject(object!)
if index < self.inputsCells.count - 1 {
focusAndScrollForIndex(index+1)
}
}
}
func done(object: AnyObject?) {
if object != nil {
let index = getIndexForObject(object!)
if index < self.inputsCells.count {
var i = 0
for arr in self.inputsCells {
if i == index {
if let textField = (arr as! NSArray)[0] as? UITextField {
textField.resignFirstResponder()
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
scrollToRow(indexPath)
}
}
i = i + 1
}
}
}
}
func prepareTableView() {
self.inputsCells = NSMutableArray()
let cardNumberNib = UINib(nibName: "MPCardNumberTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(cardNumberNib, forCellReuseIdentifier: "cardNumberCell")
self.cardNumberCell = self.tableView.dequeueReusableCellWithIdentifier("cardNumberCell") as! MPCardNumberTableViewCell
self.cardNumberCell.height = 55.0
self.cardNumberCell.setIcon(self.paymentMethod._id)
self.cardNumberCell._setSetting(self.paymentMethod.settings[0])
self.cardNumberCell.cardNumberTextField.inputAccessoryView = MPToolbar(prevEnabled: false, nextEnabled: true, delegate: self, textFieldContainer: self.cardNumberCell.cardNumberTextField)
self.inputsCells.addObject([self.cardNumberCell.cardNumberTextField, self.cardNumberCell])
let expirationDateNib = UINib(nibName: "MPExpirationDateTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(expirationDateNib, forCellReuseIdentifier: "expirationDateCell")
self.expirationDateCell = self.tableView.dequeueReusableCellWithIdentifier("expirationDateCell") as! MPExpirationDateTableViewCell
self.expirationDateCell.height = 55.0
self.expirationDateCell.expirationDateTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.expirationDateCell.expirationDateTextField)
self.inputsCells.addObject([self.expirationDateCell.expirationDateTextField, self.expirationDateCell])
let cardholderNameNib = UINib(nibName: "MPCardholderNameTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(cardholderNameNib, forCellReuseIdentifier: "cardholderNameCell")
self.cardholderNameCell = self.tableView.dequeueReusableCellWithIdentifier("cardholderNameCell") as! MPCardholderNameTableViewCell
self.cardholderNameCell.height = 55.0
self.cardholderNameCell.cardholderNameTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.cardholderNameCell.cardholderNameTextField)
self.inputsCells.addObject([self.cardholderNameCell.cardholderNameTextField, self.cardholderNameCell])
let userIdNib = UINib(nibName: "MPUserIdTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(userIdNib, forCellReuseIdentifier: "userIdCell")
self.userIdCell = self.tableView.dequeueReusableCellWithIdentifier("userIdCell") as! MPUserIdTableViewCell
self.userIdCell._setIdentificationTypes(self.identificationTypes)
self.userIdCell.height = 55.0
self.userIdCell.userIdTypeTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.userIdCell.userIdTypeTextField)
self.userIdCell.userIdValueTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.userIdCell.userIdValueTextField)
self.inputsCells.addObject([self.userIdCell.userIdTypeTextField, self.userIdCell])
self.inputsCells.addObject([self.userIdCell.userIdValueTextField, self.userIdCell])
let securityCodeNib = UINib(nibName: "SimpleSecurityCodeTableViewCell", bundle: nil)
self.tableView.registerNib(securityCodeNib, forCellReuseIdentifier: "securityCodeCell")
self.securityCodeCell = self.tableView.dequeueReusableCellWithIdentifier("securityCodeCell") as! SimpleSecurityCodeTableViewCell
self.securityCodeCell.height = 55.0
self.securityCodeCell.securityCodeTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: false, delegate: self, textFieldContainer: self.securityCodeCell.securityCodeTextField)
self.inputsCells.addObject([self.securityCodeCell.securityCodeTextField, self.securityCodeCell])
self.tableView.delegate = self
self.tableView.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 2 ? 1 : 2
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
return self.cardNumberCell
} else if indexPath.row == 1 {
return self.expirationDateCell
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
return self.cardholderNameCell
} else if indexPath.row == 1 {
return self.userIdCell
}
} else if indexPath.section == 2 {
return self.securityCodeCell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
if indexPath.row == 0 {
return self.cardNumberCell.getHeight()
} else if indexPath.row == 1 {
return self.expirationDateCell.getHeight()
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
return self.cardholderNameCell.getHeight()
} else if indexPath.row == 1 {
return self.userIdCell.getHeight()
}
} else if indexPath.section == 2 {
return self.securityCodeCell.getHeight()
}
return 55
}
override func viewDidLayoutSubviews() {
if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
self.tableView.separatorInset = UIEdgeInsetsZero
}
if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
if #available(iOS 8.0, *) {
self.tableView.layoutMargins = UIEdgeInsetsZero
} else {
}
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
cell.separatorInset = UIEdgeInsetsZero
}
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
if #available(iOS 8.0, *) {
cell.layoutMargins = UIEdgeInsetsZero
} else {
}
}
}
func validateForm(cardToken : CardToken) -> Bool {
var result : Bool = true
// Validate card number
let errorCardNumber = cardToken.validateCardNumber(paymentMethod!)
if errorCardNumber != nil {
self.cardNumberCell.setError(errorCardNumber!.userInfo["cardNumber"] as? String)
result = false
} else {
self.cardNumberCell.setError(nil)
}
// Validate expiry date
let errorExpiryDate = cardToken.validateExpiryDate()
if errorExpiryDate != nil {
self.expirationDateCell.setError(errorExpiryDate!.userInfo["expiryDate"] as? String)
result = false
} else {
self.expirationDateCell.setError(nil)
}
// Validate card holder name
let errorCardholder = cardToken.validateCardholderName()
if errorCardholder != nil {
self.cardholderNameCell.setError(errorCardholder!.userInfo["cardholder"] as? String)
result = false
} else {
self.cardholderNameCell.setError(nil)
}
// Validate identification number
let errorIdentificationType = cardToken.validateIdentificationType()
var errorIdentificationNumber : NSError? = nil
if self.identificationType != nil {
errorIdentificationNumber = cardToken.validateIdentificationNumber(self.identificationType!)
} else {
errorIdentificationNumber = cardToken.validateIdentificationNumber()
}
if errorIdentificationType != nil {
self.userIdCell.setError(errorIdentificationType!.userInfo["identification"] as? String)
result = false
} else if errorIdentificationNumber != nil {
self.userIdCell.setError(errorIdentificationNumber!.userInfo["identification"] as? String)
result = false
} else {
self.userIdCell.setError(nil)
}
let errorSecurityCode = cardToken.validateSecurityCode()
if errorSecurityCode != nil {
self.securityCodeCell.setError(errorSecurityCode!.userInfo["securityCode"] as? String)
result = false
} else {
self.securityCodeCell.setError(nil)
}
return result
}
func textFieldDidBeginEditing(textField: UITextField) {
let cell = textField.superview?.superview as! UITableViewCell?
self.tableView.scrollToRowAtIndexPath(self.tableView.indexPathForCell(cell!)!, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func createToken(cardToken: CardToken) {
let mercadoPago = MercadoPago(publicKey: self.publicKey!)
mercadoPago.createNewCardToken(cardToken, success: { (token) -> Void in
self.loadingView.removeFromSuperview()
self.callback?(token: token)
}, failure: nil)
}
}
|
mit
|
c5bb1a86f76f3be1bc566de77990cf43
| 35.763682 | 403 | 0.756817 | 4.205748 | false | false | false | false |
XavierDK/Coordinator
|
Coordinator/NavigationCoordinator.swift
|
1
|
1789
|
//
// NavigationCoordinator.swift
// Coordinator
//
// Created by Xavier De Koninck on 27/07/2017.
// Copyright © 2017 PagesJaunes. All rights reserved.
//
import UIKit
open class NavigationCoordinator: Coordinator {
public var controller: UIViewController?
public let context: Context
public let navigationController: UINavigationController
public weak var parentCoordinator: Coordinator?
public var childCoordinators: [Coordinator] = []
required public init(navigationController: UINavigationController, parentCoordinator: Coordinator?, context: Context) {
self.context = context
self.parentCoordinator = parentCoordinator
self.navigationController = navigationController
}
open func setup() throws {
throw CoordinatorError.badImplementation("‼️ERROR‼️ : Method `setup` should be overriden for the coordinator \(self)")
}
}
public extension NavigationCoordinator {
func start(withCallback completion: CoordinatorCallback? = nil) throws {
try setup()
guard let controller = controller else {
throw CoordinatorError.badImplementation("‼️ERROR‼️ : You must have initialized the controller in method `setup` for coordinator \(self)")
}
navigationController.pushViewController(controller, animated: true) { [weak self] in
guard let strongSelf = self else { return }
completion?(strongSelf)
}
}
func stop(withCallback completion: CoordinatorCallback? = nil) {
if let controller = controller,
navigationController.viewControllers.contains(controller) {
navigationController.popViewController(animated: true) { [weak self] in
guard let strongSelf = self else { return }
completion?(strongSelf)
}
}
}
}
|
mit
|
c5aece83266a038e7f8babe8cd9d2030
| 29.551724 | 144 | 0.717269 | 5.106628 | false | false | false | false |
DarielChen/DemoCode
|
iOS动画指南/iOS动画指南 - 6.可以很酷的转场动画/2.reveal/2.reveal/reveal/RWLogoLayer.swift
|
1
|
1305
|
//
// RWLogoLayer.swift
// reveal
//
// Created by Dariel on 16/7/26.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
class RWLogoLayer {
class func logoLayer() -> CAShapeLayer {
let layer = CAShapeLayer()
layer.geometryFlipped = true
//the RW bezier
let bezier = UIBezierPath()
bezier.moveToPoint(CGPoint(x: 0.0, y: 0.0))
bezier.addCurveToPoint(CGPoint(x: 0.0, y: 66.97), controlPoint1:CGPoint(x: 0.0, y: 0.0), controlPoint2:CGPoint(x: 0.0, y: 57.06))
bezier.addCurveToPoint(CGPoint(x: 16.0, y: 39.0), controlPoint1: CGPoint(x: 27.68, y: 66.97), controlPoint2:CGPoint(x: 42.35, y: 52.75))
bezier.addCurveToPoint(CGPoint(x: 26.0, y: 17.0), controlPoint1: CGPoint(x: 17.35, y: 35.41), controlPoint2:CGPoint(x: 26, y: 17))
bezier.addLineToPoint(CGPoint(x: 38.0, y: 34.0))
bezier.addLineToPoint(CGPoint(x: 49.0, y: 17.0))
bezier.addLineToPoint(CGPoint(x: 67.0, y: 51.27))
bezier.addLineToPoint(CGPoint(x: 67.0, y: 0.0))
bezier.addLineToPoint(CGPoint(x: 0.0, y: 0.0))
bezier.closePath()
//create a shape layer
layer.path = bezier.CGPath
layer.bounds = CGPathGetBoundingBox(layer.path)
return layer
}
}
|
mit
|
800259995e49ecf3b97239eede38217f
| 35.166667 | 144 | 0.613671 | 3.296203 | false | false | false | false |
steryokhin/AsciiArtPlayer
|
src/AsciiArtPlayer/AsciiArtPlayer/Classes/Core/Utils/AsciiArt/Pixel.swift
|
2
|
1791
|
//
// Pixel.swift
// SwiftAsciiArt
//
// Created by Joshua Smith on 4/25/15.
// Copyright (c) 2015 iJoshSmith. All rights reserved.
//
import Foundation
/** Represents the memory address of a pixel. */
typealias PixelPointer = UnsafePointer<UInt8>
/** A point in an image converted to an ASCII character. */
struct Pixel
{
/** The number of bytes a pixel occupies. 1 byte per channel (RGBA). */
static let bytesPerPixel = 4
fileprivate let offset: Int
fileprivate init(_ offset: Int) { self.offset = offset }
static func createPixelMatrix(_ width: Int, _ height: Int) -> [[Pixel]]
{
return (0..<height).map { row in
(0..<width).map { col in
let offset = (width * row + col) * Pixel.bytesPerPixel
return Pixel(offset)
}
}
}
func intensityFromPixelPointer(_ pointer: PixelPointer) -> Double
{
let
red = pointer[offset + 0],
green = pointer[offset + 1],
blue = pointer[offset + 2]
return Pixel.calculateIntensity(red, green, blue)
}
fileprivate static func calculateIntensity(_ r: UInt8, _ g: UInt8, _ b: UInt8) -> Double
{
// Normalize the pixel's grayscale value to between 0 and 1.
// Weights from http://en.wikipedia.org/wiki/Grayscale#Luma_coding_in_video_systems
let
redWeight = 0.229,
greenWeight = 0.587,
blueWeight = 0.114,
weightedMax = 255.0 * redWeight +
255.0 * greenWeight +
255.0 * blueWeight,
weightedSum = Double(r) * redWeight +
Double(g) * greenWeight +
Double(b) * blueWeight
return weightedSum / weightedMax
}
}
|
mit
|
c5b749e33f901b0281765e0e7113be95
| 29.87931 | 92 | 0.570631 | 4.089041 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.